From 691dde05dc0839de7803a1c1fc795b96e193e8e4 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Tue, 13 Dec 2022 13:49:08 +0800 Subject: [PATCH 001/300] =?UTF-8?q?KERNEL-13843=20refactor:=20core?= =?UTF-8?q?=E6=9C=AA=E5=AE=8C=E6=88=90es6=E5=8C=96=E6=97=B6=E4=B8=8D?= =?UTF-8?q?=E9=98=BB=E5=A1=9E=E6=99=AE=E9=80=9A=E7=BB=84=E4=BB=B6=E7=9A=84?= =?UTF-8?q?es6=E5=8C=96=E7=9A=84=E4=B8=80=E4=B8=AA=E7=A4=BA=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/1.pane.js | 100 +++++++++++++++++++++--------------------- src/core/decorator.js | 8 ++++ tsconfig.json | 3 +- 3 files changed, 60 insertions(+), 51 deletions(-) create mode 100644 src/core/decorator.js diff --git a/src/base/1.pane.js b/src/base/1.pane.js index d628ae7bf..f613cbdd7 100644 --- a/src/base/1.pane.js +++ b/src/base/1.pane.js @@ -6,41 +6,44 @@ * @extends BI.Widget * @abstract */ -BI.Pane = BI.inherit(BI.Widget, { +import { shortcut } from "../core/decorator"; - _defaultConfig: function () { - return BI.extend(BI.Pane.superclass._defaultConfig.apply(this, arguments), { - _baseCls: "bi-pane", - tipText: BI.i18nText("BI-No_Selected_Item"), - loadingText: "", - loadingSize: "small", - overlap: true, - onLoaded: BI.emptyFn, - }); - }, +@shortcut() +export class Pane extends BI.Widget { + static xtype = "bi.pane"; + static EVENT_LOADED = "EVENT_LOADED"; + static EVENT_LOADING = "EVENT_LOADING"; + + props = { + _baseCls: "bi-pane", + tipText: BI.i18nText("BI-No_Selected_Item"), + loadingText: "", + loadingSize: "small", + overlap: true, + onLoaded: BI.emptyFn, + } - _assertTip: function () { - var self = this, o = this.options; + _assertTip() { if (!this._tipText) { BI.createWidget({ type: "bi.absolute_center_adapt", element: this, items: [{ type: "bi.label", - ref: function (_ref) { - self._tipText = _ref; + ref: (_ref) => { + this._tipText = _ref; }, cls: "bi-tips", - text: o.tipText, + text: this.options.tipText, height: 25, }], }); } - }, - - loading: function () { - var self = this, o = this.options; - var loadingAnimation = BI.createWidget(BI.Providers.getProvider("bi.provider.system").getLoading({ + } + + loading() { + const o = this.options; + const loadingAnimation = BI.createWidget(BI.Providers.getProvider("bi.provider.system").getLoading({ loadingSize: o.loadingSize, context: this, })); @@ -56,7 +59,7 @@ BI.Pane = BI.inherit(BI.Widget, { element: BI.Layers.make(this.getName() + "-loading", this), }); } - BI.Layers.show(self.getName() + "-loading"); + BI.Layers.show(this.getName() + "-loading"); } else if (BI.isNull(this._loading)) { loadingAnimation.element.css("zIndex", 1); BI.createWidget({ @@ -66,17 +69,17 @@ BI.Pane = BI.inherit(BI.Widget, { items: this._getLoadingTipItems(loadingAnimation), }); } - self.fireEvent(BI.Pane.EVENT_LOADING); + this.fireEvent(Pane.EVENT_LOADING); this.element.addClass("loading-status"); - }, + } - _getSize: function (v) { + _getSize(v) { return Math.ceil(v / (this.options.loadingSize === "small" ? 2 : 1)); - }, + } - _getLoadingTipItems: function (loadingTip) { - var self = this, o = this.options; - var loadingTipItems = [{ + _getLoadingTipItems(loadingTip) { + const o = this.options; + const loadingTipItems = [{ type: "bi.horizontal_adapt", items: [loadingTip], }]; @@ -88,46 +91,43 @@ BI.Pane = BI.inherit(BI.Widget, { return [{ type: "bi.vertical", - ref: function (_ref) { - self._loading = _ref; + ref: (_ref) => { + this._loading = _ref; }, items: loadingTipItems, }]; - }, + } - loaded: function () { - var self = this, o = this.options; - BI.Layers.remove(self.getName() + "-loading"); + loaded() { + BI.Layers.remove(this.getName() + "-loading"); this._loading && this._loading.destroy(); - o.onLoaded(); - self.fireEvent(BI.Pane.EVENT_LOADED); + this.options.onLoaded(); + this.fireEvent(Pane.EVENT_LOADED); this.element.removeClass("loading-status"); - }, + } - check: function () { + check() { this.setTipVisible(BI.isEmpty(this.options.items)); - }, + } - setTipVisible: function (b) { + setTipVisible(b) { if (b === true) { this._assertTip(); this._tipText && this._tipText.setVisible(true); } else { this._tipText && this._tipText.setVisible(false); } - }, + } - setTipText: function (text) { + setTipText(text) { this._assertTip(); this._tipText.setText(text); - }, + } - populate: function (items) { + populate(items) { this.options.items = items || []; this.check(); - }, -}); -BI.Pane.EVENT_LOADED = "EVENT_LOADED"; -BI.Pane.EVENT_LOADING = "EVENT_LOADING"; + } +} -BI.shortcut("bi.pane", BI.Pane); +BI.extend(BI, { Pane }); diff --git a/src/core/decorator.js b/src/core/decorator.js new file mode 100644 index 000000000..23215d701 --- /dev/null +++ b/src/core/decorator.js @@ -0,0 +1,8 @@ +/** + * 注册widget + */ +export function shortcut() { + return function decorator(Target) { + BI.shortcut(Target.xtype, Target); + }; +} diff --git a/tsconfig.json b/tsconfig.json index 5630b275a..a964cc231 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -20,7 +20,8 @@ "noUnusedParameters": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, - "emitDeclarationOnly": true + "emitDeclarationOnly": true, + "allowJs": true, }, "include": [ "typescript/*.ts", From b6f291ae780313d4b95f7c21500cc8711fb0cfd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Wed, 14 Dec 2022 11:40:59 +0800 Subject: [PATCH 002/300] =?UTF-8?q?feat:=20=E4=BF=AE=E6=94=B9bi.a?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- demo/js/core/abstract/demo.button_group.js | 103 +++++++++++---------- src/base/single/a/a.js | 51 +++++----- 2 files changed, 85 insertions(+), 69 deletions(-) diff --git a/demo/js/core/abstract/demo.button_group.js b/demo/js/core/abstract/demo.button_group.js index 21652ad58..059b97847 100644 --- a/demo/js/core/abstract/demo.button_group.js +++ b/demo/js/core/abstract/demo.button_group.js @@ -7,54 +7,63 @@ Demo.Func = BI.inherit(BI.Widget, { return { type: "bi.vertical", items: [{ - type: "bi.button_group", - ref: function (_ref) { - ref = _ref; + type: "bi.a", + el: { + type: "bi.label", + text: "这就是一个百度超链" }, - chooseType: BI.ButtonGroup.CHOOSE_TYPE_NONE, - layouts: [{ - type: "bi.vertical", - items: [{ - type: "bi.vtape", - height: 200 - }] - }], - items: [{ - el: { - type: "bi.label", - text: "button_group是一类具有相同属性或相似属性的抽象, 本案例实现的是布局的嵌套(vertical布局下内嵌center_adapt布局)" - }, - height: 150 - }, { - el: { - type: "bi.button", - text: "1" - } - }] - }, { - type: "bi.button", - text: "populate", - handler: function () { - ref.populate([{ - el: { - type: "bi.label", - text: "1" - }, - height: 50 - }, { - el: { - type: "bi.button", - text: "2" - }, - height: 50 - }, { - el: { - type: "bi.label", - text: "3" - } - }]); - } - }] + href: "https://www.baidu.com" + }], + // type: "bi.vertical", + // items: [{ + // type: "bi.button_group", + // ref: function (_ref) { + // ref = _ref; + // }, + // chooseType: BI.ButtonGroup.CHOOSE_TYPE_NONE, + // layouts: [{ + // type: "bi.vertical", + // items: [{ + // type: "bi.vtape", + // height: 200 + // }] + // }], + // items: [{ + // el: { + // type: "bi.label", + // text: "button_group是一类具有相同属性或相似属性的抽象, 本案例实现的是布局的嵌套(vertical布局下内嵌center_adapt布局)" + // }, + // height: 150 + // }, { + // el: { + // type: "bi.button", + // text: "1" + // } + // }] + // }, { + // type: "bi.button", + // text: "populate", + // handler: function () { + // ref.populate([{ + // el: { + // type: "bi.label", + // text: "1" + // }, + // height: 50 + // }, { + // el: { + // type: "bi.button", + // text: "2" + // }, + // height: 50 + // }, { + // el: { + // type: "bi.label", + // text: "3" + // } + // }]); + // } + // }] }; } diff --git a/src/base/single/a/a.js b/src/base/single/a/a.js index 9159f0a46..a11e0f91b 100644 --- a/src/base/single/a/a.js +++ b/src/base/single/a/a.js @@ -6,29 +6,36 @@ * @extends BI.Text * @abstract */ -BI.A = BI.inherit(BI.Text, { - _defaultConfig: function () { - var conf = BI.A.superclass._defaultConfig.apply(this, arguments); +import { shortcut } from "../../../core/decorator"; +@shortcut() +export class A extends BI.Text { + static xtype = "bi.a"; + constructor() { + super(); + } + // TODO:这里如何修改有问题 + _defaultConfig() { + var conf = super._defaultConfig(arguments); + return BI.extend(conf, { + baseCls: (conf.baseCls || "") + " bi-a display-block", + href: "", + target: "_blank", + el: null, + tagName: "a", + }); + } - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-a display-block", - href: "", - target: "_blank", - el: null, - tagName: "a", + render() { + var o = this.options; + super.render(); + this.element.attr({ href: o.href, target: o.target }); + if (o.el) { + BI.createWidget(o.el, { + element: this, }); - }, + } + } - render: function () { - var o = this.options; - BI.A.superclass.render.apply(this, arguments); - this.element.attr({ href: o.href, target: o.target }); - if (o.el) { - BI.createWidget(o.el, { - element: this, - }); - } - }, -}); +} -BI.shortcut("bi.a", BI.A); +BI.extend(BI, { A }); From 4818b99ec3dd75bb77591d63cb4411fcf9aa18c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Wed, 14 Dec 2022 12:16:56 +0800 Subject: [PATCH 003/300] =?UTF-8?q?feat:=20=E8=BF=98=E5=8E=9Fdemo=E4=BF=AE?= =?UTF-8?q?=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- demo/js/core/abstract/demo.button_group.js | 103 ++++++++++----------- 1 file changed, 47 insertions(+), 56 deletions(-) diff --git a/demo/js/core/abstract/demo.button_group.js b/demo/js/core/abstract/demo.button_group.js index 059b97847..21652ad58 100644 --- a/demo/js/core/abstract/demo.button_group.js +++ b/demo/js/core/abstract/demo.button_group.js @@ -7,63 +7,54 @@ Demo.Func = BI.inherit(BI.Widget, { return { type: "bi.vertical", items: [{ - type: "bi.a", - el: { - type: "bi.label", - text: "这就是一个百度超链" + type: "bi.button_group", + ref: function (_ref) { + ref = _ref; }, - href: "https://www.baidu.com" - }], - // type: "bi.vertical", - // items: [{ - // type: "bi.button_group", - // ref: function (_ref) { - // ref = _ref; - // }, - // chooseType: BI.ButtonGroup.CHOOSE_TYPE_NONE, - // layouts: [{ - // type: "bi.vertical", - // items: [{ - // type: "bi.vtape", - // height: 200 - // }] - // }], - // items: [{ - // el: { - // type: "bi.label", - // text: "button_group是一类具有相同属性或相似属性的抽象, 本案例实现的是布局的嵌套(vertical布局下内嵌center_adapt布局)" - // }, - // height: 150 - // }, { - // el: { - // type: "bi.button", - // text: "1" - // } - // }] - // }, { - // type: "bi.button", - // text: "populate", - // handler: function () { - // ref.populate([{ - // el: { - // type: "bi.label", - // text: "1" - // }, - // height: 50 - // }, { - // el: { - // type: "bi.button", - // text: "2" - // }, - // height: 50 - // }, { - // el: { - // type: "bi.label", - // text: "3" - // } - // }]); - // } - // }] + chooseType: BI.ButtonGroup.CHOOSE_TYPE_NONE, + layouts: [{ + type: "bi.vertical", + items: [{ + type: "bi.vtape", + height: 200 + }] + }], + items: [{ + el: { + type: "bi.label", + text: "button_group是一类具有相同属性或相似属性的抽象, 本案例实现的是布局的嵌套(vertical布局下内嵌center_adapt布局)" + }, + height: 150 + }, { + el: { + type: "bi.button", + text: "1" + } + }] + }, { + type: "bi.button", + text: "populate", + handler: function () { + ref.populate([{ + el: { + type: "bi.label", + text: "1" + }, + height: 50 + }, { + el: { + type: "bi.button", + text: "2" + }, + height: 50 + }, { + el: { + type: "bi.label", + text: "3" + } + }]); + } + }] }; } From dd275132fb063dd7eba136ccacd30926bc41aa81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Wed, 14 Dec 2022 12:18:40 +0800 Subject: [PATCH 004/300] =?UTF-8?q?feat:=20=E5=88=A0=E9=99=A4todo=E6=8F=90?= =?UTF-8?q?=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/single/a/a.js | 1 - 1 file changed, 1 deletion(-) diff --git a/src/base/single/a/a.js b/src/base/single/a/a.js index a11e0f91b..2acbb2e2c 100644 --- a/src/base/single/a/a.js +++ b/src/base/single/a/a.js @@ -13,7 +13,6 @@ export class A extends BI.Text { constructor() { super(); } - // TODO:这里如何修改有问题 _defaultConfig() { var conf = super._defaultConfig(arguments); return BI.extend(conf, { From 19a5fe5298d95758b3c72913febe42aa78ac51a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Wed, 14 Dec 2022 14:18:01 +0800 Subject: [PATCH 005/300] =?UTF-8?q?feat:=20=E5=88=A0=E9=99=A4=E6=97=A0?= =?UTF-8?q?=E7=94=A8=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/single/a/a.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/base/single/a/a.js b/src/base/single/a/a.js index 2acbb2e2c..9b419c67b 100644 --- a/src/base/single/a/a.js +++ b/src/base/single/a/a.js @@ -10,9 +10,7 @@ import { shortcut } from "../../../core/decorator"; @shortcut() export class A extends BI.Text { static xtype = "bi.a"; - constructor() { - super(); - } + _defaultConfig() { var conf = super._defaultConfig(arguments); return BI.extend(conf, { From 1222710076641a879d1ec7eb3616c628884909a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Wed, 14 Dec 2022 16:07:57 +0800 Subject: [PATCH 006/300] =?UTF-8?q?KERNEL-13846=20refactor:=20=E4=BC=98?= =?UTF-8?q?=E5=8C=96=E4=BB=A3=E7=A0=81=EF=BC=8C=E9=87=87=E7=94=A8=E8=A7=A3?= =?UTF-8?q?=E6=9E=84=E6=96=B9=E5=BC=8F=E5=BC=95=E5=85=A5=E5=8F=98=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/single/a/a.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/base/single/a/a.js b/src/base/single/a/a.js index 9b419c67b..313e050ba 100644 --- a/src/base/single/a/a.js +++ b/src/base/single/a/a.js @@ -12,7 +12,7 @@ export class A extends BI.Text { static xtype = "bi.a"; _defaultConfig() { - var conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-a display-block", href: "", @@ -23,11 +23,11 @@ export class A extends BI.Text { } render() { - var o = this.options; + const { href, target, el} = this.options; super.render(); - this.element.attr({ href: o.href, target: o.target }); - if (o.el) { - BI.createWidget(o.el, { + this.element.attr({ href, target }); + if (el) { + BI.createWidget(el, { element: this, }); } From b00440694d700725609b04c77d14cb6da254a077 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Fri, 16 Dec 2022 10:03:18 +0800 Subject: [PATCH 007/300] =?UTF-8?q?KERNEL-13883=20refactor:base/single/tip?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=A4=B9es6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/single/tip/0.tip.js | 27 ++-- src/base/single/tip/tip.toast.js | 216 +++++++++++++++-------------- src/base/single/tip/tip.tooltip.js | 121 ++++++++-------- 3 files changed, 189 insertions(+), 175 deletions(-) diff --git a/src/base/single/tip/0.tip.js b/src/base/single/tip/0.tip.js index a13240d8b..21cd96deb 100644 --- a/src/base/single/tip/0.tip.js +++ b/src/base/single/tip/0.tip.js @@ -6,18 +6,19 @@ * @extends BI.Single * @abstract */ -BI.Tip = BI.inherit(BI.Single, { - _defaultConfig: function () { - var conf = BI.Tip.superclass._defaultConfig.apply(this, arguments); +export class Tip extends BI.Single { + _defaultConfig() { + const conf = super._defaultConfig(arguments); + return BI.extend(conf, { + _baseCls: (conf._baseCls || "") + " bi-tip", + zIndex: BI.zIndex_tip, + }); + } - return BI.extend(conf, { - _baseCls: (conf._baseCls || "") + " bi-tip", - zIndex: BI.zIndex_tip, - }); - }, + _init() { + super._init(); + this.element.css({ zIndex: this.options.zIndex }); + } +} - _init: function () { - BI.Tip.superclass._init.apply(this, arguments); - this.element.css({ zIndex: this.options.zIndex }); - }, -}); +BI.extend(BI, { Tip }); diff --git a/src/base/single/tip/tip.toast.js b/src/base/single/tip/tip.toast.js index e347ae062..124cf6af0 100644 --- a/src/base/single/tip/tip.toast.js +++ b/src/base/single/tip/tip.toast.js @@ -5,115 +5,123 @@ * @class BI.Toast * @extends BI.Tip */ -BI.Toast = BI.inherit(BI.Tip, { - _const: { - closableMinWidth: 146, - minWidth: 100, - closableMaxWidth: 410, - maxWidth: 400, - }, - _defaultConfig: function () { - return BI.extend(BI.Toast.superclass._defaultConfig.apply(this, arguments), { - extraCls: "bi-toast", - text: "", - level: "success", // success或warning - autoClose: true, - closable: null, - textHeight: 20, - vgap: 10, - innerHgap: 4, - hgap: 8, - }); - }, +import { shortcut } from "../../../core/decorator"; +@shortcut() +export class Toast extends BI.Tip { + _const= { + closableMinWidth: 146, + minWidth: 100, + closableMaxWidth: 410, + maxWidth: 400, + } - render: function () { - var self = this, o = this.options, c = this._const; - this.element.css({ - minWidth: BI.pixFormat(o.closable ? c.closableMinWidth : c.minWidth), - maxWidth: BI.pixFormat(o.closable ? c.closableMaxWidth : c.maxWidth), - }); - this.element.addClass("toast-" + o.level); - function fn(e) { - e.stopPropagation(); - e.stopEvent(); - - return false; - } - this.element.bind({ - click: fn, - mousedown: fn, - mouseup: fn, - mouseover: fn, - mouseenter: fn, - mouseleave: fn, - mousemove: fn, - }); - var cls; - switch (o.level) { - case "success": - cls = "toast-success-font"; - break; - case "error": - cls = "toast-error-font"; - break; - case "warning": - cls = "toast-warning-font"; - break; - case "loading": - cls = "toast-loading-font anim-rotate"; - break; - case "normal": - default: - cls = "toast-message-font"; - break; - } + static EVENT_DESTORY = "EVENT_DESTORY"; + static xtype = "bi.toast"; + + _defaultConfig() { + return BI.extend(super._defaultConfig(arguments), { + extraCls: "bi-toast", + text: "", + level: "success", // success或warning + autoClose: true, + closable: null, + textHeight: 20, + vgap: 10, + innerHgap: 4, + hgap: 8, + }); + } - function hasCloseIcon() { - return o.closable === true || (o.closable === null && o.autoClose === false); - } - var items = [{ - type: "bi.icon_label", - cls: cls + " toast-icon", - height: o.textHeight, - }, { - el: BI.isPlainObject(o.text) ? o.text : { - type: "bi.label", - whiteSpace: "normal", - text: o.text, - textHeight: o.textHeight, - textAlign: "left", + render() { + const { closable, level, autoClose, textHeight, text, hgap, vgap, innerHgap } = this.options; + const { closableMinWidth, minWidth, maxWidth, closableMaxWidth } = this._const; + this.element.css({ + minWidth: BI.pixFormat(closable ? closableMinWidth : minWidth), + maxWidth: BI.pixFormat(closable ? closableMaxWidth : maxWidth), + }); + this.element.addClass("toast-" + level); + function fn(e) { + e.stopPropagation(); + e.stopEvent(); + + return false; + } + this.element.bind({ + click: fn, + mousedown: fn, + mouseup: fn, + mouseover: fn, + mouseenter: fn, + mouseleave: fn, + mousemove: fn, + }); + let cls; + switch (level) { + case "success": + cls = "toast-success-font"; + break; + case "error": + cls = "toast-error-font"; + break; + case "warning": + cls = "toast-warning-font"; + break; + case "loading": + cls = "toast-loading-font anim-rotate"; + break; + case "normal": + default: + cls = "toast-message-font"; + break; + } + + function hasCloseIcon() { + return closable === true || (closable === null && autoClose === false); + } + const items = [{ + type: "bi.icon_label", + cls: cls + " toast-icon", + height: textHeight, + }, { + el: BI.isPlainObject(text) ? text : { + type: "bi.label", + whiteSpace: "normal", + text: text, + textHeight: textHeight, + textAlign: "left", + }, + }]; + + const columnSize = ["", "fill"]; + + if (hasCloseIcon()) { + items.push({ + type: "bi.icon_button", + cls: "close-font toast-icon", + handler: ()=> { + this.destroy(); }, - }]; + height: textHeight, + }); + columnSize.push(""); + } - var columnSize = ["", "fill"]; + return { + type: "bi.horizontal", + horizontalAlign: BI.HorizontalAlign.Stretch, + items: items, + hgap: hgap, + vgap: vgap, + innerHgap: innerHgap, + columnSize: columnSize, + }; + } - if (hasCloseIcon()) { - items.push({ - type: "bi.icon_button", - cls: "close-font toast-icon", - handler: function () { - self.destroy(); - }, - height: o.textHeight, - }); - columnSize.push(""); - } + beforeDestroy() { + this.fireEvent(Toast.EVENT_DESTORY); + } - return { - type: "bi.horizontal", - horizontalAlign: BI.HorizontalAlign.Stretch, - items: items, - hgap: o.hgap, - vgap: o.vgap, - innerHgap: o.innerHgap, - columnSize: columnSize, - }; - }, +} - beforeDestroy: function () { - this.fireEvent(BI.Toast.EVENT_DESTORY); - }, -}); -BI.Toast.EVENT_DESTORY = "EVENT_DESTORY"; -BI.shortcut("bi.toast", BI.Toast); +BI.extend(BI, { Toast }); diff --git a/src/base/single/tip/tip.tooltip.js b/src/base/single/tip/tip.tooltip.js index aae6d8e86..3d4f77382 100644 --- a/src/base/single/tip/tip.tooltip.js +++ b/src/base/single/tip/tip.tooltip.js @@ -5,85 +5,90 @@ * @class BI.Tooltip * @extends BI.Tip */ -BI.Tooltip = BI.inherit(BI.Tip, { - _const: { + +import { shortcut } from "../../../core/decorator"; +@shortcut() +export class Tooltip extends BI.Tip { + _const = { hgap: 8, vgap: 4, - }, + } + static xtype = "bi.tooltip"; + + _defaultConfig() { + return BI.extend(super._defaultConfig(arguments), { + extraCls: "bi-tooltip", + text: "", + level: "success", // success或warning + stopEvent: false, + stopPropagation: false, + textAlign: "left", + }); + } - _defaultConfig: function () { - return BI.extend(BI.Tooltip.superclass._defaultConfig.apply(this, arguments), { - extraCls: "bi-tooltip", - text: "", - level: "success", // success或warning - stopEvent: false, - stopPropagation: false, - textAlign: "left", - }); - }, + render () { + const { level, stopPropagation, stopEvent, text, textAlign } = this.options; + this.element.addClass("tooltip-" + level); + function fn(e) { + stopPropagation && e.stopPropagation(); + stopEvent && e.stopEvent(); + } + this.element.bind({ + click: fn, + mousedown: fn, + mouseup: fn, + mouseover: fn, + mouseenter: fn, + mouseleave: fn, + mousemove: fn, + }); - render: function () { - var o = this.options; - this.element.addClass("tooltip-" + o.level); - function fn(e) { - o.stopPropagation && e.stopPropagation(); - o.stopEvent && e.stopEvent(); - } - this.element.bind({ - click: fn, - mousedown: fn, - mouseup: fn, - mouseover: fn, - mouseenter: fn, - mouseleave: fn, - mousemove: fn, + const texts = (text + "").split("\n"); + if (texts.length > 1) { + BI.createWidget({ + type: "bi.vertical", + element: this, + hgap: this._const.hgap, + innerVgap: this._const.vgap, + items: BI.map(texts, function (i, text) { + return { + type: "bi.label", + textAlign: textAlign, + whiteSpace: "normal", + text: text, + textHeight: 18, + title: null, + }; + }), }); - - var texts = (o.text + "").split("\n"); - if (texts.length > 1) { - BI.createWidget({ - type: "bi.vertical", - element: this, - hgap: this._const.hgap, - innerVgap: this._const.vgap, - items: BI.map(texts, function (i, text) { - return { - type: "bi.label", - textAlign: o.textAlign, - whiteSpace: "normal", - text: text, - textHeight: 18, - title: null, - }; - }), - }); } else { this.text = BI.createWidget({ type: "bi.label", element: this, - textAlign: o.textAlign, + textAlign: textAlign, whiteSpace: "normal", - text: o.text, + text: text, title: null, textHeight: 18, hgap: this._const.hgap, vgap: this._const.vgap, }); } - }, + } - setWidth: function (width) { + setWidth(width) { this.element.width(BI.pixFormat(width - 2 * this._const.hgap)); - }, + } - setText: function (text) { + setText(text) { this.text && this.text.setText(text); - }, + } - setLevel: function (level) { + setLevel(level) { this.element.removeClass("tooltip-success").removeClass("tooltip-warning"); this.element.addClass("tooltip-" + level); - }, -}); + } + +} -BI.shortcut("bi.tooltip", BI.Tooltip); +BI.extend(BI, { Tooltip }); From b561bf5d852d5119208d4154d3128ba08b83b740 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Tue, 20 Dec 2022 14:14:14 +0800 Subject: [PATCH 008/300] =?UTF-8?q?KERNEL-13891=20refactor:base/layer?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=A4=B9es6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/layer/layer.drawer.js | 391 ++++++++------- src/base/layer/layer.popover.js | 484 +++++++++---------- src/base/layer/layer.popup.js | 798 ++++++++++++++++--------------- src/base/layer/layer.searcher.js | 210 ++++---- 4 files changed, 949 insertions(+), 934 deletions(-) diff --git a/src/base/layer/layer.drawer.js b/src/base/layer/layer.drawer.js index 23ef8b8c5..1c2e26a24 100644 --- a/src/base/layer/layer.drawer.js +++ b/src/base/layer/layer.drawer.js @@ -3,238 +3,235 @@ * @class BI.Popover * @extends BI.Widget */ -BI.Drawer = BI.inherit(BI.Widget, { - SIZE: { - SMALL: "small", - NORMAL: "normal", - BIG: "big", - }, - props: { - baseCls: "bi-drawer bi-card", - size: "normal", - placement: "right", // top/bottom/left/right - header: null, - headerHeight: 40, - body: null, - closable: true, // BI-40839 是否显示右上角的关闭按钮 - bodyHgap: 20, - bodyTgap: 10, - bodyBgap: 10, - }, - render: function () { - var self = this; - var o = this.options; - var items = [{ - el: { - type: "bi.htape", - cls: "bi-message-title bi-header-background", +import { shortcut } from "../../core/decorator"; +@shortcut() +export class Drawer extends BI.Widget { + SIZE = { + SMALL: "small", + NORMAL: "normal", + BIG: "big", + } + props = { + baseCls: "bi-drawer bi-card", + size: "normal", + placement: "right", // top/bottom/left/right + header: null, + headerHeight: 40, + body: null, + closable: true, // BI-40839 是否显示右上角的关闭按钮 + bodyHgap: 20, + bodyTgap: 10, + bodyBgap: 10, + } + static xtype = "bi.drawer"; + static EVENT_CLOSE = "EVENT_CLOSE"; + static EVENT_OPEN = "EVENT_OPEN"; + _getSuitableSize() { + const { size, height, placement, width } = this.options; + let sizeValue = 0; + switch (size) { + case "big": + sizeValue = 736; + break; + case "small": + sizeValue = 200; + break; + case "normal": + default: + sizeValue = 378; + break; + } + if (placement === "top" || placement === "bottom") { + return { + height: height || sizeValue, + }; + } + if (placement === "left" || placement === "right") { + return { + width: width || sizeValue, + }; + } + } + render() { + const { header, headerHeight, closable, body, bodyHgap, bodyTgap, bodyBgap } = this.options; + const items = [{ + el: { + type: "bi.htape", + cls: "bi-message-title bi-header-background", + items: [{ + type: "bi.absolute", items: [{ - type: "bi.absolute", - items: [{ - el: BI.isPlainObject(o.header) ? BI.extend({}, o.header, { - extraCls: "bi-font-bold", - }) : { - type: "bi.label", - cls: "bi-font-bold", - height: o.headerHeight, - text: o.header, - title: o.header, - textAlign: "left", - }, - left: 20, - top: 0, - right: 0, - bottom: 0, - }], - }, { - el: o.closable ? { - type: "bi.icon_button", - cls: "bi-message-close close-font", - height: o.headerHeight, - handler: function () { - self.close(); - }, - } : { - type: "bi.layout", + el: BI.isPlainObject(header) ? BI.extend({}, header, { + extraCls: "bi-font-bold", + }) : { + type: "bi.label", + cls: "bi-font-bold", + height: headerHeight, + text: header, + title: header, + textAlign: "left", }, - width: 56, + left: 20, + top: 0, + right: 0, + bottom: 0, }], - height: o.headerHeight, - }, - height: o.headerHeight, - }, { - el: { - type: "bi.vertical", - scrolly: true, - cls: "drawer-body", - ref: function () { - self.body = this; + }, { + el: closable ? { + type: "bi.icon_button", + cls: "bi-message-close close-font", + height: headerHeight, + handler: ()=> { + this.close(); + }, + } : { + type: "bi.layout", }, - items: [{ - el: o.body, - }], + width: 56, + }], + height: headerHeight, + }, + height: headerHeight, + }, { + el: { + type: "bi.vertical", + scrolly: true, + cls: "drawer-body", + ref: (_ref)=> { + this.body = _ref; }, - hgap: o.bodyHgap, - tgap: o.bodyTgap, - bgap: o.bodyBgap, - }]; + items: [{ + el: body, + }], + }, + hgap: bodyHgap, + tgap: bodyTgap, + bgap: bodyBgap, + }]; - return BI.extend({ - type: "bi.vtape", - items: items, - }, this._getSuitableSize()); - }, + return BI.extend({ + type: "bi.vtape", + items: items, + }, this._getSuitableSize()); + } + mounted() { + const { placement } = this.options; + switch (placement) { + case "right": + this.element.css({ + top: 0, + left: "100%", + bottom: 0, + }); + break; + case "left": + this.element.css({ + top: 0, + right: "100%", + bottom: 0, + }); + break; + case "top": + this.element.css({ + left: 0, + right: 0, + bottom: "100%", + }); + break; + case "bottom": + this.element.css({ + left: 0, + right: 0, + top: "100%", + }); + break; + default: + break; + } + } - _getSuitableSize: function () { - var o = this.options; - var size = 0; - switch (o.size) { - case "big": - size = 736; + show(callback) { + const { placement } = this.options; + requestAnimationFrame(()=> { + const size = this._getSuitableSize(); + switch (placement) { + case "right": + this.element.css({ + left: "calc(100% - " + size.width + "px)", + }); + break; + case "left": + this.element.css({ + right: "calc(100% - " + size.width + "px)", + }); + break; + case "top": + this.element.css({ + bottom: "calc(100% - " + size.height + "px)", + }); break; - case "small": - size = 200; + case "bottom": + this.element.css({ + top: "calc(100% - " + size.height + "px)", + }); break; - case "normal": default: - size = 378; break; } - if (o.placement === "top" || o.placement === "bottom") { - return { - height: o.height || size, - }; - } - if (o.placement === "left" || o.placement === "right") { - return { - width: o.width || size, - }; - } - }, + callback && callback(); + }); + } - mounted: function () { - var self = this, o = this.options; - switch (o.placement) { + hide(callback) { + const { placement } = this.options; + requestAnimationFrame(()=> { + switch (placement) { case "right": - self.element.css({ - top: 0, + this.element.css({ left: "100%", - bottom: 0, }); break; case "left": - self.element.css({ - top: 0, + this.element.css({ right: "100%", - bottom: 0, }); break; case "top": - self.element.css({ - left: 0, - right: 0, + this.element.css({ bottom: "100%", }); break; case "bottom": - self.element.css({ - left: 0, - right: 0, + this.element.css({ top: "100%", }); break; default: break; } - }, - - show: function (callback) { - var self = this, o = this.options; - requestAnimationFrame(function () { - var size = self._getSuitableSize(); - switch (o.placement) { - case "right": - self.element.css({ - left: "calc(100% - " + size.width + "px)", - }); - break; - case "left": - self.element.css({ - right: "calc(100% - " + size.width + "px)", - }); - break; - case "top": - self.element.css({ - bottom: "calc(100% - " + size.height + "px)", - }); - break; - case "bottom": - self.element.css({ - top: "calc(100% - " + size.height + "px)", - }); - break; - default: - break; - } - callback && callback(); - }); - }, - - hide: function (callback) { - var self = this, o = this.options; - requestAnimationFrame(function () { - switch (o.placement) { - case "right": - self.element.css({ - left: "100%", - }); - break; - case "left": - self.element.css({ - right: "100%", - }); - break; - case "top": - self.element.css({ - bottom: "100%", - }); - break; - case "bottom": - self.element.css({ - top: "100%", - }); - break; - default: - break; - } - setTimeout(callback, 300); - }); - }, - - open: function () { - var self = this; - this.show(function () { - self.fireEvent(BI.Drawer.EVENT_OPEN); - }); - }, + setTimeout(callback, 300); + }); + } - close: function () { - var self = this; - this.hide(function () { - self.fireEvent(BI.Drawer.EVENT_CLOSE); - }); - }, + open() { + this.show(()=> { + this.fireEvent(Drawer.EVENT_OPEN); + }); + } - setZindex: function (zindex) { - this.element.css({ "z-index": zindex }); - }, + close() { + this.hide(()=> { + this.fireEvent(Drawer.EVENT_CLOSE); + }); + } - destroyed: function () { - }, -}); + setZindex(zindex) { + this.element.css({ "z-index": zindex }); + } -BI.shortcut("bi.drawer", BI.Drawer); + destroyed() { + } -BI.Drawer.EVENT_CLOSE = "EVENT_CLOSE"; -BI.Drawer.EVENT_OPEN = "EVENT_OPEN"; +} +BI.extend(BI, { Drawer }); diff --git a/src/base/layer/layer.popover.js b/src/base/layer/layer.popover.js index 4244a1efb..802bd73bd 100644 --- a/src/base/layer/layer.popover.js +++ b/src/base/layer/layer.popover.js @@ -3,276 +3,280 @@ * @class BI.Popover * @extends BI.Widget */ -BI.Popover = BI.inherit(BI.Widget, { - _constant: { - SIZE: { - SMALL: "small", - NORMAL: "normal", - BIG: "big", - }, - MAX_HEIGHT: 600, - }, - props: function () { - return { - baseCls: "bi-popover bi-card bi-border-radius", - size: "normal", // small, normal, big - logic: { - dynamic: false, - }, - header: null, - headerHeight: 40, - body: null, - footer: null, - footerHeight: 44, - closable: true, // BI-40839 是否显示右上角的关闭按钮 - bodyHgap: BI.SIZE_CONSANTS.H_GAP_SIZE, - bodyTgap: BI.SIZE_CONSANTS.V_GAP_SIZE, - }; - }, +import { shortcut } from "../../core/decorator"; +@shortcut() +export class Popover extends BI.Widget { + _constant = { + SIZE: { + SMALL: "small", + NORMAL: "normal", + BIG: "big", + }, + MAX_HEIGHT: 600, + } - render: function () { - var self = this; - var o = this.options; - var c = this._constant; - this.startX = 0; - this.startY = 0; - var size = this._calculateSize(); - this.tracker = new BI.MouseMoveTracker(function (deltaX, deltaY) { - var W = BI.Widget._renderEngine.createElement("body").width(); - var H = BI.Widget._renderEngine.createElement("body").height(); - self.startX += deltaX; - self.startY += deltaY; - self.element.css({ - left: BI.clamp(self.startX, 0, W - self.element.width()) + "px", - top: BI.clamp(self.startY, 0, H - self.element.height()) + "px", - }); - // BI-12134 没有什么特别好的方法 - BI.Resizers._resize({ - target: self.element[0], - }); - }, function () { - self.tracker.releaseMouseMoves(); - }, _global); - var items = [{ - el: { - type: "bi.htape", - cls: "bi-message-title bi-header-background", - items: [{ - el: { - type: "bi.absolute", - ref: function (_ref) { - self.dragger = _ref; - }, - items: [{ - el: BI.isPlainObject(o.header) ? BI.extend({}, o.header, { - extraCls: "bi-font-bold", - }) : { - type: "bi.label", - cls: "bi-font-bold", - height: o.headerHeight, - text: o.header, - title: o.header, - textAlign: "left", - }, - top: 0, - bottom: 0, - left: BI.SIZE_CONSANTS.H_GAP_SIZE, - right: o.closable ? 0 : BI.SIZE_CONSANTS.H_GAP_SIZE, - }], + props() { + return { + baseCls: "bi-popover bi-card bi-border-radius", + size: "normal", // small, normal, big + logic: { + dynamic: false, + }, + header: null, + headerHeight: 40, + body: null, + footer: null, + footerHeight: 44, + closable: true, // BI-40839 是否显示右上角的关闭按钮 + bodyHgap: BI.SIZE_CONSANTS.H_GAP_SIZE, + bodyTgap: BI.SIZE_CONSANTS.V_GAP_SIZE, + }; + } + + static xtype = "bi.popover"; + static EVENT_CLOSE = "EVENT_CLOSE"; + static EVENT_OPEN = "EVENT_OPEN"; + static EVENT_CANCEL = "EVENT_CANCEL"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + + render() { + // var self = this; + const { header, headerHeight, closable, logic, footer, footerHeight, body, bodyTgap, bodyHgap } = this.options; + const c = this._constant; + this.startX = 0; + this.startY = 0; + const size = this._calculateSize(); + this.tracker = new BI.MouseMoveTracker(function (deltaX, deltaY) { + const W = BI.Widget._renderEngine.createElement("body").width(); + const H = BI.Widget._renderEngine.createElement("body").height(); + this.startX += deltaX; + this.startY += deltaY; + this.element.css({ + left: BI.clamp(this.startX, 0, W - this.element.width()) + "px", + top: BI.clamp(this.startY, 0, H - this.element.height()) + "px", + }); + // BI-12134 没有什么特别好的方法 + BI.Resizers._resize({ + target: this.element[0], + }); + }, ()=> { + this.tracker.releaseMouseMoves(); + }, _global); + const items = [{ + el: { + type: "bi.htape", + cls: "bi-message-title bi-header-background", + items: [{ + el: { + type: "bi.absolute", + ref: (_ref)=> { + this.dragger = _ref; }, - }, o.closable ? { - el: { - type: "bi.icon_button", - cls: "bi-message-close close-font", - height: o.headerHeight, - handler: function () { - self.close(); + items: [{ + el: BI.isPlainObject(header) ? BI.extend({}, header, { + extraCls: "bi-font-bold", + }) : { + type: "bi.label", + cls: "bi-font-bold", + height: headerHeight, + text: header, + title: header, + textAlign: "left", }, - }, - width: 56, - } : null], - height: o.headerHeight, - }, - height: o.headerHeight, - }, o.logic.dynamic ? { - el: { - type: "bi.vertical", - scrolly: true, - cls: "popover-body", - ref: function () { - self.body = this; + top: 0, + bottom: 0, + left: BI.SIZE_CONSANTS.H_GAP_SIZE, + right: closable ? 0 : BI.SIZE_CONSANTS.H_GAP_SIZE, + }], }, - css: { - "max-height": this._getSuitableBodyHeight(c.MAX_HEIGHT - o.headerHeight - (o.footer ? o.footerHeight : 0) - o.bodyTgap), - "min-height": this._getSuitableBodyHeight(size.height - o.headerHeight - (o.footer ? o.footerHeight : 0) - o.bodyTgap), + }, closable ? { + el: { + type: "bi.icon_button", + cls: "bi-message-close close-font", + height: headerHeight, + handler: ()=> { + this.close(); + }, }, - items: [{ - el: o.body, - }], - hgap: o.bodyHgap, - tgap: o.bodyTgap, + width: 56, + } : null], + height: headerHeight, + }, + height: headerHeight, + }, logic.dynamic ? { + el: { + type: "bi.vertical", + scrolly: true, + cls: "popover-body", + ref: (_ref)=> { + this.body = _ref; + }, + css: { + "max-height": this._getSuitableBodyHeight(c.MAX_HEIGHT - headerHeight - (footer ? footerHeight : 0) - bodyTgap), + "min-height": this._getSuitableBodyHeight(size.height - headerHeight - (footer ? footerHeight : 0) - bodyTgap), }, - } : { + items: [{ + el: body, + }], + hgap: bodyHgap, + tgap: bodyTgap, + }, + } : { + el: { + type: "bi.absolute", + items: [{ + el: body, + left: bodyHgap, + top: bodyTgap, + right: bodyHgap, + bottom: 0, + }], + }, + }]; + if (footer) { + items.push({ el: { type: "bi.absolute", items: [{ - el: o.body, - left: o.bodyHgap, - top: o.bodyTgap, - right: o.bodyHgap, + el: footer, + left: BI.SIZE_CONSANTS.H_GAP_SIZE, + top: 0, + right: BI.SIZE_CONSANTS.H_GAP_SIZE, bottom: 0, }], + height: footerHeight, }, - }]; - if (o.footer) { - items.push({ - el: { - type: "bi.absolute", - items: [{ - el: o.footer, - left: BI.SIZE_CONSANTS.H_GAP_SIZE, - top: 0, - right: BI.SIZE_CONSANTS.H_GAP_SIZE, - bottom: 0, - }], - height: o.footerHeight, - }, - height: o.footerHeight, - }); - } - - return BI.extend({ - items: items, - width: this._getSuitableWidth(size.width), - }, o.logic.dynamic ? { - type: "bi.vertical", - scrolly: false, - } : { - type: "bi.vtape", - height: this._getSuitableHeight(size.height), + height: footerHeight, }); - }, + } - // mounted之后绑定事件 - mounted: function () { - var self = this; - this.dragger.element.mousedown(function (e) { - if (self.options.draggable !== false) { - self.startX = self.element[0].offsetLeft; - self.startY = self.element[0].offsetTop; - self.tracker.captureMouseMoves(e); - } - }); - }, + return BI.extend({ + items: items, + width: this._getSuitableWidth(size.width), + }, logic.dynamic ? { + type: "bi.vertical", + scrolly: false, + } : { + type: "bi.vtape", + height: this._getSuitableHeight(size.height), + }); + } + // mounted之后绑定事件 + mounted() { + this.dragger.element.mousedown(function (e) { + if (this.options.draggable !== false) { + this.startX = this.element[0].offsetLeft; + this.startY = this.element[0].offsetTop; + this.tracker.captureMouseMoves(e); + } + }); + } - _getSuitableBodyHeight: function (height) { - var o = this.options; + _getSuitableBodyHeight(height) { + const { headerHeight, footer, footerHeight, bodyTgap } = this.options; - return BI.clamp(height, 0, BI.Widget._renderEngine.createElement("body")[0].clientHeight - o.headerHeight - (o.footer ? o.footerHeight : 0) - o.bodyTgap); - }, + return BI.clamp(height, 0, BI.Widget._renderEngine.createElement("body")[0].clientHeight - headerHeight - (footer ? footerHeight : 0) - bodyTgap); + } - _getSuitableHeight: function (height) { - return BI.clamp(height, 0, BI.Widget._renderEngine.createElement("body")[0].clientHeight); - }, + _getSuitableHeight(height) { + return BI.clamp(height, 0, BI.Widget._renderEngine.createElement("body")[0].clientHeight); + } - _getSuitableWidth: function (width) { - return BI.clamp(width, 0, BI.Widget._renderEngine.createElement("body").width()); - }, + _getSuitableWidth(width) { + return BI.clamp(width, 0, BI.Widget._renderEngine.createElement("body").width()); + } - _calculateSize: function () { - var o = this.options; - var size = {}; - if (BI.isNotNull(o.size)) { - switch (o.size) { - case this._constant.SIZE.SMALL: - size.width = 450; - size.height = 200; - size.type = "small"; - break; - case this._constant.SIZE.BIG: - size.width = 900; - size.height = 500; - size.type = "big"; - break; - default: - size.width = 550; - size.height = 500; - size.type = "default"; - } + _calculateSize() { + const { size, width, height } = this.options; + const sizeValue = {}; + if (BI.isNotNull(size)) { + switch (size) { + case this._constant.SIZE.SMALL: + sizeValue.width = 450; + sizeValue.height = 200; + sizeValue.type = "small"; + break; + case this._constant.SIZE.BIG: + sizeValue.width = 900; + sizeValue.height = 500; + sizeValue.type = "big"; + break; + default: + sizeValue.width = 550; + sizeValue.height = 500; + sizeValue.type = "default"; } + } - return { - width: o.width || size.width, - height: o.height || size.height, - type: size.type || "default", - }; - }, + return { + width: width || sizeValue.width, + height: height || sizeValue.height, + type: sizeValue.type || "default", + }; + } + setDraggable(b) { + this.options.draggable = b; + } - setDraggable: function (b) { - this.options.draggable = b; - }, + hide() { - hide: function () { + } - }, + open() { + this.show(); + this.fireEvent(Popover.EVENT_OPEN, arguments); + } - open: function () { - this.show(); - this.fireEvent(BI.Popover.EVENT_OPEN, arguments); - }, + close() { + this.hide(); + this.fireEvent(Popover.EVENT_CLOSE, arguments); + } - close: function () { - this.hide(); - this.fireEvent(BI.Popover.EVENT_CLOSE, arguments); - }, + setZindex(zindex) { + this.element.css({ "z-index": zindex }); + } +} - setZindex: function (zindex) { - this.element.css({ "z-index": zindex }); - }, -}); +BI.extend(BI, { Popover }); -BI.shortcut("bi.popover", BI.Popover); +@shortcut() +export class BarPopover extends BI.Popover { + static xtype = "bi.bar_popover"; -BI.BarPopover = BI.inherit(BI.Popover, { - _defaultConfig: function () { - return BI.extend(BI.BarPopover.superclass._defaultConfig.apply(this, arguments), { - btns: [BI.i18nText("BI-Basic_OK"), BI.i18nText("BI-Basic_Cancel")], - }); - }, + _defaultConfig() { + return BI.extend(super._defaultConfig(arguments), { + btns: [BI.i18nText("BI-Basic_OK"), BI.i18nText("BI-Basic_Cancel")], + }); + } - beforeCreate: function () { - var self = this; - var o = this.options; - o.footer || (o.footer = { - type: "bi.right_vertical_adapt", - lgap: 10, - items: [{ - type: "bi.button", - text: this.options.btns[1], - value: 1, - level: "ignore", - handler: function (v) { - self.fireEvent(BI.Popover.EVENT_CANCEL, v); - self.close(v); - }, - }, { - type: "bi.button", - text: this.options.btns[0], - warningTitle: o.warningTitle, - value: 0, - handler: function (v) { - self.fireEvent(BI.Popover.EVENT_CONFIRM, v); - self.close(v); - }, - }], - }); - }, -}); + beforeCreate() { + const { footer, warningTitle } = this.options; + footer || (this.options.footer = { + type: "bi.right_vertical_adapt", + lgap: 10, + items: [{ + type: "bi.button", + text: this.options.btns[1], + value: 1, + level: "ignore", + handler: (v)=> { + this.fireEvent(Popover.EVENT_CANCEL, v); + this.close(v); + }, + }, { + type: "bi.button", + text: this.options.btns[0], + warningTitle: warningTitle, + value: 0, + handler: (v)=> { + this.fireEvent(Popover.EVENT_CONFIRM, v); + this.close(v); + }, + }], + }); + } +} -BI.shortcut("bi.bar_popover", BI.BarPopover); +BI.extend(BI, { BarPopover }); -BI.Popover.EVENT_CLOSE = "EVENT_CLOSE"; -BI.Popover.EVENT_OPEN = "EVENT_OPEN"; -BI.Popover.EVENT_CANCEL = "EVENT_CANCEL"; -BI.Popover.EVENT_CONFIRM = "EVENT_CONFIRM"; diff --git a/src/base/layer/layer.popup.js b/src/base/layer/layer.popup.js index dbeb7e8fe..43f8c4908 100644 --- a/src/base/layer/layer.popup.js +++ b/src/base/layer/layer.popup.js @@ -3,425 +3,435 @@ * @class BI.PopupView * @extends BI.Widget */ -BI.PopupView = BI.inherit(BI.Widget, { - _const: { - TRIANGLE_LENGTH: 12, - }, - _defaultConfig: function (props) { - return BI.extend(BI.PopupView.superclass._defaultConfig.apply(this, arguments), { - _baseCls: "bi-popup-view" + (props.primary ? " bi-primary" : ""), - // 品牌色 - primary: false, - maxWidth: "auto", - minWidth: 100, - // maxHeight: 200, - minHeight: 24, - lgap: 0, - rgap: 0, - tgap: 0, - bgap: 0, - vgap: 0, - hgap: 0, - innerVgap: 0, - innerHgap: 0, - showArrow: false, - direction: BI.Direction.Top, // 工具栏的方向 - stopEvent: false, // 是否停止mousedown、mouseup事件 - stopPropagation: false, // 是否停止mousedown、mouseup向上冒泡 - logic: { - dynamic: true, - }, - tool: false, // 自定义工具栏 - tabs: [], // 导航栏 - buttons: [], // toolbar栏 +import { shortcut } from "../../core/decorator"; +@shortcut() +export class PopupView extends BI.Widget { + _const = { + TRIANGLE_LENGTH: 12, + } - el: { - type: "bi.button_group", - items: [], - chooseType: 0, - behaviors: {}, - layouts: [{ - type: "bi.vertical", - }], - }, - }); - }, + static xtype = "bi.popup_view"; + static EVENT_CHANGE = "EVENT_CHANGE"; - render: function () { - var self = this, o = this.options; - function fn (e) { - e.stopPropagation(); - } - function stop (e) { - e.stopEvent(); + _defaultConfig(props) { + return BI.extend(super._defaultConfig(arguments), { + _baseCls: "bi-popup-view" + (props.primary ? " bi-primary" : ""), + // 品牌色 + primary: false, + maxWidth: "auto", + minWidth: 100, + // maxHeight: 200, + minHeight: 24, + lgap: 0, + rgap: 0, + tgap: 0, + bgap: 0, + vgap: 0, + hgap: 0, + innerVgap: 0, + innerHgap: 0, + showArrow: false, + direction: BI.Direction.Top, // 工具栏的方向 + stopEvent: false, // 是否停止mousedown、mouseup事件 + stopPropagation: false, // 是否停止mousedown、mouseup向上冒泡 + logic: { + dynamic: true, + }, - return false; - } - this.element.css({ - "z-index": BI.zIndex_popup, - "min-width": BI.pixFormat(o.minWidth), - "max-width": BI.pixFormat(o.maxWidth), - }).bind({ click: fn }); + tool: false, // 自定义工具栏 + tabs: [], // 导航栏 + buttons: [], // toolbar栏 - this.element.bind("mousewheel", fn); + el: { + type: "bi.button_group", + items: [], + chooseType: 0, + behaviors: {}, + layouts: [{ + type: "bi.vertical", + }], + }, + }); + } + render() { + const { minWidth, maxWidth, stopPropagation, stopEvent, + direction, logic, lgap, rgap, tgap, bgap, vgap, hgap, primary, showArrow } = this.options; + function fn (e) { + e.stopPropagation(); + } + function stop (e) { + e.stopEvent(); - o.stopPropagation && this.element.bind({ mousedown: fn, mouseup: fn, mouseover: fn }); - o.stopEvent && this.element.bind({ mousedown: stop, mouseup: stop, mouseover: stop }); - this.tool = this._createTool(); - this.tab = this._createTab(); - this.view = this._createView(); - this.toolbar = this._createToolBar(); + return false; + } + this.element.css({ + "z-index": BI.zIndex_popup, + "min-width": BI.pixFormat(minWidth), + "max-width": BI.pixFormat(maxWidth), + }).bind({ click: fn }); - this.view.on(BI.Controller.EVENT_CHANGE, function (type) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if (type === BI.Events.CLICK) { - self.fireEvent(BI.PopupView.EVENT_CHANGE); - } - }); + this.element.bind("mousewheel", fn); - BI.createWidget(BI.extend({ - element: this, - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend({}, o.logic, { - scrolly: false, - lgap: o.lgap, - rgap: o.rgap, - tgap: o.tgap, - bgap: o.bgap, - vgap: o.vgap, - hgap: o.hgap, - items: BI.LogicFactory.createLogicItemsByDirection(o.direction, BI.extend({ - cls: "list-view-outer bi-card list-view-shadow" + (o.primary ? " bi-primary" : ""), - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend({}, o.logic, { - items: BI.LogicFactory.createLogicItemsByDirection(o.direction, this.tool, this.tab, this.view, this.toolbar), - }))) - ), - })))); - if (o.showArrow) { - this.arrow = BI.createWidget({ - type: "bi.absolute", - cls: "bi-bubble-arrow", - items: [{ - type: "bi.layout", - cls: "bubble-arrow", - }], - }); - this.arrowWrapper = BI.createWidget({ - type: "bi.absolute", - cls: "bi-bubble-arrow-wrapper", - items: [{ - el: this.arrow, - }], - }); - // 因为三角符号的原因位置变大了,需要占位 - this.placeholder = BI.createWidget({ - type: "bi.layout", - }); - BI.createWidget({ - type: "bi.absolute", - element: this, - items: [{ - el: this.arrowWrapper, - left: 0, - top: 0, - }, { - el: this.placeholder, - }], - }); + stopPropagation && this.element.bind({ mousedown: fn, mouseup: fn, mouseover: fn }); + stopEvent && this.element.bind({ mousedown: stop, mouseup: stop, mouseover: stop }); + this.tool = this._createTool(); + this.tab = this._createTab(); + this.view = this._createView(); + this.toolbar = this._createToolBar(); + + const self = this; + // TODO:这里需要调整转化方式,仍然采用原来的self + this.view.on(BI.Controller.EVENT_CHANGE, function (type) { + // 箭头函数没有自己的arguments,只会获取外层的,若要获取自己的,需通过剩余参数写法,但这样得到的仍然不是类数组 + self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + if (type === BI.Events.CLICK) { + self.fireEvent(PopupView.EVENT_CHANGE); } - }, + }); - _createView: function () { - var o = this.options; - this.button_group = BI.createWidget(o.el, { type: "bi.button_group", value: o.value }); - this.button_group.element.css({ - "min-height": BI.pixFormat(o.minHeight), - "padding-top": BI.pixFormat(o.innerVgap), - "padding-bottom": BI.pixFormat(o.innerVgap), - "padding-left": BI.pixFormat(o.innerHgap), - "padding-right": BI.pixFormat(o.innerHgap), + BI.createWidget(BI.extend({ + element: this, + }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(direction), BI.extend({}, logic, { + scrolly: false, + lgap, + rgap, + tgap, + bgap, + vgap, + hgap, + items: BI.LogicFactory.createLogicItemsByDirection(direction, BI.extend({ + cls: "list-view-outer bi-card list-view-shadow" + (primary ? " bi-primary" : ""), + }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(direction), BI.extend({}, logic, { + items: BI.LogicFactory.createLogicItemsByDirection(direction, this.tool, this.tab, this.view, this.toolbar), + }))) + ), + })))); + if (showArrow) { + this.arrow = BI.createWidget({ + type: "bi.absolute", + cls: "bi-bubble-arrow", + items: [{ + type: "bi.layout", + cls: "bubble-arrow", + }], + }); + this.arrowWrapper = BI.createWidget({ + type: "bi.absolute", + cls: "bi-bubble-arrow-wrapper", + items: [{ + el: this.arrow, + }], + }); + // 因为三角符号的原因位置变大了,需要占位 + this.placeholder = BI.createWidget({ + type: "bi.layout", + }); + BI.createWidget({ + type: "bi.absolute", + element: this, + items: [{ + el: this.arrowWrapper, + left: 0, + top: 0, + }, { + el: this.placeholder, + }], }); + } + } + _createView() { + const { el, value, minHeight, innerVgap, innerHgap } = this.options; + this.button_group = BI.createWidget(el, { type: "bi.button_group", value: value }); + this.button_group.element.css({ + "min-height": BI.pixFormat(minHeight), + "padding-top": BI.pixFormat(innerVgap), + "padding-bottom": BI.pixFormat(innerVgap), + "padding-left": BI.pixFormat(innerHgap), + "padding-right": BI.pixFormat(innerHgap), + }); - return this.button_group; - }, + return this.button_group; + } - _createTool: function () { - var o = this.options; - if (false === o.tool) { - return; - } + _createTool() { + const { tool } = this.options; + if (false === tool) { + return; + } - return BI.createWidget(o.tool); - }, + return BI.createWidget(tool); + } - _createTab: function () { - var o = this.options; - if (o.tabs.length === 0) { - return; - } + _createTab() { + const { tabs, value } = this.options; + if (tabs.length === 0) { + return; + } - return BI.createWidget({ - type: "bi.center", - cls: "list-view-tab", - height: 25, - items: o.tabs, - value: o.value, - }); - }, + return BI.createWidget({ + type: "bi.center", + cls: "list-view-tab", + height: 25, + items: tabs, + value: value, + }); + } - _createToolBar: function () { - var o = this.options; - if (o.buttons.length === 0) { - return; - } + _createToolBar() { + const { buttons } = this.options; + if (buttons.length === 0) { + return; + } - return BI.createWidget({ - type: "bi.center", - cls: "list-view-toolbar bi-high-light bi-split-top", - height: 24, - items: BI.createItems(o.buttons, { - once: false, - shadow: true, - isShadowShowingOnSelected: true, - }), - }); - }, + return BI.createWidget({ + type: "bi.center", + cls: "list-view-toolbar bi-high-light bi-split-top", + height: 24, + items: BI.createItems(buttons, { + once: false, + shadow: true, + isShadowShowingOnSelected: true, + }), + }); + } - setDirection: function (direction, position) { - var o = this.options; - if (o.showArrow) { - var style = {}, wrapperStyle = {}, placeholderStyle = {}; - var adjustXOffset = position.adjustXOffset || 0; - var adjustYOffset = position.adjustYOffset || 0; - var bodyBounds = BI.Widget._renderEngine.createElement("body").bounds(); - var bodyWidth = bodyBounds.width; - var bodyHeight = bodyBounds.height; - var popupWidth = this.element.outerWidth(); - var popupHeight = this.element.outerHeight(); - var offset = position.offset; - var offsetStyle = position.offsetStyle; - var middle = offsetStyle === "center" || offsetStyle === "middle"; + setDirection(direction, position) { + const { showArrow, tgap, vgap, bgap, rgap, hgap, lgap } = this.options; + if (showArrow) { + let style = {}, wrapperStyle = {}, placeholderStyle = {}; + const adjustXOffset = position.adjustXOffset || 0; + const adjustYOffset = position.adjustYOffset || 0; + const bodyBounds = BI.Widget._renderEngine.createElement("body").bounds(); + const bodyWidth = bodyBounds.width; + const bodyHeight = bodyBounds.height; + const popupWidth = this.element.outerWidth(); + const popupHeight = this.element.outerHeight(); + const offset = position.offset; + const offsetStyle = position.offsetStyle; + const middle = offsetStyle === "center" || offsetStyle === "middle"; - var minLeft = Math.max(4, offset.left + 4 + popupWidth - bodyWidth); - var minRight = Math.max(4, popupWidth - (offset.left + 4)); - var minTop = Math.max(4, offset.top + 4 + popupHeight - bodyHeight); - var minBottom = Math.max(4, popupHeight - (offset.top + 4)); + const minLeft = Math.max(4, offset.left + 4 + popupWidth - bodyWidth); + const minRight = Math.max(4, popupWidth - (offset.left + 4)); + const minTop = Math.max(4, offset.top + 4 + popupHeight - bodyHeight); + const minBottom = Math.max(4, popupHeight - (offset.top + 4)); - var maxLeft = Math.min(popupWidth - 16 - 4, offset.left + position.width - 16 - 4); - var maxRight = Math.min(popupWidth - 16 - 4, bodyWidth - (offset.left + position.width - 16 - 4)); - var maxTop = Math.min(popupHeight - 16 - 4, offset.top + position.height - 16 - 4); - var maxBottom = Math.min(popupHeight - 16 - 4, bodyHeight - (offset.top + position.height - 16 - 4)); - switch (direction) { - case "bottom": - case "bottom,right": - direction = "bottom"; - style = { - // 5表示留出一定的空间 - left: BI.clamp(((middle ? popupWidth : position.width) - adjustXOffset) / 2 - 8, minLeft, maxLeft), - }; - wrapperStyle = { - top: o.tgap + o.vgap, - left: 0, - right: "", - bottom: "", - }; - placeholderStyle = { - left: 0, - right: 0, - height: this._const.TRIANGLE_LENGTH, - top: -this._const.TRIANGLE_LENGTH, - bottom: "", - }; - break; - case "bottom,left": - direction = "bottom"; - style = { - right: BI.clamp(((middle ? popupWidth : position.width) + adjustXOffset) / 2 - 8, minRight, maxRight), - }; - wrapperStyle = { - top: o.bgap + o.vgap, - left: "", - right: 0, - bottom: "", - }; - placeholderStyle = { - left: 0, - right: 0, - height: this._const.TRIANGLE_LENGTH, - top: -this._const.TRIANGLE_LENGTH, - bottom: "", - }; - break; - case "top": - case "top,right": - direction = "top"; - style = { - left: BI.clamp(((middle ? popupWidth : position.width) - adjustXOffset) / 2 - 8, minLeft, maxLeft), - }; - wrapperStyle = { - bottom: o.bgap + o.vgap, - left: 0, - right: "", - top: "", - }; - placeholderStyle = { - left: 0, - right: 0, - height: this._const.TRIANGLE_LENGTH, - top: "", - bottom: -this._const.TRIANGLE_LENGTH, - }; - break; - case "top,left": - direction = "top"; - style = { - right: BI.clamp(((middle ? popupWidth : position.width) + adjustXOffset) / 2 - 8, minRight, maxRight), - }; - wrapperStyle = { - bottom: o.bgap + o.vgap, - right: 0, - left: "", - top: "", - }; - placeholderStyle = { - left: 0, - right: 0, - height: this._const.TRIANGLE_LENGTH, - top: "", - bottom: -this._const.TRIANGLE_LENGTH, - }; - break; - case "left": - case "left,bottom": - direction = "left"; - style = { - top: BI.clamp(((middle ? popupHeight : position.height) - adjustYOffset) / 2 - 8, minTop, maxTop), - }; - wrapperStyle = { - right: o.rgap + o.hgap, - top: 0, - bottom: "", - left: "", - }; - placeholderStyle = { - top: 0, - bottom: 0, - width: this._const.TRIANGLE_LENGTH, - right: -this._const.TRIANGLE_LENGTH, - left: "", - }; - break; - case "left,top": - direction = "left"; - style = { - bottom: BI.clamp(((middle ? popupHeight : position.height) + adjustYOffset) / 2 - 8, minBottom, maxBottom), - }; - wrapperStyle = { - right: o.rgap + o.hgap, - bottom: 0, - top: "", - left: "", - }; - placeholderStyle = { - top: 0, - bottom: 0, - width: this._const.TRIANGLE_LENGTH, - right: -this._const.TRIANGLE_LENGTH, - left: "", - }; - break; - case "right": - case "right,bottom": - direction = "right"; - style = { - top: BI.clamp(((middle ? popupHeight : position.height) - adjustYOffset) / 2 - 8, minTop, maxTop), - }; - wrapperStyle = { - left: o.lgap + o.hgap, - top: 0, - bottom: "", - right: "", - }; - placeholderStyle = { - top: 0, - bottom: 0, - width: this._const.TRIANGLE_LENGTH, - left: -this._const.TRIANGLE_LENGTH, - right: "", - }; - break; - case "right,top": - direction = "right"; - style = { - bottom: BI.clamp(((middle ? popupHeight : position.height) + adjustYOffset) / 2 - 8, minBottom, maxBottom), - }; - wrapperStyle = { - left: o.lgap + o.hgap, - bottom: 0, - top: "", - right: "", - }; - placeholderStyle = { - top: 0, - bottom: 0, - width: this._const.TRIANGLE_LENGTH, - left: -this._const.TRIANGLE_LENGTH, - right: "", - }; - break; - case "right,innerRight": - break; - case "right,innerLeft": - break; - case "innerRight": - break; - case "innerLeft": - break; - default: - break; - } - this.element - .removeClass("left") - .removeClass("right") - .removeClass("top") - .removeClass("bottom") - .addClass(direction); - this.arrow.element.css(style); - this.arrowWrapper.element.css(wrapperStyle); - this.placeholder.element.css(placeholderStyle); + const maxLeft = Math.min(popupWidth - 16 - 4, offset.left + position.width - 16 - 4); + const maxRight = Math.min(popupWidth - 16 - 4, bodyWidth - (offset.left + position.width - 16 - 4)); + const maxTop = Math.min(popupHeight - 16 - 4, offset.top + position.height - 16 - 4); + const maxBottom = Math.min(popupHeight - 16 - 4, bodyHeight - (offset.top + position.height - 16 - 4)); + switch (direction) { + case "bottom": + case "bottom,right": + direction = "bottom"; + style = { + // 5表示留出一定的空间 + left: BI.clamp(((middle ? popupWidth : position.width) - adjustXOffset) / 2 - 8, minLeft, maxLeft), + }; + wrapperStyle = { + top: tgap + vgap, + left: 0, + right: "", + bottom: "", + }; + placeholderStyle = { + left: 0, + right: 0, + height: this._const.TRIANGLE_LENGTH, + top: -this._const.TRIANGLE_LENGTH, + bottom: "", + }; + break; + case "bottom,left": + direction = "bottom"; + style = { + right: BI.clamp(((middle ? popupWidth : position.width) + adjustXOffset) / 2 - 8, minRight, maxRight), + }; + wrapperStyle = { + top: bgap + vgap, + left: "", + right: 0, + bottom: "", + }; + placeholderStyle = { + left: 0, + right: 0, + height: this._const.TRIANGLE_LENGTH, + top: -this._const.TRIANGLE_LENGTH, + bottom: "", + }; + break; + case "top": + case "top,right": + direction = "top"; + style = { + left: BI.clamp(((middle ? popupWidth : position.width) - adjustXOffset) / 2 - 8, minLeft, maxLeft), + }; + wrapperStyle = { + bottom: bgap + vgap, + left: 0, + right: "", + top: "", + }; + placeholderStyle = { + left: 0, + right: 0, + height: this._const.TRIANGLE_LENGTH, + top: "", + bottom: -this._const.TRIANGLE_LENGTH, + }; + break; + case "top,left": + direction = "top"; + style = { + right: BI.clamp(((middle ? popupWidth : position.width) + adjustXOffset) / 2 - 8, minRight, maxRight), + }; + wrapperStyle = { + bottom: bgap + vgap, + right: 0, + left: "", + top: "", + }; + placeholderStyle = { + left: 0, + right: 0, + height: this._const.TRIANGLE_LENGTH, + top: "", + bottom: -this._const.TRIANGLE_LENGTH, + }; + break; + case "left": + case "left,bottom": + direction = "left"; + style = { + top: BI.clamp(((middle ? popupHeight : position.height) - adjustYOffset) / 2 - 8, minTop, maxTop), + }; + wrapperStyle = { + right: rgap + hgap, + top: 0, + bottom: "", + left: "", + }; + placeholderStyle = { + top: 0, + bottom: 0, + width: this._const.TRIANGLE_LENGTH, + right: -this._const.TRIANGLE_LENGTH, + left: "", + }; + break; + case "left,top": + direction = "left"; + style = { + bottom: BI.clamp(((middle ? popupHeight : position.height) + adjustYOffset) / 2 - 8, minBottom, maxBottom), + }; + wrapperStyle = { + right: rgap + hgap, + bottom: 0, + top: "", + left: "", + }; + placeholderStyle = { + top: 0, + bottom: 0, + width: this._const.TRIANGLE_LENGTH, + right: -this._const.TRIANGLE_LENGTH, + left: "", + }; + break; + case "right": + case "right,bottom": + direction = "right"; + style = { + top: BI.clamp(((middle ? popupHeight : position.height) - adjustYOffset) / 2 - 8, minTop, maxTop), + }; + wrapperStyle = { + left: lgap + hgap, + top: 0, + bottom: "", + right: "", + }; + placeholderStyle = { + top: 0, + bottom: 0, + width: this._const.TRIANGLE_LENGTH, + left: -this._const.TRIANGLE_LENGTH, + right: "", + }; + break; + case "right,top": + direction = "right"; + style = { + bottom: BI.clamp(((middle ? popupHeight : position.height) + adjustYOffset) / 2 - 8, minBottom, maxBottom), + }; + wrapperStyle = { + left: lgap + hgap, + bottom: 0, + top: "", + right: "", + }; + placeholderStyle = { + top: 0, + bottom: 0, + width: this._const.TRIANGLE_LENGTH, + left: -this._const.TRIANGLE_LENGTH, + right: "", + }; + break; + case "right,innerRight": + break; + case "right,innerLeft": + break; + case "innerRight": + break; + case "innerLeft": + break; + default: + break; } - }, + this.element + .removeClass("left") + .removeClass("right") + .removeClass("top") + .removeClass("bottom") + .addClass(direction); + this.arrow.element.css(style); + this.arrowWrapper.element.css(wrapperStyle); + this.placeholder.element.css(placeholderStyle); + } + } + + getView() { + return this.view; + } + + populate(items) { + this.view.populate.apply(this.view, arguments); + } - getView: function () { - return this.view; - }, + resetWidth(w) { + this.options.width = w; + this.element.width(w); + } - populate: function (items) { - this.view.populate.apply(this.view, arguments); - }, + resetHeight(h) { + const tbHeight = this.toolbar ? (this.toolbar.attr("height") || 24) : 0, + tabHeight = this.tab ? (this.tab.attr("height") || 24) : 0, + toolHeight = ((this.tool && this.tool.attr("height")) || 24) * ((this.tool && this.tool.isVisible()) ? 1 : 0); + const resetHeight = h - tbHeight - tabHeight - toolHeight - 2 * this.options.innerVgap; + this.view.resetHeight ? this.view.resetHeight(resetHeight) : + this.view.element.css({ "max-height": BI.pixFormat(resetHeight) }); + } - resetWidth: function (w) { - this.options.width = w; - this.element.width(w); - }, + setValue(selectedValues) { + this.tab && this.tab.setValue(selectedValues); + this.view.setValue(selectedValues); + } - resetHeight: function (h) { - var tbHeight = this.toolbar ? (this.toolbar.attr("height") || 24) : 0, - tabHeight = this.tab ? (this.tab.attr("height") || 24) : 0, - toolHeight = ((this.tool && this.tool.attr("height")) || 24) * ((this.tool && this.tool.isVisible()) ? 1 : 0); - var resetHeight = h - tbHeight - tabHeight - toolHeight - 2 * this.options.innerVgap; - this.view.resetHeight ? this.view.resetHeight(resetHeight) : - this.view.element.css({ "max-height": BI.pixFormat(resetHeight) }); - }, + getValue() { + return this.view.getValue(); + } - setValue: function (selectedValues) { - this.tab && this.tab.setValue(selectedValues); - this.view.setValue(selectedValues); - }, +} - getValue: function () { - return this.view.getValue(); - }, -}); -BI.PopupView.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.popup_view", BI.PopupView); +BI.extend(BI, { PopupView }); diff --git a/src/base/layer/layer.searcher.js b/src/base/layer/layer.searcher.js index b9d8d2b41..d80ffd90c 100644 --- a/src/base/layer/layer.searcher.js +++ b/src/base/layer/layer.searcher.js @@ -6,136 +6,140 @@ * @extends BI.Pane */ -BI.SearcherView = BI.inherit(BI.Pane, { - _defaultConfig: function () { - var conf = BI.SearcherView.superclass._defaultConfig.apply(this, arguments); - - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-searcher-view bi-card", - tipText: BI.i18nText("BI-No_Select"), - chooseType: BI.Selection.Single, - - matcher: { // 完全匹配的构造器 - type: "bi.button_group", - behaviors: { - redmark: function () { - return true; - }, - }, - items: [], - layouts: [{ - type: "bi.vertical", - }], - }, - searcher: { - type: "bi.button_group", - behaviors: { - redmark: function () { - return true; - }, - }, - items: [], - layouts: [{ - type: "bi.vertical", - }], - }, - }); - }, +import { shortcut } from "../../core/decorator"; +@shortcut() +export class SearcherView extends BI.Pane { - render: function () { - var self = this, o = this.options; + static xtype = "bi.searcher_view"; + static EVENT_CHANGE = "EVENT_CHANGE"; - this.matcher = BI.createWidget(o.matcher, { + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return BI.extend(conf, { + baseCls: (conf.baseCls || "") + " bi-searcher-view bi-card", + tipText: BI.i18nText("BI-No_Select"), + chooseType: BI.Selection.Single, + + matcher: { // 完全匹配的构造器 type: "bi.button_group", - chooseType: o.chooseType, behaviors: { - redmark: function () { + redmark: ()=> { return true; }, }, + items: [], layouts: [{ type: "bi.vertical", }], - value: o.value, - }); - this.matcher.on(BI.Controller.EVENT_CHANGE, function (type, val, ob) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if (type === BI.Events.CLICK) { - self.fireEvent(BI.SearcherView.EVENT_CHANGE, val, ob); - } - }); - this.spliter = BI.createWidget({ - type: "bi.vertical", - height: 1, - hgap: 10, - items: [{ - type: "bi.layout", - height: 1, - cls: "searcher-view-spliter bi-background", - }], - }); - this.searcher = BI.createWidget(o.searcher, { + }, + searcher: { type: "bi.button_group", - chooseType: o.chooseType, behaviors: { redmark: function () { return true; }, }, + items: [], layouts: [{ type: "bi.vertical", }], - value: o.value, - }); - this.searcher.on(BI.Controller.EVENT_CHANGE, function (type, val, ob) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if (type === BI.Events.CLICK) { - self.fireEvent(BI.SearcherView.EVENT_CHANGE, val, ob); - } - }); - - BI.createWidget({ + }, + }); + } + render() { + const { matcher, chooseType, value, searcher } = this.options; + + this.matcher = BI.createWidget(matcher, { + type: "bi.button_group", + chooseType, + behaviors: { + redmark: ()=> { + return true; + }, + }, + layouts: [{ type: "bi.vertical", - element: this, - items: [this.matcher, this.spliter, this.searcher], - }); - }, + }], + value, + }); + this.matcher.on(BI.Controller.EVENT_CHANGE, (type, val, ob)=> { + this.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + if (type === BI.Events.CLICK) { + this.fireEvent(SearcherView.EVENT_CHANGE, val, ob); + } + }); + this.spliter = BI.createWidget({ + type: "bi.vertical", + height: 1, + hgap: 10, + items: [{ + type: "bi.layout", + height: 1, + cls: "searcher-view-spliter bi-background", + }], + }); + this.searcher = BI.createWidget(searcher, { + type: "bi.button_group", + chooseType, + behaviors: { + redmark: ()=> { + return true; + }, + }, + layouts: [{ + type: "bi.vertical", + }], + value, + }); + this.searcher.on(BI.Controller.EVENT_CHANGE, (type, val, ob)=> { + this.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + if (type === BI.Events.CLICK) { + this.fireEvent(BI.SearcherView.EVENT_CHANGE, val, ob); + } + }); + + BI.createWidget({ + type: "bi.vertical", + element: this, + items: [this.matcher, this.spliter, this.searcher], + }); + } - startSearch: function () { + startSearch() { - }, + } - stopSearch: function () { + stopSearch() { - }, + } - setValue: function (v) { - this.matcher.setValue(v); - this.searcher.setValue(v); - }, + setValue(v) { + this.matcher.setValue(v); + this.searcher.setValue(v); + } - getValue: function () { - return this.matcher.getValue().concat(this.searcher.getValue()); - }, + getValue() { + return this.matcher.getValue().concat(this.searcher.getValue()); + } - populate: function (searchResult, matchResult, keyword) { - searchResult || (searchResult = []); - matchResult || (matchResult = []); - this.setTipVisible(searchResult.length + matchResult.length === 0); - this.spliter.setVisible(BI.isNotEmptyArray(matchResult) && BI.isNotEmptyArray(searchResult)); - this.matcher.populate(matchResult, keyword); - this.searcher.populate(searchResult, keyword); - }, + populate(searchResult, matchResult, keyword) { + searchResult || (searchResult = []); + matchResult || (matchResult = []); + this.setTipVisible(searchResult.length + matchResult.length === 0); + this.spliter.setVisible(BI.isNotEmptyArray(matchResult) && BI.isNotEmptyArray(searchResult)); + this.matcher.populate(matchResult, keyword); + this.searcher.populate(searchResult, keyword); + } - empty: function () { - this.searcher.empty(); - this.matcher.empty(); - }, + empty() { + this.searcher.empty(); + this.matcher.empty(); + } - hasMatched: function () { - return this.matcher.getAllButtons().length > 0; - }, -}); -BI.SearcherView.EVENT_CHANGE = "EVENT_CHANGE"; + hasMatched() { + return this.matcher.getAllButtons().length > 0; + } +} -BI.shortcut("bi.searcher_view", BI.SearcherView); +BI.extend(BI, { SearcherView }); From da4a0ffac033e597d745034071d4f0ef7eb63088 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Tue, 27 Dec 2022 00:58:48 +0800 Subject: [PATCH 009/300] =?UTF-8?q?KERNEL-13947=20refactor:=20ob=E5=92=8Cw?= =?UTF-8?q?idget=E7=9A=84es6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .eslintrc | 2 +- src/core/2.base.js | 2345 ++++++++++--------- src/core/3.ob.js | 397 ++-- src/core/4.widget.js | 1889 ++++++++------- src/core/action/action.js | 23 +- src/core/action/action.show.js | 13 +- src/core/behavior/0.behavior.js | 17 +- src/core/behavior/behavior.highlight.js | 12 +- src/core/behavior/behavior.redmark.js | 10 +- src/core/controller/0.controller.js | 8 +- src/core/controller/controller.broadcast.js | 36 +- src/core/controller/controller.bubbles.js | 50 +- src/core/controller/controller.drawer.js | 88 +- src/core/controller/controller.layer.js | 83 +- src/core/controller/controller.masker.js | 10 +- src/core/controller/controller.popover.js | 88 +- src/core/controller/controller.resizer.js | 43 +- src/core/controller/controller.tooltips.js | 75 +- 18 files changed, 2591 insertions(+), 2598 deletions(-) diff --git a/.eslintrc b/.eslintrc index 3fbfc3524..eee30f2c7 100644 --- a/.eslintrc +++ b/.eslintrc @@ -27,7 +27,7 @@ "plugins": ["@typescript-eslint/eslint-plugin"], "overrides": [{ "files": ["src/*.js","src/**/*.js", "demo/*.js", "demo/**/*.js", "i18n/**/*.js", "i18n/*.js", "test/**/*.js", "test/*.js", "examples/*.js", "examples/**/*.js"], - "extends": "plugin:@fui/es5", + "extends": "plugin:@fui/es6", "rules": { "no-param-reassign": "off", "quotes": [2, "double"], diff --git a/src/core/2.base.js b/src/core/2.base.js index 63ff1821d..0f0914be3 100644 --- a/src/core/2.base.js +++ b/src/core/2.base.js @@ -3,1278 +3,1279 @@ * Create By GUY 2014\11\17 * */ -!(function (undefined) { - var traverse = function (func, context) { - return function (value, key, obj) { - return func.call(context, key, value, obj); - }; +var traverse = function (func, context) { + return function (value, key, obj) { + return func.call(context, key, value, obj); }; - var _apply = function (name) { - return function () { - return BI._[name].apply(BI._, arguments); - }; +}; +var _apply = function (name) { + return function () { + return BI._[name].apply(BI._, arguments); }; - var _applyFunc = function (name) { - return function () { - var args = Array.prototype.slice.call(arguments, 0); - args[1] = BI._.isFunction(args[1]) ? traverse(args[1], args[2]) : args[1]; - return BI._[name].apply(BI._, args); - }; +}; +var _applyFunc = function (name) { + return function () { + var args = Array.prototype.slice.call(arguments, 0); + args[1] = BI._.isFunction(args[1]) ? traverse(args[1], args[2]) : args[1]; + return BI._[name].apply(BI._, args); }; +}; - // Utility - BI._.extend(BI, { - assert: function (v, is) { - if (this.isFunction(is)) { - if (!is(v)) { - throw new Error(v + " error"); - } else { - return true; - } - } - if (!this.isArray(is)) { - is = [is]; - } - if (!this.deepContains(is, v)) { +// Utility +BI._.extend(BI, { + assert: function (v, is) { + if (this.isFunction(is)) { + if (!is(v)) { throw new Error(v + " error"); + } else { + return true; } - return true; - }, - - warn: function (message) { - console.warn(message); - }, - - UUID: function () { - var f = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; - var str = ""; - for (var i = 0; i < 16; i++) { - var r = parseInt(f.length * Math.random(), 10); - str += f[r]; - } - return str; - }, + } + if (!this.isArray(is)) { + is = [is]; + } + if (!this.deepContains(is, v)) { + throw new Error(v + " error"); + } + return true; + }, + + warn: function (message) { + console.warn(message); + }, + + UUID: function () { + var f = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; + var str = ""; + for (var i = 0; i < 16; i++) { + var r = parseInt(f.length * Math.random(), 10); + str += f[r]; + } + return str; + }, - isWidget: function (widget) { - return widget instanceof BI.Widget; - }, + isWidget: function (widget) { + return widget instanceof BI.Widget; + }, - createWidgets: function (items, options, context) { - if (!BI.isArray(items)) { - throw new Error("items必须是数组", items); + createWidgets: function (items, options, context) { + if (!BI.isArray(items)) { + throw new Error("items必须是数组", items); + } + if (BI.isWidget(options)) { + context = options; + options = {}; + } else { + options || (options = {}); + } + return BI.map(BI.flatten(items), function (i, item) { + return BI.createWidget(item, BI.deepClone(options), context); + }); + }, + + createItems: function (data, innerAttr, outerAttr) { + innerAttr = BI.isArray(innerAttr) ? innerAttr : BI.makeArray(BI.flatten(data).length, innerAttr || {}); + outerAttr = BI.isArray(outerAttr) ? outerAttr : BI.makeArray(BI.flatten(data).length, outerAttr || {}); + return BI.map(data, function (i, item) { + if (BI.isArray(item)) { + return BI.createItems(item, innerAttr, outerAttr); + } + if (item instanceof BI.Widget) { + return BI.extend({}, innerAttr.shift(), outerAttr.shift(), { + type: null, + el: item + }); } - if (BI.isWidget(options)) { - context = options; - options = {}; - } else { - options || (options = {}); + if (innerAttr[0] instanceof BI.Widget) { + outerAttr.shift(); + return BI.extend({}, item, { + el: innerAttr.shift() + }); } - return BI.map(BI.flatten(items), function (i, item) { - return BI.createWidget(item, BI.deepClone(options), context); - }); - }, - - createItems: function (data, innerAttr, outerAttr) { - innerAttr = BI.isArray(innerAttr) ? innerAttr : BI.makeArray(BI.flatten(data).length, innerAttr || {}); - outerAttr = BI.isArray(outerAttr) ? outerAttr : BI.makeArray(BI.flatten(data).length, outerAttr || {}); - return BI.map(data, function (i, item) { - if (BI.isArray(item)) { - return BI.createItems(item, innerAttr, outerAttr); - } - if (item instanceof BI.Widget) { - return BI.extend({}, innerAttr.shift(), outerAttr.shift(), { - type: null, - el: item - }); - } - if (innerAttr[0] instanceof BI.Widget) { - outerAttr.shift(); - return BI.extend({}, item, { - el: innerAttr.shift() - }); - } - if (item.el instanceof BI.Widget) { - innerAttr.shift(); - return BI.extend({}, outerAttr.shift(), { type: null }, item); - } - if (item.el) { - return BI.extend({}, outerAttr.shift(), item, { - el: BI.extend({}, innerAttr.shift(), item.el) - }); - } - return BI.extend({}, outerAttr.shift(), { - el: BI.extend({}, innerAttr.shift(), item) + if (item.el instanceof BI.Widget) { + innerAttr.shift(); + return BI.extend({}, outerAttr.shift(), { type: null }, item); + } + if (item.el) { + return BI.extend({}, outerAttr.shift(), item, { + el: BI.extend({}, innerAttr.shift(), item.el) }); + } + return BI.extend({}, outerAttr.shift(), { + el: BI.extend({}, innerAttr.shift(), item) }); - }, - - // 用容器包装items - packageItems: function (items, layouts) { - for (var i = layouts.length - 1; i >= 0; i--) { - items = BI.map(items, function (k, it) { - return BI.extend({}, layouts[i], { - items: [ - BI.extend({}, layouts[i].el, { - el: it - }) - ] - }); + }); + }, + + // 用容器包装items + packageItems: function (items, layouts) { + for (var i = layouts.length - 1; i >= 0; i--) { + items = BI.map(items, function (k, it) { + return BI.extend({}, layouts[i], { + items: [ + BI.extend({}, layouts[i].el, { + el: it + }) + ] }); - } - return items; - }, - - formatEL: function (obj) { - if (obj && !obj.type && obj.el) { - return obj; - } - return { - el: obj - }; - }, - - // 剥开EL - stripEL: function (obj) { - return obj.type && obj || obj.el || obj; - }, - - trans2Element: function (widgets) { - return BI.map(widgets, function (i, wi) { - return wi.element; }); } - }); + return items; + }, - // 集合相关方法 - BI._.each(["where", "findWhere", "invoke", "pluck", "shuffle", "sample", "toArray", "size"], function (name) { - BI[name] = _apply(name); - }); - BI._.each(["get", "set", "each", "map", "reduce", "reduceRight", "find", "filter", "reject", "every", "all", "some", "any", "max", "min", - "sortBy", "groupBy", "indexBy", "countBy", "partition", "clamp"], function (name) { - if (name === "any") { - BI[name] = _applyFunc("some"); - } else { - BI[name] = _applyFunc(name); - } - }); - BI._.extend(BI, { - // 数数 - count: function (from, to, predicate) { - var t; - if (predicate) { - for (t = from; t < to; t++) { - predicate(t); - } + formatEL: function (obj) { + if (obj && !obj.type && obj.el) { + return obj; + } + return { + el: obj + }; + }, + + // 剥开EL + stripEL: function (obj) { + return obj.type && obj || obj.el || obj; + }, + + trans2Element: function (widgets) { + return BI.map(widgets, function (i, wi) { + return wi.element; + }); + } +}); + +// 集合相关方法 +BI._.each(["where", "findWhere", "invoke", "pluck", "shuffle", "sample", "toArray", "size"], function (name) { + BI[name] = _apply(name); +}); +BI._.each(["get", "set", "each", "map", "reduce", "reduceRight", "find", "filter", "reject", "every", "all", "some", "any", "max", "min", + "sortBy", "groupBy", "indexBy", "countBy", "partition", "clamp"], function (name) { + if (name === "any") { + BI[name] = _applyFunc("some"); + } else { + BI[name] = _applyFunc(name); + } +}); +BI._.extend(BI, { + // 数数 + count: function (from, to, predicate) { + var t; + if (predicate) { + for (t = from; t < to; t++) { + predicate(t); } - return to - from; - }, - - // 倒数 - inverse: function (from, to, predicate) { - return BI.count(to, from, predicate); - }, - - firstKey: function (obj) { - var res = undefined; - BI.any(obj, function (key, value) { - res = key; - return true; - }); - return res; - }, - - lastKey: function (obj) { - var res = undefined; - BI.each(obj, function (key, value) { - res = key; - return true; - }); - return res; - }, + } + return to - from; + }, + + // 倒数 + inverse: function (from, to, predicate) { + return BI.count(to, from, predicate); + }, + + firstKey: function (obj) { + var res = undefined; + BI.any(obj, function (key, value) { + res = key; + return true; + }); + return res; + }, + + lastKey: function (obj) { + var res = undefined; + BI.each(obj, function (key, value) { + res = key; + return true; + }); + return res; + }, + + firstObject: function (obj) { + var res = undefined; + BI.any(obj, function (key, value) { + res = value; + return true; + }); + return res; + }, + + lastObject: function (obj) { + var res = undefined; + BI.each(obj, function (key, value) { + res = value; + return true; + }); + return res; + }, + + concat: function (obj1, obj2) { + if (BI.isKey(obj1)) { + return BI.map([].slice.apply(arguments), function (idx, v) { + return v; + }).join(""); + } + if (BI.isArray(obj1)) { + return BI._.concat.apply([], arguments); + } + if (BI.isObject(obj1)) { + return BI._.extend.apply({}, arguments); + } + }, - firstObject: function (obj) { - var res = undefined; - BI.any(obj, function (key, value) { - res = value; - return true; - }); - return res; - }, + backEach: function (obj, predicate, context) { + predicate = BI.iteratee(predicate, context); + for (var index = obj.length - 1; index >= 0; index--) { + predicate(index, obj[index], obj); + } + return false; + }, - lastObject: function (obj) { - var res = undefined; - BI.each(obj, function (key, value) { - res = value; + backAny: function (obj, predicate, context) { + predicate = BI.iteratee(predicate, context); + for (var index = obj.length - 1; index >= 0; index--) { + if (predicate(index, obj[index], obj)) { return true; - }); - return res; - }, - - concat: function (obj1, obj2) { - if (BI.isKey(obj1)) { - return BI.map([].slice.apply(arguments), function (idx, v) { - return v; - }).join(""); } - if (BI.isArray(obj1)) { - return BI._.concat.apply([], arguments); - } - if (BI.isObject(obj1)) { - return BI._.extend.apply({}, arguments); - } - }, + } + return false; + }, - backEach: function (obj, predicate, context) { - predicate = BI.iteratee(predicate, context); - for (var index = obj.length - 1; index >= 0; index--) { - predicate(index, obj[index], obj); + backEvery: function (obj, predicate, context) { + predicate = BI.iteratee(predicate, context); + for (var index = obj.length - 1; index >= 0; index--) { + if (!predicate(index, obj[index], obj)) { + return false; } - return false; - }, + } + return true; + }, - backAny: function (obj, predicate, context) { - predicate = BI.iteratee(predicate, context); - for (var index = obj.length - 1; index >= 0; index--) { - if (predicate(index, obj[index], obj)) { - return true; - } + backFindKey: function (obj, predicate, context) { + predicate = BI.iteratee(predicate, context); + var keys = BI._.keys(obj), key; + for (var i = keys.length - 1; i >= 0; i--) { + key = keys[i]; + if (predicate(obj[key], key, obj)) { + return key; } - return false; - }, + } + }, - backEvery: function (obj, predicate, context) { - predicate = BI.iteratee(predicate, context); - for (var index = obj.length - 1; index >= 0; index--) { - if (!predicate(index, obj[index], obj)) { - return false; + backFind: function (obj, predicate, context) { + var key; + if (BI.isArray(obj)) { + key = BI.findLastIndex(obj, predicate, context); + } else { + key = BI.backFindKey(obj, predicate, context); + } + if (key !== void 0 && key !== -1) { + return obj[key]; + } + }, + + remove: function (obj, target, context) { + var isFunction = BI.isFunction(target); + target = isFunction || BI.isArray(target) ? target : [target]; + var i; + if (BI.isArray(obj)) { + for (i = 0; i < obj.length; i++) { + if ((isFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!isFunction && BI.contains(target, obj[i]))) { + obj.splice(i--, 1); } } - return true; - }, - - backFindKey: function (obj, predicate, context) { - predicate = BI.iteratee(predicate, context); - var keys = BI._.keys(obj), key; - for (var i = keys.length - 1; i >= 0; i--) { - key = keys[i]; - if (predicate(obj[key], key, obj)) { - return key; + } else { + BI.each(obj, function (i, v) { + if ((isFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!isFunction && BI.contains(target, obj[i]))) { + delete obj[i]; } - } - }, + }); + } + }, - backFind: function (obj, predicate, context) { - var key; - if (BI.isArray(obj)) { - key = BI.findLastIndex(obj, predicate, context); - } else { - key = BI.backFindKey(obj, predicate, context); - } - if (key !== void 0 && key !== -1) { - return obj[key]; - } - }, - - remove: function (obj, target, context) { - var isFunction = BI.isFunction(target); - target = isFunction || BI.isArray(target) ? target : [target]; - var i; - if (BI.isArray(obj)) { - for (i = 0; i < obj.length; i++) { - if ((isFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!isFunction && BI.contains(target, obj[i]))) { - obj.splice(i--, 1); - } - } + removeAt: function (obj, index) { + index = BI.isArray(index) ? index : [index]; + var isArray = BI.isArray(obj), i; + for (i = 0; i < index.length; i++) { + if (isArray) { + obj[index[i]] = "$deleteIndex"; } else { - BI.each(obj, function (i, v) { - if ((isFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!isFunction && BI.contains(target, obj[i]))) { - delete obj[i]; - } - }); + delete obj[index[i]]; } - }, - - removeAt: function (obj, index) { - index = BI.isArray(index) ? index : [index]; - var isArray = BI.isArray(obj), i; - for (i = 0; i < index.length; i++) { - if (isArray) { - obj[index[i]] = "$deleteIndex"; - } else { - delete obj[index[i]]; - } - } - if (isArray) { - BI.remove(obj, "$deleteIndex"); + } + if (isArray) { + BI.remove(obj, "$deleteIndex"); + } + }, + + string2Array: function (str) { + return str.split("&-&"); + }, + + array2String: function (array) { + return array.join("&-&"); + }, + + abc2Int: function (str) { + var idx = 0, start = "A", str = str.toUpperCase(); + for (var i = 0, len = str.length; i < len; ++i) { + idx = str.charAt(i).charCodeAt(0) - start.charCodeAt(0) + 26 * idx + 1; + if (idx > (2147483646 - str.charAt(i).charCodeAt(0) + start.charCodeAt(0)) / 26) { + return 0; } - }, - - string2Array: function (str) { - return str.split("&-&"); - }, - - array2String: function (array) { - return array.join("&-&"); - }, - - abc2Int: function (str) { - var idx = 0, start = "A", str = str.toUpperCase(); - for (var i = 0, len = str.length; i < len; ++i) { - idx = str.charAt(i).charCodeAt(0) - start.charCodeAt(0) + 26 * idx + 1; - if (idx > (2147483646 - str.charAt(i).charCodeAt(0) + start.charCodeAt(0)) / 26) { - return 0; - } + } + return idx; + }, + + int2Abc: function (num) { + var DIGITS = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; + var idx = num, str = ""; + if (num === 0) { + return ""; + } + while (idx !== 0) { + var t = idx % 26; + if (t === 0) { + t = 26; } - return idx; - }, - - int2Abc: function (num) { - var DIGITS = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; - var idx = num, str = ""; - if (num === 0) { - return ""; + str = DIGITS[t - 1] + str; + idx = (idx - t) / 26; + } + return str; + } +}); + +// 数组相关的方法 +BI._.each(["first", "initial", "last", "rest", "compact", "flatten", "without", "union", "intersection", + "difference", "zip", "unzip", "object", "indexOf", "lastIndexOf", "sortedIndex", "range", "take", "takeRight", "uniqBy"], function (name) { + BI[name] = _apply(name); +}); +BI._.each(["findIndex", "findLastIndex"], function (name) { + BI[name] = _applyFunc(name); +}); +BI._.extend(BI, { + // 构建一个长度为length的数组 + makeArray: function (length, value) { + var res = []; + for (var i = 0; i < length; i++) { + if (BI.isNull(value)) { + res.push(i); + } else { + res.push(BI.deepClone(value)); } - while (idx !== 0) { - var t = idx % 26; - if (t === 0) { - t = 26; - } - str = DIGITS[t - 1] + str; - idx = (idx - t) / 26; + } + return res; + }, + + makeObject: function (array, value) { + var map = {}; + for (var i = 0; i < array.length; i++) { + if (BI.isNull(value)) { + map[array[i]] = array[i]; + } else if (BI.isFunction(value)) { + map[array[i]] = value(i, array[i]); + } else { + map[array[i]] = BI.deepClone(value); } - return str; } - }); + return map; + }, - // 数组相关的方法 - BI._.each(["first", "initial", "last", "rest", "compact", "flatten", "without", "union", "intersection", - "difference", "zip", "unzip", "object", "indexOf", "lastIndexOf", "sortedIndex", "range", "take", "takeRight", "uniqBy"], function (name) { - BI[name] = _apply(name); - }); - BI._.each(["findIndex", "findLastIndex"], function (name) { - BI[name] = _applyFunc(name); - }); - BI._.extend(BI, { - // 构建一个长度为length的数组 - makeArray: function (length, value) { - var res = []; - for (var i = 0; i < length; i++) { - if (BI.isNull(value)) { - res.push(i); - } else { - res.push(BI.deepClone(value)); - } - } + makeArrayByArray: function (array, value) { + var res = []; + if (!array) { return res; - }, - - makeObject: function (array, value) { - var map = {}; - for (var i = 0; i < array.length; i++) { - if (BI.isNull(value)) { - map[array[i]] = array[i]; - } else if (BI.isFunction(value)) { - map[array[i]] = value(i, array[i]); - } else { - map[array[i]] = BI.deepClone(value); - } + } + for (var i = 0, len = array.length; i < len; i++) { + if (BI.isArray(array[i])) { + res.push(BI.makeArrayByArray(array[i], value)); + } else { + res.push(BI.deepClone(value)); } - return map; - }, + } + return res; + }, - makeArrayByArray: function (array, value) { - var res = []; - if (!array) { - return res; - } - for (var i = 0, len = array.length; i < len; i++) { - if (BI.isArray(array[i])) { - res.push(BI.makeArrayByArray(array[i], value)); - } else { - res.push(BI.deepClone(value)); - } - } - return res; - }, + uniq: function (array, isSorted, iteratee, context) { + if (array == null) { + return []; + } + if (!BI._.isBoolean(isSorted)) { + context = iteratee; + iteratee = isSorted; + isSorted = false; + } + iteratee && (iteratee = traverse(iteratee, context)); + return BI._.uniq.call(BI._, array, isSorted, iteratee, context); + } +}); + +// 对象相关方法 +BI._.each(["keys", "allKeys", "values", "pairs", "invert", "create", "functions", "extend", "extendOwn", + "defaults", "clone", "property", "propertyOf", "matcher", "isEqual", "isMatch", "isEmpty", + "isElement", "isNumber", "isString", "isArray", "isObject", "isPlainObject", "isArguments", "isFunction", "isFinite", + "isBoolean", "isDate", "isRegExp", "isError", "isNaN", "isUndefined", "zipObject", "cloneDeep"], function (name) { + BI[name] = _apply(name); +}); +BI._.each(["mapObject", "findKey", "pick", "omit", "tap"], function (name) { + BI[name] = _applyFunc(name); +}); +BI._.extend(BI, { + + inherit: function (sp, overrides) { + var sb = function () { + return sp.apply(this, arguments); + }; + var F = function () { + }, spp = sp.prototype; + F.prototype = spp; + sb.prototype = new F(); + sb.superclass = spp; + BI._.extend(sb.prototype, overrides, { + superclass: sp + }); + return sb; + }, + + init: function () { + // 先把准备环境准备好 + while (BI.prepares && BI.prepares.length > 0) { + BI.prepares.shift()(); + } + while (_global.___fineuiExposedFunction && _global.___fineuiExposedFunction.length > 0) { + _global.___fineuiExposedFunction.shift()(); + } + BI.initialized = true; + }, - uniq: function (array, isSorted, iteratee, context) { - if (array == null) { - return []; - } - if (!BI._.isBoolean(isSorted)) { - context = iteratee; - iteratee = isSorted; - isSorted = false; + has: function (obj, keys) { + if (BI.isArray(keys)) { + if (keys.length === 0) { + return false; } - iteratee && (iteratee = traverse(iteratee, context)); - return BI._.uniq.call(BI._, array, isSorted, iteratee, context); - } - }); - - // 对象相关方法 - BI._.each(["keys", "allKeys", "values", "pairs", "invert", "create", "functions", "extend", "extendOwn", - "defaults", "clone", "property", "propertyOf", "matcher", "isEqual", "isMatch", "isEmpty", - "isElement", "isNumber", "isString", "isArray", "isObject", "isPlainObject", "isArguments", "isFunction", "isFinite", - "isBoolean", "isDate", "isRegExp", "isError", "isNaN", "isUndefined", "zipObject", "cloneDeep"], function (name) { - BI[name] = _apply(name); - }); - BI._.each(["mapObject", "findKey", "pick", "omit", "tap"], function (name) { - BI[name] = _applyFunc(name); - }); - BI._.extend(BI, { - - inherit: function (sp, overrides) { - var sb = function () { - return sp.apply(this, arguments); - }; - var F = function () { - }, spp = sp.prototype; - F.prototype = spp; - sb.prototype = new F(); - sb.superclass = spp; - BI._.extend(sb.prototype, overrides, { - superclass: sp + return BI.every(keys, function (i, key) { + return BI._.has(obj, key); }); - return sb; - }, - - init: function () { - // 先把准备环境准备好 - while (BI.prepares && BI.prepares.length > 0) { - BI.prepares.shift()(); - } - while (_global.___fineuiExposedFunction && _global.___fineuiExposedFunction.length > 0) { - _global.___fineuiExposedFunction.shift()(); + } + return BI._.has.apply(BI._, arguments); + }, + + freeze: function (value) { + // 在ES5中,如果这个方法的参数不是一个对象(一个原始值),那么它会导致 TypeError + // 在ES2015中,非对象参数将被视为要被冻结的普通对象,并被简单地返回 + if (Object.freeze && BI.isObject(value)) { + return Object.freeze(value); + } + return value; + }, + + // 数字和字符串可以作为key + isKey: function (key) { + return BI.isNumber(key) || (BI.isString(key) && key.length > 0); + }, + + // 忽略大小写的等于 + isCapitalEqual: function (a, b) { + a = BI.isNull(a) ? a : ("" + a).toLowerCase(); + b = BI.isNull(b) ? b : ("" + b).toLowerCase(); + return BI.isEqual(a, b); + }, + + isWidthOrHeight: function (w) { + if (typeof w === "number") { + return w >= 0; + } else if (typeof w === "string") { + return /^\d{1,3}(\.\d)?%$/.test(w) || w === "auto" || /^\d+(\.\d+)?px$/.test(w) || /^calc/.test(w); + } + }, + + isNotNull: function (obj) { + return !BI.isNull(obj); + }, + + isNull: function (obj) { + return typeof obj === "undefined" || obj === null; + }, + + isEmptyArray: function (arr) { + return BI.isArray(arr) && BI.isEmpty(arr); + }, + + isNotEmptyArray: function (arr) { + return BI.isArray(arr) && !BI.isEmpty(arr); + }, + + isEmptyObject: function (obj) { + return BI.isEqual(obj, {}); + }, + + isNotEmptyObject: function (obj) { + return BI.isPlainObject(obj) && !BI.isEmptyObject(obj); + }, + + isEmptyString: function (obj) { + return BI.isString(obj) && obj.length === 0; + }, + + isNotEmptyString: function (obj) { + return BI.isString(obj) && !BI.isEmptyString(obj); + }, + + isWindow: function (obj) { + return obj != null && obj == obj.window; + }, + + isPromise: function (obj) { + return !!obj && (BI.isObject(obj) || BI.isFunction(obj)) && BI.isFunction(obj.then); + } +}); + +// deep方法 +BI._.extend(BI, { + deepClone: BI._.cloneDeep, + deepExtend: BI._.merge, + + isDeepMatch: function (object, attrs) { + var keys = BI.keys(attrs), length = keys.length; + if (object == null) { + return !length; + } + var obj = Object(object); + for (var i = 0; i < length; i++) { + var key = keys[i]; + if (!BI.isEqual(attrs[key], obj[key]) || !(key in obj)) { + return false; } - BI.initialized = true; - }, - - has: function (obj, keys) { - if (BI.isArray(keys)) { - if (keys.length === 0) { - return false; + } + return true; + }, + + contains: function (obj, target, fromIndex) { + if (!BI._.isArrayLike(obj)) obj = BI._.values(obj); + return BI._.indexOf(obj, target, typeof fromIndex === "number" && fromIndex) >= 0; + }, + + deepContains: function (obj, copy) { + if (BI.isObject(copy)) { + return BI.any(obj, function (i, v) { + if (BI.isEqual(v, copy)) { + return true; } - return BI.every(keys, function (i, key) { - return BI._.has(obj, key); - }); - } - return BI._.has.apply(BI._, arguments); - }, - - freeze: function (value) { - // 在ES5中,如果这个方法的参数不是一个对象(一个原始值),那么它会导致 TypeError - // 在ES2015中,非对象参数将被视为要被冻结的普通对象,并被简单地返回 - if (Object.freeze && BI.isObject(value)) { - return Object.freeze(value); - } - return value; - }, - - // 数字和字符串可以作为key - isKey: function (key) { - return BI.isNumber(key) || (BI.isString(key) && key.length > 0); - }, - - // 忽略大小写的等于 - isCapitalEqual: function (a, b) { - a = BI.isNull(a) ? a : ("" + a).toLowerCase(); - b = BI.isNull(b) ? b : ("" + b).toLowerCase(); - return BI.isEqual(a, b); - }, - - isWidthOrHeight: function (w) { - if (typeof w === "number") { - return w >= 0; - } else if (typeof w === "string") { - return /^\d{1,3}(\.\d)?%$/.test(w) || w === "auto" || /^\d+(\.\d+)?px$/.test(w) || /^calc/.test(w); - } - }, - - isNotNull: function (obj) { - return !BI.isNull(obj); - }, - - isNull: function (obj) { - return typeof obj === "undefined" || obj === null; - }, - - isEmptyArray: function (arr) { - return BI.isArray(arr) && BI.isEmpty(arr); - }, - - isNotEmptyArray: function (arr) { - return BI.isArray(arr) && !BI.isEmpty(arr); - }, - - isEmptyObject: function (obj) { - return BI.isEqual(obj, {}); - }, - - isNotEmptyObject: function (obj) { - return BI.isPlainObject(obj) && !BI.isEmptyObject(obj); - }, - - isEmptyString: function (obj) { - return BI.isString(obj) && obj.length === 0; - }, - - isNotEmptyString: function (obj) { - return BI.isString(obj) && !BI.isEmptyString(obj); - }, - - isWindow: function (obj) { - return obj != null && obj == obj.window; - }, - - isPromise: function (obj) { - return !!obj && (BI.isObject(obj) || BI.isFunction(obj)) && BI.isFunction(obj.then); + }); } - }); - - // deep方法 - BI._.extend(BI, { - deepClone: BI._.cloneDeep, - deepExtend: BI._.merge, + return BI.contains(obj, copy); + }, - isDeepMatch: function (object, attrs) { - var keys = BI.keys(attrs), length = keys.length; - if (object == null) { - return !length; - } - var obj = Object(object); - for (var i = 0; i < length; i++) { - var key = keys[i]; - if (!BI.isEqual(attrs[key], obj[key]) || !(key in obj)) { - return false; - } - } - return true; - }, - - contains: function (obj, target, fromIndex) { - if (!BI._.isArrayLike(obj)) obj = BI._.values(obj); - return BI._.indexOf(obj, target, typeof fromIndex === "number" && fromIndex) >= 0; - }, - - deepContains: function (obj, copy) { - if (BI.isObject(copy)) { - return BI.any(obj, function (i, v) { - if (BI.isEqual(v, copy)) { - return true; - } - }); + deepIndexOf: function (obj, target) { + for (var i = 0; i < obj.length; i++) { + if (BI.isEqual(target, obj[i])) { + return i; } - return BI.contains(obj, copy); - }, - - deepIndexOf: function (obj, target) { - for (var i = 0; i < obj.length; i++) { + } + return -1; + }, + + deepRemove: function (obj, target) { + var done = false; + var i; + if (BI.isArray(obj)) { + for (i = 0; i < obj.length; i++) { if (BI.isEqual(target, obj[i])) { - return i; - } - } - return -1; - }, - - deepRemove: function (obj, target) { - var done = false; - var i; - if (BI.isArray(obj)) { - for (i = 0; i < obj.length; i++) { - if (BI.isEqual(target, obj[i])) { - obj.splice(i--, 1); - done = true; - } - } - } else { - BI.each(obj, function (i, v) { - if (BI.isEqual(target, obj[i])) { - delete obj[i]; - done = true; - } - }); - } - return done; - }, - - deepWithout: function (obj, target) { - if (BI.isArray(obj)) { - var result = []; - for (var i = 0; i < obj.length; i++) { - if (!BI.isEqual(target, obj[i])) { - result.push(obj[i]); - } + obj.splice(i--, 1); + done = true; } - return result; } - var result = {}; + } else { BI.each(obj, function (i, v) { - if (!BI.isEqual(target, obj[i])) { - result[i] = v; - } - }); - return result; - - }, - - deepUnique: function (array) { - var result = []; - BI.each(array, function (i, item) { - if (!BI.deepContains(result, item)) { - result.push(item); + if (BI.isEqual(target, obj[i])) { + delete obj[i]; + done = true; } }); - return result; - }, + } + return done; + }, - // 比较两个对象得出不一样的key值 - deepDiff: function (object, other) { - object || (object = {}); - other || (other = {}); + deepWithout: function (obj, target) { + if (BI.isArray(obj)) { var result = []; - var used = []; - for (var b in object) { - if (this.has(object, b)) { - if (!this.isEqual(object[b], other[b])) { - result.push(b); - } - used.push(b); + for (var i = 0; i < obj.length; i++) { + if (!BI.isEqual(target, obj[i])) { + result.push(obj[i]); } } - for (var b in other) { - if (this.has(other, b) && !BI.contains(used, b)) { + return result; + } + var result = {}; + BI.each(obj, function (i, v) { + if (!BI.isEqual(target, obj[i])) { + result[i] = v; + } + }); + return result; + + }, + + deepUnique: function (array) { + var result = []; + BI.each(array, function (i, item) { + if (!BI.deepContains(result, item)) { + result.push(item); + } + }); + return result; + }, + + // 比较两个对象得出不一样的key值 + deepDiff: function (object, other) { + object || (object = {}); + other || (other = {}); + var result = []; + var used = []; + for (var b in object) { + if (this.has(object, b)) { + if (!this.isEqual(object[b], other[b])) { result.push(b); } + used.push(b); + } + } + for (var b in other) { + if (this.has(other, b) && !BI.contains(used, b)) { + result.push(b); } - return result; } - }); + return result; + } +}); + +// 通用方法 +BI._.each(["uniqueId", "result", "chain", "iteratee", "escape", "unescape", "before", "after", "chunk"], function (name) { + BI[name] = function () { + return BI._[name].apply(BI._, arguments); + }; +}); - // 通用方法 - BI._.each(["uniqueId", "result", "chain", "iteratee", "escape", "unescape", "before", "after", "chunk"], function (name) { - BI[name] = function () { - return BI._[name].apply(BI._, arguments); - }; - }); +// 事件相关方法 +BI._.each(["bind", "once", "partial", "debounce", "throttle", "delay", "defer", "wrap"], function (name) { + BI[name] = function () { + return BI._[name].apply(BI._, arguments); + }; +}); - // 事件相关方法 - BI._.each(["bind", "once", "partial", "debounce", "throttle", "delay", "defer", "wrap"], function (name) { - BI[name] = function () { - return BI._[name].apply(BI._, arguments); - }; - }); - - BI._.extend(BI, { - nextTick: (function () { - var callbacks = []; - var pending = false; - var timerFunc = void 0; - - function nextTickHandler() { - pending = false; - var copies = callbacks.slice(0); - callbacks.length = 0; - for (var i = 0; i < copies.length; i++) { - copies[i](); - } - } +BI._.extend(BI, { + nextTick: (function () { + var callbacks = []; + var pending = false; + var timerFunc = void 0; - if (typeof Promise !== "undefined") { - var p = Promise.resolve(); - timerFunc = function timerFunc() { - p.then(nextTickHandler); - }; - } else if (typeof MutationObserver !== "undefined") { - var counter = 1; - var observer = new MutationObserver(nextTickHandler); - var textNode = document.createTextNode(String(counter)); - observer.observe(textNode, { - characterData: true - }); - timerFunc = function timerFunc() { - counter = (counter + 1) % 2; - textNode.data = String(counter); - }; - } else if (typeof setImmediate !== "undefined") { - timerFunc = function timerFunc() { - setImmediate(nextTickHandler); - }; - } else { - // Fallback to setTimeout. - timerFunc = function timerFunc() { - setTimeout(nextTickHandler, 0); - }; + function nextTickHandler() { + pending = false; + var copies = callbacks.slice(0); + callbacks.length = 0; + for (var i = 0; i < copies.length; i++) { + copies[i](); } + } - return function queueNextTick(cb) { - var _resolve = void 0; - var args = [].slice.call(arguments, 1); - callbacks.push(function () { - if (cb) { - try { - cb.apply(null, args); - } catch (e) { - console.error(e); - } - } else if (_resolve) { - _resolve.apply(null, args); + if (typeof Promise !== "undefined") { + var p = Promise.resolve(); + timerFunc = function timerFunc() { + p.then(nextTickHandler); + }; + } else if (typeof MutationObserver !== "undefined") { + var counter = 1; + var observer = new MutationObserver(nextTickHandler); + var textNode = document.createTextNode(String(counter)); + observer.observe(textNode, { + characterData: true + }); + timerFunc = function timerFunc() { + counter = (counter + 1) % 2; + textNode.data = String(counter); + }; + } else if (typeof setImmediate !== "undefined") { + timerFunc = function timerFunc() { + setImmediate(nextTickHandler); + }; + } else { + // Fallback to setTimeout. + timerFunc = function timerFunc() { + setTimeout(nextTickHandler, 0); + }; + } + + return function queueNextTick(cb) { + var _resolve = void 0; + var args = [].slice.call(arguments, 1); + callbacks.push(function () { + if (cb) { + try { + cb.apply(null, args); + } catch (e) { + console.error(e); } - }); - if (!pending) { - pending = true; - timerFunc(); + } else if (_resolve) { + _resolve.apply(null, args); } - // $flow-disable-line - if (!cb && typeof Promise !== 'undefined') { - return new Promise(function (resolve, reject) { - _resolve = resolve; - }); - } - }; - })() - }); - - // 数字相关方法 - BI._.each(["random"], function (name) { - BI[name] = _apply(name); - }); - BI._.extend(BI, { - - parseInt: function (number) { - var radix = 10; - if (/^0x/g.test(number)) { - radix = 16; - } - try { - return parseInt(number, radix); - } catch (e) { - throw new Error(number + "parse int error"); - return NaN; - } - }, - - parseSafeInt: function (value) { - var MAX_SAFE_INTEGER = 9007199254740991; - return value - ? this.clamp(this.parseInt(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) - : (value === 0 ? value : 0); - }, - - parseFloat: function (number) { - try { - return parseFloat(number); - } catch (e) { - throw new Error(number + "parse float error"); - return NaN; + }); + if (!pending) { + pending = true; + timerFunc(); + } + // $flow-disable-line + if (!cb && typeof Promise !== 'undefined') { + return new Promise(function (resolve, reject) { + _resolve = resolve; + }); } - }, + }; + })() +}); + +// 数字相关方法 +BI._.each(["random"], function (name) { + BI[name] = _apply(name); +}); +BI._.extend(BI, { + + parseInt: function (number) { + var radix = 10; + if (/^0x/g.test(number)) { + radix = 16; + } + try { + return parseInt(number, radix); + } catch (e) { + throw new Error(number + "parse int error"); + return NaN; + } + }, + + parseSafeInt: function (value) { + var MAX_SAFE_INTEGER = 9007199254740991; + return value + ? this.clamp(this.parseInt(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) + : (value === 0 ? value : 0); + }, + + parseFloat: function (number) { + try { + return parseFloat(number); + } catch (e) { + throw new Error(number + "parse float error"); + return NaN; + } + }, - isNaturalNumber: function (number) { - if (/^\d+$/.test(number)) { - return true; - } - return false; - }, + isNaturalNumber: function (number) { + if (/^\d+$/.test(number)) { + return true; + } + return false; + }, - isPositiveInteger: function (number) { - if (/^\+?[1-9][0-9]*$/.test(number)) { - return true; - } - return false; - }, + isPositiveInteger: function (number) { + if (/^\+?[1-9][0-9]*$/.test(number)) { + return true; + } + return false; + }, - isNegativeInteger: function (number) { - if (/^\-[1-9][0-9]*$/.test(number)) { - return true; - } - return false; - }, + isNegativeInteger: function (number) { + if (/^\-[1-9][0-9]*$/.test(number)) { + return true; + } + return false; + }, - isInteger: function (number) { - if (/^\-?\d+$/.test(number)) { - return true; - } - return false; - }, + isInteger: function (number) { + if (/^\-?\d+$/.test(number)) { + return true; + } + return false; + }, - isNumeric: function (number) { - return !isNaN(parseFloat(number)) && isFinite(number); - }, + isNumeric: function (number) { + return !isNaN(parseFloat(number)) && isFinite(number); + }, - isFloat: function (number) { - if (/^([+-]?)\d*\.\d+$/.test(number)) { - return true; - } - return false; - }, + isFloat: function (number) { + if (/^([+-]?)\d*\.\d+$/.test(number)) { + return true; + } + return false; + }, - isOdd: function (number) { - if (!BI.isInteger(number)) { - return false; - } - return (number & 1) === 1; - }, + isOdd: function (number) { + if (!BI.isInteger(number)) { + return false; + } + return (number & 1) === 1; + }, - isEven: function (number) { - if (!BI.isInteger(number)) { - return false; - } - return (number & 1) === 0; - }, - - sum: function (array, iteratee, context) { - var sum = 0; - BI.each(array, function (i, item) { - if (iteratee) { - sum += Number(iteratee.apply(context, [i, item])); - } else { - sum += Number(item); - } - }); - return sum; - }, - - average: function (array, iteratee, context) { - var sum = BI.sum(array, iteratee, context); - return sum / array.length; - } - }); - - // 字符串相关方法 - BI._.extend(BI, { - trim: function () { - return BI._.trim.apply(BI._, arguments); - }, - - toUpperCase: function (string) { - return (string + "").toLocaleUpperCase(); - }, - - toLowerCase: function (string) { - return (string + "").toLocaleLowerCase(); - }, - - isEndWithBlank: function (string) { - return /(\s|\u00A0)$/.test(string); - }, - - isLiteral: function (exp) { - var literalValueRE = /^\s?(true|false|-?[\d\.]+|'[^']*'|"[^"]*")\s?$/; - return literalValueRE.test(exp); - }, - - stripQuotes: function (str) { - var a = str.charCodeAt(0); - var b = str.charCodeAt(str.length - 1); - return a === b && (a === 0x22 || a === 0x27) - ? str.slice(1, -1) - : str; - }, - - // background-color => backgroundColor - camelize: function (str) { - return str.replace(/-(.)/g, function (_, character) { - return character.toUpperCase(); - }); - }, - - // backgroundColor => background-color - hyphenate: function (str) { - return str.replace(/([A-Z])/g, "-$1").toLowerCase(); - }, - - isNotEmptyString: function (str) { - return BI.isString(str) && !BI.isEmpty(str); - }, - - isEmptyString: function (str) { - return BI.isString(str) && BI.isEmpty(str); - }, - - /** - * 通用加密方法 - */ - encrypt: function (type, text, key) { - switch (type) { - case BI.CRYPT_TYPE.AES: - default: - return BI.aesEncrypt(text, key); - } - }, - - /** - * 通用解密方法 - * @param type 解密方式 - * @param text 文本 - * @param key 种子 - * @return {*} - */ - decrypt: function (type, text, key) { - switch (type) { - case BI.CRYPT_TYPE.AES: - default: - return BI.aesDecrypt(text, key); - } - }, - - /** - * 对字符串中的'和\做编码处理 - * @static - * @param {String} string 要做编码处理的字符串 - * @return {String} 编码后的字符串 - */ - escape: function (string) { - return string.replace(/('|\\)/g, "\\$1"); - }, - - /** - * 让字符串通过指定字符做补齐的函数 - * - * var s = BI.leftPad('123', 5, '0');//s的值为:'00123' - * - * @static - * @param {String} val 原始值 - * @param {Number} size 总共需要的位数 - * @param {String} ch 用于补齐的字符 - * @return {String} 补齐后的字符串 - */ - leftPad: function (val, size, ch) { - var result = String(val); - if (!ch) { - ch = " "; - } - while (result.length < size) { - result = ch + result; - } - return result.toString(); - }, - - /** - * 对字符串做替换的函数 - * - * var cls = 'my-class', text = 'Some text'; - * var res = BI.format('
{1}
', cls, text); - * //res的值为:'
Some text
'; - * - * @static - * @param {String} format 要做替换的字符串,替换字符串1,替换字符串2... - * @return {String} 做了替换后的字符串 - */ - format: function (format) { - var args = Array.prototype.slice.call(arguments, 1); - return format.replace(/\{(\d+)\}/g, function (m, i) { - return args[i]; - }); + isEven: function (number) { + if (!BI.isInteger(number)) { + return false; } - }); - - // 日期相关方法 - BI._.extend(BI, { - /** - * 是否是闰年 - * @param year - * @returns {boolean} - */ - isLeapYear: function (year) { - return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; - }, - - /** - * 检测是否在有效期 - * - * @param YY 年 - * @param MM 月 - * @param DD 日 - * @param minDate '1900-01-01' - * @param maxDate '2099-12-31' - * @returns {Array} 若无效返回无效状态,数组第一位为无效属性,第二位缺省为超下限,1为超上限 - */ - checkDateVoid: function (YY, MM, DD, minDate, maxDate) { - var back = []; - YY = YY | 0; - MM = MM | 0; - DD = DD | 0; - minDate = BI.isString(minDate) ? minDate.match(/\d+/g) : minDate; - maxDate = BI.isString(maxDate) ? maxDate.match(/\d+/g) : maxDate; - if (YY < minDate[0]) { - back = ["y"]; - } else if (YY > maxDate[0]) { - back = ["y", 1]; - } else if (YY >= minDate[0] && YY <= maxDate[0]) { - if (YY == minDate[0]) { - if (MM < minDate[1]) { - back = ["m"]; - } else if (MM == minDate[1]) { - if (DD < minDate[2]) { - back = ["d"]; - } + return (number & 1) === 0; + }, + + sum: function (array, iteratee, context) { + var sum = 0; + BI.each(array, function (i, item) { + if (iteratee) { + sum += Number(iteratee.apply(context, [i, item])); + } else { + sum += Number(item); + } + }); + return sum; + }, + + average: function (array, iteratee, context) { + var sum = BI.sum(array, iteratee, context); + return sum / array.length; + } +}); + +// 字符串相关方法 +BI._.extend(BI, { + trim: function () { + return BI._.trim.apply(BI._, arguments); + }, + + toUpperCase: function (string) { + return (string + "").toLocaleUpperCase(); + }, + + toLowerCase: function (string) { + return (string + "").toLocaleLowerCase(); + }, + + isEndWithBlank: function (string) { + return /(\s|\u00A0)$/.test(string); + }, + + isLiteral: function (exp) { + var literalValueRE = /^\s?(true|false|-?[\d\.]+|'[^']*'|"[^"]*")\s?$/; + return literalValueRE.test(exp); + }, + + stripQuotes: function (str) { + var a = str.charCodeAt(0); + var b = str.charCodeAt(str.length - 1); + return a === b && (a === 0x22 || a === 0x27) + ? str.slice(1, -1) + : str; + }, + + // background-color => backgroundColor + camelize: function (str) { + return str.replace(/-(.)/g, function (_, character) { + return character.toUpperCase(); + }); + }, + + // backgroundColor => background-color + hyphenate: function (str) { + return str.replace(/([A-Z])/g, "-$1").toLowerCase(); + }, + + isNotEmptyString: function (str) { + return BI.isString(str) && !BI.isEmpty(str); + }, + + isEmptyString: function (str) { + return BI.isString(str) && BI.isEmpty(str); + }, + + /** + * 通用加密方法 + */ + encrypt: function (type, text, key) { + switch (type) { + case BI.CRYPT_TYPE.AES: + default: + return BI.aesEncrypt(text, key); + } + }, + + /** + * 通用解密方法 + * @param type 解密方式 + * @param text 文本 + * @param key 种子 + * @return {*} + */ + decrypt: function (type, text, key) { + switch (type) { + case BI.CRYPT_TYPE.AES: + default: + return BI.aesDecrypt(text, key); + } + }, + + /** + * 对字符串中的'和\做编码处理 + * @static + * @param {String} string 要做编码处理的字符串 + * @return {String} 编码后的字符串 + */ + escape: function (string) { + return string.replace(/('|\\)/g, "\\$1"); + }, + + /** + * 让字符串通过指定字符做补齐的函数 + * + * var s = BI.leftPad('123', 5, '0');//s的值为:'00123' + * + * @static + * @param {String} val 原始值 + * @param {Number} size 总共需要的位数 + * @param {String} ch 用于补齐的字符 + * @return {String} 补齐后的字符串 + */ + leftPad: function (val, size, ch) { + var result = String(val); + if (!ch) { + ch = " "; + } + while (result.length < size) { + result = ch + result; + } + return result.toString(); + }, + + /** + * 对字符串做替换的函数 + * + * var cls = 'my-class', text = 'Some text'; + * var res = BI.format('
{1}
', cls, text); + * //res的值为:'
Some text
'; + * + * @static + * @param {String} format 要做替换的字符串,替换字符串1,替换字符串2... + * @return {String} 做了替换后的字符串 + */ + format: function (format) { + var args = Array.prototype.slice.call(arguments, 1); + return format.replace(/\{(\d+)\}/g, function (m, i) { + return args[i]; + }); + } +}); + +// 日期相关方法 +BI._.extend(BI, { + /** + * 是否是闰年 + * @param year + * @returns {boolean} + */ + isLeapYear: function (year) { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; + }, + + /** + * 检测是否在有效期 + * + * @param YY 年 + * @param MM 月 + * @param DD 日 + * @param minDate '1900-01-01' + * @param maxDate '2099-12-31' + * @returns {Array} 若无效返回无效状态,数组第一位为无效属性,第二位缺省为超下限,1为超上限 + */ + checkDateVoid: function (YY, MM, DD, minDate, maxDate) { + var back = []; + YY = YY | 0; + MM = MM | 0; + DD = DD | 0; + minDate = BI.isString(minDate) ? minDate.match(/\d+/g) : minDate; + maxDate = BI.isString(maxDate) ? maxDate.match(/\d+/g) : maxDate; + if (YY < minDate[0]) { + back = ["y"]; + } else if (YY > maxDate[0]) { + back = ["y", 1]; + } else if (YY >= minDate[0] && YY <= maxDate[0]) { + if (YY == minDate[0]) { + if (MM < minDate[1]) { + back = ["m"]; + } else if (MM == minDate[1]) { + if (DD < minDate[2]) { + back = ["d"]; } } - if (YY == maxDate[0]) { - if (MM > maxDate[1]) { - back = ["m", 1]; - } else if (MM == maxDate[1]) { - if (DD > maxDate[2]) { - back = ["d", 1]; - } + } + if (YY == maxDate[0]) { + if (MM > maxDate[1]) { + back = ["m", 1]; + } else if (MM == maxDate[1]) { + if (DD > maxDate[2]) { + back = ["d", 1]; } } } - return back; - }, - - checkDateLegal: function (str) { - var ar = str.match(/\d+/g); - var YY = ar[0] | 0, MM = ar[1] | 0, DD = ar[2] | 0; - if (ar.length <= 1) { - return true; - } - if (ar.length <= 2) { - return MM >= 1 && MM <= 12; - } - var MD = BI.Date._MD.slice(0); - MD[1] = BI.isLeapYear(YY) ? 29 : 28; - return MM >= 1 && MM <= 12 && DD <= MD[MM - 1]; - }, - - parseDateTime: function (str, fmt) { - var today = BI.getDate(); - var y = 0; - var m = 0; - var d = 1; - // wei : 对于fmt为‘YYYYMM’或者‘YYYYMMdd’的格式,str的值为类似'201111'的形式,因为年月之间没有分隔符,所以正则表达式分割无效,导致bug7376。 - var a = str.split(/\W+/); - if (fmt.toLowerCase() == "%y%x" || fmt.toLowerCase() == "%y%x%d") { - var yearlength = 4; - var otherlength = 2; - a[0] = str.substring(0, yearlength); - a[1] = str.substring(yearlength, yearlength + otherlength); - a[2] = str.substring(yearlength + otherlength, yearlength + otherlength * 2); - } - var b = fmt.match(/%./g); - var i = 0, j = 0; - var hr = 0; - var min = 0; - var sec = 0; - for (i = 0; i < a.length; ++i) { - switch (b[i]) { - case "%d": - case "%e": - d = parseInt(a[i], 10); - break; - - case "%X": - m = parseInt(a[i], 10) - 1; - break; - case "%x": - m = parseInt(a[i], 10) - 1; - break; + } + return back; + }, - case "%Y": - case "%y": - y = parseInt(a[i], 10); - (y < 100) && (y += (y > 29) ? 1900 : 2000); - break; + checkDateLegal: function (str) { + var ar = str.match(/\d+/g); + var YY = ar[0] | 0, MM = ar[1] | 0, DD = ar[2] | 0; + if (ar.length <= 1) { + return true; + } + if (ar.length <= 2) { + return MM >= 1 && MM <= 12; + } + var MD = BI.Date._MD.slice(0); + MD[1] = BI.isLeapYear(YY) ? 29 : 28; + return MM >= 1 && MM <= 12 && DD <= MD[MM - 1]; + }, + + parseDateTime: function (str, fmt) { + var today = BI.getDate(); + var y = 0; + var m = 0; + var d = 1; + // wei : 对于fmt为‘YYYYMM’或者‘YYYYMMdd’的格式,str的值为类似'201111'的形式,因为年月之间没有分隔符,所以正则表达式分割无效,导致bug7376。 + var a = str.split(/\W+/); + if (fmt.toLowerCase() == "%y%x" || fmt.toLowerCase() == "%y%x%d") { + var yearlength = 4; + var otherlength = 2; + a[0] = str.substring(0, yearlength); + a[1] = str.substring(yearlength, yearlength + otherlength); + a[2] = str.substring(yearlength + otherlength, yearlength + otherlength * 2); + } + var b = fmt.match(/%./g); + var i = 0, j = 0; + var hr = 0; + var min = 0; + var sec = 0; + for (i = 0; i < a.length; ++i) { + switch (b[i]) { + case "%d": + case "%e": + d = parseInt(a[i], 10); + break; - case "%b": - case "%B": - for (j = 0; j < 12; ++j) { - if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { - m = j; - break; - } - } - break; + case "%X": + m = parseInt(a[i], 10) - 1; + break; + case "%x": + m = parseInt(a[i], 10) - 1; + break; - case "%H": - case "%I": - case "%k": - case "%l": - hr = parseInt(a[i], 10); - break; + case "%Y": + case "%y": + y = parseInt(a[i], 10); + (y < 100) && (y += (y > 29) ? 1900 : 2000); + break; - case "%P": - case "%p": - if (/pm/i.test(a[i]) && hr < 12) { - hr += 12; - } else if (/am/i.test(a[i]) && hr >= 12) { - hr -= 12; - } - break; - case "%Q": - case "%q": - m = (parseInt(a[i], 10) - 1) * 3; - break; - case "%M": - min = parseInt(a[i], 10); - break; - case "%S": - sec = parseInt(a[i], 10); - break; - } - } - // if (!a[i]) { - // continue; - // } - if (isNaN(y)) { - y = today.getFullYear(); - } - if (isNaN(m)) { - m = today.getMonth(); - } - if (isNaN(d)) { - d = today.getDate(); - } - if (isNaN(hr)) { - hr = today.getHours(); - } - if (isNaN(min)) { - min = today.getMinutes(); - } - if (isNaN(sec)) { - sec = today.getSeconds(); - } - if (y != 0) { - return BI.getDate(y, m, d, hr, min, sec); - } - y = 0; - m = -1; - d = 0; - for (i = 0; i < a.length; ++i) { - if (a[i].search(/[a-zA-Z]+/) != -1) { - var t = -1; + case "%b": + case "%B": for (j = 0; j < 12; ++j) { if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { - t = j; + m = j; break; } } - if (t != -1) { - if (m != -1) { - d = m + 1; - } - m = t; - } - } else if (parseInt(a[i], 10) <= 12 && m == -1) { - m = a[i] - 1; - } else if (parseInt(a[i], 10) > 31 && y == 0) { - y = parseInt(a[i], 10); - (y < 100) && (y += (y > 29) ? 1900 : 2000); - } else if (d == 0) { - d = a[i]; - } - } - if (y == 0) { - y = today.getFullYear(); - } - if (m === -1) { - m = today.getMonth(); - } - if (m != -1 && d != 0) { - return BI.getDate(y, m, d, hr, min, sec); - } - return today; - }, - - getDate: function () { - var length = arguments.length; - var args = arguments; - var dt; - switch (length) { - // new Date() - case 0: - dt = new Date(); - break; - // new Date(long) - case 1: - dt = new Date(args[0]); - break; - // new Date(year, month) - case 2: - dt = new Date(args[0], args[1]); - break; - // new Date(year, month, day) - case 3: - dt = new Date(args[0], args[1], args[2]); - break; - // new Date(year, month, day, hour) - case 4: - dt = new Date(args[0], args[1], args[2], args[3]); - break; - // new Date(year, month, day, hour, minute) - case 5: - dt = new Date(args[0], args[1], args[2], args[3], args[4]); - break; - // new Date(year, month, day, hour, minute, second) - case 6: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); - break; - // new Date(year, month, day, hour, minute, second, millisecond) - case 7: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); break; - default: - dt = new Date(); - break; - } - if (BI.isNotNull(BI.timeZone) && (arguments.length === 0 || (arguments.length === 1 && BI.isNumber(arguments[0])))) { - var localTime = dt.getTime(); - // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 - var localOffset = dt.getTimezoneOffset() * 60000; // 获得当地时间偏移的毫秒数 - var utc = localTime + localOffset; // utc即GMT时间标准时区 - return new Date(utc + BI.timeZone);// + Pool.timeZone.offset); - } - return dt; - - }, - - getTime: function () { - var length = arguments.length; - var args = arguments; - var dt; - switch (length) { - // new Date() - case 0: - dt = new Date(); - break; - // new Date(long) - case 1: - dt = new Date(args[0]); - break; - // new Date(year, month) - case 2: - dt = new Date(args[0], args[1]); - break; - // new Date(year, month, day) - case 3: - dt = new Date(args[0], args[1], args[2]); - break; - // new Date(year, month, day, hour) - case 4: - dt = new Date(args[0], args[1], args[2], args[3]); + + case "%H": + case "%I": + case "%k": + case "%l": + hr = parseInt(a[i], 10); break; - // new Date(year, month, day, hour, minute) - case 5: - dt = new Date(args[0], args[1], args[2], args[3], args[4]); + + case "%P": + case "%p": + if (/pm/i.test(a[i]) && hr < 12) { + hr += 12; + } else if (/am/i.test(a[i]) && hr >= 12) { + hr -= 12; + } break; - // new Date(year, month, day, hour, minute, second) - case 6: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); + case "%Q": + case "%q": + m = (parseInt(a[i], 10) - 1) * 3; break; - // new Date(year, month, day, hour, minute, second, millisecond) - case 7: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + case "%M": + min = parseInt(a[i], 10); break; - default: - dt = new Date(); + case "%S": + sec = parseInt(a[i], 10); break; } - if (BI.isNotNull(BI.timeZone)) { - // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 - return dt.getTime() - BI.timeZone - new Date().getTimezoneOffset() * 60000; + } + // if (!a[i]) { + // continue; + // } + if (isNaN(y)) { + y = today.getFullYear(); + } + if (isNaN(m)) { + m = today.getMonth(); + } + if (isNaN(d)) { + d = today.getDate(); + } + if (isNaN(hr)) { + hr = today.getHours(); + } + if (isNaN(min)) { + min = today.getMinutes(); + } + if (isNaN(sec)) { + sec = today.getSeconds(); + } + if (y != 0) { + return BI.getDate(y, m, d, hr, min, sec); + } + y = 0; + m = -1; + d = 0; + for (i = 0; i < a.length; ++i) { + if (a[i].search(/[a-zA-Z]+/) != -1) { + var t = -1; + for (j = 0; j < 12; ++j) { + if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { + t = j; + break; + } + } + if (t != -1) { + if (m != -1) { + d = m + 1; + } + m = t; + } + } else if (parseInt(a[i], 10) <= 12 && m == -1) { + m = a[i] - 1; + } else if (parseInt(a[i], 10) > 31 && y == 0) { + y = parseInt(a[i], 10); + (y < 100) && (y += (y > 29) ? 1900 : 2000); + } else if (d == 0) { + d = a[i]; } - return dt.getTime(); - } - }); -})(); + if (y == 0) { + y = today.getFullYear(); + } + if (m === -1) { + m = today.getMonth(); + } + if (m != -1 && d != 0) { + return BI.getDate(y, m, d, hr, min, sec); + } + return today; + }, + + getDate: function () { + var length = arguments.length; + var args = arguments; + var dt; + switch (length) { + // new Date() + case 0: + dt = new Date(); + break; + // new Date(long) + case 1: + dt = new Date(args[0]); + break; + // new Date(year, month) + case 2: + dt = new Date(args[0], args[1]); + break; + // new Date(year, month, day) + case 3: + dt = new Date(args[0], args[1], args[2]); + break; + // new Date(year, month, day, hour) + case 4: + dt = new Date(args[0], args[1], args[2], args[3]); + break; + // new Date(year, month, day, hour, minute) + case 5: + dt = new Date(args[0], args[1], args[2], args[3], args[4]); + break; + // new Date(year, month, day, hour, minute, second) + case 6: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); + break; + // new Date(year, month, day, hour, minute, second, millisecond) + case 7: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + break; + default: + dt = new Date(); + break; + } + if (BI.isNotNull(BI.timeZone) && (arguments.length === 0 || (arguments.length === 1 && BI.isNumber(arguments[0])))) { + var localTime = dt.getTime(); + // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 + var localOffset = dt.getTimezoneOffset() * 60000; // 获得当地时间偏移的毫秒数 + var utc = localTime + localOffset; // utc即GMT时间标准时区 + return new Date(utc + BI.timeZone);// + Pool.timeZone.offset); + } + return dt; + + }, + + getTime: function () { + var length = arguments.length; + var args = arguments; + var dt; + switch (length) { + // new Date() + case 0: + dt = new Date(); + break; + // new Date(long) + case 1: + dt = new Date(args[0]); + break; + // new Date(year, month) + case 2: + dt = new Date(args[0], args[1]); + break; + // new Date(year, month, day) + case 3: + dt = new Date(args[0], args[1], args[2]); + break; + // new Date(year, month, day, hour) + case 4: + dt = new Date(args[0], args[1], args[2], args[3]); + break; + // new Date(year, month, day, hour, minute) + case 5: + dt = new Date(args[0], args[1], args[2], args[3], args[4]); + break; + // new Date(year, month, day, hour, minute, second) + case 6: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); + break; + // new Date(year, month, day, hour, minute, second, millisecond) + case 7: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + break; + default: + dt = new Date(); + break; + } + if (BI.isNotNull(BI.timeZone)) { + // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 + return dt.getTime() - BI.timeZone - new Date().getTimezoneOffset() * 60000; + } + return dt.getTime(); + + } +}); + +// TODO: 暂时先直接export全部,下一步拆function +export default BI; \ No newline at end of file diff --git a/src/core/3.ob.js b/src/core/3.ob.js index 100fcac17..f6e9396de 100644 --- a/src/core/3.ob.js +++ b/src/core/3.ob.js @@ -1,220 +1,221 @@ -!(function () { - function extend() { - var target = arguments[0] || {}, length = arguments.length, i = 1, options, name, src, copy; - for (; i < length; i++) { - // Only deal with non-null/undefined values - if ((options = arguments[i]) != null) { - // Extend the base object - for (name in options) { - src = target[name]; - copy = options[name]; - - // Prevent never-ending loop - if (target === copy) { - continue; - } +import BI from "./2.base"; + +function extend() { + let target = arguments[0] || {}, length = arguments.length, i = 1, name, copy; + for (; i < length; i++) { + // Only deal with non-null/undefined values + const options = arguments[i]; + if (options !== null) { + // Extend the base object + for (name in options) { + copy = options[name]; + + // Prevent never-ending loop + if (target === copy) { + continue; + } - if (copy !== undefined) { - target[name] = copy; - } + + if (copy !== undefined) { + target[name] = copy; } } } - return target; } - /** - * 客户端观察者,主要处理事件的添加、删除、执行等 - * @class BI.OB - * @abstract - */ - var OB = function (config) { - this._constructor(config); - }; - BI._.extend(OB.prototype, { - props: {}, + return target; +} - init: null, +export default class OB { + // props = {}; - destroyed: null, + // init = null; - _constructor: function (config) { - this._initProps(config); - this._init(); - this._initRef(); - }, + // destroyed = null; - _defaultConfig: function (config) { - return {}; - }, + constructor(config) { + this._constructor(config); + } + + _constructor(config) { + this._initProps(config); + this._init(); + this._initRef(); + } - _initProps: function (config) { - var props = this.props; - if (BI.isFunction(this.props)) { - props = this.props(config); - } - var defaultProps = extend(this._defaultConfig(config), props); - var modifiedDefaultProps = (config && config.type && BI.OB.configFunctions[config.type + ".props"]) ? BI.reduce(BI.OB.configFunctions[config.type + ".props"], function (value, conf, index) { - return extend(conf, value.fn(defaultProps, config, value.opt)); - }, {}) : null; - this.options = extend(defaultProps, modifiedDefaultProps, config); - }, - - _init: function () { - this._initListeners(); - this.init && this.init(); - }, - - _initListeners: function () { - var self = this; - if (this.options.listeners != null) { - BI._.each(this.options.listeners, function (lis, eventName) { - if (BI._.isFunction(lis)) { - self.on(eventName, lis); - return; - } - if (BI._.isArray(lis)) { - BI._.each(lis, function (l) { - self.on(eventName, l); - }); - return; - } - (lis.target ? lis.target : self)[lis.once ? "once" : "on"](lis.eventName, BI._.bind(lis.action, self)); - }); - delete this.options.listeners; - } - }, + _defaultConfig(config) { + return {}; + } - // 获得一个当前对象的引用 - _initRef: function () { - var o = this.options; - if (o.__ref) { - BI.isFunction(o.__ref) ? o.__ref.call(this, this) : o.__ref.current = this; - } - if (o.ref) { - BI.isFunction(o.ref) ? o.ref.call(this, this) : o.ref.current = this; - } - }, - - //释放当前对象 - _purgeRef: function () { - var o = this.options; - if (o.__ref) { - BI.isFunction(o.__ref) ? o.__ref.call(null, null) : o.__ref.current = null; - o.__ref = null; - } - if (o.ref) { - BI.isFunction(o.ref) ? o.ref.call(null, null) : o.ref.current = null; - o.ref = null; - } - }, + _initProps(config) { + let props = this.props; + if (BI.isFunction(this.props)) { + props = this.props(config); + } + const defaultProps = extend(this._defaultConfig(config), props); + const modifiedDefaultProps = (config && config.type && OB.configFunctions[config.type + ".props"]) ? BI.reduce(OB.configFunctions[config.type + ".props"], function (value, conf, index) { + return extend(conf, value.fn(defaultProps, config, value.opt)); + }, {}) : null; + this.options = extend(defaultProps, modifiedDefaultProps, config); + } - _getEvents: function () { - if (!BI._.isObject(this.events)) { - this.events = {}; - } - return this.events; - }, - - /** - * 给观察者绑定一个事件 - * @param {String} eventName 事件的名字 - * @param {Function} fn 事件对应的执行函数 - */ - on: function (eventName, fn) { - var self = this; - eventName = eventName.toLowerCase(); - var fns = this._getEvents()[eventName]; - if (!BI._.isArray(fns)) { - fns = []; - this._getEvents()[eventName] = fns; - } - fns.push(fn); - - return function () { - self.un(eventName, fn); - }; - }, - - /** - * 给观察者绑定一个只执行一次的事件 - * @param {String} eventName 事件的名字 - * @param {Function} fn 事件对应的执行函数 - */ - once: function (eventName, fn) { - var proxy = function () { - fn.apply(this, arguments); - this.un(eventName, proxy); - }; - this.on(eventName, proxy); - }, - - /** - * 解除观察者绑定的指定事件 - * @param {String} eventName 要解除绑定事件的名字 - * @param {Function} fn 事件对应的执行函数,该参数是可选的,没有该参数时,将解除绑定所有同名字的事件 - */ - un: function (eventName, fn) { - eventName = eventName.toLowerCase(); - - /* alex:如果fn是null,就是把eventName上面所有方法都un掉*/ - if (fn == null) { - delete this._getEvents()[eventName]; - } else { - var fns = this._getEvents()[eventName]; - if (BI._.isArray(fns)) { - var newFns = []; - BI._.each(fns, function (ifn) { - if (ifn != fn) { - newFns.push(ifn); - } + _init() { + this._initListeners(); + this.init && this.init(); + } + + _initListeners() { + if (this.options.listeners !== null) { + BI._.each(this.options.listeners, (lis, eventName) => { + if (BI._.isFunction(lis)) { + this.on(eventName, lis); + + return; + } + if (BI._.isArray(lis)) { + BI._.each(lis, (l) => { + this.on(eventName, l); }); - this._getEvents()[eventName] = newFns; + + return; } - } - }, + (lis.target ? lis.target : this)[lis.once ? "once" : "on"](lis.eventName, BI._.bind(lis.action, this)); + }); + delete this.options.listeners; + } + } + + // 获得一个当前对象的引用 + _initRef() { + const o = this.options; + if (o.__ref) { + BI.isFunction(o.__ref) ? o.__ref.call(this, this) : o.__ref.current = this; + } + if (o.ref) { + BI.isFunction(o.ref) ? o.ref.call(this, this) : o.ref.current = this; + } + } + + // 释放当前对象 + _purgeRef() { + const o = this.options; + if (o.__ref) { + BI.isFunction(o.__ref) ? o.__ref.call(null, null) : o.__ref.current = null; + o.__ref = null; + } + if (o.ref) { + BI.isFunction(o.ref) ? o.ref.call(null, null) : o.ref.current = null; + o.ref = null; + } + } - /** - * 清除观察者的所有事件绑定 - */ - purgeListeners: function () { - /* alex:清空events*/ + _getEvents() { + if (!BI._.isObject(this.events)) { this.events = {}; - }, - - /** - * 触发绑定过的事件 - * - * @param {String} eventName 要触发的事件的名字 - * @returns {Boolean} 如果事件函数返回false,则返回false并中断其他同名事件的执行,否则执行所有的同名事件并返回true - */ - fireEvent: function () { - var eventName = arguments[0].toLowerCase(); - var fns = this._getEvents()[eventName]; - if (BI.isArray(fns)) { - if (BI.isArguments(arguments[1])) { - for (var i = 0; i < fns.length; i++) { - if (fns[i].apply(this, arguments[1]) === false) { - return false; - } + } + + return this.events; + } + + /** + * 给观察者绑定一个事件 + * @param {String} eventName 事件的名字 + * @param {Function} fn 事件对应的执行函数 + */ + on(eventName, fn) { + eventName = eventName.toLowerCase(); + let fns = this._getEvents()[eventName]; + if (!BI._.isArray(fns)) { + fns = []; + this._getEvents()[eventName] = fns; + } + fns.push(fn); + + return () => this.un(eventName, fn); + } + + /** + * 给观察者绑定一个只执行一次的事件 + * @param {String} eventName 事件的名字 + * @param {Function} fn 事件对应的执行函数 + */ + once(eventName, fn) { + const proxy = () => { + fn.apply(this, arguments); + this.un(eventName, proxy); + }; + this.on(eventName, proxy); + } + + /** + * 解除观察者绑定的指定事件 + * @param {String} eventName 要解除绑定事件的名字 + * @param {Function} fn 事件对应的执行函数,该参数是可选的,没有该参数时,将解除绑定所有同名字的事件 + */ + un(eventName, fn) { + eventName = eventName.toLowerCase(); + + /* alex:如果fn是null,就是把eventName上面所有方法都un掉*/ + if (fn === null) { + delete this._getEvents()[eventName]; + } else { + const fns = this._getEvents()[eventName]; + if (BI._.isArray(fns)) { + const newFns = []; + BI._.each(fns, function (ifn) { + if (ifn !== fn) { + newFns.push(ifn); + } + }); + this._getEvents()[eventName] = newFns; + } + } + } + + /** + * 清除观察者的所有事件绑定 + */ + purgeListeners() { + /* alex:清空events*/ + this.events = {}; + } + + /** + * 触发绑定过的事件 + * + * @param {String} eventName 要触发的事件的名字 + * @returns {Boolean} 如果事件函数返回false,则返回false并中断其他同名事件的执行,否则执行所有的同名事件并返回true + */ + fireEvent() { + const eventName = arguments[0].toLowerCase(); + const fns = this._getEvents()[eventName]; + if (BI.isArray(fns)) { + if (BI.isArguments(arguments[1])) { + for (let i = 0; i < fns.length; i++) { + if (fns[i].apply(this, arguments[1]) === false) { + return false; } - } else { - var args = Array.prototype.slice.call(arguments, 1); - for (var i = 0; i < fns.length; i++) { - if (fns[i].apply(this, args) === false) { - return false; - } + } + } else { + const args = Array.prototype.slice.call(arguments, 1); + for (let i = 0; i < fns.length; i++) { + if (fns[i].apply(this, args) === false) { + return false; } } } - return true; - }, - - destroy: function () { - this.destroyed && this.destroyed(); - this._purgeRef(); - this.purgeListeners(); } - }); - BI.OB = BI.OB || OB; -})(); + + return true; + } + + destroy() { + this.destroyed && this.destroyed(); + this._purgeRef(); + this.purgeListeners(); + } +} + +// BI.OB = BI.OB || OB; + +BI.extend(BI, { OB }); diff --git a/src/core/4.widget.js b/src/core/4.widget.js index e541191df..1e6c4b746 100644 --- a/src/core/4.widget.js +++ b/src/core/4.widget.js @@ -6,1078 +6,1075 @@ * @cfg {JSON} options 配置属性 */ -!(function () { - var cancelAnimationFrame = - _global.cancelAnimationFrame || - _global.webkitCancelAnimationFrame || - _global.mozCancelAnimationFrame || - _global.oCancelAnimationFrame || - _global.msCancelAnimationFrame || - _global.clearTimeout; - - var requestAnimationFrame = _global.requestAnimationFrame || _global.webkitRequestAnimationFrame || _global.mozRequestAnimationFrame || _global.oRequestAnimationFrame || _global.msRequestAnimationFrame || _global.setTimeout; - - function callLifeHook(self, life) { - var hooks = [], hook; - hook = self[life]; - if (hook) { - hooks = hooks.concat(BI.isArray(hook) ? hook : [hook]); - } - hook = self.options[life]; - if (hook) { - hooks = hooks.concat(BI.isArray(hook) ? hook : [hook]); - } - BI.each(hooks, function (i, hook) { - hook.call(self); +import BI from "./2.base"; +import OB from "./3.ob"; + +const cancelAnimationFrame = + _global.cancelAnimationFrame || + _global.webkitCancelAnimationFrame || + _global.mozCancelAnimationFrame || + _global.oCancelAnimationFrame || + _global.msCancelAnimationFrame || + _global.clearTimeout; + +const requestAnimationFrame = _global.requestAnimationFrame || _global.webkitRequestAnimationFrame || _global.mozRequestAnimationFrame || _global.oRequestAnimationFrame || _global.msRequestAnimationFrame || _global.setTimeout; + +function callLifeHook(self, life) { + let hooks = [], hook; + hook = self[life]; + if (hook) { + hooks = hooks.concat(BI.isArray(hook) ? hook : [hook]); + } + hook = self.options[life]; + if (hook) { + hooks = hooks.concat(BI.isArray(hook) ? hook : [hook]); + } + BI.each(hooks, function (i, hook) { + hook.call(self); + }); +} + +export default class Widget extends OB { + _defaultConfig () { + return BI.extend(super._defaultConfig(), { + root: false, + tagName: "div", + attributes: null, + data: null, + key: null, + + tag: null, + disabled: false, + invisible: false, + animation: "", + animationDuring: 0, + invalid: false, + baseCls: "", + extraCls: "", + cls: "", + css: null + + // vdom: false }); } - BI.Widget = BI.Widget || BI.inherit(BI.OB, { - _defaultConfig: function () { - return BI.extend(BI.Widget.superclass._defaultConfig.apply(this), { - root: false, - tagName: "div", - attributes: null, - data: null, - key: null, - - tag: null, - disabled: false, - invisible: false, - animation: "", - animationDuring: 0, - invalid: false, - baseCls: "", - extraCls: "", - cls: "", - css: null - - // vdom: false - }); - }, + _constructor () { - _constructor: function () { - - }, + } - // 覆盖父类的_constructor方法,widget不走ob的生命周期 - _constructed: function () { - if (this.setup) { - pushTarget(this); - var delegate = this.setup(this.options); - if (BI.isPlainObject(delegate)) { - // 如果setup返回一个json,即对外暴露的方法 - BI.extend(this, delegate); - } else { - this.render = delegate; - } - popTarget(); + // 覆盖父类的_constructor方法,widget不走ob的生命周期 + _constructed () { + if (this.setup) { + pushTarget(this); + const delegate = this.setup(this.options); + if (BI.isPlainObject(delegate)) { + // 如果setup返回一个json,即对外暴露的方法 + BI.extend(this, delegate); + } else { + this.render = delegate; } - }, + popTarget(); + } + } - _lazyConstructor: function () { - if (!this.__constructed) { - this.__constructed = true; - this._init(); - this._initRef(); - } - }, + _lazyConstructor () { + if (!this.__constructed) { + this.__constructed = true; + this._init(); + this._initRef(); + } + } - // 生命周期函数 - beforeInit: null, + // // 生命周期函数 + // beforeInit = null; - beforeRender: null, + // beforeRender = null; - beforeCreate: null, + // beforeCreate = null - created: null, + // created = null - render: null, + // render = null - beforeMount: null, + // beforeMount = null - mounted: null, - // 不想重写mounted时用 - _mounted: null, + // mounted = null + // // 不想重写mounted时用 + // _mounted = null - shouldUpdate: null, + // shouldUpdate = null - update: null, + // update = null - beforeUpdate: null, + // beforeUpdate = null - updated: null, + // updated = null - beforeDestroy: null, + // beforeDestroy = null - destroyed: null, - // 不想重写destroyed时用 - _destroyed: null, + // destroyed = null + // // 不想重写destroyed时用 + // _destroyed = null + + _init() { + super._init(...arguments); + this._initVisual(); + this._initState(); + this._initRender(); + } - _init: function () { - BI.Widget.superclass._init.apply(this, arguments); - this._initVisual(); - this._initState(); - this._initRender(); - }, + _initRender() { + let initCallbackCalled = false; + let renderCallbackCalled = false; - _initRender: function () { - var self = this; - var initCallbackCalled = false; - var renderCallbackCalled = false; + const init = () => { + // 加个保险 + if (initCallbackCalled === true) { + _global.console && console.error("组件: 请检查beforeInit内部的写法,callback只能执行一次"); + return; + } + initCallbackCalled = true; - function init() { + const render = () => { // 加个保险 - if (initCallbackCalled === true) { - _global.console && console.error("组件: 请检查beforeInit内部的写法,callback只能执行一次"); + if (renderCallbackCalled === true) { + _global.console && console.error("组件: 请检查beforeRender内部的写法,callback只能执行一次"); return; } - initCallbackCalled = true; - - function render() { - // 加个保险 - if (renderCallbackCalled === true) { - _global.console && console.error("组件: 请检查beforeRender内部的写法,callback只能执行一次"); - return; - } - renderCallbackCalled = true; - self._render(); - self.__afterRender(); - } - - if (self.options.beforeRender || self.beforeRender) { - self.__async = true; - var beforeRenderResult = (self.options.beforeRender || self.beforeRender).call(self, render); - if (beforeRenderResult instanceof Promise) { - beforeRenderResult.then(render).catch(function (e) { - _global.console && console.error(e); - render(); - }); - } - } else { - self._render(); - self.__afterRender(); - } + renderCallbackCalled = true; + this._render(); + this.__afterRender(); } - if (this.options.beforeInit || this.beforeInit) { - this.__asking = true; - var beforeInitResult = (this.options.beforeInit || this.beforeInit).call(this, init); - if (beforeInitResult instanceof Promise) { - beforeInitResult.then(init).catch(function (e) { + if (this.options.beforeRender || this.beforeRender) { + this.__async = true; + const beforeRenderResult = (this.options.beforeRender || this.beforeRender).call(this, render); + if (beforeRenderResult instanceof Promise) { + beforeRenderResult.then(render).catch(function (e) { _global.console && console.error(e); - init(); + render(); }); } } else { - init(); + this._render(); + this.__afterRender(); } - }, + } - __afterRender: function () { - pushTarget(this); - var async = this.__async; - this.__async = false; - if (async && this._isMounted) { - callLifeHook(this, "beforeMount"); - this._mount(); - callLifeHook(this, "mounted"); - this.fireEvent(BI.Events.MOUNT); - } else { - this._mount(); + if (this.options.beforeInit || this.beforeInit) { + this.__asking = true; + const beforeInitResult = (this.options.beforeInit || this.beforeInit).call(this, init); + if (beforeInitResult instanceof Promise) { + beforeInitResult.then(init).catch(function (e) { + _global.console && console.error(e); + init(); + }); } - popTarget(); - }, + } else { + init(); + } + } - _render: function () { - this.__asking = false; - pushTarget(this); - callLifeHook(this, "beforeCreate"); - this._initElement(); - this._initEffects(); - callLifeHook(this, "created"); - popTarget(); - }, - - _initCurrent: function () { - var self = this, o = this.options; - this._initElementWidth(); - this._initElementHeight(); - if (o._baseCls || o.baseCls || o.extraCls) { - this.element.addClass((o._baseCls || "") + " " + (o.baseCls || "") + " " + (o.extraCls || "")); - } - if (o.cls) { - if (BI.isFunction(o.cls)) { - var cls = this.__watch(o.cls, function (context, newValue) { - self.element.removeClass(cls).addClass(cls = newValue); - }); - this.element.addClass(cls); - } else { - this.element.addClass(o.cls); - } - } - // if (o.key != null) { - // this.element.attr("key", o.key); - // } - if (o.attributes) { - this.element.attr(o.attributes); - } - if (o.data) { - this.element.data(o.data); - } - if (o.css) { - if (BI.isFunction(o.css)) { - var css = this.__watch(o.css, function (context, newValue) { - for (var k in css) { - if (BI.isNull(newValue[k])) { - newValue[k] = ""; - } - } - self.element.css(css = newValue); - }); - this.element.css(css); - } else { - this.element.css(o.css); - } - } - }, - - __watch: function (getter, handler, options) { - var self = this; - if (_global.Fix) { - this._watchers = this._watchers || []; - var watcher = new Fix.Watcher(null, function () { - return getter.call(self, self); - }, (handler && function (v) { - handler.call(self, self, v); - }) || BI.emptyFn, BI.extend({ deep: true }, options)); - this._watchers.push(function unwatchFn() { - watcher.teardown(); + __afterRender() { + pushTarget(this); + const async = this.__async; + this.__async = false; + if (async && this._isMounted) { + callLifeHook(this, "beforeMount"); + this._mount(); + callLifeHook(this, "mounted"); + this.fireEvent(BI.Events.MOUNT); + } else { + this._mount(); + } + popTarget(); + } + + _render() { + this.__asking = false; + pushTarget(this); + callLifeHook(this, "beforeCreate"); + this._initElement(); + this._initEffects(); + callLifeHook(this, "created"); + popTarget(); + } + + _initCurrent() { + const o = this.options; + this._initElementWidth(); + this._initElementHeight(); + if (o._baseCls || o.baseCls || o.extraCls) { + this.element.addClass((o._baseCls || "") + " " + (o.baseCls || "") + " " + (o.extraCls || "")); + } + if (o.cls) { + if (BI.isFunction(o.cls)) { + const cls = this.__watch(o.cls, (context, newValue) => { + this.element.removeClass(cls).addClass(cls = newValue); }); - return watcher.value; + this.element.addClass(cls); } else { - return getter(); + this.element.addClass(o.cls); } - }, - - /** - * 初始化根节点 - * @private - */ - _initRoot: function () { - var o = this.options; - this.widgetName = o.widgetName || BI.uniqueId("widget"); - this._isRoot = o.root; - this._children = {}; - if (BI.isWidget(o.element)) { - this.element = this.options.element.element; - this._parent = o.element; - this._parent.addWidget(this.widgetName, this); - } else if (o.element) { - this.element = BI.Widget._renderEngine.createElement(this); - this._isRoot = true; + } + // if (o.key != null) { + // this.element.attr("key", o.key); + // } + if (o.attributes) { + this.element.attr(o.attributes); + } + if (o.data) { + this.element.data(o.data); + } + if (o.css) { + if (BI.isFunction(o.css)) { + const css = this.__watch(o.css, (context, newValue) => { + for (const k in css) { + if (BI.isNull(newValue[k])) { + newValue[k] = ""; + } + } + this.element.css(css = newValue); + }); + this.element.css(css); } else { - this.element = BI.Widget._renderEngine.createElement(this); - } - this.element._isWidget = true; - // var widgets = this.element.data("__widgets") || []; - // widgets.push(this); - // this.element.data("__widgets", widgets); - this._initCurrent(); - }, - - _initElementWidth: function () { - var o = this.options; - if (BI.isWidthOrHeight(o.width)) { - this.element.css("width", BI.pixFormat(o.width)); + this.element.css(o.css); } - }, + } + } + + __watch(getter, handler, options) { + if (_global.Fix) { + this._watchers = this._watchers || []; + const watcher = new Fix.Watcher(null, () => { + return getter.call(this, this); + }, (handler && ((v) => { + handler.call(this, this, v); + })) || BI.emptyFn, BI.extend({ deep: true }, options)); + this._watchers.push(() => { + watcher.teardown(); + }); + return watcher.value; + } else { + return getter(); + } + } + + /** + * 初始化根节点 + * @private + */ + _initRoot() { + const o = this.options; + this.widgetName = o.widgetName || BI.uniqueId("widget"); + this._isRoot = o.root; + this._children = {}; + if (BI.isWidget(o.element)) { + this.element = this.options.element.element; + this._parent = o.element; + this._parent._children && this._parent.addWidget(this.widgetName, this); + } else if (o.element) { + this.element = BI.Widget._renderEngine.createElement(this); + this._isRoot = true; + } else { + this.element = BI.Widget._renderEngine.createElement(this); + } + this.element._isWidget = true; + // const widgets = this.element.data("__widgets") || []; + // widgets.push(this); + // this.element.data("__widgets", widgets); + this._initCurrent(); + } + + _initElementWidth() { + const o = this.options; + if (BI.isWidthOrHeight(o.width)) { + this.element.css("width", BI.pixFormat(o.width)); + } + } - _initElementHeight: function () { - var o = this.options; - if (BI.isWidthOrHeight(o.height)) { - this.element.css("height", BI.pixFormat(o.height)); + _initElementHeight() { + const o = this.options; + if (BI.isWidthOrHeight(o.height)) { + this.element.css("height", BI.pixFormat(o.height)); + } + } + + _initVisual() { + const o = this.options; + if (o.invisible) { + const invisible = o.invisible = BI.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); } - }, - - _initVisual: function () { - var self = this, o = this.options; - if (o.invisible) { - var invisible = o.invisible = BI.isFunction(o.invisible) ? this.__watch(o.invisible, function (context, newValue) { - self.setVisible(!newValue); - }) : o.invisible; - if (invisible) { - // 用display属性做显示和隐藏,否则jquery会在显示时将display设为block会覆盖掉display:flex属性 - this.__setElementVisible(false); + } + } + + _initEffects() { + const o = this.options; + if (o.disabled || o.invalid) { + if (this.options.disabled) { + const disabled = o.disabled = BI.isFunction(o.disabled) ? this.__watch(o.disabled, (context, newValue) => { + this.setEnable(!newValue); + }) : o.disabled; + if (disabled) { + this.setEnable(false); } } - }, - - _initEffects: function () { - var self = this, o = this.options; - if (o.disabled || o.invalid) { - if (this.options.disabled) { - var disabled = o.disabled = BI.isFunction(o.disabled) ? this.__watch(o.disabled, function (context, newValue) { - self.setEnable(!newValue); - }) : o.disabled; - if (disabled) { - this.setEnable(false); - } - } - if (this.options.invalid) { - var invalid = o.invalid = BI.isFunction(o.invalid) ? this.__watch(o.invalid, function (context, newValue) { - self.setValid(!newValue); - }) : o.invalid; - if (invalid) { - this.setValid(false); - } + if (this.options.invalid) { + const invalid = o.invalid = BI.isFunction(o.invalid) ? this.__watch(o.invalid, (context, newValue) => { + this.setValid(!newValue); + }) : o.invalid; + if (invalid) { + this.setValid(false); } } - if (o.effect) { - if (BI.isArray(o.effect)) { - if (BI.isArray(o.effect[0])) { - BI.each(o.effect, function (i, effect) { - self.__watch(effect[0], effect[1]); - }); - } else { - self.__watch(o.effect[0], o.effect[1]); - } + } + if (o.effect) { + if (BI.isArray(o.effect)) { + if (BI.isArray(o.effect[0])) { + BI.each(o.effect, (i, effect) => { + this.__watch(effect[0], effect[1]); + }); } else { - this.__watch(o.effect); - } - } - }, - - _initState: function () { - this._isMounted = false; - this._isDestroyed = false; - }, - - __initWatch: function () { - // initWatch拦截的方法 - }, - - _initElement: function () { - var self = this; - this.__isMounting = true; - // 当开启worker模式时,可以通过$render来实现另一种效果 - var workerMode = BI.Providers.getProvider("bi.provider.system").getWorkerMode(); - var render = BI.isFunction(this.options.render) ? this.options.render : (workerMode ? (this.$render || this.render) : this.render); - var els = render && render.call(this); - els = this.options.configRender ? this.options.configRender.call(this, els) : els; - els = BI.Plugin.getRender(this.options.type, els); - if (BI.isPlainObject(els)) { - els = [els]; - } - this.__initWatch(); - if (BI.isArray(els)) { - BI.each(els, function (i, el) { - if (el) { - BI._lazyCreateWidget(el, { - element: self - }); - } - }); - } - }, - - _setParent: function (parent) { - this._parent = parent; - }, - - /** - * - * @param force 是否强制挂载子节点 - * @param deep 子节点是否也是按照当前force处理 - * @param lifeHook 生命周期钩子触不触发,默认触发 - * @param predicate 递归每个widget的回调 - * @param layer 组件层级 - * @returns {boolean} - * @private - */ - _mount: function (force, deep, lifeHook, predicate, layer) { - var self = this; - 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"); - this._isMounted = true; - this.__isMounting = false; - for (var key in this._children) { - var child = this._children[key]; - child._mount && child._mount(deep ? force : false, deep, lifeHook, predicate, layer + 1); - } - if (this._parent) { - if (!this._parent.isEnabled()) { - this._setEnable(false); - } - if (!this._parent.isValid()) { - this._setValid(false); - } - } - this._mountChildren && this._mountChildren(); - if (layer === 0) { - // mounted里面会执行scrollTo之类的方法,如果放宏任务里会闪 - // setTimeout(function () { - self.__afterMount(lifeHook, predicate); - // }, 0); - } - return true; - }, - - __afterMount: function (lifeHook, predicate) { - if (this._isMounted) { - for (var key in this._children) { - var child = this._children[key]; - child.__afterMount && child.__afterMount(lifeHook, predicate); - } - if (lifeHook !== false && !this.__async) { - callLifeHook(this, "_mounted"); - callLifeHook(this, "mounted"); - this.fireEvent(BI.Events.MOUNT); + this.__watch(o.effect[0], o.effect[1]); } - predicate && predicate(this); + } else { + this.__watch(o.effect); } - }, + } + } - _mountChildren: null, + _initState() { + this._isMounted = false; + this._isDestroyed = false; + } - _update: function (nextProps, shouldUpdate) { - callLifeHook(this, "beforeUpdate"); - if (shouldUpdate) { - var res = this.update && this.update(nextProps, shouldUpdate); - } - callLifeHook(this, "updated"); - return res; - }, - - isMounted: function () { - return this._isMounted; - }, - - isDestroyed: function () { - return this._isDestroyed; - }, - - setWidth: function (w) { - this.options.width = w; - this._initElementWidth(); - }, - - setHeight: function (h) { - this.options.height = h; - this._initElementHeight(); - }, - - _setEnable: function (enable) { - if (enable === true) { - this.options._disabled = false; - } else if (enable === false) { - this.options._disabled = true; - } - // 递归将所有子组件使能 - BI.each(this._children, function (i, child) { - !child._manualSetEnable && child._setEnable && child._setEnable(enable); + __initWatch() { + // initWatch拦截的方法 + } + + _initElement() { + this.__isMounting = true; + // 当开启worker模式时,可以通过$render来实现另一种效果 + const workerMode = BI.Providers.getProvider("bi.provider.system").getWorkerMode(); + const render = BI.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 = BI.Plugin.getRender(this.options.type, els); + if (BI.isPlainObject(els)) { + els = [els]; + } + this.__initWatch(); + if (BI.isArray(els)) { + BI.each(els, (i, el) => { + if (el) { + BI._lazyCreateWidget(el, { + element: this + }); + } }); - }, + } + } + + _setParent(parent) { + this._parent = parent; + } - _setValid: function (valid) { - if (valid === true) { - this.options._invalid = false; - } else if (valid === false) { - this.options._invalid = true; + /** + * + * @param force 是否强制挂载子节点 + * @param deep 子节点是否也是按照当前force处理 + * @param lifeHook 生命周期钩子触不触发,默认触发 + * @param predicate 递归每个widget的回调 + * @param layer 组件层级 + * @returns {boolean} + * @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)))) { + return false; + } + layer = layer || 0; + 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); + } + if (this._parent) { + if (!this._parent.isEnabled()) { + this._setEnable(false); } - // 递归将所有子组件使有效 - BI.each(this._children, function (i, child) { - !child._manualSetValid && child._setValid && child._setValid(valid); - }); - }, + if (!this._parent.isValid()) { + this._setValid(false); + } + } + this._mountChildren && this._mountChildren(); + if (layer === 0) { + // mounted里面会执行scrollTo之类的方法,如果放宏任务里会闪 + // setTimeout(function () { + this.__afterMount(lifeHook, predicate); + // }, 0); + } + return true; + } - _setVisible: function (visible) { - if (visible === true) { - this.options.invisible = false; - } else if (visible === false) { - this.options.invisible = true; + __afterMount(lifeHook, predicate) { + if (this._isMounted) { + for (const key in this._children) { + const child = this._children[key]; + child.__afterMount && child.__afterMount(lifeHook, predicate); } - }, - - setEnable: function (enable) { - this._manualSetEnable = true; - this.options.disabled = !enable; - this._setEnable(enable); - if (enable === true) { - this.element.removeClass("base-disabled disabled"); - } else if (enable === false) { - this.element.addClass("base-disabled disabled"); + if (lifeHook !== false && !this.__async) { + callLifeHook(this, "_mounted"); + callLifeHook(this, "mounted"); + this.fireEvent(BI.Events.MOUNT); } - }, - - __setElementVisible: function (visible) { - this.element.css("display", visible ? "" : "none"); - }, - - _innerSetVisible: function (visible) { - var self = this, o = this.options; - var lastVisible = !o.invisible; - this._setVisible(visible); - if (visible === true) { - // 用this.element.show()会把display属性改成block - this.__setElementVisible(true); - this._mount(); - if (o.animation && !lastVisible) { - this.element.removeClass(o.animation + "-leave").removeClass(o.animation + "-leave-active").addClass(o.animation + "-enter"); - if (this._requestAnimationFrame) { - cancelAnimationFrame(this._requestAnimationFrame); - } - this._requestAnimationFrame = function () { - self.element.addClass(o.animation + "-enter-active"); - }; - requestAnimationFrame(this._requestAnimationFrame); - if (this._animationDuring) { - clearTimeout(this._animationDuring); - } - this._animationDuring = setTimeout(function () { - self.element.removeClass(o.animation + "-enter").removeClass(o.animation + "-enter-active"); - }, o.animationDuring); + predicate && predicate(this); + } + } + + // _mountChildren = null; + + _update(nextProps, shouldUpdate) { + callLifeHook(this, "beforeUpdate"); + if (shouldUpdate) { + const res = this.update && this.update(nextProps, shouldUpdate); + } + callLifeHook(this, "updated"); + return res; + } + + isMounted() { + return this._isMounted; + } + + isDestroyed() { + return this._isDestroyed; + } + + setWidth(w) { + this.options.width = w; + this._initElementWidth(); + } + + setHeight(h) { + this.options.height = h; + this._initElementHeight(); + } + + _setEnable(enable) { + if (enable === true) { + this.options._disabled = false; + } else if (enable === false) { + this.options._disabled = true; + } + // 递归将所有子组件使能 + BI.each(this._children, function (i, child) { + !child._manualSetEnable && child._setEnable && child._setEnable(enable); + }); + } + + _setValid(valid) { + if (valid === true) { + this.options._invalid = false; + } else if (valid === false) { + this.options._invalid = true; + } + // 递归将所有子组件使有效 + BI.each(this._children, function (i, child) { + !child._manualSetValid && child._setValid && child._setValid(valid); + }); + } + + _setVisible(visible) { + if (visible === true) { + this.options.invisible = false; + } else if (visible === false) { + this.options.invisible = true; + } + } + + setEnable(enable) { + this._manualSetEnable = true; + this.options.disabled = !enable; + this._setEnable(enable); + if (enable === true) { + this.element.removeClass("base-disabled disabled"); + } else if (enable === false) { + this.element.addClass("base-disabled disabled"); + } + } + + __setElementVisible(visible) { + this.element.css("display", visible ? "" : "none"); + } + + _innerSetVisible(visible) { + const o = this.options; + const lastVisible = !o.invisible; + this._setVisible(visible); + if (visible === true) { + // 用this.element.show()会把display属性改成block + this.__setElementVisible(true); + this._mount(); + if (o.animation && !lastVisible) { + this.element.removeClass(o.animation + "-leave").removeClass(o.animation + "-leave-active").addClass(o.animation + "-enter"); + if (this._requestAnimationFrame) { + cancelAnimationFrame(this._requestAnimationFrame); } - } else if (visible === false) { - if (o.animation && lastVisible) { - this.element.removeClass(o.animation + "-enter").removeClass(o.animation + "-enter-active").addClass(o.animation + "-leave"); - if (this._requestAnimationFrame) { - cancelAnimationFrame(this._requestAnimationFrame); - } - this._requestAnimationFrame = function () { - self.element.addClass(o.animation + "-leave-active"); - }; - requestAnimationFrame(this._requestAnimationFrame); - if (this._animationDuring) { - clearTimeout(this._animationDuring); - } - this._animationDuring = setTimeout(function () { - self.element.removeClass(o.animation + "-leave").removeClass(o.animation + "-leave-active"); - self.__setElementVisible(false); - }, o.animationDuring); - } else { - this.__setElementVisible(false); + this._requestAnimationFrame = () => { + this.element.addClass(o.animation + "-enter-active"); + }; + requestAnimationFrame(this._requestAnimationFrame); + if (this._animationDuring) { + clearTimeout(this._animationDuring); } + this._animationDuring = setTimeout(() => { + this.element.removeClass(o.animation + "-enter").removeClass(o.animation + "-enter-active"); + }, o.animationDuring); } - }, - - setVisible: function (visible) { - this._innerSetVisible(visible); - this.fireEvent(BI.Events.VIEW, visible); - }, - - setValid: function (valid) { - this._manualSetValid = true; - this.options.invalid = !valid; - this._setValid(valid); - if (valid === true) { - this.element.removeClass("base-invalid invalid"); - } else if (valid === false) { - this.element.addClass("base-invalid invalid"); + } else if (visible === false) { + if (o.animation && lastVisible) { + this.element.removeClass(o.animation + "-enter").removeClass(o.animation + "-enter-active").addClass(o.animation + "-leave"); + if (this._requestAnimationFrame) { + cancelAnimationFrame(this._requestAnimationFrame); + } + this._requestAnimationFrame = () => { + this.element.addClass(o.animation + "-leave-active"); + }; + requestAnimationFrame(this._requestAnimationFrame); + if (this._animationDuring) { + clearTimeout(this._animationDuring); + } + this._animationDuring = setTimeout(() => { + this.element.removeClass(o.animation + "-leave").removeClass(o.animation + "-leave-active"); + this.__setElementVisible(false); + }, o.animationDuring); + } else { + this.__setElementVisible(false); } - }, + } + } - doBehavior: function () { - var args = arguments; - // 递归将所有子组件使有效 - BI.each(this._children, function (i, child) { - child.doBehavior && child.doBehavior.apply(child, args); - }); - }, + setVisible(visible) { + this._innerSetVisible(visible); + this.fireEvent(BI.Events.VIEW, visible); + } - getWidth: function () { - return this.options.width; - }, + setValid(valid) { + this._manualSetValid = true; + this.options.invalid = !valid; + this._setValid(valid); + if (valid === true) { + this.element.removeClass("base-invalid invalid"); + } else if (valid === false) { + this.element.addClass("base-invalid invalid"); + } + } - getHeight: function () { - return this.options.height; - }, + doBehavior() { + const args = arguments; + // 递归将所有子组件使有效 + BI.each(this._children, function (i, child) { + child.doBehavior && child.doBehavior.apply(child, args); + }); + } - addWidget: function (name, widget) { - var self = this; - if (name instanceof BI.Widget) { - widget = name; - name = widget.getName(); - } - if (BI.isKey(name)) { - name = name + ""; - } - name = name || widget.getName() || BI.uniqueId("widget"); - if (this._children[name]) { - throw new Error("组件:组件名已存在,不能进行添加"); - } - widget._setParent && widget._setParent(this); - widget.on(BI.Events.DESTROY, function () { - BI.remove(self._children, this); - }); - return (this._children[name] = widget); - }, + getWidth() { + return this.options.width; + } - getWidgetByName: function (name) { - if (!BI.isKey(name) || name === this.getName()) { - return this; - } + getHeight() { + return this.options.height; + } + + addWidget(name, widget) { + const self = this; + if (name instanceof BI.Widget) { + widget = name; + name = widget.getName(); + } + if (BI.isKey(name)) { name = name + ""; - var widget = void 0, other = {}; - BI.any(this._children, function (i, wi) { - if (i === name) { - widget = wi; - return true; - } - other[i] = wi; - }); - if (!widget) { - BI.any(other, function (i, wi) { - return (widget = wi.getWidgetByName(i)); - }); - } - return widget; - }, + } + name = name || widget.getName() || BI.uniqueId("widget"); + if (this._children[name]) { + throw new Error("组件:组件名已存在,不能进行添加"); + } + widget._setParent && widget._setParent(this); + widget.on(BI.Events.DESTROY, function () { + // TODO: self待删 + BI.remove(self._children, this); + }); + return (this._children[name] = widget); + } - removeWidget: function (nameOrWidget) { - if (BI.isWidget(nameOrWidget)) { - BI.remove(this._children, nameOrWidget); - } else { - delete this._children[nameOrWidget]; + getWidgetByName(name) { + if (!BI.isKey(name) || name === this.getName()) { + return this; + } + name = name + ""; + let widget = void 0, other = {}; + BI.any(this._children, function (i, wi) { + if (i === name) { + widget = wi; + return true; } - }, + other[i] = wi; + }); + if (!widget) { + BI.any(other, function (i, wi) { + return (widget = wi.getWidgetByName(i)); + }); + } + return widget; + } - hasWidget: function (name) { - return this._children[name] != null; - }, + removeWidget(nameOrWidget) { + if (BI.isWidget(nameOrWidget)) { + BI.remove(this._children, nameOrWidget); + } else { + delete this._children[nameOrWidget]; + } + } - getName: function () { - return this.widgetName; - }, + hasWidget(name) { + return this._children[name] != null; + } - setTag: function (tag) { - this.options.tag = tag; - }, + getName() { + return this.widgetName; + } - getTag: function () { - return this.options.tag; - }, + setTag(tag) { + this.options.tag = tag; + } - attr: function (key, value) { - var self = this; - if (BI.isPlainObject(key)) { - BI.each(key, function (k, v) { - self.attr(k, v); - }); - return; - } - if (BI.isNotNull(value)) { - return this.options[key] = value; - } - return this.options[key]; - }, + getTag() { + return this.options.tag; + } - css: function (name, value) { - return this.element.css(name, value); - }, + attr(key, value) { + if (BI.isPlainObject(key)) { + BI.each(key, (k, v) => this.attr(k, v)); + return; + } + if (BI.isNotNull(value)) { + return this.options[key] = value; + } + return this.options[key]; + } - getText: function () { + css(name, value) { + return this.element.css(name, value); + } - }, + getText() { - setText: function (text) { + } - }, + setText(text) { - getValue: function () { + } - }, + getValue() { - setValue: function (value) { + } - }, + setValue(value) { - isEnabled: function () { - return this.options.disabled === true ? false : !this.options._disabled; - }, + } - isValid: function () { - return this.options.invalid === true ? false : !this.options._invalid; - }, + isEnabled() { + return this.options.disabled === true ? false : !this.options._disabled; + } - isVisible: function () { - return !this.options.invisible; - }, + isValid() { + return this.options.invalid === true ? false : !this.options._invalid; + } - disable: function () { - this.setEnable(false); - }, + isVisible() { + return !this.options.invisible; + } - enable: function () { - this.setEnable(true); - }, + disable() { + this.setEnable(false); + } - valid: function () { - this.setValid(true); - }, + enable() { + this.setEnable(true); + } - invalid: function () { - this.setValid(false); - }, + valid() { + this.setValid(true); + } - invisible: function () { - this.setVisible(false); - }, + invalid() { + this.setValid(false); + } - visible: function () { - this.setVisible(true); - }, + invisible() { + this.setVisible(false); + } - __d: function () { - BI.each(this._children, function (i, widget) { - widget && widget._unMount && widget._unMount(); - }); - this._children = {}; - }, - - // 主要是因为_destroy已经提供了protected方法 - __destroy: function () { - callLifeHook(this, "beforeDestroy"); - this.beforeDestroy = null; - this.__d(); - this._parent = null; - this._isMounted = false; - callLifeHook(this, "_destroyed"); - callLifeHook(this, "destroyed"); - this.destroyed = null; - this._isDestroyed = true; - // this._purgeRef(); // 清除ref的时机还是要仔细考虑一下 - - }, - - _unMount: function () { - this._assetMounted(); - this.__destroy(); - this.fireEvent(BI.Events.UNMOUNT); - this.purgeListeners(); - }, - - _assetMounted: function () { - if (!this.isVisible()) { - this._setVisible(true); - this._mount(false, false, false); - this._setVisible(false); - } - }, + visible() { + this.setVisible(true); + } - _empty: function () { - this._assetMounted(); - BI.each(this._children, function (i, widget) { - widget && widget._unMount && widget._unMount(); - }); - this._children = {}; - this.element.empty(); - }, + __d() { + BI.each(this._children, function (i, widget) { + widget && widget._unMount && widget._unMount(); + }); + this._children = {}; + } - isolate: function () { - if (this._parent) { - this._parent.removeWidget(this); - } - BI.DOM.hang([this]); - }, + // 主要是因为_destroy已经提供了protected方法 + __destroy() { + callLifeHook(this, "beforeDestroy"); + this.beforeDestroy = null; + this.__d(); + this._parent = null; + this._isMounted = false; + callLifeHook(this, "_destroyed"); + callLifeHook(this, "destroyed"); + this.destroyed = null; + this._isDestroyed = true; + // this._purgeRef(); // 清除ref的时机还是要仔细考虑一下 - empty: function () { - this._empty(); - }, + } - // 默认的reset方法就是干掉重来 - reset: function () { - // 还在异步状态的不需要执行reset - if (this.__async === true || this.__asking === true) { - return; - } - // if (this.options.vdom) { - // var vnode = this._renderVNode(); - // BI.patchVNode(this.vnode, vnode); - // this.vnode = vnode; - // return; - // } - // this._isMounted = false; - // this.purgeListeners(); - - // 去掉组件绑定的watcher - BI.each(this._watchers, function (i, unwatches) { - unwatches = BI.isArray(unwatches) ? unwatches : [unwatches]; - BI.each(unwatches, function (j, unwatch) { - unwatch(); - }); - }); - this._watchers && (this._watchers = []); - this._assetMounted(); - this.__d(); - this.element.empty(); - this.element.unbind(); - this._initCurrent(); - this._init(); - // this._initRef(); - }, + _unMount() { + this._assetMounted(); + this.__destroy(); + this.fireEvent(BI.Events.UNMOUNT); + this.purgeListeners(); + } - _destroy: function () { - this._assetMounted(); - this.__destroy(); - this.element.destroy(); - this.purgeListeners(); - }, - - destroy: function () { - var self = this, o = this.options; - this._assetMounted(); - this.__destroy(); - if (o.animation) { - this._innerSetVisible(false); - setTimeout(function () { - self.element.destroy(); - }, o.animationDuring); - } else { - this.element.destroy(); - } - this.fireEvent(BI.Events.UNMOUNT); - this.fireEvent(BI.Events.DESTROY); - this._purgeRef(); - this.purgeListeners(); - } - }); - var context = null, current = null; - var contextStack = [], currentStack = []; - - BI.Widget.pushContext = function (_context) { - if (context) contextStack.push(context); - BI.Widget.context = context = _context; - }; - - BI.Widget.popContext = function () { - BI.Widget.context = context = contextStack.pop(); - }; - - BI.Widget.execWithContext = function (context, execFunc) { - BI.Widget.pushContext(context); - try { - execFunc(); - } catch (e) { - throw e; - } finally { - BI.Widget.popContext(); + _assetMounted() { + if (!this.isVisible()) { + this._setVisible(true); + this._mount(false, false, false); + this._setVisible(false); } - }; + } - function pushTarget(_current) { - if (current) currentStack.push(current); - BI.Widget.current = current = _current; + _empty () { + this._assetMounted(); + BI.each(this._children, function (i, widget) { + widget && widget._unMount && widget._unMount(); + }); + this._children = {}; + this.element.empty(); } - function popTarget() { - BI.Widget.current = current = currentStack.pop(); + isolate () { + if (this._parent) { + this._parent.removeWidget(this); + } + BI.DOM.hang([this]); } - BI.useStore = function (_store) { - if (current && current.store) { - return current.store; + empty () { + this._empty(); + } + + // 默认的reset方法就是干掉重来 + reset () { + // 还在异步状态的不需要执行reset + if (this.__async === true || this.__asking === true) { + return; } - if (current && current.$storeDelegate) { - return current.$storeDelegate; + // if (this.options.vdom) { + // const vnode = this._renderVNode(); + // BI.patchVNode(this.vnode, vnode); + // this.vnode = vnode; + // return; + // } + // this._isMounted = false; + // this.purgeListeners(); + + // 去掉组件绑定的watcher + BI.each(this._watchers, function (i, unwatches) { + unwatches = BI.isArray(unwatches) ? unwatches : [unwatches]; + BI.each(unwatches, function (j, unwatch) { + unwatch(); + }); + }); + this._watchers && (this._watchers = []); + this._assetMounted(); + this.__d(); + this.element.empty(); + this.element.unbind(); + this._initCurrent(); + this._init(); + // this._initRef(); + } + + _destroy() { + this._assetMounted(); + this.__destroy(); + this.element.destroy(); + this.purgeListeners(); + } + + destroy() { + const o = this.options; + this._assetMounted(); + this.__destroy(); + if (o.animation) { + this._innerSetVisible(false); + setTimeout(() => this.element.destroy(), o.animationDuring); + } else { + this.element.destroy(); } - if (current) { - var currentStore = current._store; - var delegate = {}, origin; - if (_global.Proxy) { - var proxy = new Proxy(delegate, { - get: function (target, key) { - return Reflect.get(origin, key); - }, - set: function (target, key, value) { - return Reflect.set(origin, key, value); - } - }); - current._store = function () { - origin = (_store || currentStore).apply(this, arguments); - delegate.$delegate = origin; - return origin; - }; - return current.$storeDelegate = proxy; - } + this.fireEvent(BI.Events.UNMOUNT); + this.fireEvent(BI.Events.DESTROY); + this._purgeRef(); + this.purgeListeners(); + } +}; + +BI.extend(BI, { Widget }); + + +let context = null, current = null; +const contextStack = [], currentStack = []; + +BI.Widget.pushContext = function (_context) { + if (context) contextStack.push(context); + BI.Widget.context = context = _context; +}; + +BI.Widget.popContext = function () { + BI.Widget.context = context = contextStack.pop(); +}; + +BI.Widget.execWithContext = function (context, execFunc) { + BI.Widget.pushContext(context); + try { + execFunc(); + } catch (e) { + throw e; + } finally { + BI.Widget.popContext(); + } +}; + +function pushTarget(_current) { + if (current) currentStack.push(current); + BI.Widget.current = current = _current; +} + +function popTarget() { + BI.Widget.current = current = currentStack.pop(); +} + +BI.useStore = function (_store) { + if (current && current.store) { + return current.store; + } + if (current && current.$storeDelegate) { + return current.$storeDelegate; + } + if (current) { + const currentStore = current._store; + let delegate = {}, origin; + if (_global.Proxy) { + const proxy = new Proxy(delegate, { + get: function (target, key) { + return Reflect.get(origin, key); + }, + set: function (target, key, value) { + return Reflect.set(origin, key, value); + } + }); current._store = function () { - var st = (_store || currentStore).apply(this, arguments); - BI.extend(delegate, st); - return st; + origin = (_store || currentStore).apply(this, arguments); + delegate.$delegate = origin; + return origin; }; - return current.$storeDelegate = delegate; + return current.$storeDelegate = proxy; } - }; - - BI.useContext = function (inject) { - // 通过组件找最近的store - var vm = BI.Widget.findStore(BI.Widget.current || BI.Widget.context); - if (vm) { - if (inject) { - if (vm.$$computed && inject in vm.$$computed) { - return vm; - } - if (vm.$$state && inject in vm.$$state) { - return vm; - } - if (vm.$$model && inject in vm.$$model) { + current._store = function () { + const st = (_store || currentStore).apply(this, arguments); + BI.extend(delegate, st); + return st; + }; + return current.$storeDelegate = delegate; + } +}; + +BI.useContext = function (inject) { + // 通过组件找最近的store + const vm = BI.Widget.findStore(BI.Widget.current || BI.Widget.context); + if (vm) { + if (inject) { + if (vm.$$computed && inject in vm.$$computed) { + return vm; + } + if (vm.$$state && inject in vm.$$state) { + return vm; + } + if (vm.$$model && inject in vm.$$model) { + return vm; + } + while (vm) { + if (vm.$$context && inject in vm.$$context) { return vm; } - while (vm) { - if (vm.$$context && inject in vm.$$context) { - return vm; - } - vm = vm._parent; - } - return null; + vm = vm._parent; } + return null; } - return vm; - }; - - BI.watch = function (vm, watch, handler) { - // 必须要保证组件当前环境存在 - if (BI.Widget.current) { - if (vm instanceof BI.Model) { - var watchers = []; - if (BI.isKey(watch)) { - var k = watch; - watch = {}; - watch[k] = handler; - } - for (var key in watch) { - var innerHandler = watch[key]; - if (BI.isArray(handler)) { - for (var i = 0; i < handler.length; i++) { - watchers.push(Fix.watch(vm.model, key, innerHandler, { - store: vm - })); - } - } else { + } + return vm; +}; + +BI.watch = function (vm, watch, handler) { + // 必须要保证组件当前环境存在 + if (BI.Widget.current) { + if (vm instanceof BI.Model) { + const watchers = []; + if (BI.isKey(watch)) { + const k = watch; + watch = {}; + watch[k] = handler; + } + for (const key in watch) { + const innerHandler = watch[key]; + if (BI.isArray(handler)) { + for (let i = 0; i < handler.length; i++) { watchers.push(Fix.watch(vm.model, key, innerHandler, { store: vm })); } + } else { + watchers.push(Fix.watch(vm.model, key, innerHandler, { + store: vm + })); } - // vm中一定有_widget - BI.Widget.current._watchers || (BI.Widget.current._watchers = []); - BI.Widget.current._watchers = BI.Widget.current._watchers.concat(watchers); - return; } - handler = watch; - watch = vm; - BI.Widget.current.$watchDelayCallbacks || (BI.Widget.current.$watchDelayCallbacks = []); - BI.Widget.current.$watchDelayCallbacks.push([watch, handler]); + // vm中一定有_widget + BI.Widget.current._watchers || (BI.Widget.current._watchers = []); + BI.Widget.current._watchers = BI.Widget.current._watchers.concat(watchers); + return; } - }; + handler = watch; + watch = vm; + BI.Widget.current.$watchDelayCallbacks || (BI.Widget.current.$watchDelayCallbacks = []); + BI.Widget.current.$watchDelayCallbacks.push([watch, handler]); + } +}; - BI.onBeforeMount = function (beforeMount) { - if (current) { - if (current.__isMounting) { - beforeMount(); - return; - } - if (!current.beforeMount) { - current.beforeMount = []; - } else if (!BI.isArray(current.beforeMount)) { - current.beforeMount = [current.beforeMount]; - } - current.beforeMount.push(beforeMount); +BI.onBeforeMount = function (beforeMount) { + if (current) { + if (current.__isMounting) { + beforeMount(); + return; } - }; - BI.onMounted = function (mounted) { - if (current) { - if (current._isMounted && !this.__async) { - mounted(); - return; - } - if (!current.mounted) { - current.mounted = []; - } else if (!BI.isArray(current.mounted)) { - current.mounted = [current.mounted]; - } - current.mounted.push(mounted); + if (!current.beforeMount) { + current.beforeMount = []; + } else if (!BI.isArray(current.beforeMount)) { + current.beforeMount = [current.beforeMount]; } - }; - BI.onBeforeUnmount = function (beforeDestroy) { - if (current) { - if (!current.beforeDestroy) { - current.beforeDestroy = []; - } else if (!BI.isArray(current.beforeDestroy)) { - current.beforeDestroy = [current.beforeDestroy]; - } - current.beforeDestroy.push(beforeDestroy); + current.beforeMount.push(beforeMount); + } +}; +BI.onMounted = function (mounted) { + if (current) { + if (current._isMounted && !this.__async) { + mounted(); + return; } - }; - BI.onUnmounted = function (destroyed) { - if (current) { - if (!current.destroyed) { - current.destroyed = []; - } else if (!BI.isArray(current.destroyed)) { - current.destroyed = [current.destroyed]; - } - current.destroyed.push(destroyed); + if (!current.mounted) { + current.mounted = []; + } else if (!BI.isArray(current.mounted)) { + current.mounted = [current.mounted]; } - }; - - BI.Widget.registerRenderEngine = function (engine) { - BI.Widget._renderEngine = engine; - }; - BI.Widget.registerRenderEngine({ - createElement: function (widget) { - if (BI.isWidget(widget)) { - var o = widget.options; - if (o.element) { - return BI.$(o.element); - } - if (o.tagName) { - return BI.$(document.createElement(o.tagName)); - } - return BI.$(document.createDocumentFragment()); - } - return BI.$(widget); - }, - createFragment: function () { - return document.createDocumentFragment(); + current.mounted.push(mounted); + } +}; +BI.onBeforeUnmount = function (beforeDestroy) { + if (current) { + if (!current.beforeDestroy) { + current.beforeDestroy = []; + } else if (!BI.isArray(current.beforeDestroy)) { + current.beforeDestroy = [current.beforeDestroy]; } - }); - - BI.mount = function (widget, container, predicate, hydrate) { - if (hydrate === true) { - // 将widget的element元素都挂载好,并建立相互关系 - widget.element.data("__widgets", [widget]); - var res = widget._mount(true, false, false, function (w) { - BI.each(w._children, function (i, child) { - var ws = child.element.data("__widgets"); - if (!ws) { - ws = []; - } - ws.push(child); - child.element.data("__widgets", ws); - }); - predicate && predicate.apply(this, arguments); - }); - // 将新的dom树属性(事件等)patch到已存在的dom上 - var c = BI.Widget._renderEngine.createElement; - BI.DOM.patchProps(widget.element, c(c(container).children()[0])); - - var triggerLifeHook = function (w) { - w.beforeMount && w.beforeMount(); - w.mounted && w.mounted(); - BI.each(w._children, function (i, child) { - triggerLifeHook(child); - }); - }; - // 最后触发组件树生命周期函数 - triggerLifeHook(widget); - return res; + current.beforeDestroy.push(beforeDestroy); + } +}; +BI.onUnmounted = function (destroyed) { + if (current) { + if (!current.destroyed) { + current.destroyed = []; + } else if (!BI.isArray(current.destroyed)) { + current.destroyed = [current.destroyed]; } - if (container) { - BI.Widget._renderEngine.createElement(container).append(widget.element); + current.destroyed.push(destroyed); + } +}; + +BI.Widget.registerRenderEngine = function (engine) { + BI.Widget._renderEngine = engine; +}; +BI.Widget.registerRenderEngine({ + createElement: function (widget) { + if (BI.isWidget(widget)) { + const o = widget.options; + if (o.element) { + return BI.$(o.element); + } + if (o.tagName) { + return BI.$(document.createElement(o.tagName)); + } + return BI.$(document.createDocumentFragment()); } - return widget._mount(true, false, false, predicate); - }; -})(); + return BI.$(widget); + }, + createFragment: function () { + return document.createDocumentFragment(); + } +}); + +BI.mount = function (widget, container, predicate, hydrate) { + if (hydrate === true) { + // 将widget的element元素都挂载好,并建立相互关系 + widget.element.data("__widgets", [widget]); + const res = widget._mount(true, false, false, function (w) { + BI.each(w._children, function (i, child) { + const ws = child.element.data("__widgets"); + if (!ws) { + ws = []; + } + ws.push(child); + child.element.data("__widgets", ws); + }); + predicate && predicate.apply(this, arguments); + }); + // 将新的dom树属性(事件等)patch到已存在的dom上 + const c = BI.Widget._renderEngine.createElement; + BI.DOM.patchProps(widget.element, c(c(container).children()[0])); + + const triggerLifeHook = function (w) { + w.beforeMount && w.beforeMount(); + w.mounted && w.mounted(); + BI.each(w._children, function (i, child) { + triggerLifeHook(child); + }); + }; + // 最后触发组件树生命周期函数 + triggerLifeHook(widget); + return res; + } + if (container) { + BI.Widget._renderEngine.createElement(container).append(widget.element); + } + return widget._mount(true, false, false, predicate); +}; diff --git a/src/core/action/action.js b/src/core/action/action.js index 3639c00e5..3ed7acd44 100644 --- a/src/core/action/action.js +++ b/src/core/action/action.js @@ -5,22 +5,23 @@ * @extends BI.OB * @abstract */ -BI.Action = BI.inherit(BI.OB, { - props: function () { - return { - src: null, - tar: null - }; - }, +import OB from "../3.ob"; +export default class Action extends OB { + props = { + src: null, + tar: null + }; - actionPerformed: function (src, tar, callback) { + actionPerformed(src, tar, callback) { - }, + } - actionBack: function (tar, src, callback) { + actionBack(tar, src, callback) { } -}); +} + +BI.extend(BI, { Action }); BI.ActionFactory = { createAction: function (key, options) { diff --git a/src/core/action/action.show.js b/src/core/action/action.show.js index 68296ae19..34903513e 100644 --- a/src/core/action/action.show.js +++ b/src/core/action/action.show.js @@ -4,16 +4,19 @@ * @class BI.ShowAction * @extends BI.Action */ -BI.ShowAction = BI.inherit(BI.Action, { - actionPerformed: function (src, tar, callback) { +import Action from "./action"; +export default class ShowAction extends Action { + actionPerformed(src, tar, callback) { tar = tar || this.options.tar; tar.setVisible(true); callback && callback(); - }, + } - actionBack: function (tar, src, callback) { + actionBack(tar, src, callback) { tar = tar || this.options.tar; tar.setVisible(false); callback && callback(); } -}); +} + +BI.extend(BI, { ShowAction }); diff --git a/src/core/behavior/0.behavior.js b/src/core/behavior/0.behavior.js index 3645f87b7..dcd82a58d 100644 --- a/src/core/behavior/0.behavior.js +++ b/src/core/behavior/0.behavior.js @@ -19,14 +19,17 @@ BI.BehaviorFactory = { * @class BI.Behavior * @extends BI.OB */ -BI.Behavior = BI.inherit(BI.OB, { - _defaultConfig: function () { - return BI.extend(BI.Behavior.superclass._defaultConfig.apply(this, arguments), { - rule: function () {return true;} + +import OB from "../3.ob"; +export default class Behavior extends OB { + _defaultConfig() { + return BI.extend(super._defaultConfig(arguments), { + rule: () => true }); - }, + } - doBehavior: function () { + doBehavior() { } -}); +} +BI.extend(BI, { Behavior }); diff --git a/src/core/behavior/behavior.highlight.js b/src/core/behavior/behavior.highlight.js index 683bc061e..de7306c49 100644 --- a/src/core/behavior/behavior.highlight.js +++ b/src/core/behavior/behavior.highlight.js @@ -4,13 +4,14 @@ * @class BI.HighlightBehavior * @extends BI.Behavior */ -BI.HighlightBehavior = BI.inherit(BI.Behavior, { - doBehavior: function (items) { - var args = Array.prototype.slice.call(arguments, 1), +import Behavior from "./0.behavior"; +export default class HighlightBehavior extends Behavior { + doBehavior(items) { + const args = Array.prototype.slice.call(arguments, 1), o = this.options; BI.each(items, function (i, item) { if (item instanceof BI.Single) { - var rule = o.rule(item.getValue(), item); + const rule = o.rule(item.getValue(), item); function doBe (run) { if (run === true) { @@ -30,4 +31,5 @@ BI.HighlightBehavior = BI.inherit(BI.Behavior, { } }); } -}); +} +BI.extend(BI, { HighlightBehavior }); diff --git a/src/core/behavior/behavior.redmark.js b/src/core/behavior/behavior.redmark.js index b9c6572e9..e59cde9f3 100644 --- a/src/core/behavior/behavior.redmark.js +++ b/src/core/behavior/behavior.redmark.js @@ -4,9 +4,10 @@ * @class BI.RedMarkBehavior * @extends BI.Behavior */ -BI.RedMarkBehavior = BI.inherit(BI.Behavior, { - doBehavior: function (items) { - var args = Array.prototype.slice.call(arguments, 1), +import Behavior from "./0.behavior"; +export default class RedMarkBehavior extends Behavior { + doBehavior(items) { + const args = Array.prototype.slice.call(arguments, 1), o = this.options; BI.each(items, function (i, item) { if(item instanceof BI.Single) { @@ -20,4 +21,5 @@ BI.RedMarkBehavior = BI.inherit(BI.Behavior, { } }); } -}); +} +BI.extend(BI, { RedMarkBehavior }) diff --git a/src/core/controller/0.controller.js b/src/core/controller/0.controller.js index 4eba2c0ad..fd79f532d 100644 --- a/src/core/controller/0.controller.js +++ b/src/core/controller/0.controller.js @@ -6,6 +6,8 @@ * @extends BI.OB * @abstract */ -BI.Controller = BI.inherit(BI.OB, { -}); -BI.Controller.EVENT_CHANGE = "__EVENT_CHANGE__"; +import OB from "../3.ob"; +export default class Controller extends OB { + static EVENT_CHANGE = "__EVENT_CHANGE__"; +} +BI.extend(BI, { Controller }) diff --git a/src/core/controller/controller.broadcast.js b/src/core/controller/controller.broadcast.js index 71d7330c7..8cb4db3a3 100644 --- a/src/core/controller/controller.broadcast.js +++ b/src/core/controller/controller.broadcast.js @@ -4,35 +4,28 @@ * Created by GUY on 2015/12/23. * @class */ -BI.BroadcastController = BI.inherit(BI.Controller, { - init: function () { +import Controller from "./0.controller"; +export default class BroadcastController extends Controller { + init() { this._broadcasts = {}; - }, + } - on: function (name, fn) { - var self = this; + on(name, fn) { if (!this._broadcasts[name]) { this._broadcasts[name] = []; } this._broadcasts[name].push(fn); - return function () { - self.remove(name, fn); - }; - }, + return () => this.remove(name, fn); + } - send: function (name) { - var args = [].slice.call(arguments, 1); - BI.each(this._broadcasts[name], function (i, fn) { - fn.apply(null, args); - }); - }, + send(name) { + const args = [].slice.call(arguments, 1); + BI.each(this._broadcasts[name], (i, fn) => fn.apply(null, args)); + } - remove: function (name, fn) { - var self = this; + remove(name, fn) { if (fn) { - BI.remove(this._broadcasts[name], function (index, cb) { - return fn === cb; - }); + BI.remove(this._broadcasts[name], (index, cb) => fn === cb); if (this._broadcasts[name].length === 0) { delete this._broadcasts[name]; } @@ -41,4 +34,5 @@ BI.BroadcastController = BI.inherit(BI.Controller, { } return this; } -}); +} +BI.extend(BI, { BroadcastController }) \ No newline at end of file diff --git a/src/core/controller/controller.bubbles.js b/src/core/controller/controller.bubbles.js index fa5cefb5f..fcdd69f4b 100644 --- a/src/core/controller/controller.bubbles.js +++ b/src/core/controller/controller.bubbles.js @@ -5,11 +5,12 @@ * Created by GUY on 2015/8/21. * @class */ -BI.BubblesController = BI.inherit(BI.Controller, { - init: function () { +import Controller from "./0.controller"; +export default class BubblesController extends Controller { + init() { this.storeBubbles = {}; this.storePoppers = {}; - }, + } /** * @@ -19,14 +20,14 @@ BI.BubblesController = BI.inherit(BI.Controller, { * @param offsetStyle center, left, right三种类型, 默认left * @returns {BI.BubblesController} */ - show: function (name, text, context, opt) { + show(name, text, context, opt) { opt || (opt = {}); - var container = opt.container || context; - var offsetStyle = opt.offsetStyle || "left"; - var level = opt.level || "error"; - var adjustYOffset = opt.adjustYOffset || 0; - var adjustXOffset = opt.adjustXOffset || 0; - // var fixed = opt.fixed !== false; + const container = opt.container || context; + const offsetStyle = opt.offsetStyle || "left"; + const level = opt.level || "error"; + const adjustYOffset = opt.adjustYOffset || 0; + const adjustXOffset = opt.adjustXOffset || 0; + // const fixed = opt.fixed !== false; if (!this.storeBubbles[name]) { this.storeBubbles[name] = BI.createWidget({ @@ -37,7 +38,7 @@ BI.BubblesController = BI.inherit(BI.Controller, { height: 18 }); } - var bubble = this.storeBubbles[name]; + const bubble = this.storeBubbles[name]; if (bubble.getText() !== text) { bubble.setText(text); } @@ -69,18 +70,18 @@ BI.BubblesController = BI.inherit(BI.Controller, { ] }); return this; - }, + } - hide: function (name) { + hide(name) { this.remove(name); return this; - }, + } - has: function (name) { + has(name) { return this.storeBubbles[name] != null; - }, + } - remove: function (name) { + remove(name) { if (!this.has(name)) { return this; } @@ -88,17 +89,14 @@ BI.BubblesController = BI.inherit(BI.Controller, { this.storePoppers[name] && this.storePoppers[name].destroy(); delete this.storeBubbles[name]; return this; - }, + } - removeAll: function () { - BI.each(this.storeBubbles, function (name, bubble) { - bubble.destroy(); - }); - BI.each(this.storePoppers, function (name, popper) { - popper.destroy(); - }); + removeAll() { + BI.each(this.storeBubbles, (name, bubble) => bubble.destroy()); + BI.each(this.storePoppers, (name, popper) => popper.destroy()); this.storeBubbles = {}; this.storePoppers = {}; return this; } -}); +} +BI.extend(BI, { BubblesController }); diff --git a/src/core/controller/controller.drawer.js b/src/core/controller/controller.drawer.js index 68fdadbc8..d90c226f2 100644 --- a/src/core/controller/controller.drawer.js +++ b/src/core/controller/controller.drawer.js @@ -4,62 +4,61 @@ * @class BI.popoverController * @extends BI.Controller */ -BI.DrawerController = BI.inherit(BI.Controller, { - props: function () { - return { - modal: true, // 模态窗口 - render: "body" - }; - }, +import Controller from "./0.controller"; +export default class DrawerController extends Controller { + props = { + modal: true, // 模态窗口 + render: "body" + } - init: function () { + init() { this.modal = this.options.modal; this.floatManager = {}; this.floatLayer = {}; this.floatContainer = {}; this.floatOpened = {}; this.zindexMap = {}; - }, + } - create: function (name, options, context) { + create(name, options, context) { if (this.has(name)) { return this; } - var popover = BI.createWidget(options || {}, { + const popover = BI.createWidget(options || {}, { type: "bi.drawer" }, context); this.add(name, popover, options, context); return this; - }, + } - open: function (name) { - var self = this, o = this.options; + open(name) { + const o = this.options; if (!this.has(name)) { return this; } if (!this.floatOpened[name]) { this.floatOpened[name] = true; - var container = this.floatContainer[name]; - var zIndex = BI.Popovers._getZIndex(); + const container = this.floatContainer[name]; + const zIndex = BI.Popovers._getZIndex(); container.element.css("zIndex", zIndex); this.modal && container.element.__hasZIndexMask__(this.zindexMap[name]) && container.element.__releaseZIndexMask__(this.zindexMap[name]); this.zindexMap[name] = zIndex; if (this.modal) { - var mask = container.element.__buildZIndexMask__(BI.Popovers._getZIndex()); - mask.click(function () { + const mask = container.element.__buildZIndexMask__(BI.Popovers._getZIndex()); + mask.click(() => { mask.destroy(); - self.get(name).close(); + this.get(name).close(); }); } this.get(name).setZindex(BI.Popovers._getZIndex()); this.floatContainer[name].visible(); - var popover = this.get(name); + const popover = this.get(name); popover.show && popover.show(); } return this; - }, + } - close: function (name) { + close(name) { if (!this.has(name)) { return this; } @@ -69,22 +68,21 @@ BI.DrawerController = BI.inherit(BI.Controller, { this.modal && this.floatContainer[name].element.__releaseZIndexMask__(this.zindexMap[name]); } return this; - }, + } - show: function (name) { + show(name) { return this.open(name); - }, + } - hide: function (name) { + hide(name) { return this.close(name); - }, + } - isVisible: function (name) { + isVisible(name) { return this.has(name) && this.floatOpened[name] === true; - }, + } - add: function (name, popover, options, context) { - var self = this; + add(name, popover, options, context) { options || (options = {}); if (this.has(name)) { return this; @@ -105,9 +103,7 @@ BI.DrawerController = BI.inherit(BI.Controller, { }); this.floatManager[name] = popover; (function (key) { - popover.on(BI.Drawer.EVENT_CLOSE, function () { - self.close(key); - }); + popover.on(BI.Drawer.EVENT_CLOSE, () => this.close(key)); })(name); BI.createWidget({ type: "bi.absolute", @@ -121,17 +117,17 @@ BI.DrawerController = BI.inherit(BI.Controller, { }] }); return this; - }, + } - get: function (name) { + get(name) { return this.floatManager[name]; - }, + } - has: function (name) { + has(name) { return BI.isNotNull(this.floatManager[name]); - }, + } - remove: function (name) { + remove(name) { if (!this.has(name)) { return this; } @@ -143,13 +139,12 @@ BI.DrawerController = BI.inherit(BI.Controller, { delete this.floatContainer[name]; delete this.floatOpened[name]; return this; - }, + } - removeAll: function () { - var self = this; - BI.each(this.floatContainer, function (name, container) { + removeAll() { + BI.each(this.floatContainer, (name, container) => { container.destroy(); - self.modal && self.floatContainer[name].element.__releaseZIndexMask__(self.zindexMap[name]); + this.modal && this.floatContainer[name].element.__releaseZIndexMask__(this.zindexMap[name]); }); this.floatManager = {}; this.floatLayer = {}; @@ -158,4 +153,5 @@ BI.DrawerController = BI.inherit(BI.Controller, { this.zindexMap = {}; return this; } -}); +} +BI.extend(BI, { DrawerController }); diff --git a/src/core/controller/controller.layer.js b/src/core/controller/controller.layer.js index 6887603f7..d12c807d7 100644 --- a/src/core/controller/controller.layer.js +++ b/src/core/controller/controller.layer.js @@ -4,32 +4,31 @@ * Created by GUY on 2015/6/24. * @class */ -BI.LayerController = BI.inherit(BI.Controller, { - props: function () { - return { - render: "body" - }; - }, +import Controller from "./0.controller"; +export default class LayerController extends Controller { + props = { + render: "body" + } - init: function () { + init() { this.layerManager = {}; this.layouts = {}; this.zindex = BI.zIndex_layer; - }, + } - _initResizer: function () { + _initResizer() { this.resizer = BI.Resizers.add("layerController" + BI.uniqueId(), BI.bind(this._resize, this)); - }, + } - _resize: function () { + _resize() { BI.each(this.layouts, function (i, layer) { if (layer.element.is(":visible")) { layer.element.trigger("__resize__"); } }); - }, + } - make: function (name, container, op, context) { + make(name, container, op, context) { if (BI.isWidget(container)) { op = op || {}; op.container = container; @@ -38,16 +37,16 @@ BI.LayerController = BI.inherit(BI.Controller, { op = container; } return this.create(name, null, op, context); - }, + } - create: function (name, from, op, context) { + create(name, from, op, context) { BI.isNull(this.resizer) && this._initResizer(); if (this.has(name)) { return this.get(name); } op || (op = {}); - var offset = op.offset || {}; - var w = from; + const offset = op.offset || {}; + let w = from; if (BI.isWidget(from)) { w = from.element; } @@ -57,10 +56,10 @@ BI.LayerController = BI.inherit(BI.Controller, { if (this.has(name)) { return this.get(name); } - var widget = BI.createWidget((op.render || {}), BI.extend({ + const widget = BI.createWidget((op.render || {}), BI.extend({ type: "bi.layout" }, op), context); - var layout = BI.createWidget({ + const layout = BI.createWidget({ type: "bi.absolute", invisible: true, items: [{ @@ -102,31 +101,31 @@ BI.LayerController = BI.inherit(BI.Controller, { } this.add(name, widget, layout); return widget; - }, + } - show: function (name, callback) { + show(name, callback) { if (!this.has(name)) { return this; } this._getLayout(name).visible(); this._getLayout(name).element.css("z-index", this.zindex++).show(0, callback).trigger("__resize__"); return this; - }, + } - hide: function (name, callback) { + hide(name, callback) { if (!this.has(name)) { return this; } this._getLayout(name).invisible(); this._getLayout(name).element.hide(0, callback); return this; - }, + } - isVisible: function (name) { + isVisible(name) { return this.has(name) && this._getLayout(name).isVisible(); - }, + } - add: function (name, layer, layout) { + add(name, layer, layout) { if (this.has(name)) { throw new Error("不能创建同名的Layer"); } @@ -135,21 +134,21 @@ BI.LayerController = BI.inherit(BI.Controller, { this.layouts[name] = layout; layout.element.css("z-index", this.zindex++); return this; - }, + } - _getLayout: function (name) { + _getLayout(name) { return this.layouts[name]; - }, + } - get: function (name) { + get(name) { return this.layerManager[name]; - }, + } - has: function (name) { + has(name) { return this.layerManager[name] != null; - }, + } - remove: function (name) { + remove(name) { if (!this.has(name)) { return this; } @@ -158,16 +157,16 @@ BI.LayerController = BI.inherit(BI.Controller, { delete this.layerManager[name]; delete this.layouts[name]; return this; - }, + } - removeAll: function () { - var self = this; - BI.each(BI.keys(this.layerManager), function (index, name) { - self.layerManager[name].destroy(); - self.layouts[name].destroy(); + removeAll() { + BI.each(BI.keys(this.layerManager), (index, name) => { + this.layerManager[name].destroy(); + this.layouts[name].destroy(); }); this.layerManager = {}; this.layouts = {}; return this; } -}); +} +BI.extend(BI, { LayerController }); diff --git a/src/core/controller/controller.masker.js b/src/core/controller/controller.masker.js index 0b55b0781..cda5be1e6 100644 --- a/src/core/controller/controller.masker.js +++ b/src/core/controller/controller.masker.js @@ -4,9 +4,11 @@ * Created by GUY on 2015/6/24. * @class */ -BI.MaskersController = BI.inherit(BI.LayerController, { - init: function () { - BI.MaskersController.superclass.init.apply(this, arguments); +import LayerController from "./controller.layer"; +export default class MaskersController extends LayerController { + init() { + super.init(arguments); this.zindex = BI.zIndex_masker; } -}); +} +BI.extend(BI, { MaskersController }); diff --git a/src/core/controller/controller.popover.js b/src/core/controller/controller.popover.js index 9e36e5849..08f40cf60 100644 --- a/src/core/controller/controller.popover.js +++ b/src/core/controller/controller.popover.js @@ -4,15 +4,14 @@ * @class BI.popoverController * @extends BI.Controller */ -BI.PopoverController = BI.inherit(BI.Controller, { - props: function () { - return { - modal: true, // 模态窗口 - render: "body" - }; - }, +import Controller from "./0.controller"; +export default class PopoverController extends Controller { + props = { + modal: true, // 模态窗口 + render: "body" + } - init: function () { + init() { this.modal = this.options.modal; this.floatManager = {}; this.floatLayer = {}; @@ -20,38 +19,38 @@ BI.PopoverController = BI.inherit(BI.Controller, { this.floatOpened = {}; this.zindex = BI.zIndex_popover; this.zindexMap = {}; - }, + } - create: function (name, options, context) { + create(name, options, context) { if (this.has(name)) { return this; } - var popover = BI.createWidget(options || {}, { + const popover = BI.createWidget(options || {}, { type: "bi.popover" }, context); this.add(name, popover, options, context); return this; - }, + } - open: function (name) { + open(name) { if (!this.has(name)) { return this; } if (!this.floatOpened[name]) { this.floatOpened[name] = true; - var container = this.floatContainer[name]; + const container = this.floatContainer[name]; container.element.css("zIndex", this.zindex++); this.modal && container.element.__hasZIndexMask__(this.zindexMap[name]) && container.element.__releaseZIndexMask__(this.zindexMap[name]); this.zindexMap[name] = this.zindex; this.modal && container.element.__buildZIndexMask__(this.zindex++); this.get(name).setZindex(this.zindex++); this.floatContainer[name].visible(); - var popover = this.get(name); + const popover = this.get(name); popover.show && popover.show(); - var W = BI.Widget._renderEngine.createElement(this.options.render).width(), + const W = BI.Widget._renderEngine.createElement(this.options.render).width(), H = BI.Widget._renderEngine.createElement(this.options.render).height(); - var w = popover.element.width(), h = popover.element.height(); - var left = (W - w) / 2, top = (H - h) / 2; + const w = popover.element.width(), h = popover.element.height(); + const left = (W - w) / 2, top = (H - h) / 2; if (left < 0) { left = 0; } @@ -65,9 +64,9 @@ BI.PopoverController = BI.inherit(BI.Controller, { }); } return this; - }, + } - close: function (name) { + close(name) { if (!this.has(name)) { return this; } @@ -77,22 +76,21 @@ BI.PopoverController = BI.inherit(BI.Controller, { this.modal && this.floatContainer[name].element.__releaseZIndexMask__(this.zindexMap[name]); } return this; - }, + } - show: function (name) { + show(name) { return this.open(name); - }, + } - hide: function (name) { + hide(name) { return this.close(name); - }, + } - isVisible: function (name) { + isVisible(name) { return this.has(name) && this.floatOpened[name] === true; - }, + } - add: function (name, popover, options, context) { - var self = this; + add(name, popover, options, context) { options || (options = {}); if (this.has(name)) { return this; @@ -113,9 +111,7 @@ BI.PopoverController = BI.inherit(BI.Controller, { }); this.floatManager[name] = popover; (function (key) { - popover.on(BI.Popover.EVENT_CLOSE, function () { - self.close(key); - }); + popover.on(BI.Popover.EVENT_CLOSE, () => self.close(key)); })(name); BI.createWidget({ type: "bi.absolute", @@ -129,17 +125,17 @@ BI.PopoverController = BI.inherit(BI.Controller, { }] }); return this; - }, + } - get: function (name) { + get(name) { return this.floatManager[name]; - }, + } - has: function (name) { + has(name) { return BI.isNotNull(this.floatManager[name]); - }, + } - remove: function (name) { + remove(name) { if (!this.has(name)) { return this; } @@ -151,13 +147,12 @@ BI.PopoverController = BI.inherit(BI.Controller, { delete this.floatContainer[name]; delete this.floatOpened[name]; return this; - }, + } - removeAll: function () { - var self = this; - BI.each(this.floatContainer, function (name, container) { + removeAll() { + BI.each(this.floatContainer, (name, container) => { container.destroy(); - self.modal && self.floatContainer[name].element.__releaseZIndexMask__(self.zindexMap[name]); + this.modal && this.floatContainer[name].element.__releaseZIndexMask__(this.zindexMap[name]); }); this.floatManager = {}; this.floatLayer = {}; @@ -165,9 +160,10 @@ BI.PopoverController = BI.inherit(BI.Controller, { this.floatOpened = {}; this.zindexMap = {}; return this; - }, + } - _getZIndex: function () { + _getZIndex() { return this.zindex++; } -}); +} +BI.extend(BI, { PopoverController }); diff --git a/src/core/controller/controller.resizer.js b/src/core/controller/controller.resizer.js index 900bd3927..13eaa441e 100644 --- a/src/core/controller/controller.resizer.js +++ b/src/core/controller/controller.resizer.js @@ -4,25 +4,23 @@ * Created by GUY on 2015/6/24. * @class */ -BI.ResizeController = BI.inherit(BI.Controller, { +import Controller from "./0.controller"; +export default class ResizeController extends Controller { - init: function () { + init() { this.resizerManger = {}; - }, + } - _initResizeListener: function () { - var self = this; - this.resizeHandler = BI.debounce(function (ev) { - self._resize(ev); - }, 30); + _initResizeListener() { + this.resizeHandler = BI.debounce((ev) => this._resize(ev), 30); if ("onorientationchange" in _global) { _global.onorientationchange = this.resizeHandler; } else { BI.Widget._renderEngine.createElement(_global).resize(this.resizeHandler); } - }, + } - _resize: function (ev) { + _resize(ev) { BI.each(this.resizerManger, function (key, resizer) { if (resizer instanceof BI.$) { if (resizer.is(":visible")) { @@ -38,34 +36,33 @@ BI.ResizeController = BI.inherit(BI.Controller, { resizer(ev); } }); - }, + } - add: function (name, resizer) { - var self = this; + add(name, resizer) { BI.isNull(this.resizeHandler) && this._initResizeListener(); if (this.has(name)) { return this; } this.resizerManger[name] = resizer; - return function () { - self.remove(name); - }; - }, + return () => this.remove(name); + } - get: function (name) { + get(name) { return this.resizerManger[name]; - }, + } - has: function (name) { + has(name) { return this.resizerManger[name] != null; - }, + } - remove: function (name) { + remove(name) { if (!this.has(name)) { return this; } delete this.resizerManger[name]; return this; } -}); +} + +BI.extend(BI, { ResizeController }); diff --git a/src/core/controller/controller.tooltips.js b/src/core/controller/controller.tooltips.js index 98f90fb0b..efc0a1517 100644 --- a/src/core/controller/controller.tooltips.js +++ b/src/core/controller/controller.tooltips.js @@ -6,11 +6,12 @@ * @class BI.TooltipsController * @extends BI.Controller */ -BI.TooltipsController = BI.inherit(BI.Controller, { - init: function () { +import Controller from "./0.controller"; +export default class TooltipsController extends Controller { + init() { this.tooltipsManager = {}; this.showingTips = {};// 存储正在显示的tooltip - }, + } /** * @@ -21,34 +22,31 @@ BI.TooltipsController = BI.inherit(BI.Controller, { * @returns {*} * @private */ - _createTooltip: function (opt) { + _createTooltip(opt) { return BI.createWidget({ type: "bi.tooltip", ...opt, stopEvent: true }); - }, + } // opt: {container: '', belowMouse: false} - show: function (e, name, tooltipOpt, context, opt) { + show(e, name, tooltipOpt, context, opt) { opt || (opt = {}); - var self = this; - BI.each(this.showingTips, function (i, tip) { - self.hide(i); - }); + BI.each(this.showingTips, (i, tip) => this.hide(i)); this.showingTips = {}; if (!this.has(name)) { this.create(name, tooltipOpt, document.fullscreenElement ? context : (opt.container || "body")); } if (!opt.belowMouse) { - var offset = context.element.offset(); - var bounds = context.element.bounds(); + const offset = context.element.offset(); + const bounds = context.element.bounds(); if (bounds.height === 0 || bounds.width === 0) { return; } - var top = offset.top + bounds.height + 5; + const top = offset.top + bounds.height + 5; } - var tooltip = this.get(name); + const tooltip = this.get(name); tooltip.element.css({ left: "0px", top: "0px" @@ -57,13 +55,13 @@ BI.TooltipsController = BI.inherit(BI.Controller, { tooltip.element.height(tooltip.element[0].scrollHeight); this.showingTips[name] = true; // scale影响要计算在内 - // var scale = context.element.offset().left / context.element.get(0).getBoundingClientRect().left; - // var x = (e.pageX || e.clientX) * scale + 15, y = (e.pageY || e.clientY) * scale + 15; - var x = (e.pageX || e.clientX) + 15, y = (e.pageY || e.clientY) + 15; + // const scale = context.element.offset().left / context.element.get(0).getBoundingClientRect().left; + // const x = (e.pageX || e.clientX) * scale + 15, y = (e.pageY || e.clientY) * scale + 15; + const x = (e.pageX || e.clientX) + 15, y = (e.pageY || e.clientY) + 15; if (x + tooltip.element.outerWidth() > BI.Widget._renderEngine.createElement("body").outerWidth()) { x -= tooltip.element.outerWidth() + 15; } - var bodyHeight = BI.Widget._renderEngine.createElement("body").outerHeight(); + const bodyHeight = BI.Widget._renderEngine.createElement("body").outerHeight(); if (y + tooltip.element.outerHeight() > bodyHeight || top + tooltip.element.outerHeight() > bodyHeight) { y -= tooltip.element.outerHeight() + 15; !opt.belowMouse && (y = Math.min(y, offset.top - tooltip.element.outerHeight() - 5)); @@ -75,14 +73,14 @@ BI.TooltipsController = BI.inherit(BI.Controller, { left: x < 0 ? 0 : x + "px", top: y < 0 ? 0 : y + "px" }); - tooltip.element.hover(function () { - self.remove(name); + tooltip.element.hover(() => { + this.remove(name); context.element.trigger("mouseleave.title" + context.getName()); }); return this; - }, + } - hide: function (name, callback) { + hide(name, callback) { if (!this.has(name)) { return this; } @@ -90,11 +88,11 @@ BI.TooltipsController = BI.inherit(BI.Controller, { this.get(name).element.hide(0, callback); this.get(name).invisible(); return this; - }, + } - create: function (name, tooltipOpt, context) { + create(name, tooltipOpt, context) { if (!this.has(name)) { - var tooltip = this._createTooltip(tooltipOpt); + const tooltip = this._createTooltip(tooltipOpt); this.add(name, tooltip); BI.createWidget({ type: "bi.absolute", @@ -106,38 +104,38 @@ BI.TooltipsController = BI.inherit(BI.Controller, { tooltip.invisible(); } return this.get(name); - }, + } - add: function (name, bubble) { + add(name, bubble) { if (this.has(name)) { return this; } this.set(name, bubble); return this; - }, + } - get: function (name) { + get(name) { return this.tooltipsManager[name]; - }, + } - set: function (name, bubble) { + set(name, bubble) { this.tooltipsManager[name] = bubble; - }, + } - has: function (name) { + has(name) { return this.tooltipsManager[name] != null; - }, + } - remove: function (name) { + remove(name) { if (!this.has(name)) { return this; } this.tooltipsManager[name].destroy(); delete this.tooltipsManager[name]; return this; - }, + } - removeAll: function () { + removeAll() { BI.each(this.tooltipsManager, function (name, tooltip) { tooltip.destroy(); }); @@ -145,4 +143,5 @@ BI.TooltipsController = BI.inherit(BI.Controller, { this.showingTips = {}; return this; } -}); +} +BI.extend(BI, { TooltipsController }); From 2b80c6783909deca5d0b28ef920aabf2a4953ebf Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Tue, 27 Dec 2022 01:17:11 +0800 Subject: [PATCH 010/300] =?UTF-8?q?KERNEL-13947=20refactor:=20=E7=BB=9F?= =?UTF-8?q?=E4=B8=80=E6=8C=82=E8=BD=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/action/action.js | 2 - src/core/action/action.show.js | 2 - src/core/behavior/0.behavior.js | 1 - src/core/behavior/behavior.highlight.js | 1 - src/core/behavior/behavior.redmark.js | 1 - src/core/controller/0.controller.js | 1 - src/core/controller/controller.broadcast.js | 3 +- src/core/controller/controller.bubbles.js | 1 - src/core/controller/controller.drawer.js | 1 - src/core/controller/controller.layer.js | 1 - src/core/controller/controller.masker.js | 1 - src/core/controller/controller.popover.js | 1 - src/core/controller/controller.resizer.js | 2 - src/core/controller/controller.tooltips.js | 3 +- src/core/index.js | 48 +++++++++++++++++++++ 15 files changed, 50 insertions(+), 19 deletions(-) create mode 100644 src/core/index.js diff --git a/src/core/action/action.js b/src/core/action/action.js index 3ed7acd44..e582778ea 100644 --- a/src/core/action/action.js +++ b/src/core/action/action.js @@ -21,8 +21,6 @@ export default class Action extends OB { } } -BI.extend(BI, { Action }); - BI.ActionFactory = { createAction: function (key, options) { var action; diff --git a/src/core/action/action.show.js b/src/core/action/action.show.js index 34903513e..6ab3b7e1c 100644 --- a/src/core/action/action.show.js +++ b/src/core/action/action.show.js @@ -18,5 +18,3 @@ export default class ShowAction extends Action { callback && callback(); } } - -BI.extend(BI, { ShowAction }); diff --git a/src/core/behavior/0.behavior.js b/src/core/behavior/0.behavior.js index dcd82a58d..25d82b529 100644 --- a/src/core/behavior/0.behavior.js +++ b/src/core/behavior/0.behavior.js @@ -32,4 +32,3 @@ export default class Behavior extends OB { } } -BI.extend(BI, { Behavior }); diff --git a/src/core/behavior/behavior.highlight.js b/src/core/behavior/behavior.highlight.js index de7306c49..6ba710da0 100644 --- a/src/core/behavior/behavior.highlight.js +++ b/src/core/behavior/behavior.highlight.js @@ -32,4 +32,3 @@ export default class HighlightBehavior extends Behavior { }); } } -BI.extend(BI, { HighlightBehavior }); diff --git a/src/core/behavior/behavior.redmark.js b/src/core/behavior/behavior.redmark.js index e59cde9f3..1b2b349cf 100644 --- a/src/core/behavior/behavior.redmark.js +++ b/src/core/behavior/behavior.redmark.js @@ -22,4 +22,3 @@ export default class RedMarkBehavior extends Behavior { }); } } -BI.extend(BI, { RedMarkBehavior }) diff --git a/src/core/controller/0.controller.js b/src/core/controller/0.controller.js index fd79f532d..0b5bd7b09 100644 --- a/src/core/controller/0.controller.js +++ b/src/core/controller/0.controller.js @@ -10,4 +10,3 @@ import OB from "../3.ob"; export default class Controller extends OB { static EVENT_CHANGE = "__EVENT_CHANGE__"; } -BI.extend(BI, { Controller }) diff --git a/src/core/controller/controller.broadcast.js b/src/core/controller/controller.broadcast.js index 8cb4db3a3..f6d7b8951 100644 --- a/src/core/controller/controller.broadcast.js +++ b/src/core/controller/controller.broadcast.js @@ -34,5 +34,4 @@ export default class BroadcastController extends Controller { } return this; } -} -BI.extend(BI, { BroadcastController }) \ No newline at end of file +} \ No newline at end of file diff --git a/src/core/controller/controller.bubbles.js b/src/core/controller/controller.bubbles.js index fcdd69f4b..a62717081 100644 --- a/src/core/controller/controller.bubbles.js +++ b/src/core/controller/controller.bubbles.js @@ -99,4 +99,3 @@ export default class BubblesController extends Controller { return this; } } -BI.extend(BI, { BubblesController }); diff --git a/src/core/controller/controller.drawer.js b/src/core/controller/controller.drawer.js index d90c226f2..4b2daca9e 100644 --- a/src/core/controller/controller.drawer.js +++ b/src/core/controller/controller.drawer.js @@ -154,4 +154,3 @@ export default class DrawerController extends Controller { return this; } } -BI.extend(BI, { DrawerController }); diff --git a/src/core/controller/controller.layer.js b/src/core/controller/controller.layer.js index d12c807d7..a2a6735b7 100644 --- a/src/core/controller/controller.layer.js +++ b/src/core/controller/controller.layer.js @@ -169,4 +169,3 @@ export default class LayerController extends Controller { return this; } } -BI.extend(BI, { LayerController }); diff --git a/src/core/controller/controller.masker.js b/src/core/controller/controller.masker.js index cda5be1e6..33bffef75 100644 --- a/src/core/controller/controller.masker.js +++ b/src/core/controller/controller.masker.js @@ -11,4 +11,3 @@ export default class MaskersController extends LayerController { this.zindex = BI.zIndex_masker; } } -BI.extend(BI, { MaskersController }); diff --git a/src/core/controller/controller.popover.js b/src/core/controller/controller.popover.js index 08f40cf60..bcb129f3b 100644 --- a/src/core/controller/controller.popover.js +++ b/src/core/controller/controller.popover.js @@ -166,4 +166,3 @@ export default class PopoverController extends Controller { return this.zindex++; } } -BI.extend(BI, { PopoverController }); diff --git a/src/core/controller/controller.resizer.js b/src/core/controller/controller.resizer.js index 13eaa441e..3a6dcd31a 100644 --- a/src/core/controller/controller.resizer.js +++ b/src/core/controller/controller.resizer.js @@ -64,5 +64,3 @@ export default class ResizeController extends Controller { return this; } } - -BI.extend(BI, { ResizeController }); diff --git a/src/core/controller/controller.tooltips.js b/src/core/controller/controller.tooltips.js index efc0a1517..4b99266e0 100644 --- a/src/core/controller/controller.tooltips.js +++ b/src/core/controller/controller.tooltips.js @@ -57,7 +57,7 @@ export default class TooltipsController extends Controller { // scale影响要计算在内 // const scale = context.element.offset().left / context.element.get(0).getBoundingClientRect().left; // const x = (e.pageX || e.clientX) * scale + 15, y = (e.pageY || e.clientY) * scale + 15; - const x = (e.pageX || e.clientX) + 15, y = (e.pageY || e.clientY) + 15; + let x = (e.pageX || e.clientX) + 15, y = (e.pageY || e.clientY) + 15; if (x + tooltip.element.outerWidth() > BI.Widget._renderEngine.createElement("body").outerWidth()) { x -= tooltip.element.outerWidth() + 15; } @@ -144,4 +144,3 @@ export default class TooltipsController extends Controller { return this; } } -BI.extend(BI, { TooltipsController }); diff --git a/src/core/index.js b/src/core/index.js new file mode 100644 index 000000000..1937cff2e --- /dev/null +++ b/src/core/index.js @@ -0,0 +1,48 @@ +import Action from "./action/action"; +import ShowAction from "./action/action.show"; +import Behavior from "./behavior/0.behavior"; +import HighlightBehavior from "./behavior/behavior.highlight"; +import RedMarkBehavior from "./behavior/behavior.redmark"; +import Controller from "./controller/0.controller"; +import BroadcastController from "./controller/controller.broadcast"; +import BubblesController from "./controller/controller.bubbles"; +import DrawerController from "./controller/controller.drawer"; +import LayerController from "./controller/controller.layer"; +import MaskersController from "./controller/controller.masker"; +import PopoverController from "./controller/controller.popover"; +import ResizeController from "./controller/controller.resizer"; +import TooltipsController from "./controller/controller.tooltips"; + +BI.extend(BI, { + Action, + ShowAction, + Behavior, + HighlightBehavior, + RedMarkBehavior, + Controller, + BroadcastController, + BubblesController, + DrawerController, + LayerController, + MaskersController, + PopoverController, + ResizeController, + TooltipsController, +}); + +export { + Action, + ShowAction, + Behavior, + HighlightBehavior, + RedMarkBehavior, + Controller, + BroadcastController, + BubblesController, + DrawerController, + LayerController, + MaskersController, + PopoverController, + ResizeController, + TooltipsController, +} \ No newline at end of file From e9a87a8528757c42dbef22337850566e3d4e9422 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Tue, 27 Dec 2022 13:50:21 +0800 Subject: [PATCH 011/300] =?UTF-8?q?KERNEL-13947=20refactor:=20OB=E5=92=8CW?= =?UTF-8?q?idget=E4=BB=8Eindex=20export?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/index.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/core/index.js b/src/core/index.js index 1937cff2e..d168cc0bc 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -1,3 +1,5 @@ +import OB from "./3.ob"; +import Widget from "./4.widget"; import Action from "./action/action"; import ShowAction from "./action/action.show"; import Behavior from "./behavior/0.behavior"; @@ -14,6 +16,8 @@ import ResizeController from "./controller/controller.resizer"; import TooltipsController from "./controller/controller.tooltips"; BI.extend(BI, { + OB, + Widget, Action, ShowAction, Behavior, @@ -31,6 +35,8 @@ BI.extend(BI, { }); export { + OB, + Widget, Action, ShowAction, Behavior, From 8c8fd18c6cefe604fc6d780eaa46cec1e91f0dc0 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Tue, 27 Dec 2022 15:17:37 +0800 Subject: [PATCH 012/300] =?UTF-8?q?KERNEL-13947=20refactor:=20base?= =?UTF-8?q?=E7=9A=84es6=E5=8C=96demo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/1.pane.js | 22 +++++++++++----------- src/base/index.js | 9 +++++++++ src/core/index.js | 2 ++ 3 files changed, 22 insertions(+), 11 deletions(-) create mode 100644 src/base/index.js diff --git a/src/base/1.pane.js b/src/base/1.pane.js index f613cbdd7..c87e33bfc 100644 --- a/src/base/1.pane.js +++ b/src/base/1.pane.js @@ -6,21 +6,23 @@ * @extends BI.Widget * @abstract */ -import { shortcut } from "../core/decorator"; +import { Widget, shortcut } from "../core"; @shortcut() -export class Pane extends BI.Widget { +export default class Pane extends Widget { static xtype = "bi.pane"; static EVENT_LOADED = "EVENT_LOADED"; static EVENT_LOADING = "EVENT_LOADING"; - props = { - _baseCls: "bi-pane", - tipText: BI.i18nText("BI-No_Selected_Item"), - loadingText: "", - loadingSize: "small", - overlap: true, - onLoaded: BI.emptyFn, + _defaultConfig() { + return BI.extend(super._defaultConfig(), { + _baseCls: "bi-pane", + tipText: BI.i18nText("BI-No_Selected_Item"), + loadingText: "", + loadingSize: "small", + overlap: true, + onLoaded: BI.emptyFn, + }); } _assertTip() { @@ -129,5 +131,3 @@ export class Pane extends BI.Widget { this.check(); } } - -BI.extend(BI, { Pane }); diff --git a/src/base/index.js b/src/base/index.js new file mode 100644 index 000000000..c10043847 --- /dev/null +++ b/src/base/index.js @@ -0,0 +1,9 @@ +import Pane from "./1.pane"; + +BI.extend(BI, { + Pane, +}); + +export { + Pane, +} \ No newline at end of file diff --git a/src/core/index.js b/src/core/index.js index d168cc0bc..8c345df4c 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -1,3 +1,4 @@ +import { shortcut } from "./decorator"; import OB from "./3.ob"; import Widget from "./4.widget"; import Action from "./action/action"; @@ -35,6 +36,7 @@ BI.extend(BI, { }); export { + shortcut, OB, Widget, Action, From ff266d986447447308cdb135cb73ae0bf552479d Mon Sep 17 00:00:00 2001 From: impact Date: Wed, 28 Dec 2022 11:37:50 +0800 Subject: [PATCH 013/300] =?UTF-8?q?KERNEL-13928=20refactor:=20=E9=87=8D?= =?UTF-8?q?=E6=9E=84=E4=B8=80=E4=BA=9B=E7=94=A8=E5=88=B0=E7=9A=84=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/0.base.js | 54 ++++++++++++++++++---- src/core/controller/controller.tooltips.js | 6 ++- src/core/index.js | 3 ++ src/core/loader/loader.style.js | 34 +++++++------- 4 files changed, 70 insertions(+), 27 deletions(-) diff --git a/src/base/0.base.js b/src/base/0.base.js index 1100c0709..3d342a8d3 100644 --- a/src/base/0.base.js +++ b/src/base/0.base.js @@ -1,9 +1,45 @@ -BI.Resizers = new BI.ResizeController(); -BI.Layers = new BI.LayerController(); -BI.Maskers = new BI.MaskersController(); -BI.Bubbles = new BI.BubblesController(); -BI.Tooltips = new BI.TooltipsController(); -BI.Popovers = new BI.PopoverController(); -BI.Drawers = new BI.DrawerController(); -BI.Broadcasts = new BI.BroadcastController(); -BI.StyleLoaders = new BI.StyleLoaderManager(); +import { + BroadcastController, + BubblesController, + DrawerController, + LayerController, + MaskersController, + PopoverController, + ResizeController, + TooltipsController, + StyleLoaderManager +} from "../core"; + +const Resizers = new ResizeController(); +const Layers = new LayerController(); +const Maskers = new MaskersController(); +const Bubbles = new BubblesController(); +const Tooltips = new TooltipsController(); +const Popovers = new PopoverController(); +const Drawers = new DrawerController(); +const Broadcasts = new BroadcastController(); +const StyleLoaders = new StyleLoaderManager(); + +BI.extend(BI, { + Resizers, + Layers, + Maskers, + Bubbles, + Tooltips, + Popovers, + Drawers, + Broadcasts, + StyleLoaders +}); + +export { + Resizers, + Layers, + Maskers, + Bubbles, + Tooltips, + Popovers, + Drawers, + Broadcasts, + StyleLoaders +}; diff --git a/src/core/controller/controller.tooltips.js b/src/core/controller/controller.tooltips.js index 4b99266e0..0e397aa33 100644 --- a/src/core/controller/controller.tooltips.js +++ b/src/core/controller/controller.tooltips.js @@ -38,13 +38,15 @@ export default class TooltipsController extends Controller { if (!this.has(name)) { this.create(name, tooltipOpt, document.fullscreenElement ? context : (opt.container || "body")); } + const offset = context.element.offset(); + let top; + if (!opt.belowMouse) { - const offset = context.element.offset(); const bounds = context.element.bounds(); if (bounds.height === 0 || bounds.width === 0) { return; } - const top = offset.top + bounds.height + 5; + top = offset.top + bounds.height + 5; } const tooltip = this.get(name); tooltip.element.css({ diff --git a/src/core/index.js b/src/core/index.js index 8c345df4c..3727548fc 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -15,6 +15,7 @@ import MaskersController from "./controller/controller.masker"; import PopoverController from "./controller/controller.popover"; import ResizeController from "./controller/controller.resizer"; import TooltipsController from "./controller/controller.tooltips"; +import StyleLoaderManager from "./loader/loader.style"; BI.extend(BI, { OB, @@ -33,6 +34,7 @@ BI.extend(BI, { PopoverController, ResizeController, TooltipsController, + StyleLoaderManager, }); export { @@ -53,4 +55,5 @@ export { PopoverController, ResizeController, TooltipsController, + StyleLoaderManager, } \ No newline at end of file diff --git a/src/core/loader/loader.style.js b/src/core/loader/loader.style.js index ad5500ee5..e10007cc3 100644 --- a/src/core/loader/loader.style.js +++ b/src/core/loader/loader.style.js @@ -4,21 +4,23 @@ * Created by GUY on 2015/9/7. * @class */ -BI.StyleLoaderManager = BI.inherit(BI.OB, { - _defaultConfig: function () { - return BI.extend(BI.StyleLoaderManager.superclass._defaultConfig.apply(this, arguments), {}); - }, +import OB from "../3.ob"; - _init: function () { - BI.StyleLoaderManager.superclass._init.apply(this, arguments); +export default class StyleLoaderManager extends OB { + _defaultConfig() { + return BI.extend(super._defaultConfig(arguments), {}); + } + + _init() { + super._init(arguments); this.stylesManager = {}; - }, + } - loadStyle: function (name, styleString) { + loadStyle(name, styleString) { if(!_global.document) { return; } - var d = document, styles = d.createElement("style"); + const d = document, styles = d.createElement("style"); d.getElementsByTagName("head")[0].appendChild(styles); styles.setAttribute("type", "text/css"); if (styles.styleSheet) { @@ -29,17 +31,17 @@ BI.StyleLoaderManager = BI.inherit(BI.OB, { this.stylesManager[name] = styles; return this; - }, + } - get: function (name) { + get(name) { return this.stylesManager[name]; - }, + } - has: function (name) { + has(name) { return this.stylesManager[name] != null; - }, + } - removeStyle: function (name) { + removeStyle(name) { if (!this.has(name)) { return this; } @@ -47,4 +49,4 @@ BI.StyleLoaderManager = BI.inherit(BI.OB, { delete this.stylesManager[name]; return this; } -}); \ No newline at end of file +} From a10539682f7d15a9f20108a0327e4c00ef40159f Mon Sep 17 00:00:00 2001 From: impact Date: Wed, 28 Dec 2022 11:43:55 +0800 Subject: [PATCH 014/300] =?UTF-8?q?KERNEL-13928=20refactor:=20es6=E5=8C=96?= =?UTF-8?q?0.single.js?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/index.js | 3 + src/base/single/0.single.js | 227 ++++++++++++++++++------------------ 2 files changed, 118 insertions(+), 112 deletions(-) diff --git a/src/base/index.js b/src/base/index.js index c10043847..46e185ad2 100644 --- a/src/base/index.js +++ b/src/base/index.js @@ -1,9 +1,12 @@ import Pane from "./1.pane"; +import Single from "./single/0.single"; BI.extend(BI, { Pane, + Single, }); export { Pane, + Single, } \ No newline at end of file diff --git a/src/base/single/0.single.js b/src/base/single/0.single.js index c13e02e81..3bb243b85 100644 --- a/src/base/single/0.single.js +++ b/src/base/single/0.single.js @@ -10,11 +10,16 @@ * @abstract */ -var delayingTooltips; +import { Widget, shortcut } from "../../core"; +import BI from "../../core/2.base"; +import { Tooltips } from "../0.base"; -BI.Single = BI.inherit(BI.Widget, { - _defaultConfig: function () { - var conf = BI.Single.superclass._defaultConfig.apply(this, arguments); +@shortcut() +export default class Single extends Widget { + static xtype = "bi.single"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); return BI.extend(conf, { readonly: false, @@ -24,13 +29,22 @@ BI.Single = BI.inherit(BI.Widget, { belowMouse: false, // title是否跟随鼠标 enableHover: false, }); - }, + } - _showToolTip: function (e, opt) { + _showToolTip(e, opt) { opt || (opt = {}); - var self = this; - var o = this.options; - var title = this.getTitle(); + const { action } = this.options; + const title = this.getTitle(); + + const showToolTip = (tooltipOpt) => { + if (BI.isKey(tooltipOpt.text) && !Tooltips.has(this.getName())) { + Tooltips.show(e, this.getName(), tooltipOpt, this, opt); + if (action) { + BI.Actions.runAction(action, "hover", this.options, this); + } + BI.Actions.runGlobalAction("hover", this.options, this); + } + } if (title instanceof Promise) { this.requestingTitle = title; @@ -42,47 +56,37 @@ BI.Single = BI.inherit(BI.Widget, { showToolTip(this._getTooltipOptions(title)); } - function showToolTip(tooltipOpt) { - if (BI.isKey(tooltipOpt.text) && !BI.Tooltips.has(self.getName())) { - BI.Tooltips.show(e, self.getName(), tooltipOpt, self, opt); - if (o.action) { - BI.Actions.runAction(o.action, "hover", o, self); - } - BI.Actions.runGlobalAction("hover", o, self); - } - } - }, + } - _hideTooltip: function () { - var self = this; - var tooltip = BI.Tooltips.get(this.getName()); + _hideTooltip() { + const tooltip = Tooltips.get(this.getName()); if (BI.isNotNull(tooltip)) { - tooltip.element.fadeOut(200, function () { - BI.Tooltips.remove(self.getName()); + tooltip.element.fadeOut(200, () => { + Tooltips.remove(this.getName()); }); } - }, - - _init: function () { - var self = this, o = this.options; - o.value = BI.isFunction(o.value) ? this.__watch(o.value, function (context, newValue) { - self.setValue(newValue); - }) : o.value; - BI.Single.superclass._init.apply(this, arguments); - }, - - _mounted: function () { - var o = this.options; - if (o.enableHover || BI.isKey(o.title) || BI.isKey(o.warningTitle) - || BI.isFunction(o.title) || BI.isFunction(o.warningTitle)) { + } + + _init() { + let { value } = this.options; + value = BI.isFunction(value) ? this.__watch(value, (context, newValue) => { + this.setValue(newValue); + }) : value; + super._init(arguments); + } + + _mounted() { + const { enableHover, title, warningTitle, belowMouse, container } = this.options; + if (enableHover || BI.isKey(title) || BI.isKey(warningTitle) + || BI.isFunction(title) || BI.isFunction(warningTitle)) { this.enableHover({ - belowMouse: o.belowMouse, - container: o.container, + belowMouse, + container, }); } - }, + } - _clearTimeOut: function () { + _clearTimeOut() { if (BI.isNotNull(this.showTimeout)) { clearTimeout(this.showTimeout); this.showTimeout = null; @@ -91,88 +95,88 @@ BI.Single = BI.inherit(BI.Widget, { clearTimeout(this.hideTimeout); this.hideTimeout = null; } - }, + } - _getTooltipOptions: function (title) { - var o = this.options; - var tooltipOpt = {}; + _getTooltipOptions(title) { + const { tipType } = this.options; + let tooltipOpt = {}; if (BI.isPlainObject(title)) { tooltipOpt = title; } else { tooltipOpt.level = this.getTipType() || "success"; // 由于以前的用法,存在大量disabled:true搭配warningTitle的情况,所以这里做一个兼容,disabled:true的情况下,依然优先显示warningTitle,避免只设置了warningTitle而没有设置title的情况 - if (BI.isNull(o.tipType) && !this.isEnabled()) { + if (BI.isNull(tipType) && !this.isEnabled()) { tooltipOpt.text = (this.getWarningTitle() || title); } else { tooltipOpt.text = tooltipOpt.level === "success" ? title : (this.getWarningTitle() || title); } } return tooltipOpt; - }, + } - enableHover: function (opt) { + enableHover(opt) { opt || (opt = {}); - var self = this; + let delayingTooltips; if (!this._hoverBinded) { - this.element.unbind("mouseenter.title").on("mouseenter.title", function (e) { - self._e = e; - self.mouseOver = true; - if (self.getTipType() === "warning" || (BI.isKey(self.getWarningTitle()) && !self.isEnabled())) { - delayingTooltips = self.getName(); - self.showTimeout = BI.delay(function () { - if (BI.isNotNull(self.showTimeout) && delayingTooltips === self.getName()) { - self._showToolTip(self._e || e, opt); + this.element.unbind("mouseenter.title").on("mouseenter.title", (e) => { + this._e = e; + this.mouseOver = true; + if (this.getTipType() === "warning" || (BI.isKey(this.getWarningTitle()) && !this.isEnabled())) { + delayingTooltips = this.getName(); + this.showTimeout = BI.delay(() => { + if (BI.isNotNull(this.showTimeout) && delayingTooltips === this.getName()) { + this._showToolTip(this._e || e, opt); } }, 200); - } else if (self.getTipType() === "success" || self.isEnabled()) { - delayingTooltips = self.getName(); - self.showTimeout = BI.delay(function () { - if (BI.isNotNull(self.showTimeout) && delayingTooltips === self.getName()) { - self._showToolTip(self._e || e, opt); + } else if (this.getTipType() === "success" || this.isEnabled()) { + delayingTooltips = this.getName(); + this.showTimeout = BI.delay(() => { + if (BI.isNotNull(this.showTimeout) && delayingTooltips === this.getName()) { + this._showToolTip(this._e || e, opt); } }, 500); } }); - this.element.unbind("mousemove.title").on("mousemove.title", function (e) { - self._e = e; - if (BI.isNotNull(self.showTimeout)) { - clearTimeout(self.showTimeout); - self.showTimeout = null; + this.element.unbind("mousemove.title").on("mousemove.title", (e) => { + this._e = e; + if (BI.isNotNull(this.showTimeout)) { + clearTimeout(this.showTimeout); + this.showTimeout = null; } - if (BI.isNull(self.hideTimeout)) { - self.hideTimeout = BI.delay(function () { - if (BI.isNotNull(self.hideTimeout)) { - self._hideTooltip(); + if (BI.isNull(this.hideTimeout)) { + this.hideTimeout = BI.delay(() => { + if (BI.isNotNull(this.hideTimeout)) { + this._hideTooltip(); } }, 500); } - self.showTimeout = BI.delay(function () { + this.showTimeout = BI.delay(() => { // DEC-5321 IE下如果回调已经进入事件队列,clearTimeout将不会起作用 - if (BI.isNotNull(self.showTimeout)) { - if (BI.isNotNull(self.hideTimeout)) { - clearTimeout(self.hideTimeout); - self.hideTimeout = null; + if (BI.isNotNull(this.showTimeout)) { + if (BI.isNotNull(this.hideTimeout)) { + clearTimeout(this.hideTimeout); + this.hideTimeout = null; } // CHART-10611 在拖拽的情况下, 鼠标拖拽着元素离开了拖拽元素的容器,但是子元素在dom结构上仍然属于容器 // 这样会认为鼠标仍然在容器中, 500ms内放开的话,会在容器之外显示鼠标停留处显示容器的title - if (self.element.__isMouseInBounds__(self._e || e)) { - self._showToolTip(self._e || e, opt); + if (this.element.__isMouseInBounds__(this._e || e)) { + this._showToolTip(this._e || e, opt); } } }, 500); }); - this.element.unbind("mouseleave.title").on("mouseleave.title", function (e) { - self._e = null; - self.mouseOver = false; - self._clearTimeOut(); - self._hideTooltip(); + this.element.unbind("mouseleave.title").on("mouseleave.title", (e) => { + this._e = null; + this.mouseOver = false; + this._clearTimeOut(); + this._hideTooltip(); }); this._hoverBinded = true; } - }, + } - disabledHover: function () { + disabledHover() { // 取消hover事件 this._clearTimeOut(); this._hideTooltip(); @@ -180,74 +184,73 @@ BI.Single = BI.inherit(BI.Widget, { .unbind("mousemove.title") .unbind("mouseleave.title"); this._hoverBinded = false; - }, + } // opt: {container: '', belowMouse: false} - setTitle: function (title, opt) { + setTitle(title, opt) { this.options.title = title; if (BI.isKey(title) || BI.isFunction(title)) { this.enableHover(opt); } else { this.disabledHover(); } - }, + } - setWarningTitle: function (title, opt) { + setWarningTitle(title, opt) { this.options.warningTitle = title; if (BI.isKey(title) || BI.isFunction(title)) { this.enableHover(opt); } else { this.disabledHover(); } - }, + } - setTipType: function (type) { + setTipType(type) { this.options.tipType = type; - }, + } - getTipType: function () { + getTipType() { return this.options.tipType; - }, + } - isReadOnly: function () { + isReadOnly() { return !!this.options.readonly; - }, + } - getTitle: function () { - var title = this.options.title; + getTitle() { + const title = this.options.title; if (BI.isFunction(title)) { return title(); } return title; - }, + } - getWarningTitle: function () { - var title = this.options.warningTitle; + getWarningTitle() { + const title = this.options.warningTitle; if (BI.isFunction(title)) { return title(); } return title; - }, + } - setValue: function (val) { + setValue(val) { if (!this.options.readonly) { this.options.value = val; this.options.setValue && this.options.setValue(val); } - }, + } - getValue: function () { + getValue() { return this.options.value; - }, + } - _destroyed: function () { + _destroyed() { if (BI.isNotNull(this.showTimeout)) { clearTimeout(this.showTimeout); this.showTimeout = null; } - BI.Tooltips.remove(this.getName()); - }, -}); -BI.shortcut("bi.single", BI.Single); + Tooltips.remove(this.getName()); + } +} From 2314d4b58b3b9b5abf889e2221e400ba6edcfdbc Mon Sep 17 00:00:00 2001 From: impact Date: Wed, 28 Dec 2022 14:13:55 +0800 Subject: [PATCH 015/300] =?UTF-8?q?KERNEL-13928=20refactor:=20es6=E5=8C=96?= =?UTF-8?q?1.text.js?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/index.js | 3 + src/base/single/1.text.js | 331 +++++++++++++++++++------------------- 2 files changed, 170 insertions(+), 164 deletions(-) diff --git a/src/base/index.js b/src/base/index.js index 46e185ad2..b3a77f840 100644 --- a/src/base/index.js +++ b/src/base/index.js @@ -1,12 +1,15 @@ import Pane from "./1.pane"; import Single from "./single/0.single"; +import Text from "./single/1.text"; BI.extend(BI, { Pane, Single, + Text, }); export { Pane, Single, + Text, } \ No newline at end of file diff --git a/src/base/single/1.text.js b/src/base/single/1.text.js index f31ebfe43..d1ccec69b 100644 --- a/src/base/single/1.text.js +++ b/src/base/single/1.text.js @@ -3,172 +3,175 @@ * @class BI.Text * @extends BI.Single */ -!(function () { - BI.Text = BI.inherit(BI.Single, { - - props: { - baseCls: "bi-text", - textAlign: "left", - whiteSpace: "normal", - lineHeight: null, - handler: null, // 如果传入handler,表示处理文字的点击事件,不是区域的 - hgap: 0, - vgap: 0, - lgap: 0, - rgap: 0, - tgap: 0, - bgap: 0, - py: "", - highLight: false, - }, - - render: function () { - var self = this, o = this.options; - if (o.hgap + o.lgap > 0) { - this.element.css({ - "padding-left": BI.pixFormat(o.hgap + o.lgap), - }); - } - if (o.hgap + o.rgap > 0) { - this.element.css({ - "padding-right": BI.pixFormat(o.hgap + o.rgap), - }); - } - if (o.vgap + o.tgap > 0) { - this.element.css({ - "padding-top": BI.pixFormat(o.vgap + o.tgap), - }); - } - if (o.vgap + o.bgap > 0) { - this.element.css({ - "padding-bottom": BI.pixFormat(o.vgap + o.bgap), - }); - } - if (BI.isWidthOrHeight(o.height)) { - this.element.css({ lineHeight: BI.pixFormat(o.height) }); - } - if (BI.isWidthOrHeight(o.lineHeight)) { - this.element.css({ lineHeight: BI.pixFormat(o.lineHeight) }); - } - if (BI.isWidthOrHeight(o.maxWidth)) { - this.element.css({ maxWidth: BI.pixFormat(o.maxWidth) }); - } +import { shortcut } from "../../core/decorator"; +import { Single } from "../index"; +import BI from "../../core/2.base"; + +@shortcut() +export default class Text extends Single { + static xtype = "bi.text"; + + props = { + baseCls: "bi-text", + textAlign: "left", + whiteSpace: "normal", + lineHeight: null, + handler: null, // 如果传入handler,表示处理文字的点击事件,不是区域的 + hgap: 0, + vgap: 0, + lgap: 0, + rgap: 0, + tgap: 0, + bgap: 0, + py: "", + highLight: false, + } + + render() { + const { vgap, hgap, lgap, rgap, tgap, bgap, height, lineHeight, maxWidth, textAlign, whiteSpace, handler, disabled, invalid, text: optionsText, value, keyword, highLight } = this.options; + if (hgap + lgap > 0) { this.element.css({ - textAlign: o.textAlign, - whiteSpace: this._getTextWrap(), - textOverflow: o.whiteSpace === "nowrap" ? "ellipsis" : "", - overflow: o.whiteSpace === "nowrap" ? "" : (BI.isWidthOrHeight(o.height) ? "auto" : ""), + "padding-left": BI.pixFormat(hgap + lgap), }); - if (o.handler && o.handler !== BI.emptyFn) { - this.text = BI.createWidget({ - type: "bi.layout", - tagName: "span", - }); - this.text.element.click(function (e) { - !o.disabled && !o.invalid && o.handler.call(self, self.getValue(), self, e); - }); - BI.createWidget({ - type: "bi.default", - element: this, - items: [this.text], - }); - } else { - this.text = this; - } - - var text = BI.isFunction(o.text) ? this.__watch(o.text, function (context, newValue) { - self.setText(newValue); - }) : o.text; - // 只要不是undefined就可以显示text值,否则显示value - if (!BI.isUndefined(text)) { - this.setText(text); - } else if (BI.isKey(o.value)) { - this.setText(o.value); - } - if (BI.isKey(o.keyword)) { - this.doRedMark(o.keyword); - } - if (o.highLight) { - this.doHighLight(); - } - }, - - _getTextWrap: function () { - var o = this.options; - switch (o.whiteSpace) { - case "nowrap": - return "pre"; - case "normal": - return "pre-wrap"; - default: - return o.whiteSpace; - } - }, - - _getShowText: function () { - var o = this.options; - var text = BI.isFunction(o.text) ? o.text() : o.text; - - return BI.isKey(text) ? BI.Text.formatText(text + "") : text; - }, - - _doRedMark: function (keyword) { - var o = this.options; - // render之后做的doRedMark,这个时候虽然标红了,但是之后text mounted执行的时候并没有keyword - o.keyword = keyword; - this.text.element.__textKeywordMarked__(this._getShowText(), keyword, o.py); - }, - - doRedMark: function (keyword) { - if (BI.isKey(keyword)) { - this._doRedMark(keyword); - } - }, - - unRedMark: function () { - var o = this.options; - o.keyword = ""; - this.text.element.__textKeywordMarked__(this._getShowText(), "", o.py); - }, - - doHighLight: function () { - this.text.element.addClass("bi-high-light"); - }, - - unHighLight: function () { - this.text.element.removeClass("bi-high-light"); - }, - - setValue: function (text) { - BI.Text.superclass.setValue.apply(this, arguments); - if (!this.isReadOnly()) { - this.setText(text); - } - }, - - setStyle: function (css) { - this.text.element.css(css); - }, - - setText: function (text) { - BI.Text.superclass.setText.apply(this, arguments); - this.options.text = text; - this._doRedMark(this.options.keyword); - }, - }); - var formatters = []; - BI.Text.addTextFormatter = function (formatter) { - formatters.push(formatter); - }; - BI.Text.formatText = function (text) { - if (formatters.length > 0) { - for (var i = 0, len = formatters.length; i < len; i++) { - text = formatters[i](text); - } } + if (hgap + rgap > 0) { + this.element.css({ + "padding-right": BI.pixFormat(hgap + rgap), + }); + } + if (vgap + tgap > 0) { + this.element.css({ + "padding-top": BI.pixFormat(vgap + tgap), + }); + } + if (vgap + bgap > 0) { + this.element.css({ + "padding-bottom": BI.pixFormat(vgap + bgap), + }); + } + if (BI.isWidthOrHeight(height)) { + this.element.css({ lineHeight: BI.pixFormat(height) }); + } + if (BI.isWidthOrHeight(lineHeight)) { + this.element.css({ lineHeight: BI.pixFormat(lineHeight) }); + } + if (BI.isWidthOrHeight(maxWidth)) { + this.element.css({ maxWidth: BI.pixFormat(maxWidth) }); + } + this.element.css({ + textAlign: textAlign, + whiteSpace: this._getTextWrap(), + textOverflow: whiteSpace === "nowrap" ? "ellipsis" : "", + overflow: whiteSpace === "nowrap" ? "" : (BI.isWidthOrHeight(height) ? "auto" : ""), + }); + if (handler && handler !== BI.emptyFn) { + this.text = BI.createWidget({ + type: "bi.layout", + tagName: "span", + }); + this.text.element.click((e) => { + !disabled && !invalid && handler.call(this, this.getValue(), this, e); + }); + BI.createWidget({ + type: "bi.default", + element: this, + items: [this.text], + }); + } else { + this.text = this; + } + + const text = BI.isFunction(optionsText) ? this.__watch(optionsText, (context, newValue) => { + this.setText(newValue); + }) : optionsText; + // 只要不是undefined就可以显示text值,否则显示value + if (!BI.isUndefined(text)) { + this.setText(text); + } else if (BI.isKey(value)) { + this.setText(value); + } + if (BI.isKey(keyword)) { + this.doRedMark(keyword); + } + if (highLight) { + this.doHighLight(); + } + } + + _getTextWrap() { + const { whiteSpace } = this.options; + switch (whiteSpace) { + case "nowrap": + return "pre"; + case "normal": + return "pre-wrap"; + default: + return whiteSpace; + } + } - return text; - }; - BI.shortcut("bi.text", BI.Text); -}()); + _getShowText() { + const { text: optionsText } = this.options; + const text = BI.isFunction(optionsText) ? optionsText() : optionsText; + + return BI.isKey(text) ? Text.formatText(text + "") : text; + } + + _doRedMark(keyword) { + const { py } = this.options; + // render之后做的doRedMark,这个时候虽然标红了,但是之后text mounted执行的时候并没有keyword + this.options.keyword = keyword; + this.text.element.__textKeywordMarked__(this._getShowText(), keyword, py); + } + + doRedMark(keyword) { + if (BI.isKey(keyword)) { + this._doRedMark(keyword); + } + } + + unRedMark() { + const { py } = this.options; + this.options.keyword = ""; + this.text.element.__textKeywordMarked__(this._getShowText(), "", py); + } + + doHighLight() { + this.text.element.addClass("bi-high-light"); + } + + unHighLight() { + this.text.element.removeClass("bi-high-light"); + } + + setValue(text) { + super.setValue(text); + if (!this.isReadOnly()) { + this.setText(text); + } + } + + setStyle(css) { + this.text.element.css(css); + } + + setText(text) { + super.setText(text); + this.options.text = text; + this._doRedMark(this.options.keyword); + } +} + +const formatters = []; +Text.addTextFormatter = (formatter) => { + formatters.push(formatter); +}; +Text.formatText = (text) => { + if (formatters.length > 0) { + for (let i = 0; i < formatters.length; i++) { + text = formatters[i](text); + } + } + return text; +}; From 7f5eeb430c732927b379809d2eb94293620ccf61 Mon Sep 17 00:00:00 2001 From: impact Date: Wed, 28 Dec 2022 14:32:46 +0800 Subject: [PATCH 016/300] =?UTF-8?q?KERNEL-13928=20refactor:=20=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E8=A7=A3=E6=9E=84=E8=B5=8B=E5=80=BC=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E7=9A=84=E5=9C=B0=E6=96=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/single/0.single.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/base/single/0.single.js b/src/base/single/0.single.js index 3bb243b85..41550402b 100644 --- a/src/base/single/0.single.js +++ b/src/base/single/0.single.js @@ -68,8 +68,8 @@ export default class Single extends Widget { } _init() { - let { value } = this.options; - value = BI.isFunction(value) ? this.__watch(value, (context, newValue) => { + const { value } = this.options; + this.options.value = BI.isFunction(value) ? this.__watch(value, (context, newValue) => { this.setValue(newValue); }) : value; super._init(arguments); From a941b90118c0e27f6f54e4c1d927056836133a78 Mon Sep 17 00:00:00 2001 From: impact Date: Wed, 28 Dec 2022 14:38:13 +0800 Subject: [PATCH 017/300] =?UTF-8?q?KERNEL-13928=20refactor:=20=E5=8E=BB?= =?UTF-8?q?=E6=8E=89=E5=A4=9A=E4=BD=99=E7=9A=84=E5=BC=95=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/single/0.single.js | 1 - src/base/single/1.text.js | 1 - 2 files changed, 2 deletions(-) diff --git a/src/base/single/0.single.js b/src/base/single/0.single.js index 41550402b..845e8c33d 100644 --- a/src/base/single/0.single.js +++ b/src/base/single/0.single.js @@ -11,7 +11,6 @@ */ import { Widget, shortcut } from "../../core"; -import BI from "../../core/2.base"; import { Tooltips } from "../0.base"; @shortcut() diff --git a/src/base/single/1.text.js b/src/base/single/1.text.js index d1ccec69b..33001a7bd 100644 --- a/src/base/single/1.text.js +++ b/src/base/single/1.text.js @@ -5,7 +5,6 @@ */ import { shortcut } from "../../core/decorator"; import { Single } from "../index"; -import BI from "../../core/2.base"; @shortcut() export default class Text extends Single { From 67cfec57aec6464bf1f5a6552c8ba2d612b311a4 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Wed, 28 Dec 2022 17:56:18 +0800 Subject: [PATCH 018/300] =?UTF-8?q?KERNEL-13947=20refactor:=20=E5=A4=84?= =?UTF-8?q?=E7=90=86=E7=BB=A7=E6=89=BFOB=E5=AF=B9=E8=B1=A1=E7=9A=84?= =?UTF-8?q?=E6=89=A7=E8=A1=8C=E9=A1=BA=E5=BA=8F=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/controller/controller.drawer.js | 6 +++++- src/core/controller/controller.layer.js | 5 +++++ src/core/controller/controller.popover.js | 13 ++++++++----- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/core/controller/controller.drawer.js b/src/core/controller/controller.drawer.js index 4b2daca9e..b808699c2 100644 --- a/src/core/controller/controller.drawer.js +++ b/src/core/controller/controller.drawer.js @@ -6,13 +6,17 @@ */ import Controller from "./0.controller"; export default class DrawerController extends Controller { + constructor() { + super(); + this._constructor(); + this.modal = this.options.modal; + } props = { modal: true, // 模态窗口 render: "body" } init() { - this.modal = this.options.modal; this.floatManager = {}; this.floatLayer = {}; this.floatContainer = {}; diff --git a/src/core/controller/controller.layer.js b/src/core/controller/controller.layer.js index a2a6735b7..10092b560 100644 --- a/src/core/controller/controller.layer.js +++ b/src/core/controller/controller.layer.js @@ -6,6 +6,11 @@ */ import Controller from "./0.controller"; export default class LayerController extends Controller { + constructor() { + super(); + this._constructor(); + } + props = { render: "body" } diff --git a/src/core/controller/controller.popover.js b/src/core/controller/controller.popover.js index bcb129f3b..0c48b68ec 100644 --- a/src/core/controller/controller.popover.js +++ b/src/core/controller/controller.popover.js @@ -6,13 +6,18 @@ */ import Controller from "./0.controller"; export default class PopoverController extends Controller { + constructor() { + super(); + this._constructor(); + this.modal = this.options.modal; + } + props = { modal: true, // 模态窗口 render: "body" } init() { - this.modal = this.options.modal; this.floatManager = {}; this.floatLayer = {}; this.floatContainer = {}; @@ -50,7 +55,7 @@ export default class PopoverController extends Controller { const W = BI.Widget._renderEngine.createElement(this.options.render).width(), H = BI.Widget._renderEngine.createElement(this.options.render).height(); const w = popover.element.width(), h = popover.element.height(); - const left = (W - w) / 2, top = (H - h) / 2; + let left = (W - w) / 2, top = (H - h) / 2; if (left < 0) { left = 0; } @@ -110,9 +115,7 @@ export default class PopoverController extends Controller { }] }); this.floatManager[name] = popover; - (function (key) { - popover.on(BI.Popover.EVENT_CLOSE, () => self.close(key)); - })(name); + popover.on(BI.Popover.EVENT_CLOSE, () => this.close(name)); BI.createWidget({ type: "bi.absolute", element: options.container || this.options.render, From 0af2b5afdbcb60b320f03c398a2b6105a2108818 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Thu, 29 Dec 2022 13:59:29 +0800 Subject: [PATCH 019/300] =?UTF-8?q?KERNEL-13947=20refactor:=20Drawer?= =?UTF-8?q?=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/controller/controller.drawer.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/core/controller/controller.drawer.js b/src/core/controller/controller.drawer.js index b808699c2..c288d019f 100644 --- a/src/core/controller/controller.drawer.js +++ b/src/core/controller/controller.drawer.js @@ -106,9 +106,7 @@ export default class DrawerController extends Controller { }] }); this.floatManager[name] = popover; - (function (key) { - popover.on(BI.Drawer.EVENT_CLOSE, () => this.close(key)); - })(name); + popover.on(BI.Drawer.EVENT_CLOSE, () => this.close(name)); BI.createWidget({ type: "bi.absolute", element: options.container || this.options.render, From 3c98a6b4b8727586ddaa99565f775921e3d5478e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Thu, 29 Dec 2022 14:00:25 +0800 Subject: [PATCH 020/300] =?UTF-8?q?KERNEL-13841=20refactor:base=E6=96=87?= =?UTF-8?q?=E4=BB=B6es6=E5=8C=96=E4=B8=8Eimport=E5=BC=95=E5=85=A5=E9=80=82?= =?UTF-8?q?=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/grid/grid.js | 305 ++++++++++++------------ src/base/index.js | 42 ++++ src/base/layer/layer.drawer.js | 6 +- src/base/layer/layer.popover.js | 9 +- src/base/layer/layer.popup.js | 14 +- src/base/layer/layer.searcher.js | 7 +- src/base/list/listview.js | 250 ++++++++++---------- src/base/list/virtualgrouplist.js | 353 ++++++++++++++-------------- src/base/list/virtuallist.js | 357 +++++++++++++++-------------- src/base/pager/pager.js | 151 ++++++------ src/base/single/a/a.js | 7 +- src/base/single/tip/0.tip.js | 5 +- src/base/single/tip/tip.toast.js | 6 +- src/base/single/tip/tip.tooltip.js | 7 +- 14 files changed, 782 insertions(+), 737 deletions(-) diff --git a/src/base/grid/grid.js b/src/base/grid/grid.js index 944a82d4a..4ee6e6332 100644 --- a/src/base/grid/grid.js +++ b/src/base/grid/grid.js @@ -5,9 +5,11 @@ * @class BI.GridView * @extends BI.Widget */ -BI.GridView = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.GridView.superclass._defaultConfig.apply(this, arguments), { +import { Widget, shortcut } from "../../core"; +@shortcut() +export default class GridView extends Widget { + _defaultConfig() { + return BI.extend(super._defaultConfig(arguments), { baseCls: "bi-grid-view", // width: 400, //必设 // height: 300, //必设 @@ -28,50 +30,54 @@ BI.GridView = BI.inherit(BI.Widget, { scrollLeft: 0, scrollTop: 0, items: [], - itemFormatter: function (item, row, col) { + itemFormatter: (item, row, col)=> { return item; }, }); - }, + } - render: function () { - var self = this, o = this.options; + static xtype = "bi.grid_view"; + static EVENT_SCROLL = "EVENT_SCROLL"; + + render() { + const o = this.options; + const { overflowX, overflowY, el } = this.options; this.renderedCells = []; this.renderedKeys = []; this.renderRange = {}; this._scrollLock = false; - this._debounceRelease = BI.debounce(function () { - self._scrollLock = false; + this._debounceRelease = BI.debounce(()=> { + this._scrollLock = false; }, 1000 / 60); this.container = BI._lazyCreateWidget({ type: "bi.absolute", }); - this.element.scroll(function () { - if (self._scrollLock === true) { + this.element.scroll(()=> { + if (this._scrollLock === true) { return; } - o.scrollLeft = self.element.scrollLeft(); - o.scrollTop = self.element.scrollTop(); - self._calculateChildrenToRender(); - self.fireEvent(BI.GridView.EVENT_SCROLL, { + o.scrollLeft = this.element.scrollLeft(); + o.scrollTop = this.element.scrollTop(); + this._calculateChildrenToRender(); + this.fireEvent(GridView.EVENT_SCROLL, { scrollLeft: o.scrollLeft, scrollTop: o.scrollTop, }); }); // 兼容一下 - var scrollable = o.scrollable, scrollx = o.scrollx, scrolly = o.scrolly; - if (o.overflowX === false) { - if (o.overflowY === false) { + let scrollable = o.scrollable, scrollx = o.scrollx, scrolly = o.scrolly; + if (overflowX === false) { + if (overflowY === false) { scrollable = false; } else { scrollable = "y"; } } else { - if (o.overflowY === false) { + if (overflowY === false) { scrollable = "x"; } } - BI._lazyCreateWidget(o.el, { + BI._lazyCreateWidget(el, { type: "bi.vertical", element: this, scrollable: scrollable, @@ -79,111 +85,113 @@ BI.GridView = BI.inherit(BI.Widget, { scrollx: scrollx, items: [this.container], }); - o.items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + o.items = BI.isFunction(o.items) ? this.__watch(o.items, (context, newValue)=> { + this.populate(newValue); }) : o.items; if (o.items.length > 0) { this._calculateSizeAndPositionData(); this._populate(); } - }, + } // mounted之后绑定事件 - mounted: function () { - var o = this.options; - if (o.scrollLeft !== 0 || o.scrollTop !== 0) { - this.element.scrollTop(o.scrollTop); - this.element.scrollLeft(o.scrollLeft); + mounted() { + const { scrollLeft, scrollTop } = this.options; + if (scrollLeft !== 0 || scrollTop !== 0) { + this.element.scrollTop(scrollTop); + this.element.scrollLeft(scrollLeft); } - }, + } - destroyed: function () { - BI.each(this.renderedCells, function(i, cell) { + destroyed() { + BI.each(this.renderedCells, (i, cell)=> { cell.el._destroy(); }) - }, + } - _calculateSizeAndPositionData: function () { - var o = this.options; + _calculateSizeAndPositionData() { + const { columnCount, items, rowCount, columnWidthGetter, estimatedColumnSize, rowHeightGetter, estimatedRowSize } = this.options; this.rowCount = 0; this.columnCount = 0; - if (BI.isNumber(o.columnCount)) { - this.columnCount = o.columnCount; - } else if (o.items.length > 0) { - this.columnCount = o.items[0].length; + if (BI.isNumber(columnCount)) { + this.columnCount = columnCount; + } else if (items.length > 0) { + this.columnCount = items[0].length; } - if (BI.isNumber(o.rowCount)) { - this.rowCount = o.rowCount; + if (BI.isNumber(rowCount)) { + this.rowCount = rowCount; } else { - this.rowCount = o.items.length; + this.rowCount = items.length; } - this._columnSizeAndPositionManager = new BI.ScalingCellSizeAndPositionManager(this.columnCount, o.columnWidthGetter, o.estimatedColumnSize); - this._rowSizeAndPositionManager = new BI.ScalingCellSizeAndPositionManager(this.rowCount, o.rowHeightGetter, o.estimatedRowSize); - }, + this._columnSizeAndPositionManager = new BI.ScalingCellSizeAndPositionManager(this.columnCount, columnWidthGetter, estimatedColumnSize); + this._rowSizeAndPositionManager = new BI.ScalingCellSizeAndPositionManager(this.rowCount, rowHeightGetter, estimatedRowSize); + } - _getOverscanIndices: function (cellCount, overscanCellsCount, startIndex, stopIndex) { + _getOverscanIndices(cellCount, overscanCellsCount, startIndex, stopIndex) { return { overscanStartIndex: Math.max(0, startIndex - overscanCellsCount), overscanStopIndex: Math.min(cellCount - 1, stopIndex + overscanCellsCount), }; - }, + } + + _calculateChildrenToRender() { + const o = this.options; - _calculateChildrenToRender: function () { - var self = this, o = this.options; + const { itemFormatter, items } = this.options; - var width = o.width, height = o.height, scrollLeft = BI.clamp(o.scrollLeft, 0, this._getMaxScrollLeft()), + const width = o.width, height = o.height, scrollLeft = BI.clamp(o.scrollLeft, 0, this._getMaxScrollLeft()), scrollTop = BI.clamp(o.scrollTop, 0, this._getMaxScrollTop()), overscanColumnCount = o.overscanColumnCount, overscanRowCount = o.overscanRowCount; if (height > 0 && width > 0) { - var visibleColumnIndices = this._columnSizeAndPositionManager.getVisibleCellRange(width, scrollLeft); - var visibleRowIndices = this._rowSizeAndPositionManager.getVisibleCellRange(height, scrollTop); + const visibleColumnIndices = this._columnSizeAndPositionManager.getVisibleCellRange(width, scrollLeft); + const visibleRowIndices = this._rowSizeAndPositionManager.getVisibleCellRange(height, scrollTop); - var renderedCells = [], renderedKeys = {}, renderedWidgets = {}; + const renderedCells = [], renderedKeys = {}, renderedWidgets = {}; + let minX = this._getMaxScrollLeft(), minY = this._getMaxScrollTop(), maxX = 0, maxY = 0; // 没有可见的单元格就干掉所有渲染过的 if (!BI.isEmpty(visibleColumnIndices) && !BI.isEmpty(visibleRowIndices)) { - var horizontalOffsetAdjustment = this._columnSizeAndPositionManager.getOffsetAdjustment(width, scrollLeft); - var verticalOffsetAdjustment = this._rowSizeAndPositionManager.getOffsetAdjustment(height, scrollTop); + const horizontalOffsetAdjustment = this._columnSizeAndPositionManager.getOffsetAdjustment(width, scrollLeft); + const verticalOffsetAdjustment = this._rowSizeAndPositionManager.getOffsetAdjustment(height, scrollTop); this._renderedColumnStartIndex = visibleColumnIndices.start; this._renderedColumnStopIndex = visibleColumnIndices.stop; this._renderedRowStartIndex = visibleRowIndices.start; this._renderedRowStopIndex = visibleRowIndices.stop; - var overscanColumnIndices = this._getOverscanIndices(this.columnCount, overscanColumnCount, this._renderedColumnStartIndex, this._renderedColumnStopIndex); + const overscanColumnIndices = this._getOverscanIndices(this.columnCount, overscanColumnCount, this._renderedColumnStartIndex, this._renderedColumnStopIndex); - var overscanRowIndices = this._getOverscanIndices(this.rowCount, overscanRowCount, this._renderedRowStartIndex, this._renderedRowStopIndex); + const overscanRowIndices = this._getOverscanIndices(this.rowCount, overscanRowCount, this._renderedRowStartIndex, this._renderedRowStopIndex); - var columnStartIndex = overscanColumnIndices.overscanStartIndex; - var columnStopIndex = overscanColumnIndices.overscanStopIndex; - var rowStartIndex = overscanRowIndices.overscanStartIndex; - var rowStopIndex = overscanRowIndices.overscanStopIndex; + const columnStartIndex = overscanColumnIndices.overscanStartIndex; + const columnStopIndex = overscanColumnIndices.overscanStopIndex; + const rowStartIndex = overscanRowIndices.overscanStartIndex; + const rowStopIndex = overscanRowIndices.overscanStopIndex; // 算区间size - var minRowDatum = this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowStartIndex); - var minColumnDatum = this._columnSizeAndPositionManager.getSizeAndPositionOfCell(columnStartIndex); - var maxRowDatum = this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowStopIndex); - var maxColumnDatum = this._columnSizeAndPositionManager.getSizeAndPositionOfCell(columnStopIndex); - var top = minRowDatum.offset + verticalOffsetAdjustment; - var left = minColumnDatum.offset + horizontalOffsetAdjustment; - var bottom = maxRowDatum.offset + verticalOffsetAdjustment + maxRowDatum.size; - var right = maxColumnDatum.offset + horizontalOffsetAdjustment + maxColumnDatum.size; + const minRowDatum = this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowStartIndex); + const minColumnDatum = this._columnSizeAndPositionManager.getSizeAndPositionOfCell(columnStartIndex); + const maxRowDatum = this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowStopIndex); + const maxColumnDatum = this._columnSizeAndPositionManager.getSizeAndPositionOfCell(columnStopIndex); + const top = minRowDatum.offset + verticalOffsetAdjustment; + const left = minColumnDatum.offset + horizontalOffsetAdjustment; + const bottom = maxRowDatum.offset + verticalOffsetAdjustment + maxRowDatum.size; + const right = maxColumnDatum.offset + horizontalOffsetAdjustment + maxColumnDatum.size; // 如果滚动的区间并没有超出渲染的范围 if (top >= this.renderRange.minY && bottom <= this.renderRange.maxY && left >= this.renderRange.minX && right <= this.renderRange.maxX) { return; } - var minX = this._getMaxScrollLeft(), minY = this._getMaxScrollTop(), maxX = 0, maxY = 0; - var count = 0; - for (var rowIndex = rowStartIndex; rowIndex <= rowStopIndex; rowIndex++) { - var rowDatum = this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowIndex); + let count = 0; + for (let rowIndex = rowStartIndex; rowIndex <= rowStopIndex; rowIndex++) { + const rowDatum = this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowIndex); - for (var columnIndex = columnStartIndex; columnIndex <= columnStopIndex; columnIndex++) { - var key = rowIndex + "-" + columnIndex; - var columnDatum = this._columnSizeAndPositionManager.getSizeAndPositionOfCell(columnIndex); + for (let columnIndex = columnStartIndex; columnIndex <= columnStopIndex; columnIndex++) { + const key = rowIndex + "-" + columnIndex; + const columnDatum = this._columnSizeAndPositionManager.getSizeAndPositionOfCell(columnIndex); - var index = this.renderedKeys[key] && this.renderedKeys[key][2]; - var child; + const index = this.renderedKeys[key] && this.renderedKeys[key][2]; + let child; if (index >= 0) { this.renderedCells[index].el.setWidth(columnDatum.size); this.renderedCells[index].el.setHeight(rowDatum.size); @@ -193,7 +201,7 @@ BI.GridView = BI.inherit(BI.Widget, { child = this.renderedCells[index].el; renderedCells.push(this.renderedCells[index]); } else { - var item = o.itemFormatter(o.items[rowIndex][columnIndex], rowIndex, columnIndex); + const item = itemFormatter(items[rowIndex][columnIndex], rowIndex, columnIndex); child = BI._lazyCreateWidget(BI.extend({ type: "bi.label", width: columnDatum.size, @@ -226,9 +234,9 @@ BI.GridView = BI.inherit(BI.Widget, { } } // 已存在的, 需要添加的和需要删除的 - var existSet = {}, addSet = {}, deleteArray = []; - BI.each(renderedKeys, function (i, key) { - if (self.renderedKeys[i]) { + const existSet = {}, addSet = {}, deleteArray = []; + BI.each(renderedKeys, (i, key)=> { + if (this.renderedKeys[i]) { existSet[i] = key; } else { addSet[i] = key; @@ -243,11 +251,11 @@ BI.GridView = BI.inherit(BI.Widget, { } deleteArray.push(key[2]); }); - BI.each(deleteArray, function (i, index) { + BI.each(deleteArray, (i, index)=> { // 性能优化,不调用destroy方法防止触发destroy事件 - self.renderedCells[index].el._destroy(); + this.renderedCells[index].el._destroy(); }); - var addedItems = []; + const addedItems = []; BI.each(addSet, function (index, key) { addedItems.push(renderedCells[key[2]]); }); @@ -260,13 +268,12 @@ BI.GridView = BI.inherit(BI.Widget, { this.renderedKeys = renderedKeys; this.renderRange = { minX: minX, minY: minY, maxX: maxX, maxY: maxY }; } - }, + } - _isOverflowX: function () { - var o = this.options; + _isOverflowX() { + const { scrollable, scrollx, overflowX } = this.options; // 兼容一下 - var scrollable = o.scrollable, scrollx = o.scrollx; - if (o.overflowX === false) { + if (overflowX === false) { return false; } if (scrollx) { @@ -276,13 +283,13 @@ BI.GridView = BI.inherit(BI.Widget, { return true; } return false; - }, + } - _isOverflowY: function () { - var o = this.options; + _isOverflowY() { + const { scrollable, scrolly, overflowX } = this.options; // 兼容一下 - var scrollable = o.scrollable, scrolly = o.scrolly; - if (o.overflowX === false) { + // var scrollable = o.scrollable, scrolly = o.scrolly; + if (overflowX === false) { return false; } if (scrolly) { @@ -292,26 +299,26 @@ BI.GridView = BI.inherit(BI.Widget, { return true; } return false; - }, + } - _getMaxScrollLeft: function () { + _getMaxScrollLeft() { return Math.max(0, this._getContainerWidth() - this.options.width + (this._isOverflowX() ? BI.DOM.getScrollWidth() : 0)); - }, + } - _getMaxScrollTop: function () { + _getMaxScrollTop() { return Math.max(0, this._getContainerHeight() - this.options.height + (this._isOverflowY() ? BI.DOM.getScrollWidth() : 0)); - }, + } - _getContainerWidth: function () { + _getContainerWidth() { return this.columnCount * this.options.estimatedColumnSize; - }, + } - _getContainerHeight: function () { + _getContainerHeight() { return this.rowCount * this.options.estimatedRowSize; - }, + } - _populate: function (items) { - var o = this.options; + _populate(items) { + const { scrollTop, scrollLeft } = this.options; this._reRange(); if (items && items !== this.options.items) { this.options.items = items; @@ -323,14 +330,14 @@ BI.GridView = BI.inherit(BI.Widget, { // 元素未挂载时不能设置scrollTop this._debounceRelease(); try { - this.element.scrollTop(o.scrollTop); - this.element.scrollLeft(o.scrollLeft); + this.element.scrollTop(scrollTop); + this.element.scrollLeft(scrollLeft); } catch (e) { } this._calculateChildrenToRender(); - }, + } - setScrollLeft: function (scrollLeft) { + setScrollLeft(scrollLeft) { if (this.options.scrollLeft === scrollLeft) { return; } @@ -339,9 +346,9 @@ BI.GridView = BI.inherit(BI.Widget, { this._debounceRelease(); this.element.scrollLeft(this.options.scrollLeft); this._calculateChildrenToRender(); - }, + } - setScrollTop: function (scrollTop) { + setScrollTop(scrollTop) { if (this.options.scrollTop === scrollTop) { return; } @@ -350,72 +357,68 @@ BI.GridView = BI.inherit(BI.Widget, { this._debounceRelease(); this.element.scrollTop(this.options.scrollTop); this._calculateChildrenToRender(); - }, + } - setColumnCount: function (columnCount) { + setColumnCount(columnCount) { this.options.columnCount = columnCount; - }, + } - setRowCount: function (rowCount) { + setRowCount(rowCount) { this.options.rowCount = rowCount; - }, + } - setOverflowX: function (b) { - var self = this; + setOverflowX(b) { if (this.options.overflowX !== !!b) { this.options.overflowX = !!b; - BI.nextTick(function () { - self.element.css({ overflowX: b ? "auto" : "hidden" }); + BI.nextTick(()=> { + this.element.css({ overflowX: b ? "auto" : "hidden" }); }); } - }, + } - setOverflowY: function (b) { - var self = this; + setOverflowY(b) { if (this.options.overflowY !== !!b) { this.options.overflowY = !!b; - BI.nextTick(function () { - self.element.css({ overflowY: b ? "auto" : "hidden" }); + BI.nextTick(()=> { + this.element.css({ overflowY: b ? "auto" : "hidden" }); }); } - }, + } - getScrollLeft: function () { + getScrollLeft() { return this.options.scrollLeft; - }, - - getScrollTop: function () { + } + getScrollTop() { return this.options.scrollTop; - }, + } - getMaxScrollLeft: function () { + getMaxScrollLeft() { return this._getMaxScrollLeft(); - }, + } - getMaxScrollTop: function () { + getMaxScrollTop() { return this._getMaxScrollTop(); - }, + } - setEstimatedColumnSize: function (width) { + setEstimatedColumnSize(width) { this.options.estimatedColumnSize = width; - }, + } - setEstimatedRowSize: function (height) { + setEstimatedRowSize(height) { this.options.estimatedRowSize = height; - }, - + } // 重新计算children - _reRange: function () { + _reRange() { this.renderRange = {}; - }, + } - _clearChildren: function () { + _clearChildren() { this.container._children = {}; this.container.attr("items", []); - }, + } - restore: function () { - BI.each(this.renderedCells, function (i, cell) { + restore() { + BI.each(this.renderedCells, (i, cell)=> { cell.el._destroy(); }); this._clearChildren(); @@ -423,14 +426,12 @@ BI.GridView = BI.inherit(BI.Widget, { this.renderedKeys = []; this.renderRange = {}; this._scrollLock = false; - }, + } - populate: function (items) { + populate(items) { if (items && items !== this.options.items) { this.restore(); } this._populate(items); - }, -}); -BI.GridView.EVENT_SCROLL = "EVENT_SCROLL"; -BI.shortcut("bi.grid_view", BI.GridView); + } +} diff --git a/src/base/index.js b/src/base/index.js index b3a77f840..b5f9c4faa 100644 --- a/src/base/index.js +++ b/src/base/index.js @@ -1,15 +1,57 @@ import Pane from "./1.pane"; import Single from "./single/0.single"; import Text from "./single/1.text"; +import A from "./single/a/a"; +import Tip from "./single/tip/0.tip"; +import Toast from "./single/tip/tip.toast"; +import Tooltip from "./single/tip/tip.tooltip"; +import Drawer from "./layer/layer.drawer"; +import { Popover, BarPopover } from "./layer/layer.popover"; +import PopupView from "./layer/layer.popup"; +import SearcherView from "./layer/layer.searcher"; +import ListView from "./list/listview"; +import VirtualGroupList from "./list/virtualgrouplist"; +import VirtualList from "./list/virtuallist"; +import GridView from "./grid/grid"; +import Pager from "./pager/pager"; + BI.extend(BI, { Pane, Single, Text, + A, + Tip, + Toast, + Tooltip, + Drawer, + Popover, + BarPopover, + PopupView, + SearcherView, + ListView, + VirtualGroupList, + VirtualList, + GridView, + Pager, }); export { Pane, Single, Text, + A, + Tip, + Toast, + Tooltip, + Drawer, + Popover, + BarPopover, + PopupView, + SearcherView, + ListView, + VirtualGroupList, + VirtualList, + GridView, + Pager, } \ No newline at end of file diff --git a/src/base/layer/layer.drawer.js b/src/base/layer/layer.drawer.js index 1c2e26a24..5f0efd278 100644 --- a/src/base/layer/layer.drawer.js +++ b/src/base/layer/layer.drawer.js @@ -4,9 +4,9 @@ * @extends BI.Widget */ -import { shortcut } from "../../core/decorator"; +import { Widget, shortcut } from "../../core"; @shortcut() -export class Drawer extends BI.Widget { +export default class Drawer extends Widget { SIZE = { SMALL: "small", NORMAL: "normal", @@ -234,4 +234,4 @@ export class Drawer extends BI.Widget { } } -BI.extend(BI, { Drawer }); + diff --git a/src/base/layer/layer.popover.js b/src/base/layer/layer.popover.js index 802bd73bd..64f457d0b 100644 --- a/src/base/layer/layer.popover.js +++ b/src/base/layer/layer.popover.js @@ -4,9 +4,9 @@ * @extends BI.Widget */ -import { shortcut } from "../../core/decorator"; +import { Widget, shortcut } from "../../core"; @shortcut() -export class Popover extends BI.Widget { +export class Popover extends Widget { _constant = { SIZE: { SMALL: "small", @@ -238,10 +238,8 @@ export class Popover extends BI.Widget { } } -BI.extend(BI, { Popover }); - @shortcut() -export class BarPopover extends BI.Popover { +export class BarPopover extends Popover { static xtype = "bi.bar_popover"; _defaultConfig() { @@ -278,5 +276,4 @@ export class BarPopover extends BI.Popover { } } -BI.extend(BI, { BarPopover }); diff --git a/src/base/layer/layer.popup.js b/src/base/layer/layer.popup.js index 43f8c4908..93d7bee37 100644 --- a/src/base/layer/layer.popup.js +++ b/src/base/layer/layer.popup.js @@ -4,9 +4,9 @@ * @extends BI.Widget */ -import { shortcut } from "../../core/decorator"; +import { Widget, shortcut } from "../../core"; @shortcut() -export class PopupView extends BI.Widget { +export default class PopupView extends Widget { _const = { TRIANGLE_LENGTH: 12, } @@ -80,13 +80,10 @@ export class PopupView extends BI.Widget { this.view = this._createView(); this.toolbar = this._createToolBar(); - const self = this; - // TODO:这里需要调整转化方式,仍然采用原来的self - this.view.on(BI.Controller.EVENT_CHANGE, function (type) { - // 箭头函数没有自己的arguments,只会获取外层的,若要获取自己的,需通过剩余参数写法,但这样得到的仍然不是类数组 - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.view.on(BI.Controller.EVENT_CHANGE, (type, ...args)=> { + this.fireEvent.apply(this, [BI.Controller.EVENT_CHANGE, type, args]); if (type === BI.Events.CLICK) { - self.fireEvent(PopupView.EVENT_CHANGE); + this.fireEvent(PopupView.EVENT_CHANGE); } }); @@ -434,4 +431,3 @@ export class PopupView extends BI.Widget { } -BI.extend(BI, { PopupView }); diff --git a/src/base/layer/layer.searcher.js b/src/base/layer/layer.searcher.js index d80ffd90c..8b8d037f7 100644 --- a/src/base/layer/layer.searcher.js +++ b/src/base/layer/layer.searcher.js @@ -6,9 +6,11 @@ * @extends BI.Pane */ -import { shortcut } from "../../core/decorator"; +import { shortcut } from "../../core"; +import Pane from "../1.pane"; + @shortcut() -export class SearcherView extends BI.Pane { +export default class SearcherView extends Pane { static xtype = "bi.searcher_view"; static EVENT_CHANGE = "EVENT_CHANGE"; @@ -142,4 +144,3 @@ export class SearcherView extends BI.Pane { } } -BI.extend(BI, { SearcherView }); diff --git a/src/base/list/listview.js b/src/base/list/listview.js index 13a8895c7..03da49d3b 100644 --- a/src/base/list/listview.js +++ b/src/base/list/listview.js @@ -5,141 +5,145 @@ * @class BI.ListView * @extends BI.Widget */ -BI.ListView = BI.inherit(BI.Widget, { - props: function () { - return { - baseCls: "bi-list-view", - overscanHeight: 100, - blockSize: 10, - scrollTop: 0, - el: {}, - items: [], - itemFormatter: function (item, index) { - return item; - }, - }; - }, - - init: function () { - this.renderedIndex = -1; - this.cache = {}; - }, +import { Widget, shortcut } from "../../core"; +@shortcut() +export default class ListView extends Widget { + props() { + return { + baseCls: "bi-list-view", + overscanHeight: 100, + blockSize: 10, + scrollTop: 0, + el: {}, + items: [], + itemFormatter: (item, index)=> { + return item; + }, + }; + } - render: function () { - var self = this, o = this.options; + init() { + this.renderedIndex = -1; + this.cache = {}; + } - return { - type: "bi.vertical", - items: [BI.extend({ - type: "bi.vertical", - scrolly: false, - ref: function (_ref) { - self.container = _ref; - }, - }, o.el)], - element: this, - }; - }, + static xtype = "bi.list_view"; - // mounted之后绑定事件 - mounted: function () { - var self = this, o = this.options; - o.items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); - }) : o.items; - this._populate(); - this.element.scroll(function (e) { - o.scrollTop = self.element.scrollTop(); - self._calculateBlocksToRender(); - }); - var lastWidth = this.element.width(), - lastHeight = this.element.height(); - BI.ResizeDetector.addResizeListener(this, function () { - if (!self.element.is(":visible")) { - return; - } - var width = self.element.width(), - height = self.element.height(); - if (width !== lastWidth || height !== lastHeight) { - lastWidth = width; - lastHeight = height; - self._calculateBlocksToRender(); - } - }); - }, + render() { + const { el } = this.options; - _renderMoreIf: function () { - var self = this, o = this.options; - var height = this.element.height(); - var minContentHeight = o.scrollTop + height + o.overscanHeight; - var index = (this.cache[this.renderedIndex] && (this.cache[this.renderedIndex].index + o.blockSize)) || 0; - var cnt = this.renderedIndex + 1; - var lastHeight; + return { + type: "bi.vertical", + items: [BI.extend({ + type: "bi.vertical", + scrolly: false, + ref: (_ref)=> { + this.container = _ref; + }, + }, el)], + element: this, + }; + } - function getElementHeight() { - return self.container.element.height(); + // mounted之后绑定事件 + mounted() { + const o = this.options; + // 这里无法进行结构,因为存在赋值操作,如果使用结构则this.options的值不会跟随变化 + o.items = BI.isFunction(o.items) ? this.__watch(o.items, (context, newValue)=> { + this.populate(newValue); + }) : o.items; + this._populate(); + this.element.scroll((e)=> { + o.scrollTop = this.element.scrollTop(); + this._calculateBlocksToRender(); + }); + let lastWidth = this.element.width(), + lastHeight = this.element.height(); + BI.ResizeDetector.addResizeListener(this, ()=> { + if (!this.element.is(":visible")) { + return; + } + const width = this.element.width(), + height = this.element.height(); + if (width !== lastWidth || height !== lastHeight) { + lastWidth = width; + lastHeight = height; + this._calculateBlocksToRender(); } + }); + } + + _renderMoreIf() { + const { scrollTop, overscanHeight, blockSize, items, itemFormatter } = this.options; + const height = this.element.height(); + const minContentHeight = scrollTop + height + overscanHeight; + let index = (this.cache[this.renderedIndex] && (this.cache[this.renderedIndex].index + blockSize)) || 0; + let cnt = this.renderedIndex + 1; + let lastHeight; + + const getElementHeight = ()=> { + return this.container.element.height(); + } + lastHeight = getElementHeight(); + while ((lastHeight) < minContentHeight && index < items.length) { + const itemsArr = items.slice(index, index + blockSize); + this.container.addItems(itemsArr.map((item, i)=> { + return itemFormatter(item, index + i); + }), this); + const addedHeight = getElementHeight() - lastHeight; + this.cache[cnt] = { + index: index, + scrollTop: lastHeight, + height: addedHeight, + }; + this.renderedIndex = cnt; + cnt++; + index += blockSize; lastHeight = getElementHeight(); - while ((lastHeight) < minContentHeight && index < o.items.length) { - var items = o.items.slice(index, index + o.blockSize); - this.container.addItems(items.map(function (item, i) { - return o.itemFormatter(item, index + i); - }), this); - var addedHeight = getElementHeight() - lastHeight; - this.cache[cnt] = { - index: index, - scrollTop: lastHeight, - height: addedHeight, - }; - this.renderedIndex = cnt; - cnt++; - index += o.blockSize; - lastHeight = getElementHeight(); - } - }, + } + } + _calculateBlocksToRender() { + // BI-115750 不可见状态下依赖元素实际尺寸构造的线段树会分段错误,所以不进行后续计算和线段树的初始化。 + // 这样从不可见状态变为可见状态能够重新触发线段树初始化 + if (!this.element.is(":visible")) { + return; + } + this._renderMoreIf(); + } - _calculateBlocksToRender: function () { - // BI-115750 不可见状态下依赖元素实际尺寸构造的线段树会分段错误,所以不进行后续计算和线段树的初始化。 - // 这样从不可见状态变为可见状态能够重新触发线段树初始化 - if (!this.element.is(":visible")) { - return; - } - this._renderMoreIf(); - }, + _populate(items) { + const { scrollTop } = this.options; + if (items && this.options.items !== items) { + this.options.items = items; + } + this._calculateBlocksToRender(); + this.element.scrollTop(scrollTop); + } - _populate: function (items) { - var o = this.options; - if (items && this.options.items !== items) { - this.options.items = items; - } - this._calculateBlocksToRender(); - this.element.scrollTop(o.scrollTop); - }, + restore() { + this.renderedIndex = -1; + this.container.empty(); + this.cache = {}; + } - restore: function () { - this.renderedIndex = -1; - this.container.empty(); - this.cache = {}; - }, + scrollTo(scrollTop) { + this.options.scrollTop = scrollTop; + this._calculateBlocksToRender(); + this.element.scrollTop(scrollTop); + } - scrollTo: function (scrollTop) { - this.options.scrollTop = scrollTop; - this._calculateBlocksToRender(); - this.element.scrollTop(scrollTop); - }, + populate(items) { + if (items && this.options.items !== items) { + this.restore(); + } + this._populate(items); + } - populate: function (items) { - if (items && this.options.items !== items) { - this.restore(); - } - this._populate(items); - }, + beforeDestroy() { + BI.ResizeDetector.removeResizeListener(this); + this.restore(); + } - beforeDestroy: function () { - BI.ResizeDetector.removeResizeListener(this); - this.restore(); - }, -}); -BI.shortcut("bi.list_view", BI.ListView); +} diff --git a/src/base/list/virtualgrouplist.js b/src/base/list/virtualgrouplist.js index 95b5276bd..a9b113833 100644 --- a/src/base/list/virtualgrouplist.js +++ b/src/base/list/virtualgrouplist.js @@ -5,194 +5,197 @@ * @class BI.VirtualList * @extends BI.Widget */ -BI.VirtualGroupList = BI.inherit(BI.Widget, { - props: function () { - return { - baseCls: "bi-virtual-group-list", - overscanHeight: 100, - blockSize: 10, - scrollTop: 0, - rowHeight: "auto", - items: [], - el: {}, - itemFormatter: function (item, index) { - return item; - }, - }; - }, - init: function () { - this.renderedIndex = -1; - }, +import { Widget, shortcut } from "../../core"; +@shortcut() +export default class VirtualGroupList extends Widget { + props() { + return { + baseCls: "bi-virtual-group-list", + overscanHeight: 100, + blockSize: 10, + scrollTop: 0, + rowHeight: "auto", + items: [], + el: {}, + itemFormatter: (item, index)=> { + return item; + }, + }; + } - render: function () { - var self = this, o = this.options; + init() { + this.renderedIndex = -1; + } - return { - type: "bi.vertical", - items: [{ - type: "bi.layout", - ref: function () { - self.topBlank = this; - }, - }, { - type: "bi.virtual_group", - height: o.rowHeight * o.items.length, - ref: function () { - self.container = this; - }, - layouts: [BI.extend({ - type: "bi.vertical", - scrolly: false, - }, o.el)], - }, { - type: "bi.layout", - ref: function () { - self.bottomBlank = this; - }, - }], - element: this, - }; - }, + static xtype = "bi.virtual_group_list"; - // mounted之后绑定事件 - mounted: function () { - var self = this, o = this.options; - o.items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); - }) : o.items; - this._populate(); - this.ticking = false; - this.element.scroll(function () { - o.scrollTop = self.element.scrollTop(); - if (!self.ticking) { - requestAnimationFrame(function () { - self._calculateBlocksToRender(); - self.ticking = false; - }); - self.ticking = true; - } - }); - BI.ResizeDetector.addResizeListener(this, function () { - if (self.element.is(":visible")) { - self._calculateBlocksToRender(); - } - }); - }, + render() { + const { rowHeight, items, el } = this.options; - _isAutoHeight: function () { - return !BI.isNumber(this.options.rowHeight); - }, - - _renderMoreIf: function () { - var self = this, o = this.options; - var height = this.element.height(); - var minContentHeight = o.scrollTop + height + o.overscanHeight; - var index = (this.renderedIndex + 1) * o.blockSize, cnt = this.renderedIndex + 1; - var lastHeight; - function getElementHeight () { - return self.container.element.height() + self.topBlank.element.height() + self.bottomBlank.element.height(); + return { + type: "bi.vertical", + items: [{ + type: "bi.layout", + ref: ()=> { + this.topBlank = this; + }, + }, { + type: "bi.virtual_group", + height: rowHeight * items.length, + ref: ()=> { + this.container = this; + }, + layouts: [BI.extend({ + type: "bi.vertical", + scrolly: false, + }, el)], + }, { + type: "bi.layout", + ref: ()=> { + this.bottomBlank = this; + }, + }], + element: this, + }; + } + // mounted之后绑定事件 + mounted() { + // 这里无法进行结构,因为存在赋值操作,如果使用结构则this.options的值不会跟随变化 + const o = this.options; + o.items = BI.isFunction(o.items) ? this.__watch(o.items, (context, newValue)=> { + this.populate(newValue); + }) : o.items; + this._populate(); + this.ticking = false; + this.element.scroll(()=> { + o.scrollTop = this.element.scrollTop(); + if (!this.ticking) { + requestAnimationFrame(function () { + this._calculateBlocksToRender(); + this.ticking = false; + }); + this.ticking = true; } - lastHeight = this.renderedIndex === -1 ? 0 : getElementHeight(); - while (lastHeight < minContentHeight && index < o.items.length) { - var items = o.items.slice(index, index + o.blockSize); - this.container[self.renderedIndex === -1 ? "populate" : "addItems"](items.map(function (item, i) { - return o.itemFormatter(item, index + i); - }), this); - var elementHeight = getElementHeight(); - var addedHeight = elementHeight - lastHeight; - this.tree.set(cnt, addedHeight); - this.renderedIndex = cnt; - cnt++; - index += o.blockSize; - lastHeight = this.renderedIndex === -1 ? 0 : elementHeight; + }); + BI.ResizeDetector.addResizeListener(this, ()=> { + if (this.element.is(":visible")) { + this._calculateBlocksToRender(); } - }, + }); + } - _calculateBlocksToRender: function () { - // BI-115750 不可见状态下依赖元素实际尺寸构造的线段树会分段错误,所以不进行后续计算和线段树的初始化。 - // 这样从不可见状态变为可见状态能够重新触发线段树初始化 - if (!this.element.is(":visible")) { - return; - } - var o = this.options; - this._isAutoHeight() && this._renderMoreIf(); - var height = this.element.height(); - var minContentHeightFrom = o.scrollTop - o.overscanHeight; - var minContentHeightTo = o.scrollTop + height + o.overscanHeight; - var start = this.tree.greatestLowerBound(minContentHeightFrom); - var end = this.tree.leastUpperBound(minContentHeightTo); - var items = []; - var topHeight = this.tree.sumTo(Math.max(-1, start - 1)); - this.topBlank.setHeight(topHeight + "px"); - if (this._isAutoHeight()) { - for (var i = (start < 0 ? 0 : start); i <= end && i <= this.renderedIndex; i++) { - var index = i * o.blockSize; - for (var j = index; j < index + o.blockSize && j < o.items.length; j++) { - items.push(o.items[j]); - } - } - this.bottomBlank.setHeight(this.tree.sumTo(this.renderedIndex) - this.tree.sumTo(Math.min(end, this.renderedIndex)) + "px"); - this.container.populate(items.map(function (item, i) { - return o.itemFormatter(item, (start < 0 ? 0 : start) * o.blockSize + i); - })); - } else { - for (var i = (start < 0 ? 0 : start); i <= end; i++) { - var index = i * o.blockSize; - for (var j = index; j < index + o.blockSize && j < o.items.length; j++) { - items.push(o.items[j]); - } - } - this.container.element.height(o.rowHeight * o.items.length - topHeight); - this.container.populate(items.map(function (item, i) { - return o.itemFormatter(item, (start < 0 ? 0 : start) * o.blockSize + i); - })); - } - }, - - _populate: function (items) { - var o = this.options; - if (items && this.options.items !== items) { - // 重新populate一组items,需要重新对线段树分块 - this.options.items = items; - this._restore(); - } - this.tree = BI.PrefixIntervalTree.uniform(Math.ceil(o.items.length / o.blockSize), this._isAutoHeight() ? 0 : o.rowHeight * o.blockSize); + _isAutoHeight() { + return !BI.isNumber(this.options.rowHeight); + } - this._calculateBlocksToRender(); - try { - this.element.scrollTop(o.scrollTop); - } catch (e) { - } - }, + _renderMoreIf() { + const { scrollTop, overscanHeight, blockSize, items, itemFormatter } = this.options; + const height = this.element.height(); + const minContentHeight = scrollTop + height + overscanHeight; + let index = (this.renderedIndex + 1) * blockSize, cnt = this.renderedIndex + 1; + let lastHeight; + const getElementHeight = ()=> { + return this.container.element.height() + this.topBlank.element.height() + this.bottomBlank.element.height(); + } + lastHeight = this.renderedIndex === -1 ? 0 : getElementHeight(); + while (lastHeight < minContentHeight && index < items.length) { + const itemsArr = items.slice(index, index + blockSize); + this.container[this.renderedIndex === -1 ? "populate" : "addItems"](itemsArr.map((item, i)=> { + return itemFormatter(item, index + i); + }), this); + const elementHeight = getElementHeight(); + const addedHeight = elementHeight - lastHeight; + this.tree.set(cnt, addedHeight); + this.renderedIndex = cnt; + cnt++; + index += blockSize; + lastHeight = this.renderedIndex === -1 ? 0 : elementHeight; + } + } - _restore: function () { - this.renderedIndex = -1; - // 依赖于cache的占位元素也要初始化 - this.topBlank.setHeight(0); - this.bottomBlank.setHeight(0); - }, + _calculateBlocksToRender() { + // BI-115750 不可见状态下依赖元素实际尺寸构造的线段树会分段错误,所以不进行后续计算和线段树的初始化。 + // 这样从不可见状态变为可见状态能够重新触发线段树初始化 + if (!this.element.is(":visible")) { + return; + } + const { scrollTop, overscanHeight, blockSize, items, itemFormatter, rowHeight } = this.options; + this._isAutoHeight() && this._renderMoreIf(); + const height = this.element.height(); + const minContentHeightFrom = scrollTop - overscanHeight; + const minContentHeightTo = scrollTop + height + overscanHeight; + const start = this.tree.greatestLowerBound(minContentHeightFrom); + const end = this.tree.leastUpperBound(minContentHeightTo); + const itemsArr = []; + const topHeight = this.tree.sumTo(Math.max(-1, start - 1)); + this.topBlank.setHeight(topHeight + "px"); + if (this._isAutoHeight()) { + for (let i = (start < 0 ? 0 : start); i <= end && i <= this.renderedIndex; i++) { + const index = i * blockSize; + for (let j = index; j < index + blockSize && j < items.length; j++) { + itemsArr.push(items[j]); + } + } + this.bottomBlank.setHeight(this.tree.sumTo(this.renderedIndex) - this.tree.sumTo(Math.min(end, this.renderedIndex)) + "px"); + this.container.populate(itemsArr.map((item, i)=> { + return itemFormatter(item, (start < 0 ? 0 : start) * blockSize + i); + })); + } else { + for (let i = (start < 0 ? 0 : start); i <= end; i++) { + const index = i * blockSize; + for (let j = index; j < index + blockSize && j < items.length; j++) { + itemsArr.push(items[j]); + } + } + this.container.element.height(rowHeight * items.length - topHeight); + this.container.populate(itemsArr.map((item, i)=> { + return itemFormatter(item, (start < 0 ? 0 : start) * blockSize + i); + })); + } + } + _populate(items) { + const { blockSize, rowHeight, scrollTop } = this.options; + if (items && this.options.items !== items) { + // 重新populate一组items,需要重新对线段树分块 + this.options.items = items; + this._restore(); + } + this.tree = BI.PrefixIntervalTree.uniform(Math.ceil(this.options.items.length / blockSize), this._isAutoHeight() ? 0 : rowHeight * blockSize); - // 暂时只支持固定行高的场景 - scrollTo: function (scrollTop) { - this.options.scrollTop = scrollTop; - this._calculateBlocksToRender(); + this._calculateBlocksToRender(); + try { this.element.scrollTop(scrollTop); - }, + } catch (e) { + } + } - restore: function () { - this.options.scrollTop = 0; - this._restore(); - }, + _restore() { + this.renderedIndex = -1; + // 依赖于cache的占位元素也要初始化 + this.topBlank.setHeight(0); + this.bottomBlank.setHeight(0); + } - populate: function (items) { - this._populate(items); - }, + // 暂时只支持固定行高的场景 + scrollTo(scrollTop) { + this.options.scrollTop = scrollTop; + this._calculateBlocksToRender(); + this.element.scrollTop(scrollTop); + } - beforeDestroy: function () { - BI.ResizeDetector.removeResizeListener(this); - this.restore(); - } -}); -BI.shortcut("bi.virtual_group_list", BI.VirtualGroupList); + restore() { + this.options.scrollTop = 0; + this._restore(); + } + + populate(items) { + this._populate(items); + } + + beforeDestroy() { + BI.ResizeDetector.removeResizeListener(this); + this.restore(); + } +} diff --git a/src/base/list/virtuallist.js b/src/base/list/virtuallist.js index 618d66c2a..bf4cca217 100644 --- a/src/base/list/virtuallist.js +++ b/src/base/list/virtuallist.js @@ -5,213 +5,214 @@ * @class BI.VirtualList * @extends BI.Widget */ -BI.VirtualList = BI.inherit(BI.Widget, { - props: function () { + +import { Widget, shortcut } from "../../core"; +@shortcut() +export default class VirtualList extends Widget { + props() { return { baseCls: "bi-virtual-list", overscanHeight: 100, blockSize: 10, scrollTop: 0, items: [], - itemFormatter: function (item, index) { + itemFormatter: (item, index)=> { return item; }, }; - }, + } - init: function () { + init() { this.renderedIndex = -1; this.cache = {}; - }, - - render: function () { - var self = this; + } - return { - type: "bi.vertical", - items: [{ - type: "bi.layout", - ref: function () { - self.topBlank = this; - }, - }, { - type: "bi.vertical", - scrolly: false, - ref: function () { - self.container = this; - }, - }, { - type: "bi.layout", - ref: function () { - self.bottomBlank = this; - }, - }], - }; - }, + static xtype = "bi.virtual_list"; + render() { + return { + type: "bi.vertical", + items: [{ + type: "bi.layout", + ref: (_ref)=> { + this.topBlank = _ref; + }, + }, { + type: "bi.vertical", + scrolly: false, + ref: (_ref)=> { + this.container = _ref; + }, + }, { + type: "bi.layout", + ref: (_ref)=> { + this.bottomBlank = _ref; + }, + }], + }; + } // mounted之后绑定事件 - mounted: function () { - var self = this, o = this.options; - o.items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); - }) : o.items; - this._populate(); - this.element.scroll(function (e) { - o.scrollTop = self.element.scrollTop(); - self._calculateBlocksToRender(); - }); - BI.ResizeDetector.addResizeListener(this, function () { - if (self.element.is(":visible")) { - self._calculateBlocksToRender(); - } - }); - }, + mounted() { + // 这里无法进行结构,因为存在赋值操作,如果使用结构则this.options的值不会跟随变化 + const o = this.options; + o.items = BI.isFunction(o.items) ? this.__watch(o.items, (context, newValue)=> { + this.populate(newValue); + }) : o.items; + this._populate(); + this.element.scroll((e)=> { + o.scrollTop = this.element.scrollTop(); + this._calculateBlocksToRender(); + }); + BI.ResizeDetector.addResizeListener(this, ()=> { + if (this.element.is(":visible")) { + this._calculateBlocksToRender(); + } + }); + } - _renderMoreIf: function () { - var self = this, o = this.options; - var height = this.element.height(); - var minContentHeight = o.scrollTop + height + o.overscanHeight; - var index = (this.renderedIndex + 1) * o.blockSize, cnt = this.renderedIndex + 1; - var lastHeight; - function getElementHeight() { - return self.container.element.height() + self.topBlank.element.height() + self.bottomBlank.element.height(); - } - lastHeight = getElementHeight(); - while (lastHeight < minContentHeight && index < o.items.length) { - var items = o.items.slice(index, index + o.blockSize); - this.container.addItems(items.map(function (item, i) { - return o.itemFormatter(item, index + i); - }), this); - var addedHeight = getElementHeight() - lastHeight; - this.tree.set(cnt, addedHeight); - this.renderedIndex = cnt; - cnt++; - index += o.blockSize; - lastHeight = getElementHeight(); - } - }, + _renderMoreIf() { + const { scrollTop, overscanHeight, blockSize, items, itemFormatter } = this.options; + const height = this.element.height(); + const minContentHeight = scrollTop + height + overscanHeight; + let index = (this.renderedIndex + 1) * blockSize, cnt = this.renderedIndex + 1; + let lastHeight; + const getElementHeight = ()=> { + return this.container.element.height() + this.topBlank.element.height() + this.bottomBlank.element.height(); + } + lastHeight = getElementHeight(); + while (lastHeight < minContentHeight && index < items.length) { + const itemsArr = items.slice(index, index + blockSize); + this.container.addItems(itemsArr.map((item, i)=> { + return itemFormatter(item, index + i); + }), this); + const addedHeight = getElementHeight() - lastHeight; + this.tree.set(cnt, addedHeight); + this.renderedIndex = cnt; + cnt++; + index += blockSize; + lastHeight = getElementHeight(); + } + } - _calculateBlocksToRender: function () { - var o = this.options; - // BI-115750 不可见状态下依赖元素实际尺寸构造的线段树会分段错误,所以不进行后续计算和线段树的初始化。 - // 这样从不可见状态变为可见状态能够重新触发线段树初始化 - if (!this.element.is(":visible")) { - return; + _calculateBlocksToRender() { + const { scrollTop, overscanHeight, blockSize, items, itemFormatter } = this.options; + // BI-115750 不可见状态下依赖元素实际尺寸构造的线段树会分段错误,所以不进行后续计算和线段树的初始化。 + // 这样从不可见状态变为可见状态能够重新触发线段树初始化 + if (!this.element.is(":visible")) { + return; + } + this._renderMoreIf(); + const height = this.element.height(); + const minContentHeightFrom = scrollTop - overscanHeight; + const minContentHeightTo = scrollTop + height + overscanHeight; + const start = this.tree.greatestLowerBound(minContentHeightFrom); + const end = this.tree.leastUpperBound(minContentHeightTo); + const needDestroyed = [], needMount = []; + for (let i = 0; i < start; i++) { + let index = i * blockSize; + if (!this.cache[i]) { + this.cache[i] = {}; } - this._renderMoreIf(); - var height = this.element.height(); - var minContentHeightFrom = o.scrollTop - o.overscanHeight; - var minContentHeightTo = o.scrollTop + height + o.overscanHeight; - var start = this.tree.greatestLowerBound(minContentHeightFrom); - var end = this.tree.leastUpperBound(minContentHeightTo); - var needDestroyed = [], needMount = []; - for (var i = 0; i < start; i++) { - var index = i * o.blockSize; - if (!this.cache[i]) { - this.cache[i] = {}; - } - if (!this.cache[i].destroyed) { - for (var j = index; j < index + o.blockSize && j < o.items.length; j++) { - needDestroyed.push(this.container._children[j]); - this.container._children[j] = null; - } - this.cache[i].destroyed = true; + if (!this.cache[i].destroyed) { + for (let j = index; j < index + blockSize && j < items.length; j++) { + needDestroyed.push(this.container._children[j]); + this.container._children[j] = null; } + this.cache[i].destroyed = true; } - for (var i = end + 1; i <= this.renderedIndex; i++) { - var index = i * o.blockSize; - if (!this.cache[i]) { - this.cache[i] = {}; - } - if (!this.cache[i].destroyed) { - for (var j = index; j < index + o.blockSize && j < o.items.length; j++) { - needDestroyed.push(this.container._children[j]); - this.container._children[j] = null; - } - this.cache[i].destroyed = true; - } + } + for (let i = end + 1; i <= this.renderedIndex; i++) { + let index = i * blockSize; + if (!this.cache[i]) { + this.cache[i] = {}; + } + if (!this.cache[i].destroyed) { + for (let j = index; j < index + blockSize && j < items.length; j++) { + needDestroyed.push(this.container._children[j]); + this.container._children[j] = null; } - var firstFragment = BI.Widget._renderEngine.createFragment(), - lastFragment = BI.Widget._renderEngine.createFragment(); - var currentFragment = firstFragment; - for (var i = (start < 0 ? 0 : start); i <= end && i <= this.renderedIndex; i++) { - var index = i * o.blockSize; - if (!this.cache[i]) { - this.cache[i] = {}; - } - if (!this.cache[i].destroyed) { - currentFragment = lastFragment; - } - if (this.cache[i].destroyed === true) { - for (var j = index; j < index + o.blockSize && j < o.items.length; j++) { - var w = this.container._addElement(j, o.itemFormatter(o.items[j], j), this); - needMount.push(w); - currentFragment.appendChild(w.element[0]); - } - this.cache[i].destroyed = false; - } + this.cache[i].destroyed = true; + } + } + const firstFragment = BI.Widget._renderEngine.createFragment(), + lastFragment = BI.Widget._renderEngine.createFragment(); + let currentFragment = firstFragment; + for (let i = (start < 0 ? 0 : start); i <= end && i <= this.renderedIndex; i++) { + const index = i * blockSize; + if (!this.cache[i]) { + this.cache[i] = {}; } - this.container.element.prepend(firstFragment); - this.container.element.append(lastFragment); - this.topBlank.setHeight(this.tree.sumTo(Math.max(-1, start - 1)) + "px"); - this.bottomBlank.setHeight(this.tree.sumTo(this.renderedIndex) - this.tree.sumTo(Math.min(end, this.renderedIndex)) + "px"); - BI.each(needMount, function (i, child) { - child && child._mount(); - }); - BI.each(needDestroyed, function (i, child) { - child && child._destroy(); - }); - }, - - _populate: function (items) { - var o = this.options; - if (items && this.options.items !== items) { - this.options.items = items; + if (!this.cache[i].destroyed) { + currentFragment = lastFragment; } - this.tree = BI.PrefixIntervalTree.empty(Math.ceil(o.items.length / o.blockSize)); - - this._calculateBlocksToRender(); - try { - this.element.scrollTop(o.scrollTop); - } catch (e) { + if (this.cache[i].destroyed === true) { + for (let j = index; j < index + blockSize && j < items.length; j++) { + const w = this.container._addElement(j, itemFormatter(items[j], j), this); + needMount.push(w); + currentFragment.appendChild(w.element[0]); + } + this.cache[i].destroyed = false; } - }, - - _clearChildren: function () { - BI.each(this.container._children, function (i, cell) { - cell && cell._destroy(); - }); - this.container._children = {}; - this.container.attr("items", []); - }, + } + this.container.element.prepend(firstFragment); + this.container.element.append(lastFragment); + this.topBlank.setHeight(this.tree.sumTo(Math.max(-1, start - 1)) + "px"); + this.bottomBlank.setHeight(this.tree.sumTo(this.renderedIndex) - this.tree.sumTo(Math.min(end, this.renderedIndex)) + "px"); + BI.each(needMount, (i, child)=> { + child && child._mount(); + }); + BI.each(needDestroyed, (i, child)=> { + child && child._destroy(); + }); + } + _populate(items) { + const { blockSize, scrollTop } = this.options; + if (items && this.options.items !== items) { + this.options.items = items; + } + this.tree = BI.PrefixIntervalTree.empty(Math.ceil(this.options.items.length / blockSize)); - scrollTo: function (scrollTop) { - this.options.scrollTop = scrollTop; - this._calculateBlocksToRender(); + this._calculateBlocksToRender(); + try { this.element.scrollTop(scrollTop); - }, + } catch (e) { + } + } - restore: function () { - this.renderedIndex = -1; - this._clearChildren(); - this.cache = {}; - this.options.scrollTop = 0; - // 依赖于cache的占位元素也要初始化 - this.topBlank.setHeight(0); - this.bottomBlank.setHeight(0); - }, + _clearChildren() { + BI.each(this.container._children, (i, cell)=> { + cell && cell._destroy(); + }); + this.container._children = {}; + this.container.attr("items", []); + } - populate: function (items) { - if (items && this.options.items !== items) { - this.restore(); - } - this._populate(items); - }, + scrollTo(scrollTop) { + this.options.scrollTop = scrollTop; + this._calculateBlocksToRender(); + this.element.scrollTop(scrollTop); + } + + restore() { + this.renderedIndex = -1; + this._clearChildren(); + this.cache = {}; + this.options.scrollTop = 0; + // 依赖于cache的占位元素也要初始化 + this.topBlank.setHeight(0); + this.bottomBlank.setHeight(0); + } - beforeDestroy: function () { - BI.ResizeDetector.removeResizeListener(this); + populate(items) { + if (items && this.options.items !== items) { this.restore(); } -}); -BI.shortcut("bi.virtual_list", BI.VirtualList); + this._populate(items); + } + + beforeDestroy() { + BI.ResizeDetector.removeResizeListener(this); + this.restore(); + } +} diff --git a/src/base/pager/pager.js b/src/base/pager/pager.js index 06514fb99..a8b2d9418 100644 --- a/src/base/pager/pager.js +++ b/src/base/pager/pager.js @@ -5,9 +5,11 @@ * @class BI.Pager * @extends BI.Widget */ -BI.Pager = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.Pager.superclass._defaultConfig.apply(this, arguments), { +import { Widget, shortcut } from "../../core"; +@shortcut() +export default class Pager extends Widget { + _defaultConfig() { + return BI.extend(super._defaultConfig(arguments), { baseCls: "bi-pager", behaviors: {}, layouts: [{ @@ -32,15 +34,18 @@ BI.Pager = BI.inherit(BI.Widget, { next: "下一页", firstPage: 1, - lastPage: function () { // 在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 + lastPage: ()=> { // 在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 return 1; }, hasPrev: BI.emptyFn, // pages不可用时有效 hasNext: BI.emptyFn, // pages不可用时有效 }); - }, + } - render: function () { + static xtype = "bi.pager"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_AFTER_POPULATE = "EVENT_AFTER_POPULATE"; + render() { this.currPage = BI.result(this.options, "curr"); // 翻页太灵敏 // this._lock = false; @@ -48,18 +53,19 @@ BI.Pager = BI.inherit(BI.Widget, { // self._lock = false; // }, 300); this._populate(); - }, + } - _populate: function () { - var self = this, o = this.options, view = [], dict = {}; + _populate() { + const o = this.options, view = [], dict = {}; + const { dynamicShow, dynamicShowPrevNext, hasPrev, dynamicShowFirstLast, hasNext, behaviors, layouts, jump } = this.options; this.empty(); - var pages = BI.result(o, "pages"); - var curr = BI.result(this, "currPage"); - var groups = BI.result(o, "groups"); - var first = BI.result(o, "first"); - var last = BI.result(o, "last"); - var prev = BI.result(o, "prev"); - var next = BI.result(o, "next"); + const pages = BI.result(o, "pages"); + const curr = BI.result(this, "currPage"); + let groups = BI.result(o, "groups"); + let first = BI.result(o, "first"); + let last = BI.result(o, "last"); + const prev = BI.result(o, "prev"); + const next = BI.result(o, "next"); if (pages === false) { groups = 0; @@ -73,24 +79,24 @@ BI.Pager = BI.inherit(BI.Widget, { dict.index = Math.ceil((curr + ((groups > 1 && groups !== pages) ? 1 : 0)) / (groups === 0 ? 1 : groups)); // 当前页非首页,则输出上一页 - if (((!o.dynamicShow && !o.dynamicShowPrevNext) || curr > 1) && prev !== false) { + if (((!dynamicShow && !dynamicShowPrevNext) || curr > 1) && prev !== false) { if (BI.isKey(prev)) { view.push({ text: prev, value: "prev", - disabled: pages === false ? o.hasPrev(curr) === false : !(curr > 1 && prev !== false), + disabled: pages === false ? hasPrev(curr) === false : !(curr > 1 && prev !== false), }); } else { view.push({ el: BI.extend({ - disabled: pages === false ? o.hasPrev(curr) === false : !(curr > 1 && prev !== false), + disabled: pages === false ? hasPrev(curr) === false : !(curr > 1 && prev !== false), }, prev), }); } } // 当前组非首组,则输出首页 - if (((!o.dynamicShow && !o.dynamicShowFirstLast) || (dict.index > 1 && groups !== 0)) && first) { + if (((!dynamicShow && !dynamicShowFirstLast) || (dict.index > 1 && groups !== 0)) && first) { view.push({ text: first, value: "first", @@ -109,14 +115,14 @@ BI.Pager = BI.inherit(BI.Widget, { dict.poor = Math.floor((groups - 1) / 2); dict.start = dict.index > 1 ? curr - dict.poor : 1; dict.end = dict.index > 1 ? (function () { - var max = curr + (groups - dict.poor - 1); + const max = curr + (groups - dict.poor - 1); return max > pages ? pages : max; }()) : groups; if (dict.end - dict.start < groups - 1) { // 最后一组状态 dict.start = dict.end - groups + 1; } - var s = dict.start, e = dict.end; + let s = dict.start, e = dict.end; if (first && last && (dict.index > 1 && groups !== 0) && (pages > groups && dict.end < pages && groups !== 0)) { s++; e--; @@ -137,7 +143,7 @@ BI.Pager = BI.inherit(BI.Widget, { } // 总页数大于连续分页数,且当前组最大页小于总页,输出尾页 - if (((!o.dynamicShow && !o.dynamicShowFirstLast) || (pages > groups && dict.end < pages && groups !== 0)) && last) { + if (((!dynamicShow && !dynamicShowFirstLast) || (pages > groups && dict.end < pages && groups !== 0)) && last) { if (pages > groups && dict.end < pages && groups !== 0 && groups !== pages - 1) { view.push({ type: "bi.label", @@ -154,11 +160,11 @@ BI.Pager = BI.inherit(BI.Widget, { // 当前页不为尾页时,输出下一页 dict.flow = !prev && groups === 0; - if (((!o.dynamicShow && !o.dynamicShowPrevNext) && next) || (curr !== pages && next || dict.flow)) { + if (((!dynamicShow && !dynamicShowPrevNext) && next) || (curr !== pages && next || dict.flow)) { view.push((function () { if (BI.isKey(next)) { if (pages === false) { - return { text: next, value: "next", disabled: o.hasNext(curr) === false }; + return { text: next, value: "next", disabled: hasNext(curr) === false }; } return (dict.flow && curr === pages) @@ -170,7 +176,7 @@ BI.Pager = BI.inherit(BI.Widget, { return { el: BI.extend({ - disabled: pages === false ? o.hasNext(curr) === false : !(curr !== pages && next || dict.flow), + disabled: pages === false ? hasNext(curr) === false : !(curr !== pages && next || dict.flow), }, next), }; }())); @@ -179,7 +185,7 @@ BI.Pager = BI.inherit(BI.Widget, { this.button_group = BI.createWidget({ type: "bi.button_group", element: this, - items: BI.map(view, function (idx, v) { + items: BI.map(view, (idx, v)=> { v = BI.extend({ cls: "bi-list-item-select bi-border-radius", height: 23, @@ -189,87 +195,85 @@ BI.Pager = BI.inherit(BI.Widget, { return BI.formatEL(v); }), - behaviors: o.behaviors, - layouts: o.layouts, + behaviors, + layouts, }); - this.button_group.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { + this.button_group.on(BI.Controller.EVENT_CHANGE, (type, value, obj, ...args)=> { // if (self._lock === true) { // return; // } // self._lock = true; // self._debouce(); if (type === BI.Events.CLICK) { - var v = self.button_group.getValue()[0]; + var v = this.button_group.getValue()[0]; switch (v) { case "first": - self.currPage = 1; + this.currPage = 1; break; case "last": - self.currPage = pages; + this.currPage = pages; break; case "prev": - self.currPage--; + this.currPage--; break; case "next": - self.currPage++; + this.currPage++; break; default: - self.currPage = v; + this.currPage = v; break; } - o.jump.apply(self, [{ + jump.apply(this, [{ pages: pages, - curr: self.currPage, + curr: this.currPage, }]); - self._populate(); - self.fireEvent(BI.Pager.EVENT_CHANGE, obj); + this._populate(); + this.fireEvent(Pager.EVENT_CHANGE, obj); } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.fireEvent.apply(this, [BI.Controller.EVENT_CHANGE, type, value, obj, args]); }); - this.fireEvent(BI.Pager.EVENT_AFTER_POPULATE); - }, + this.fireEvent(Pager.EVENT_AFTER_POPULATE); + } - getCurrentPage: function () { + getCurrentPage() { return this.currPage; - }, + } - setAllPages: function (pages) { + setAllPages(pages) { this.options.pages = pages; this._populate(); - }, + } - hasPrev: function (v) { + hasPrev(v) { v || (v = 1); - var o = this.options; - var pages = this.options.pages; + const { pages, hasPrev } = this.options; - return pages === false ? o.hasPrev(v) : v > 1; - }, + return pages === false ? hasPrev(v) : v > 1; + } - hasNext: function (v) { + hasNext(v) { v || (v = 1); - var o = this.options; - var pages = this.options.pages; + const { pages, hasNext } = this.options; + return pages === false ? hasNext(v) : v < pages; + } - return pages === false ? o.hasNext(v) : v < pages; - }, - - setValue: function (v) { - var o = this.options; + setValue(v) { + const o = this.options; + const { pages } = this.options; v = v || 0; v = v < 1 ? 1 : v; - if (o.pages === false) { + if (pages === false) { var lastPage = BI.result(o, "lastPage"), firstPage = 1; this.currPage = v > lastPage ? lastPage : ((firstPage = BI.result(o, "firstPage")), (v < firstPage ? firstPage : v)); } else { - v = v > o.pages ? o.pages : v; + v = v > pages ? pages : v; this.currPage = v; } this._populate(); - }, + } - getValue: function () { - var val = this.button_group.getValue()[0]; + getValue() { + const val = this.button_group.getValue()[0]; switch (val) { case "prev": return -1; @@ -282,19 +286,16 @@ BI.Pager = BI.inherit(BI.Widget, { default: return val; } - }, + } - attr: function (key, value) { - BI.Pager.superclass.attr.apply(this, arguments); + attr(key, value) { + super.attr(arguments); if (key === "curr") { this.currPage = BI.result(this.options, "curr"); } - }, + } - populate: function () { + populate() { this._populate(); - }, -}); -BI.Pager.EVENT_CHANGE = "EVENT_CHANGE"; -BI.Pager.EVENT_AFTER_POPULATE = "EVENT_AFTER_POPULATE"; -BI.shortcut("bi.pager", BI.Pager); + } +} \ No newline at end of file diff --git a/src/base/single/a/a.js b/src/base/single/a/a.js index 313e050ba..7acf03231 100644 --- a/src/base/single/a/a.js +++ b/src/base/single/a/a.js @@ -6,9 +6,10 @@ * @extends BI.Text * @abstract */ -import { shortcut } from "../../../core/decorator"; +import { shortcut } from "../../../core"; +import Text from "../1.text"; @shortcut() -export class A extends BI.Text { +export default class A extends Text { static xtype = "bi.a"; _defaultConfig() { @@ -34,5 +35,3 @@ export class A extends BI.Text { } } - -BI.extend(BI, { A }); diff --git a/src/base/single/tip/0.tip.js b/src/base/single/tip/0.tip.js index 21cd96deb..d9ac9fee7 100644 --- a/src/base/single/tip/0.tip.js +++ b/src/base/single/tip/0.tip.js @@ -6,7 +6,9 @@ * @extends BI.Single * @abstract */ -export class Tip extends BI.Single { + +import Single from "../0.single"; +export default class Tip extends Single { _defaultConfig() { const conf = super._defaultConfig(arguments); return BI.extend(conf, { @@ -21,4 +23,3 @@ export class Tip extends BI.Single { } } -BI.extend(BI, { Tip }); diff --git a/src/base/single/tip/tip.toast.js b/src/base/single/tip/tip.toast.js index 124cf6af0..1fa33187a 100644 --- a/src/base/single/tip/tip.toast.js +++ b/src/base/single/tip/tip.toast.js @@ -6,9 +6,10 @@ * @extends BI.Tip */ -import { shortcut } from "../../../core/decorator"; +import { shortcut } from "../../../core"; +import Tip from "./0.tip"; @shortcut() -export class Toast extends BI.Tip { +export default class Toast extends Tip { _const= { closableMinWidth: 146, minWidth: 100, @@ -124,4 +125,3 @@ export class Toast extends BI.Tip { } -BI.extend(BI, { Toast }); diff --git a/src/base/single/tip/tip.tooltip.js b/src/base/single/tip/tip.tooltip.js index 3d4f77382..ab95c113a 100644 --- a/src/base/single/tip/tip.tooltip.js +++ b/src/base/single/tip/tip.tooltip.js @@ -6,9 +6,10 @@ * @extends BI.Tip */ -import { shortcut } from "../../../core/decorator"; +import { shortcut } from "../../../core"; +import Tip from "./0.tip"; @shortcut() -export class Tooltip extends BI.Tip { +export default class Tooltip extends Tip { _const = { hgap: 8, vgap: 4, @@ -90,5 +91,3 @@ export class Tooltip extends BI.Tip { } } - -BI.extend(BI, { Tooltip }); From 3db612aa389ee5386bcc7c05d8e7ff029ef7d337 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Thu, 29 Dec 2022 15:03:57 +0800 Subject: [PATCH 021/300] =?UTF-8?q?KERNEL-13841=20refactor:base=E6=96=87?= =?UTF-8?q?=E4=BB=B6es6=E5=8C=96=E7=AE=AD=E5=A4=B4=E5=87=BD=E6=95=B0?= =?UTF-8?q?=E5=92=8Cthis=E4=BB=A3=E7=A0=81=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/grid/grid.js | 24 ++++++++++++------------ src/base/layer/layer.drawer.js | 12 ++++++------ src/base/layer/layer.popover.js | 16 ++++++++-------- src/base/layer/layer.popup.js | 4 ++-- src/base/layer/layer.searcher.js | 16 ++++++++-------- src/base/list/listview.js | 14 +++++++------- src/base/list/virtualgrouplist.js | 24 ++++++++++++------------ src/base/list/virtuallist.js | 24 ++++++++++++------------ src/base/pager/pager.js | 10 +++++----- src/base/single/tip/tip.toast.js | 2 +- src/base/single/tip/tip.tooltip.js | 2 +- 11 files changed, 74 insertions(+), 74 deletions(-) diff --git a/src/base/grid/grid.js b/src/base/grid/grid.js index 4ee6e6332..3798a8e46 100644 --- a/src/base/grid/grid.js +++ b/src/base/grid/grid.js @@ -30,7 +30,7 @@ export default class GridView extends Widget { scrollLeft: 0, scrollTop: 0, items: [], - itemFormatter: (item, row, col)=> { + itemFormatter: (item, row, col) => { return item; }, }); @@ -46,13 +46,13 @@ export default class GridView extends Widget { this.renderedKeys = []; this.renderRange = {}; this._scrollLock = false; - this._debounceRelease = BI.debounce(()=> { + this._debounceRelease = BI.debounce(() => { this._scrollLock = false; }, 1000 / 60); this.container = BI._lazyCreateWidget({ type: "bi.absolute", }); - this.element.scroll(()=> { + this.element.scroll(() => { if (this._scrollLock === true) { return; } @@ -85,7 +85,7 @@ export default class GridView extends Widget { scrollx: scrollx, items: [this.container], }); - o.items = BI.isFunction(o.items) ? this.__watch(o.items, (context, newValue)=> { + o.items = BI.isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { this.populate(newValue); }) : o.items; if (o.items.length > 0) { @@ -104,7 +104,7 @@ export default class GridView extends Widget { } destroyed() { - BI.each(this.renderedCells, (i, cell)=> { + BI.each(this.renderedCells, (i, cell) => { cell.el._destroy(); }) } @@ -235,14 +235,14 @@ export default class GridView extends Widget { } // 已存在的, 需要添加的和需要删除的 const existSet = {}, addSet = {}, deleteArray = []; - BI.each(renderedKeys, (i, key)=> { + BI.each(renderedKeys, (i, key) => { if (this.renderedKeys[i]) { existSet[i] = key; } else { addSet[i] = key; } }); - BI.each(this.renderedKeys, function (i, key) { + BI.each(this.renderedKeys, (i, key) => { if (existSet[i]) { return; } @@ -251,12 +251,12 @@ export default class GridView extends Widget { } deleteArray.push(key[2]); }); - BI.each(deleteArray, (i, index)=> { + BI.each(deleteArray, (i, index) => { // 性能优化,不调用destroy方法防止触发destroy事件 this.renderedCells[index].el._destroy(); }); const addedItems = []; - BI.each(addSet, function (index, key) { + BI.each(addSet, (index, key) => { addedItems.push(renderedCells[key[2]]); }); // 与listview一样, 给上下文 @@ -370,7 +370,7 @@ export default class GridView extends Widget { setOverflowX(b) { if (this.options.overflowX !== !!b) { this.options.overflowX = !!b; - BI.nextTick(()=> { + BI.nextTick(() => { this.element.css({ overflowX: b ? "auto" : "hidden" }); }); } @@ -379,7 +379,7 @@ export default class GridView extends Widget { setOverflowY(b) { if (this.options.overflowY !== !!b) { this.options.overflowY = !!b; - BI.nextTick(()=> { + BI.nextTick(() => { this.element.css({ overflowY: b ? "auto" : "hidden" }); }); } @@ -418,7 +418,7 @@ export default class GridView extends Widget { } restore() { - BI.each(this.renderedCells, (i, cell)=> { + BI.each(this.renderedCells, (i, cell) => { cell.el._destroy(); }); this._clearChildren(); diff --git a/src/base/layer/layer.drawer.js b/src/base/layer/layer.drawer.js index 5f0efd278..890981d0e 100644 --- a/src/base/layer/layer.drawer.js +++ b/src/base/layer/layer.drawer.js @@ -82,7 +82,7 @@ export default class Drawer extends Widget { type: "bi.icon_button", cls: "bi-message-close close-font", height: headerHeight, - handler: ()=> { + handler: () => { this.close(); }, } : { @@ -98,7 +98,7 @@ export default class Drawer extends Widget { type: "bi.vertical", scrolly: true, cls: "drawer-body", - ref: (_ref)=> { + ref: (_ref) => { this.body = _ref; }, items: [{ @@ -153,7 +153,7 @@ export default class Drawer extends Widget { show(callback) { const { placement } = this.options; - requestAnimationFrame(()=> { + requestAnimationFrame(() => { const size = this._getSuitableSize(); switch (placement) { case "right": @@ -185,7 +185,7 @@ export default class Drawer extends Widget { hide(callback) { const { placement } = this.options; - requestAnimationFrame(()=> { + requestAnimationFrame(() => { switch (placement) { case "right": this.element.css({ @@ -215,13 +215,13 @@ export default class Drawer extends Widget { } open() { - this.show(()=> { + this.show(() => { this.fireEvent(Drawer.EVENT_OPEN); }); } close() { - this.hide(()=> { + this.hide(() => { this.fireEvent(Drawer.EVENT_CLOSE); }); } diff --git a/src/base/layer/layer.popover.js b/src/base/layer/layer.popover.js index 64f457d0b..cd91db05e 100644 --- a/src/base/layer/layer.popover.js +++ b/src/base/layer/layer.popover.js @@ -47,7 +47,7 @@ export class Popover extends Widget { this.startX = 0; this.startY = 0; const size = this._calculateSize(); - this.tracker = new BI.MouseMoveTracker(function (deltaX, deltaY) { + this.tracker = new BI.MouseMoveTracker((deltaX, deltaY) => { const W = BI.Widget._renderEngine.createElement("body").width(); const H = BI.Widget._renderEngine.createElement("body").height(); this.startX += deltaX; @@ -60,7 +60,7 @@ export class Popover extends Widget { BI.Resizers._resize({ target: this.element[0], }); - }, ()=> { + }, () => { this.tracker.releaseMouseMoves(); }, _global); const items = [{ @@ -70,7 +70,7 @@ export class Popover extends Widget { items: [{ el: { type: "bi.absolute", - ref: (_ref)=> { + ref: (_ref) => { this.dragger = _ref; }, items: [{ @@ -95,7 +95,7 @@ export class Popover extends Widget { type: "bi.icon_button", cls: "bi-message-close close-font", height: headerHeight, - handler: ()=> { + handler: () => { this.close(); }, }, @@ -109,7 +109,7 @@ export class Popover extends Widget { type: "bi.vertical", scrolly: true, cls: "popover-body", - ref: (_ref)=> { + ref: (_ref) => { this.body = _ref; }, css: { @@ -164,7 +164,7 @@ export class Popover extends Widget { } // mounted之后绑定事件 mounted() { - this.dragger.element.mousedown(function (e) { + this.dragger.element.mousedown((e) => { if (this.options.draggable !== false) { this.startX = this.element[0].offsetLeft; this.startY = this.element[0].offsetTop; @@ -258,7 +258,7 @@ export class BarPopover extends Popover { text: this.options.btns[1], value: 1, level: "ignore", - handler: (v)=> { + handler: (v) => { this.fireEvent(Popover.EVENT_CANCEL, v); this.close(v); }, @@ -267,7 +267,7 @@ export class BarPopover extends Popover { text: this.options.btns[0], warningTitle: warningTitle, value: 0, - handler: (v)=> { + handler: (v) => { this.fireEvent(Popover.EVENT_CONFIRM, v); this.close(v); }, diff --git a/src/base/layer/layer.popup.js b/src/base/layer/layer.popup.js index 93d7bee37..ea4a35196 100644 --- a/src/base/layer/layer.popup.js +++ b/src/base/layer/layer.popup.js @@ -80,8 +80,8 @@ export default class PopupView extends Widget { this.view = this._createView(); this.toolbar = this._createToolBar(); - this.view.on(BI.Controller.EVENT_CHANGE, (type, ...args)=> { - this.fireEvent.apply(this, [BI.Controller.EVENT_CHANGE, type, args]); + this.view.on(BI.Controller.EVENT_CHANGE, (type, ...args) => { + this.fireEvent.apply(this, [BI.Controller.EVENT_CHANGE, type, ...args]); if (type === BI.Events.CLICK) { this.fireEvent(PopupView.EVENT_CHANGE); } diff --git a/src/base/layer/layer.searcher.js b/src/base/layer/layer.searcher.js index 8b8d037f7..f76aa7a17 100644 --- a/src/base/layer/layer.searcher.js +++ b/src/base/layer/layer.searcher.js @@ -26,7 +26,7 @@ export default class SearcherView extends Pane { matcher: { // 完全匹配的构造器 type: "bi.button_group", behaviors: { - redmark: ()=> { + redmark: () => { return true; }, }, @@ -38,7 +38,7 @@ export default class SearcherView extends Pane { searcher: { type: "bi.button_group", behaviors: { - redmark: function () { + redmark: () => { return true; }, }, @@ -56,7 +56,7 @@ export default class SearcherView extends Pane { type: "bi.button_group", chooseType, behaviors: { - redmark: ()=> { + redmark: () => { return true; }, }, @@ -65,8 +65,8 @@ export default class SearcherView extends Pane { }], value, }); - this.matcher.on(BI.Controller.EVENT_CHANGE, (type, val, ob)=> { - this.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.matcher.on(BI.Controller.EVENT_CHANGE, (type, val, ob, ...args) => { + this.fireEvent.apply(this, [BI.Controller.EVENT_CHANGE, type, val, ob, ...args]); if (type === BI.Events.CLICK) { this.fireEvent(SearcherView.EVENT_CHANGE, val, ob); } @@ -85,7 +85,7 @@ export default class SearcherView extends Pane { type: "bi.button_group", chooseType, behaviors: { - redmark: ()=> { + redmark: () => { return true; }, }, @@ -94,8 +94,8 @@ export default class SearcherView extends Pane { }], value, }); - this.searcher.on(BI.Controller.EVENT_CHANGE, (type, val, ob)=> { - this.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.searcher.on(BI.Controller.EVENT_CHANGE, (type, val, ob, ...args) => { + this.fireEvent.apply(this, [BI.Controller.EVENT_CHANGE, type, val, ob, ...args]); if (type === BI.Events.CLICK) { this.fireEvent(BI.SearcherView.EVENT_CHANGE, val, ob); } diff --git a/src/base/list/listview.js b/src/base/list/listview.js index 03da49d3b..3ec9dc162 100644 --- a/src/base/list/listview.js +++ b/src/base/list/listview.js @@ -16,7 +16,7 @@ export default class ListView extends Widget { scrollTop: 0, el: {}, items: [], - itemFormatter: (item, index)=> { + itemFormatter: (item, index) => { return item; }, }; @@ -37,7 +37,7 @@ export default class ListView extends Widget { items: [BI.extend({ type: "bi.vertical", scrolly: false, - ref: (_ref)=> { + ref: (_ref) => { this.container = _ref; }, }, el)], @@ -49,17 +49,17 @@ export default class ListView extends Widget { mounted() { const o = this.options; // 这里无法进行结构,因为存在赋值操作,如果使用结构则this.options的值不会跟随变化 - o.items = BI.isFunction(o.items) ? this.__watch(o.items, (context, newValue)=> { + o.items = BI.isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { this.populate(newValue); }) : o.items; this._populate(); - this.element.scroll((e)=> { + this.element.scroll((e) => { o.scrollTop = this.element.scrollTop(); this._calculateBlocksToRender(); }); let lastWidth = this.element.width(), lastHeight = this.element.height(); - BI.ResizeDetector.addResizeListener(this, ()=> { + BI.ResizeDetector.addResizeListener(this, () => { if (!this.element.is(":visible")) { return; } @@ -81,14 +81,14 @@ export default class ListView extends Widget { let cnt = this.renderedIndex + 1; let lastHeight; - const getElementHeight = ()=> { + const getElementHeight = () => { return this.container.element.height(); } lastHeight = getElementHeight(); while ((lastHeight) < minContentHeight && index < items.length) { const itemsArr = items.slice(index, index + blockSize); - this.container.addItems(itemsArr.map((item, i)=> { + this.container.addItems(itemsArr.map((item, i) => { return itemFormatter(item, index + i); }), this); const addedHeight = getElementHeight() - lastHeight; diff --git a/src/base/list/virtualgrouplist.js b/src/base/list/virtualgrouplist.js index a9b113833..be9845cc1 100644 --- a/src/base/list/virtualgrouplist.js +++ b/src/base/list/virtualgrouplist.js @@ -18,7 +18,7 @@ export default class VirtualGroupList extends Widget { rowHeight: "auto", items: [], el: {}, - itemFormatter: (item, index)=> { + itemFormatter: (item, index) => { return item; }, }; @@ -37,13 +37,13 @@ export default class VirtualGroupList extends Widget { type: "bi.vertical", items: [{ type: "bi.layout", - ref: ()=> { + ref: () => { this.topBlank = this; }, }, { type: "bi.virtual_group", height: rowHeight * items.length, - ref: ()=> { + ref: () => { this.container = this; }, layouts: [BI.extend({ @@ -52,7 +52,7 @@ export default class VirtualGroupList extends Widget { }, el)], }, { type: "bi.layout", - ref: ()=> { + ref: () => { this.bottomBlank = this; }, }], @@ -63,22 +63,22 @@ export default class VirtualGroupList extends Widget { mounted() { // 这里无法进行结构,因为存在赋值操作,如果使用结构则this.options的值不会跟随变化 const o = this.options; - o.items = BI.isFunction(o.items) ? this.__watch(o.items, (context, newValue)=> { + o.items = BI.isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { this.populate(newValue); }) : o.items; this._populate(); this.ticking = false; - this.element.scroll(()=> { + this.element.scroll(() => { o.scrollTop = this.element.scrollTop(); if (!this.ticking) { - requestAnimationFrame(function () { + requestAnimationFrame(() => { this._calculateBlocksToRender(); this.ticking = false; }); this.ticking = true; } }); - BI.ResizeDetector.addResizeListener(this, ()=> { + BI.ResizeDetector.addResizeListener(this, () => { if (this.element.is(":visible")) { this._calculateBlocksToRender(); } @@ -95,13 +95,13 @@ export default class VirtualGroupList extends Widget { const minContentHeight = scrollTop + height + overscanHeight; let index = (this.renderedIndex + 1) * blockSize, cnt = this.renderedIndex + 1; let lastHeight; - const getElementHeight = ()=> { + const getElementHeight = () => { return this.container.element.height() + this.topBlank.element.height() + this.bottomBlank.element.height(); } lastHeight = this.renderedIndex === -1 ? 0 : getElementHeight(); while (lastHeight < minContentHeight && index < items.length) { const itemsArr = items.slice(index, index + blockSize); - this.container[this.renderedIndex === -1 ? "populate" : "addItems"](itemsArr.map((item, i)=> { + this.container[this.renderedIndex === -1 ? "populate" : "addItems"](itemsArr.map((item, i) => { return itemFormatter(item, index + i); }), this); const elementHeight = getElementHeight(); @@ -138,7 +138,7 @@ export default class VirtualGroupList extends Widget { } } this.bottomBlank.setHeight(this.tree.sumTo(this.renderedIndex) - this.tree.sumTo(Math.min(end, this.renderedIndex)) + "px"); - this.container.populate(itemsArr.map((item, i)=> { + this.container.populate(itemsArr.map((item, i) => { return itemFormatter(item, (start < 0 ? 0 : start) * blockSize + i); })); } else { @@ -149,7 +149,7 @@ export default class VirtualGroupList extends Widget { } } this.container.element.height(rowHeight * items.length - topHeight); - this.container.populate(itemsArr.map((item, i)=> { + this.container.populate(itemsArr.map((item, i) => { return itemFormatter(item, (start < 0 ? 0 : start) * blockSize + i); })); } diff --git a/src/base/list/virtuallist.js b/src/base/list/virtuallist.js index bf4cca217..ed788acdd 100644 --- a/src/base/list/virtuallist.js +++ b/src/base/list/virtuallist.js @@ -16,7 +16,7 @@ export default class VirtualList extends Widget { blockSize: 10, scrollTop: 0, items: [], - itemFormatter: (item, index)=> { + itemFormatter: (item, index) => { return item; }, }; @@ -34,18 +34,18 @@ export default class VirtualList extends Widget { type: "bi.vertical", items: [{ type: "bi.layout", - ref: (_ref)=> { + ref: (_ref) => { this.topBlank = _ref; }, }, { type: "bi.vertical", scrolly: false, - ref: (_ref)=> { + ref: (_ref) => { this.container = _ref; }, }, { type: "bi.layout", - ref: (_ref)=> { + ref: (_ref) => { this.bottomBlank = _ref; }, }], @@ -55,15 +55,15 @@ export default class VirtualList extends Widget { mounted() { // 这里无法进行结构,因为存在赋值操作,如果使用结构则this.options的值不会跟随变化 const o = this.options; - o.items = BI.isFunction(o.items) ? this.__watch(o.items, (context, newValue)=> { + o.items = BI.isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { this.populate(newValue); }) : o.items; this._populate(); - this.element.scroll((e)=> { + this.element.scroll((e) => { o.scrollTop = this.element.scrollTop(); this._calculateBlocksToRender(); }); - BI.ResizeDetector.addResizeListener(this, ()=> { + BI.ResizeDetector.addResizeListener(this, () => { if (this.element.is(":visible")) { this._calculateBlocksToRender(); } @@ -76,13 +76,13 @@ export default class VirtualList extends Widget { const minContentHeight = scrollTop + height + overscanHeight; let index = (this.renderedIndex + 1) * blockSize, cnt = this.renderedIndex + 1; let lastHeight; - const getElementHeight = ()=> { + const getElementHeight = () => { return this.container.element.height() + this.topBlank.element.height() + this.bottomBlank.element.height(); } lastHeight = getElementHeight(); while (lastHeight < minContentHeight && index < items.length) { const itemsArr = items.slice(index, index + blockSize); - this.container.addItems(itemsArr.map((item, i)=> { + this.container.addItems(itemsArr.map((item, i) => { return itemFormatter(item, index + i); }), this); const addedHeight = getElementHeight() - lastHeight; @@ -158,10 +158,10 @@ export default class VirtualList extends Widget { this.container.element.append(lastFragment); this.topBlank.setHeight(this.tree.sumTo(Math.max(-1, start - 1)) + "px"); this.bottomBlank.setHeight(this.tree.sumTo(this.renderedIndex) - this.tree.sumTo(Math.min(end, this.renderedIndex)) + "px"); - BI.each(needMount, (i, child)=> { + BI.each(needMount, (i, child) => { child && child._mount(); }); - BI.each(needDestroyed, (i, child)=> { + BI.each(needDestroyed, (i, child) => { child && child._destroy(); }); } @@ -180,7 +180,7 @@ export default class VirtualList extends Widget { } _clearChildren() { - BI.each(this.container._children, (i, cell)=> { + BI.each(this.container._children, (i, cell) => { cell && cell._destroy(); }); this.container._children = {}; diff --git a/src/base/pager/pager.js b/src/base/pager/pager.js index a8b2d9418..4eba409e6 100644 --- a/src/base/pager/pager.js +++ b/src/base/pager/pager.js @@ -23,7 +23,7 @@ export default class Pager extends Widget { dynamicShowFirstLast: false, // 是否动态显示首页、尾页 dynamicShowPrevNext: false, // 是否动态显示上一页、下一页 pages: false, // 总页数 - curr: function () { + curr: () => { return 1; }, // 初始化当前页 groups: 0, // 连续显示分页数 @@ -34,7 +34,7 @@ export default class Pager extends Widget { next: "下一页", firstPage: 1, - lastPage: ()=> { // 在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 + lastPage: () => { // 在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 return 1; }, hasPrev: BI.emptyFn, // pages不可用时有效 @@ -185,7 +185,7 @@ export default class Pager extends Widget { this.button_group = BI.createWidget({ type: "bi.button_group", element: this, - items: BI.map(view, (idx, v)=> { + items: BI.map(view, (idx, v) => { v = BI.extend({ cls: "bi-list-item-select bi-border-radius", height: 23, @@ -198,7 +198,7 @@ export default class Pager extends Widget { behaviors, layouts, }); - this.button_group.on(BI.Controller.EVENT_CHANGE, (type, value, obj, ...args)=> { + this.button_group.on(BI.Controller.EVENT_CHANGE, (type, value, obj, ...args) => { // if (self._lock === true) { // return; // } @@ -230,7 +230,7 @@ export default class Pager extends Widget { this._populate(); this.fireEvent(Pager.EVENT_CHANGE, obj); } - this.fireEvent.apply(this, [BI.Controller.EVENT_CHANGE, type, value, obj, args]); + this.fireEvent.apply(this, [BI.Controller.EVENT_CHANGE, type, value, obj, ...args]); }); this.fireEvent(Pager.EVENT_AFTER_POPULATE); } diff --git a/src/base/single/tip/tip.toast.js b/src/base/single/tip/tip.toast.js index 1fa33187a..e93b3627a 100644 --- a/src/base/single/tip/tip.toast.js +++ b/src/base/single/tip/tip.toast.js @@ -100,7 +100,7 @@ export default class Toast extends Tip { items.push({ type: "bi.icon_button", cls: "close-font toast-icon", - handler: ()=> { + handler: () => { this.destroy(); }, height: textHeight, diff --git a/src/base/single/tip/tip.tooltip.js b/src/base/single/tip/tip.tooltip.js index ab95c113a..d50a52c19 100644 --- a/src/base/single/tip/tip.tooltip.js +++ b/src/base/single/tip/tip.tooltip.js @@ -51,7 +51,7 @@ export default class Tooltip extends Tip { element: this, hgap: this._const.hgap, innerVgap: this._const.vgap, - items: BI.map(texts, function (i, text) { + items: BI.map(texts, (i, text) => { return { type: "bi.label", textAlign: textAlign, From c04901c7bfc498714a1689846fe42bd9be1ecaff Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Tue, 3 Jan 2023 00:47:14 +0800 Subject: [PATCH 022/300] =?UTF-8?q?KERNEL-13947=20refactor:=20base?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E6=96=B9=E6=B3=95=E7=9A=84es6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/1.pane.js | 10 +- src/core/2.base.js | 2372 +++++++++++++++++++++++------------------- src/core/3.ob.js | 32 +- src/core/4.widget.js | 160 +-- src/core/index.js | 4 +- 5 files changed, 1376 insertions(+), 1202 deletions(-) diff --git a/src/base/1.pane.js b/src/base/1.pane.js index c87e33bfc..1f7f1cc59 100644 --- a/src/base/1.pane.js +++ b/src/base/1.pane.js @@ -6,7 +6,7 @@ * @extends BI.Widget * @abstract */ -import { Widget, shortcut } from "../core"; +import { Widget, shortcut, isNotEmptyString, extend, isNull, isEmpty } from "../core"; @shortcut() export default class Pane extends Widget { @@ -15,7 +15,7 @@ export default class Pane extends Widget { static EVENT_LOADING = "EVENT_LOADING"; _defaultConfig() { - return BI.extend(super._defaultConfig(), { + return extend(super._defaultConfig(), { _baseCls: "bi-pane", tipText: BI.i18nText("BI-No_Selected_Item"), loadingText: "", @@ -62,7 +62,7 @@ export default class Pane extends Widget { }); } BI.Layers.show(this.getName() + "-loading"); - } else if (BI.isNull(this._loading)) { + } else if (isNull(this._loading)) { loadingAnimation.element.css("zIndex", 1); BI.createWidget({ type: "bi.center_adapt", @@ -85,7 +85,7 @@ export default class Pane extends Widget { type: "bi.horizontal_adapt", items: [loadingTip], }]; - BI.isNotEmptyString(o.loadingText) && loadingTipItems.push({ + isNotEmptyString(o.loadingText) && loadingTipItems.push({ type: "bi.text", text: o.loadingText, tgap: this._getSize(10), @@ -109,7 +109,7 @@ export default class Pane extends Widget { } check() { - this.setTipVisible(BI.isEmpty(this.options.items)); + this.setTipVisible(isEmpty(this.options.items)); } setTipVisible(b) { diff --git a/src/core/2.base.js b/src/core/2.base.js index 7b200ed01..46bf10e92 100644 --- a/src/core/2.base.js +++ b/src/core/2.base.js @@ -21,127 +21,136 @@ var _applyFunc = function (name) { }; }; -// Utility -BI._.extend(BI, { - assert: function (v, is) { - if (this.isFunction(is)) { - if (!is(v)) { - throw new Error(v + " error"); - } else { - return true; - } - } - if (!this.isArray(is)) { - is = [is]; - } - if (!this.deepContains(is, v)) { +export function assert(v, is) { + if (isFunction(is)) { + if (!is(v)) { throw new Error(v + " error"); + } else { + return true; } - return true; - }, - - warn: function (message) { - console.warn(message); - }, - - UUID: function () { - var f = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; - var str = ""; - for (var i = 0; i < 16; i++) { - var r = parseInt(f.length * Math.random(), 10); - str += f[r]; - } - return str; - }, + } + if (!isArray(is)) { + is = [is]; + } + if (!deepContains(is, v)) { + throw new Error(v + " error"); + } + return true; +} + +export function warn(message) { + console.warn(message); +} + +export function UUID() { + var f = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; + var str = ""; + for (var i = 0; i < 16; i++) { + var r = _global.parseInt(f.length * Math.random(), 10); + str += f[r]; + } + return str; +} - isWidget: function (widget) { - return widget instanceof BI.Widget; - }, +export function isWidget(widget) { + return widget instanceof BI.Widget; +} - createWidgets: function (items, options, context) { - if (!BI.isArray(items)) { - throw new Error("items必须是数组", items); +export function createWidgets(items, options, context) { + if (!isArray(items)) { + throw new Error("items必须是数组", items); + } + if (isWidget(options)) { + context = options; + options = {}; + } else { + options || (options = {}); + } + return map(flatten(items), function (i, item) { + return BI.createWidget(item, deepClone(options), context); + }); +} + +export function createItems(data, innerAttr, outerAttr) { + innerAttr = isArray(innerAttr) ? innerAttr : makeArray(flatten(data).length, innerAttr || {}); + outerAttr = isArray(outerAttr) ? outerAttr : makeArray(flatten(data).length, outerAttr || {}); + return map(data, function (i, item) { + if (isArray(item)) { + return createItems(item, innerAttr, outerAttr); + } + if (item instanceof BI.Widget) { + return extend({}, innerAttr.shift(), outerAttr.shift(), { + type: null, + el: item + }); } - if (BI.isWidget(options)) { - context = options; - options = {}; - } else { - options || (options = {}); + if (innerAttr[0] instanceof BI.Widget) { + outerAttr.shift(); + return extend({}, item, { + el: innerAttr.shift() + }); } - return BI.map(BI.flatten(items), function (i, item) { - return BI.createWidget(item, BI.deepClone(options), context); - }); - }, - - createItems: function (data, innerAttr, outerAttr) { - innerAttr = BI.isArray(innerAttr) ? innerAttr : BI.makeArray(BI.flatten(data).length, innerAttr || {}); - outerAttr = BI.isArray(outerAttr) ? outerAttr : BI.makeArray(BI.flatten(data).length, outerAttr || {}); - return BI.map(data, function (i, item) { - if (BI.isArray(item)) { - return BI.createItems(item, innerAttr, outerAttr); - } - if (item instanceof BI.Widget) { - return BI.extend({}, innerAttr.shift(), outerAttr.shift(), { - type: null, - el: item - }); - } - if (innerAttr[0] instanceof BI.Widget) { - outerAttr.shift(); - return BI.extend({}, item, { - el: innerAttr.shift() - }); - } - if (item.el instanceof BI.Widget) { - innerAttr.shift(); - return BI.extend({}, outerAttr.shift(), { type: null }, item); - } - if (item.el) { - return BI.extend({}, outerAttr.shift(), item, { - el: BI.extend({}, innerAttr.shift(), item.el) - }); - } - return BI.extend({}, outerAttr.shift(), { - el: BI.extend({}, innerAttr.shift(), item) + if (item.el instanceof BI.Widget) { + innerAttr.shift(); + return extend({}, outerAttr.shift(), { type: null }, item); + } + if (item.el) { + return extend({}, outerAttr.shift(), item, { + el: extend({}, innerAttr.shift(), item.el) }); + } + return extend({}, outerAttr.shift(), { + el: extend({}, innerAttr.shift(), item) }); - }, - - // 用容器包装items - packageItems: function (items, layouts) { - for (var i = layouts.length - 1; i >= 0; i--) { - items = BI.map(items, function (k, it) { - return BI.extend({}, layouts[i], { - items: [ - BI.extend({}, layouts[i].el, { - el: it - }) - ] - }); + }); +} + +// 用容器包装items +export function packageItems(items, layouts) { + for (var i = layouts.length - 1; i >= 0; i--) { + items = map(items, function (k, it) { + return extend({}, layouts[i], { + items: [ + extend({}, layouts[i].el, { + el: it + }) + ] }); - } - return items; - }, + }); + } + return items; +} - formatEL: function (obj) { - if (obj && !obj.type && obj.el) { - return obj; - } - return { - el: obj - }; - }, +export function formatEL(obj) { + if (obj && !obj.type && obj.el) { + return obj; + } + return { + el: obj + }; +} - // 剥开EL - stripEL: function (obj) { - return obj.type && obj || obj.el || obj; - }, +// 剥开EL +export function stripEL(obj) { + return obj.type && obj || obj.el || obj; +} - trans2Element: function (widgets) { - return BI.map(widgets, function (i, wi) { - return wi.element; - }); - } +export function trans2Element(widgets) { + return map(widgets, (i, wi) => wi.element); +} + +// Utility +BI._.extend(BI, { + assert, + warn, + UUID, + isWidget, + createWidgets, + createItems, + packageItems, + formatEL, + stripEL, + trans2Element, }); // 集合相关方法 @@ -156,193 +165,242 @@ BI._.each(["get", "set", "each", "map", "reduce", "reduceRight", "find", "filter BI[name] = _applyFunc(name); } }); -BI._.extend(BI, { - // 数数 - count: function (from, to, predicate) { - var t; - if (predicate) { - for (t = from; t < to; t++) { - predicate(t); - } +export const where = BI.where; +export const findWhere = BI.findWhere; +export const invoke = BI.invoke; +export const pluck = BI.pluck; +export const shuffle = BI.shuffle; +export const sample = BI.sample; +export const toArray = BI.toArray; +export const size = BI.size; +export const get = BI.get; +export const set = BI.set; +export const each = BI.each; +export const map = BI.map; +export const reduce = BI.reduce; +export const reduceRight = BI.reduceRight; +export const find = BI.find; +export const filter = BI.filter; +export const reject = BI.reject; +export const every = BI.every; +export const all = BI.all; +export const some = BI.some; +export const any = BI.any; +export const max = BI.max; +export const min = BI.min; +export const sortBy = BI.sortBy; +export const groupBy = BI.groupBy; +export const indexBy = BI.indexBy; +export const countBy = BI.countBy; +export const partition = BI.partition; +export const clamp = BI.clamp; + +// 数数 +export function count(from, to, predicate) { + var t; + if (predicate) { + for (t = from; t < to; t++) { + predicate(t); } - return to - from; - }, - - // 倒数 - inverse: function (from, to, predicate) { - return BI.count(to, from, predicate); - }, - - firstKey: function (obj) { - var res = undefined; - BI.any(obj, function (key, value) { - res = key; - return true; - }); - return res; - }, - - lastKey: function (obj) { - var res = undefined; - BI.each(obj, function (key, value) { - res = key; - return true; - }); - return res; - }, + } + return to - from; +} + +// 倒数 +export function inverse(from, to, predicate) { + return count(to, from, predicate); +} + +export function firstKey(obj) { + let res = undefined; + any(obj, function (key, value) { + res = key; + return true; + }); + return res; +} + +export function lastKey(obj) { + let res = undefined; + each(obj, function (key, value) { + res = key; + return true; + }); + return res; +} + +export function firstObject(obj) { + let res = undefined; + any(obj, function (key, value) { + res = value; + return true; + }); + return res; +} + +export function lastObject(obj) { + let res = undefined; + each(obj, function (key, value) { + res = value; + return true; + }); + return res; +} + +export function concat(obj1, obj2) { + if (isKey(obj1)) { + return map([].slice.apply(arguments), function (idx, v) { + return v; + }).join(""); + } + if (isArray(obj1)) { + return BI._.concat.apply([], arguments); + } + if (isObject(obj1)) { + return extend.apply({}, arguments); + } +} - firstObject: function (obj) { - var res = undefined; - BI.any(obj, function (key, value) { - res = value; - return true; - }); - return res; - }, +export function backEach(obj, predicate, context) { + predicate = iteratee(predicate, context); + for (let index = obj.length - 1; index >= 0; index--) { + predicate(index, obj[index], obj); + } + return false; +} - lastObject: function (obj) { - var res = undefined; - BI.each(obj, function (key, value) { - res = value; +export function backAny(obj, predicate, context) { + predicate = iteratee(predicate, context); + for (let index = obj.length - 1; index >= 0; index--) { + if (predicate(index, obj[index], obj)) { return true; - }); - return res; - }, - - concat: function (obj1, obj2) { - if (BI.isKey(obj1)) { - return BI.map([].slice.apply(arguments), function (idx, v) { - return v; - }).join(""); - } - if (BI.isArray(obj1)) { - return BI._.concat.apply([], arguments); } - if (BI.isObject(obj1)) { - return BI._.extend.apply({}, arguments); - } - }, + } + return false; +} - backEach: function (obj, predicate, context) { - predicate = BI.iteratee(predicate, context); - for (var index = obj.length - 1; index >= 0; index--) { - predicate(index, obj[index], obj); +export function backEvery(obj, predicate, context) { + predicate = iteratee(predicate, context); + for (let index = obj.length - 1; index >= 0; index--) { + if (!predicate(index, obj[index], obj)) { + return false; } - return false; - }, + } + return true; +} - backAny: function (obj, predicate, context) { - predicate = BI.iteratee(predicate, context); - for (var index = obj.length - 1; index >= 0; index--) { - if (predicate(index, obj[index], obj)) { - return true; - } +export function backFindKey(obj, predicate, context) { + predicate = iteratee(predicate, context); + let objKeys = keys(obj), key; + for (let i = objKeys.length - 1; i >= 0; i--) { + key = objKeys[i]; + if (predicate(obj[key], key, obj)) { + return key; } - return false; - }, + } +} - backEvery: function (obj, predicate, context) { - predicate = BI.iteratee(predicate, context); - for (var index = obj.length - 1; index >= 0; index--) { - if (!predicate(index, obj[index], obj)) { - return false; - } - } - return true; - }, - - backFindKey: function (obj, predicate, context) { - predicate = BI.iteratee(predicate, context); - var keys = BI._.keys(obj), key; - for (var i = keys.length - 1; i >= 0; i--) { - key = keys[i]; - if (predicate(obj[key], key, obj)) { - return key; +export function backFind(obj, predicate, context) { + let key; + if (isArray(obj)) { + key = findLastIndex(obj, predicate, context); + } else { + key = backFindKey(obj, predicate, context); + } + if (key !== void 0 && key !== -1) { + return obj[key]; + } +} + +export function remove(obj, target, context) { + const targetIsFunction = isFunction(target); + target = targetIsFunction || isArray(target) ? target : [target]; + let i; + if (isArray(obj)) { + for (i = 0; i < obj.length; i++) { + if ((targetIsFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!targetIsFunction && contains(target, obj[i]))) { + obj.splice(i--, 1); } } - }, - - backFind: function (obj, predicate, context) { - var key; - if (BI.isArray(obj)) { - key = BI.findLastIndex(obj, predicate, context); - } else { - key = BI.backFindKey(obj, predicate, context); - } - if (key !== void 0 && key !== -1) { - return obj[key]; - } - }, - - remove: function (obj, target, context) { - var isFunction = BI.isFunction(target); - target = isFunction || BI.isArray(target) ? target : [target]; - var i; - if (BI.isArray(obj)) { - for (i = 0; i < obj.length; i++) { - if ((isFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!isFunction && BI.contains(target, obj[i]))) { - obj.splice(i--, 1); - } + } else { + each(obj, function (i, v) { + if ((targetIsFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!targetIsFunction && contains(target, obj[i]))) { + delete obj[i]; } + }); + } +} + +export function removeAt(obj, index) { + index = isArray(index) ? index : [index]; + let objIsArray = isArray(obj), i; + for (i = 0; i < index.length; i++) { + if (objIsArray) { + obj[index[i]] = "$deleteIndex"; } else { - BI.each(obj, function (i, v) { - if ((isFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!isFunction && BI.contains(target, obj[i]))) { - delete obj[i]; - } - }); - } - }, - - removeAt: function (obj, index) { - index = BI.isArray(index) ? index : [index]; - var isArray = BI.isArray(obj), i; - for (i = 0; i < index.length; i++) { - if (isArray) { - obj[index[i]] = "$deleteIndex"; - } else { - delete obj[index[i]]; - } - } - if (isArray) { - BI.remove(obj, "$deleteIndex"); + delete obj[index[i]]; } - }, - - string2Array: function (str) { - return str.split("&-&"); - }, - - array2String: function (array) { - return array.join("&-&"); - }, - - abc2Int: function (str) { - var idx = 0, start = "A", str = str.toUpperCase(); - for (var i = 0, len = str.length; i < len; ++i) { - idx = str.charAt(i).charCodeAt(0) - start.charCodeAt(0) + 26 * idx + 1; - if (idx > (2147483646 - str.charAt(i).charCodeAt(0) + start.charCodeAt(0)) / 26) { - return 0; - } - } - return idx; - }, - - int2Abc: function (num) { - var DIGITS = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; - var idx = num, str = ""; - if (num === 0) { - return ""; + } + if (objIsArray) { + remove(obj, "$deleteIndex"); + } +} + +export function string2Array(str) { + return str.split("&-&"); +} + +export function array2String(array) { + return array.join("&-&"); +} + +export function abc2Int(string) { + let idx = 0, start = "A", str = string.toUpperCase(); + for (let i = 0, len = str.length; i < len; ++i) { + idx = str.charAt(i).charCodeAt(0) - start.charCodeAt(0) + 26 * idx + 1; + if (idx > (2147483646 - str.charAt(i).charCodeAt(0) + start.charCodeAt(0)) / 26) { + return 0; } - while (idx !== 0) { - var t = idx % 26; - if (t === 0) { - t = 26; - } - str = DIGITS[t - 1] + str; - idx = (idx - t) / 26; + } + return idx; +} + +export function int2Abc(num) { + const DIGITS = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; + let idx = num, str = ""; + if (num === 0) { + return ""; + } + while (idx !== 0) { + let t = idx % 26; + if (t === 0) { + t = 26; } - return str; + str = DIGITS[t - 1] + str; + idx = (idx - t) / 26; } + return str; +} + +BI._.extend(BI, { + count, + inverse, + firstKey, + lastKey, + firstObject, + lastObject, + concat, + backEach, + backAny, + backEvery, + backFindKey, + backFind, + remove, + removeAt, + string2Array, + array2String, + abc2Int, + int2Abc, }); // 数组相关的方法 @@ -353,61 +411,89 @@ BI._.each(["first", "initial", "last", "rest", "compact", "flatten", "without", BI._.each(["findIndex", "findLastIndex"], function (name) { BI[name] = _applyFunc(name); }); -BI._.extend(BI, { - // 构建一个长度为length的数组 - makeArray: function (length, value) { - var res = []; - for (var i = 0; i < length; i++) { - if (BI.isNull(value)) { - res.push(i); - } else { - res.push(BI.deepClone(value)); - } +export const first = BI.first; +export const initial = BI.initial; +export const last = BI.last; +export const rest = BI.rest; +export const compact = BI.compact; +export const flatten = BI.flatten; +export const without = BI.without; +export const union = BI.union; +export const intersection = BI.intersection; +export const difference = BI.difference; +export const zip = BI.zip; +export const unzip = BI.unzip; +export const object = BI.object; +export const indexOf = BI.indexOf; +export const lastIndexOf = BI.lastIndexOf; +export const sortedIndex = BI.sortedIndex; +export const range = BI.range; +export const take = BI.take; +export const takeRight = BI.takeRight; +export const uniqBy = BI.uniqBy; +export const findIndex = BI.findIndex; +export const findLastIndex = BI.findLastIndex; + +// 构建一个长度为length的数组 +export function makeArray(length, value) { + let res = []; + for (let i = 0; i < length; i++) { + if (isNull(value)) { + res.push(i); + } else { + res.push(deepClone(value)); } - return res; - }, - - makeObject: function (array, value) { - var map = {}; - for (var i = 0; i < array.length; i++) { - if (BI.isNull(value)) { - map[array[i]] = array[i]; - } else if (BI.isFunction(value)) { - map[array[i]] = value(i, array[i]); - } else { - map[array[i]] = BI.deepClone(value); - } + } + return res; +} + +export function makeObject(array, value) { + let map = {}; + for (let i = 0; i < array.length; i++) { + if (isNull(value)) { + map[array[i]] = array[i]; + } else if (isFunction(value)) { + map[array[i]] = value(i, array[i]); + } else { + map[array[i]] = deepClone(value); } - return map; - }, + } + return map; +} - makeArrayByArray: function (array, value) { - var res = []; - if (!array) { - return res; - } - for (var i = 0, len = array.length; i < len; i++) { - if (BI.isArray(array[i])) { - res.push(BI.makeArrayByArray(array[i], value)); - } else { - res.push(BI.deepClone(value)); - } - } +export function makeArrayByArray(array, value) { + let res = []; + if (!array) { return res; - }, - - uniq: function (array, isSorted, iteratee, context) { - if (array == null) { - return []; - } - if (!BI._.isBoolean(isSorted)) { - context = iteratee; - iteratee = isSorted; - isSorted = false; + } + for (let i = 0, len = array.length; i < len; i++) { + if (isArray(array[i])) { + res.push(makeArrayByArray(array[i], value)); + } else { + res.push(deepClone(value)); } - iteratee && (iteratee = traverse(iteratee, context)); - return BI._.uniq.call(BI._, array, isSorted, iteratee, context); } + return res; +} + +export function uniq(array, isSorted, iteratee, context) { + if (array == null) { + return []; + } + if (!isBoolean(isSorted)) { + context = iteratee; + iteratee = isSorted; + isSorted = false; + } + iteratee && (iteratee = traverse(iteratee, context)); + return uniq.call(BI._, array, isSorted, iteratee, context); +} + +BI._.extend(BI, { + makeArray, + makeObject, + makeArrayByArray, + uniq, }); // 对象相关方法 @@ -417,244 +503,305 @@ BI._.each(["keys", "allKeys", "values", "pairs", "invert", "create", "functions" "isBoolean", "isDate", "isRegExp", "isError", "isNaN", "isUndefined", "zipObject", "cloneDeep"], function (name) { BI[name] = _apply(name); }); +export const keys = BI.keys; +export const allKeys = BI.allKeys; +export const values = BI.values; +export const pairs = BI.pairs; +export const invert = BI.invert; +export const create = BI.create; +export const functions = BI.functions; +export const extend = BI.extend; +export const extendOwn = BI.extendOwn; +export const defaults = BI.defaults; +export const clone = BI.clone; +export const property = BI.property; +export const propertyOf = BI.propertyOf; +export const matcher = BI.matcher; +export const isEqual = BI.isEqual; +export const isMatch = BI.isMatch; +export const isEmpty = BI.isEmpty; +export const isElement = BI.isElement; +export const isNumber = BI.isNumber; +export const isString = BI.isString; +export const isArray = BI.isArray; +export const isObject = BI.isObject; +export const isPlainObject = BI.isPlainObject; +export const isArguments = BI.isArguments; +export const isFunction = BI.isFunction; +export const isFinite = BI.isFinite; +export const isBoolean = BI.isBoolean; +export const isDate = BI.isDate; +export const isRegExp = BI.isRegExp; +export const isError = BI.isError; +export const isNaN = BI.isNaN; +export const isUndefined = BI.isUndefined; +export const zipObject = BI.zipObject; +export const cloneDeep = BI.cloneDeep; + BI._.each(["mapObject", "findKey", "pick", "omit", "tap"], function (name) { BI[name] = _applyFunc(name); }); -BI._.extend(BI, { - - inherit: function (sp, overrides) { - var sb = function () { - return sp.apply(this, arguments); - }; - var F = function () { - }, spp = sp.prototype; - F.prototype = spp; - sb.prototype = new F(); - sb.superclass = spp; - BI._.extend(sb.prototype, overrides, { - superclass: sp - }); - return sb; - }, - - init: function () { - // 先把准备环境准备好 - while (BI.prepares && BI.prepares.length > 0) { - BI.prepares.shift()(); - } - while (_global.___fineuiExposedFunction && _global.___fineuiExposedFunction.length > 0) { - _global.___fineuiExposedFunction.shift()(); - } - BI.initialized = true; - }, +export const mapObject = BI.mapObject; +export const findKey = BI.findKey; +export const pick = BI.pick; +export const omit = BI.omit; +export const tap = BI.tap; + +export function inherit(sp, overrides) { + let sb = function () { + return sp.apply(this, arguments); + }; + let F = function () { + }, spp = sp.prototype; + F.prototype = spp; + sb.prototype = new F(); + sb.superclass = spp; + extend(sb.prototype, overrides, { + superclass: sp + }); + return sb; +} + +export function init() { + // 先把准备环境准备好 + while (BI.prepares && BI.prepares.length > 0) { + BI.prepares.shift()(); + } + while (_global.___fineuiExposedFunction && _global.___fineuiExposedFunction.length > 0) { + _global.___fineuiExposedFunction.shift()(); + } + BI.initialized = true; +} - has: function (obj, keys) { - if (BI.isArray(keys)) { - if (keys.length === 0) { - return false; - } - return BI.every(keys, function (i, key) { - return BI._.has(obj, key); - }); - } - return BI._.has.apply(BI._, arguments); - }, - - freeze: function (value) { - // 在ES5中,如果这个方法的参数不是一个对象(一个原始值),那么它会导致 TypeError - // 在ES2015中,非对象参数将被视为要被冻结的普通对象,并被简单地返回 - if (Object.freeze && BI.isObject(value)) { - return Object.freeze(value); - } - return value; - }, - - // 数字和字符串可以作为key - isKey: function (key) { - return BI.isNumber(key) || (BI.isString(key) && key.length > 0); - }, - - // 忽略大小写的等于 - isCapitalEqual: function (a, b) { - a = BI.isNull(a) ? a : ("" + a).toLowerCase(); - b = BI.isNull(b) ? b : ("" + b).toLowerCase(); - return BI.isEqual(a, b); - }, - - isWidthOrHeight: function (w) { - if (typeof w === "number") { - return w >= 0; - } else if (typeof w === "string") { - return /^\d{1,3}(\.\d)?%$/.test(w) || w === "auto" || /^\d+(\.\d+)?px$/.test(w) || /^calc/.test(w); +export function has(obj, keys) { + if (isArray(keys)) { + if (keys.length === 0) { + return false; } - }, + return every(keys, function (i, key) { + return BI._.has(obj, key); + }); + } + return BI._.has.apply(BI._, arguments); +} + +export function freeze(value) { + // 在ES5中,如果这个方法的参数不是一个对象(一个原始值),那么它会导致 TypeError + // 在ES2015中,非对象参数将被视为要被冻结的普通对象,并被简单地返回 + if (Object.freeze && isObject(value)) { + return Object.freeze(value); + } + return value; +} + +// 数字和字符串可以作为key +export function isKey(key) { + return isNumber(key) || (isString(key) && key.length > 0); +} + +// 忽略大小写的等于 +export function isCapitalEqual(a, b) { + a = isNull(a) ? a : ("" + a).toLowerCase(); + b = isNull(b) ? b : ("" + b).toLowerCase(); + return isEqual(a, b); +} + +export function isWidthOrHeight(w) { + if (typeof w === "number") { + return w >= 0; + } else if (typeof w === "string") { + return /^\d{1,3}(\.\d)?%$/.test(w) || w === "auto" || /^\d+(\.\d+)?px$/.test(w) || /^calc/.test(w); + } +} - isNotNull: function (obj) { - return !BI.isNull(obj); - }, +export function isNotNull(obj) { + return !isNull(obj); +} - isNull: function (obj) { - return typeof obj === "undefined" || obj === null; - }, +export function isNull(obj) { + return typeof obj === "undefined" || obj === null; +} - isEmptyArray: function (arr) { - return BI.isArray(arr) && BI.isEmpty(arr); - }, +export function isEmptyArray(arr) { + return isArray(arr) && isEmpty(arr); +} - isNotEmptyArray: function (arr) { - return BI.isArray(arr) && !BI.isEmpty(arr); - }, +export function isNotEmptyArray(arr) { + return isArray(arr) && !isEmpty(arr); +} - isEmptyObject: function (obj) { - return BI.isEqual(obj, {}); - }, +export function isEmptyObject(obj) { + return isEqual(obj, {}); +} - isNotEmptyObject: function (obj) { - return BI.isPlainObject(obj) && !BI.isEmptyObject(obj); - }, +export function isNotEmptyObject(obj) { + return isPlainObject(obj) && !isEmptyObject(obj); +} - isEmptyString: function (obj) { - return BI.isString(obj) && obj.length === 0; - }, +export function isWindow(obj) { + return obj != null && obj == obj.window; +} - isNotEmptyString: function (obj) { - return BI.isString(obj) && !BI.isEmptyString(obj); - }, +export function isPromise(obj) { + return !!obj && (isObject(obj) || isFunction(obj)) && isFunction(obj.then); +} - isWindow: function (obj) { - return obj != null && obj == obj.window; - }, +BI._.extend(BI, { + inherit, + init, + has, + freeze, + isKey, + isCapitalEqual, + isWidthOrHeight, + isNotNull, + isNull, + isEmptyArray, + isNotEmptyArray, + isEmptyObject, + isNotEmptyObject, + isWindow, + isPromise, +}); - isPromise: function (obj) { - return !!obj && (BI.isObject(obj) || BI.isFunction(obj)) && BI.isFunction(obj.then); +export const deepClone = BI._.cloneDeep; +export const deepExtend = BI._.deepExtend; +export function isDeepMatch(object, attrs) { + let attrsKeys = keys(attrs), length = attrsKeys.length; + if (object == null) { + return !length; } -}); + const obj = Object(object); + for (let i = 0; i < length; i++) { + const key = attrsKeys[i]; + if (!isEqual(attrs[key], obj[key]) || !(key in obj)) { + return false; + } + } + return true; +} -// deep方法 -BI._.extend(BI, { - deepClone: BI._.cloneDeep, - deepExtend: BI._.merge, +export function contains(obj, target, fromIndex) { + if (!BI._.isArrayLike(obj)) obj = values(obj); + return indexOf(obj, target, typeof fromIndex === "number" && fromIndex) >= 0; +} - isDeepMatch: function (object, attrs) { - var keys = BI.keys(attrs), length = keys.length; - if (object == null) { - return !length; - } - var obj = Object(object); - for (var i = 0; i < length; i++) { - var key = keys[i]; - if (!BI.isEqual(attrs[key], obj[key]) || !(key in obj)) { - return false; - } - } - return true; - }, - - contains: function (obj, target, fromIndex) { - if (!BI._.isArrayLike(obj)) obj = BI._.values(obj); - return BI._.indexOf(obj, target, typeof fromIndex === "number" && fromIndex) >= 0; - }, - - deepContains: function (obj, copy) { - if (BI.isObject(copy)) { - return BI.any(obj, function (i, v) { - if (BI.isEqual(v, copy)) { - return true; - } - }); - } - return BI.contains(obj, copy); - }, +export function deepContains(obj, copy) { + if (isObject(copy)) { + return any(obj, (i, v) => isEqual(v, copy)); + } + return contains(obj, copy); +} - deepIndexOf: function (obj, target) { - for (var i = 0; i < obj.length; i++) { - if (BI.isEqual(target, obj[i])) { - return i; - } - } - return -1; - }, - - deepRemove: function (obj, target) { - var done = false; - var i; - if (BI.isArray(obj)) { - for (i = 0; i < obj.length; i++) { - if (BI.isEqual(target, obj[i])) { - obj.splice(i--, 1); - done = true; - } - } - } else { - BI.each(obj, function (i, v) { - if (BI.isEqual(target, obj[i])) { - delete obj[i]; - done = true; - } - }); +export function deepIndexOf(obj, target) { + for (let i = 0; i < obj.length; i++) { + if (isEqual(target, obj[i])) { + return i; } - return done; - }, - - deepWithout: function (obj, target) { - if (BI.isArray(obj)) { - var result = []; - for (var i = 0; i < obj.length; i++) { - if (!BI.isEqual(target, obj[i])) { - result.push(obj[i]); - } + } + return -1; +} + +export function deepRemove(obj, target) { + let done = false; + let i; + if (isArray(obj)) { + for (i = 0; i < obj.length; i++) { + if (isEqual(target, obj[i])) { + obj.splice(i--, 1); + done = true; } - return result; } - var result = {}; - BI.each(obj, function (i, v) { - if (!BI.isEqual(target, obj[i])) { - result[i] = v; - } - }); - return result; - - }, - - deepUnique: function (array) { - var result = []; - BI.each(array, function (i, item) { - if (!BI.deepContains(result, item)) { - result.push(item); + } else { + each(obj, (i, v) => { + if (isEqual(target, obj[i])) { + delete obj[i]; + done = true; } }); - return result; - }, - - // 比较两个对象得出不一样的key值 - deepDiff: function (object, other) { - object || (object = {}); - other || (other = {}); - var result = []; - var used = []; - for (var b in object) { - if (this.has(object, b)) { - if (!this.isEqual(object[b], other[b])) { - result.push(b); - } - used.push(b); + } + return done; +} + +export function deepWithout(obj, target) { + if (isArray(obj)) { + let result = []; + for (let i = 0; i < obj.length; i++) { + if (!isEqual(target, obj[i])) { + result.push(obj[i]); } } - for (var b in other) { - if (this.has(other, b) && !BI.contains(used, b)) { + return result; + } + let result = {}; + each(obj, (i, v) => { + if (!isEqual(target, obj[i])) { + result[i] = v; + } + }); + return result; +} + +export function deepUnique(array) { + let result = []; + each(array, (i, item) => { + if (!deepContains(result, item)) { + result.push(item); + } + }); + return result; +} + +// 比较两个对象得出不一样的key值 +export function deepDiff(object, other) { + object || (object = {}); + other || (other = {}); + let result = []; + let used = []; + for (let b in object) { + if (has(object, b)) { + if (!isEqual(object[b], other[b])) { result.push(b); } + used.push(b); + } + } + for (let b in other) { + if (has(other, b) && !contains(used, b)) { + result.push(b); } - return result; } + return result; +} + +// deep方法 +BI._.extend(BI, { + deepClone: BI._.cloneDeep, + deepExtend: BI._.merge, + isDeepMatch, + contains, + deepContains, + deepIndexOf, + deepRemove, + deepWithout, + deepUnique, + deepDiff, }); // 通用方法 -BI._.each(["uniqueId", "result", "chain", "iteratee", "escape", "unescape", "before", "after", "chunk"], function (name) { +BI._.each(["uniqueId", "result", "chain", "iteratee", "unescape", "before", "after", "chunk"], function (name) { BI[name] = function () { return BI._[name].apply(BI._, arguments); }; }); +export const uniqueId = BI.uniqueId; +export const result = BI.result; +export const chain = BI.chain; +export const iteratee = BI.iteratee; +export const unescape = BI.unescape; +export const before = BI.before; +export const after = BI.after; +export const chunk = BI.chunk; // 事件相关方法 BI._.each(["bind", "once", "partial", "debounce", "throttle", "delay", "defer", "wrap"], function (name) { @@ -662,627 +809,654 @@ BI._.each(["bind", "once", "partial", "debounce", "throttle", "delay", "defer", return BI._[name].apply(BI._, arguments); }; }); - -BI._.extend(BI, { - nextTick: (function () { - var callbacks = []; - var pending = false; - var timerFunc = void 0; - - function nextTickHandler() { - pending = false; - var copies = callbacks.slice(0); - callbacks.length = 0; - for (var i = 0; i < copies.length; i++) { - copies[i](); - } +export const bind = BI.bind; +export const once = BI.once; +export const partial = BI.partial; +export const debounce = BI.debounce; +export const throttle = BI.throttle; +export const delay = BI.delay; +export const defer = BI.defer; +export const wrap = BI.wrap; + +export const nextTick = (function () { + let callbacks = []; + let pending = false; + let timerFunc = void 0; + + function nextTickHandler() { + pending = false; + let copies = callbacks.slice(0); + callbacks.length = 0; + for (let i = 0; i < copies.length; i++) { + copies[i](); } + } - if (typeof Promise !== "undefined") { - var p = Promise.resolve(); - timerFunc = function timerFunc() { - p.then(nextTickHandler); - }; - } else if (typeof MutationObserver !== "undefined") { - var counter = 1; - var observer = new MutationObserver(nextTickHandler); - var textNode = document.createTextNode(String(counter)); - observer.observe(textNode, { - characterData: true - }); - timerFunc = function timerFunc() { - counter = (counter + 1) % 2; - textNode.data = String(counter); - }; - } else if (typeof setImmediate !== "undefined") { - timerFunc = function timerFunc() { - setImmediate(nextTickHandler); - }; - } else { - // Fallback to setTimeout. - timerFunc = function timerFunc() { - setTimeout(nextTickHandler, 0); - }; - } + if (typeof Promise !== "undefined") { + let p = Promise.resolve(); + timerFunc = function timerFunc() { + p.then(nextTickHandler); + }; + } else if (typeof MutationObserver !== "undefined") { + let counter = 1; + let observer = new MutationObserver(nextTickHandler); + let textNode = document.createTextNode(String(counter)); + observer.observe(textNode, { + characterData: true + }); + timerFunc = function timerFunc() { + counter = (counter + 1) % 2; + textNode.data = String(counter); + }; + } else if (typeof setImmediate !== "undefined") { + timerFunc = function timerFunc() { + setImmediate(nextTickHandler); + }; + } else { + // Fallback to setTimeout. + timerFunc = function timerFunc() { + setTimeout(nextTickHandler, 0); + }; + } - return function queueNextTick(cb) { - var _resolve = void 0; - var args = [].slice.call(arguments, 1); - callbacks.push(function () { - if (cb) { - try { - cb.apply(null, args); - } catch (e) { - console.error(e); - } - } else if (_resolve) { - _resolve.apply(null, args); + return function queueNextTick(cb) { + let _resolve = void 0; + let args = [].slice.call(arguments, 1); + callbacks.push(function () { + if (cb) { + try { + cb.apply(null, args); + } catch (e) { + console.error(e); } - }); - if (!pending) { - pending = true; - timerFunc(); - } - // $flow-disable-line - if (!cb && typeof Promise !== 'undefined') { - return new Promise(function (resolve, reject) { - _resolve = resolve; - }); + } else if (_resolve) { + _resolve.apply(null, args); } - }; - })() -}); + }); + if (!pending) { + pending = true; + timerFunc(); + } + // $flow-disable-line + if (!cb && typeof Promise !== 'undefined') { + return new Promise(function (resolve, reject) { + _resolve = resolve; + }); + } + }; +})(); + +BI._.extend(BI, { nextTick }); // 数字相关方法 BI._.each(["random"], function (name) { BI[name] = _apply(name); }); -BI._.extend(BI, { +export const random = BI.random; - parseInt: function (number) { - var radix = 10; - if (/^0x/g.test(number)) { - radix = 16; - } - try { - return parseInt(number, radix); - } catch (e) { - throw new Error(number + "parse int error"); - return NaN; - } - }, - - parseSafeInt: function (value) { - var MAX_SAFE_INTEGER = 9007199254740991; - return value - ? this.clamp(this.parseInt(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) - : (value === 0 ? value : 0); - }, - - parseFloat: function (number) { - try { - return parseFloat(number); - } catch (e) { - throw new Error(number + "parse float error"); - return NaN; - } - }, +export function parseInt(number) { + let radix = 10; + if (/^0x/g.test(number)) { + radix = 16; + } + try { + return _global.parseInt(number, radix); + } catch (e) { + throw new Error(number + "parse int error"); + return NaN; + } +} + +export function parseSafeInt(value) { + let MAX_SAFE_INTEGER = 9007199254740991; + return value + ? clamp(parseInt(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) + : (value === 0 ? value : 0); +} + +export function parseFloat(number) { + try { + return _global.parseFloat(number); + } catch (e) { + throw new Error(number + "parse float error"); + return NaN; + } +} - isNaturalNumber: function (number) { - if (/^\d+$/.test(number)) { - return true; - } - return false; - }, +export function isNaturalNumber(number) { + return /^\d+$/.test(number); +} - isPositiveInteger: function (number) { - if (/^\+?[1-9][0-9]*$/.test(number)) { - return true; - } - return false; - }, +export function isPositiveInteger(number) { + return /^\+?[1-9][0-9]*$/.test(number); +} - isNegativeInteger: function (number) { - if (/^\-[1-9][0-9]*$/.test(number)) { - return true; - } - return false; - }, +export function isNegativeInteger(number) { + return /^\-[1-9][0-9]*$/.test(number); +} - isInteger: function (number) { - if (/^\-?\d+$/.test(number)) { - return true; - } - return false; - }, +export function isInteger(number) { + return /^\-?\d+$/.test(number); +} - isNumeric: function (number) { - return !isNaN(parseFloat(number)) && isFinite(number); - }, +export function isNumeric(number) { + return !_global.isNaN(_global.parseFloat(number)) && _global.isFinite(number); +} - isFloat: function (number) { - if (/^([+-]?)\d*\.\d+$/.test(number)) { - return true; - } +export function isFloat(number) { + return /^([+-]?)\d*\.\d+$/.test(number); +} + +export function isOdd(number) { + if (!isInteger(number)) { return false; - }, + } + return (number & 1) === 1; +} - isOdd: function (number) { - if (!BI.isInteger(number)) { - return false; +export function isEven(number) { + if (!isInteger(number)) { + return false; + } + return (number & 1) === 0; +} + +export function sum(array, iteratee, context) { + let sum = 0; + each(array, (i, item) => { + if (iteratee) { + sum += Number(iteratee.apply(context, [i, item])); + } else { + sum += Number(item); } - return (number & 1) === 1; - }, + }); + return sum; +} - isEven: function (number) { - if (!BI.isInteger(number)) { - return false; - } - return (number & 1) === 0; - }, - - sum: function (array, iteratee, context) { - var sum = 0; - BI.each(array, function (i, item) { - if (iteratee) { - sum += Number(iteratee.apply(context, [i, item])); - } else { - sum += Number(item); - } - }); - return sum; - }, +export function average(array, iteratee, context) { + const sumResult = sum(array, iteratee, context); + return sumResult / array.length; +} - average: function (array, iteratee, context) { - var sum = BI.sum(array, iteratee, context); - return sum / array.length; - } +BI._.extend(BI, { + parseInt, + parseSafeInt, + parseFloat, + isNaturalNumber, + isPositiveInteger, + isNegativeInteger, + isInteger, + isNumeric, + isFloat, + isOdd, + isEven, + sum, + average, }); +export function trim() { + return BI._.trim.apply(BI._, arguments); +} + +export function toUpperCase(string) { + return (string + "").toLocaleUpperCase(); +} + +export function toLowerCase(string) { + return (string + "").toLocaleLowerCase(); +} + +export function isEndWithBlank(string) { + return /(\s|\u00A0)$/.test(string); +} + +export function isLiteral(exp) { + return /^\s?(true|false|-?[\d\.]+|'[^']*'|"[^"]*")\s?$/.test(exp); +} + +export function stripQuotes(str) { + const a = str.charCodeAt(0); + const b = str.charCodeAt(str.length - 1); + return a === b && (a === 0x22 || a === 0x27) + ? str.slice(1, -1) + : str; +} + +// background-color => backgroundColor +export function camelize(str) { + return str.replace(/-(.)/g, (_, character) => character.toUpperCase()); +} + +// backgroundColor => background-color +export function hyphenate(str) { + return str.replace(/([A-Z])/g, "-$1").toLowerCase(); +} + +export function isNotEmptyString(str) { + return isString(str) && !isEmpty(str); +} + +export function isEmptyString(str) { + return isString(str) && isEmpty(str); +} + +/** + * 通用解密方法 + * @param type 解密方式 + * @param text 文本 + * @param key 种子 + * @return {*} + */ +export function encrypt(type, text, key) { + switch (type) { + case BI.CRYPT_TYPE.AES: + default: + return BI.aesEncrypt(text, key); + } +} + +/** + * 通用解密方法 + * @param type 解密方式 + * @param text 文本 + * @param key 种子 + * @return {*} + */ +export function decrypt(type, text, key) { + switch (type) { + case BI.CRYPT_TYPE.AES: + default: + return BI.aesDecrypt(text, key); + } +} + +/** + * 对字符串中的'和\做编码处理 + * @static + * @param {String} string 要做编码处理的字符串 + * @return {String} 编码后的字符串 + */ +export function escape(string) { + return string.replace(/('|\\)/g, "\\$1"); +} + + +/** + * 让字符串通过指定字符做补齐的函数 + * + * var s = BI.leftPad('123', 5, '0');//s的值为:'00123' + * + * @static + * @param {String} val 原始值 + * @param {Number} size 总共需要的位数 + * @param {String} ch 用于补齐的字符 + * @return {String} 补齐后的字符串 + */ +export function leftPad(val, size, ch) { + let result = String(val); + if (!ch) { + ch = " "; + } + while (result.length < size) { + result = ch + result; + } + return result.toString(); +} + +/** + * 对字符串做替换的函数 + * + * var cls = 'my-class', text = 'Some text'; + * var res = BI.format('
{1}
', cls, text); + * //res的值为:'
Some text
'; + * + * @static + * @param {String} format 要做替换的字符串,替换字符串1,替换字符串2... + * @return {String} 做了替换后的字符串 + */ +export function format(format) { + var args = Array.prototype.slice.call(arguments, 1); + return format.replace(/\{(\d+)\}/g, (m, i) => args[i]); +} + // 字符串相关方法 BI._.extend(BI, { - trim: function () { - return BI._.trim.apply(BI._, arguments); - }, - - toUpperCase: function (string) { - return (string + "").toLocaleUpperCase(); - }, - - toLowerCase: function (string) { - return (string + "").toLocaleLowerCase(); - }, - - isEndWithBlank: function (string) { - return /(\s|\u00A0)$/.test(string); - }, - - isLiteral: function (exp) { - var literalValueRE = /^\s?(true|false|-?[\d\.]+|'[^']*'|"[^"]*")\s?$/; - return literalValueRE.test(exp); - }, - - stripQuotes: function (str) { - var a = str.charCodeAt(0); - var b = str.charCodeAt(str.length - 1); - return a === b && (a === 0x22 || a === 0x27) - ? str.slice(1, -1) - : str; - }, - - // background-color => backgroundColor - camelize: function (str) { - return str.replace(/-(.)/g, function (_, character) { - return character.toUpperCase(); - }); - }, - - // backgroundColor => background-color - hyphenate: function (str) { - return str.replace(/([A-Z])/g, "-$1").toLowerCase(); - }, - - isNotEmptyString: function (str) { - return BI.isString(str) && !BI.isEmpty(str); - }, - - isEmptyString: function (str) { - return BI.isString(str) && BI.isEmpty(str); - }, - - /** - * 通用加密方法 - */ - encrypt: function (type, text, key) { - switch (type) { - case BI.CRYPT_TYPE.AES: - default: - return BI.aesEncrypt(text, key); - } - }, - - /** - * 通用解密方法 - * @param type 解密方式 - * @param text 文本 - * @param key 种子 - * @return {*} - */ - decrypt: function (type, text, key) { - switch (type) { - case BI.CRYPT_TYPE.AES: - default: - return BI.aesDecrypt(text, key); - } - }, - - /** - * 对字符串中的'和\做编码处理 - * @static - * @param {String} string 要做编码处理的字符串 - * @return {String} 编码后的字符串 - */ - escape: function (string) { - return string.replace(/('|\\)/g, "\\$1"); - }, - - /** - * 让字符串通过指定字符做补齐的函数 - * - * var s = BI.leftPad('123', 5, '0');//s的值为:'00123' - * - * @static - * @param {String} val 原始值 - * @param {Number} size 总共需要的位数 - * @param {String} ch 用于补齐的字符 - * @return {String} 补齐后的字符串 - */ - leftPad: function (val, size, ch) { - var result = String(val); - if (!ch) { - ch = " "; - } - while (result.length < size) { - result = ch + result; - } - return result.toString(); - }, - - /** - * 对字符串做替换的函数 - * - * var cls = 'my-class', text = 'Some text'; - * var res = BI.format('
{1}
', cls, text); - * //res的值为:'
Some text
'; - * - * @static - * @param {String} format 要做替换的字符串,替换字符串1,替换字符串2... - * @return {String} 做了替换后的字符串 - */ - format: function (format) { - var args = Array.prototype.slice.call(arguments, 1); - return format.replace(/\{(\d+)\}/g, function (m, i) { - return args[i]; - }); - } + trim, + toUpperCase, + toLowerCase, + isEndWithBlank, + isLiteral, + stripQuotes, + camelize, + hyphenate, + isNotEmptyString, + isEmptyString, + encrypt, + decrypt, + escape, + leftPad, + format, }); -// 日期相关方法 -BI._.extend(BI, { - /** - * 是否是闰年 - * @param year - * @returns {boolean} - */ - isLeapYear: function (year) { - return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; - }, - - /** - * 检测是否在有效期 - * - * @param YY 年 - * @param MM 月 - * @param DD 日 - * @param minDate '1900-01-01' - * @param maxDate '2099-12-31' - * @returns {Array} 若无效返回无效状态,数组第一位为无效属性,第二位缺省为超下限,1为超上限 - */ - checkDateVoid: function (YY, MM, DD, minDate, maxDate) { - var back = []; - YY = YY | 0; - MM = MM | 0; - DD = DD | 0; - minDate = BI.isString(minDate) ? minDate.match(/\d+/g) : minDate; - maxDate = BI.isString(maxDate) ? maxDate.match(/\d+/g) : maxDate; - if (YY < minDate[0]) { - back = ["y"]; - } else if (YY > maxDate[0]) { - back = ["y", 1]; - } else if (YY >= minDate[0] && YY <= maxDate[0]) { - if (YY == minDate[0]) { - if (MM < minDate[1]) { - back = ["m"]; - } else if (MM == minDate[1]) { - if (DD < minDate[2]) { - back = ["d"]; - } +/** + * 是否是闰年 + * @param year + * @returns {boolean} + */ +export function isLeapYear(year) { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +/** + * 检测是否在有效期 + * + * @param YY 年 + * @param MM 月 + * @param DD 日 + * @param minDate '1900-01-01' + * @param maxDate '2099-12-31' + * @returns {Array} 若无效返回无效状态,数组第一位为无效属性,第二位缺省为超下限,1为超上限 + */ +export function checkDateVoid(YY, MM, DD, minDate, maxDate) { + let back = []; + YY = YY | 0; + MM = MM | 0; + DD = DD | 0; + minDate = isString(minDate) ? minDate.match(/\d+/g) : minDate; + maxDate = isString(maxDate) ? maxDate.match(/\d+/g) : maxDate; + if (YY < minDate[0]) { + back = ["y"]; + } else if (YY > maxDate[0]) { + back = ["y", 1]; + } else if (YY >= minDate[0] && YY <= maxDate[0]) { + if (YY == minDate[0]) { + if (MM < minDate[1]) { + back = ["m"]; + } else if (MM == minDate[1]) { + if (DD < minDate[2]) { + back = ["d"]; } } - if (YY == maxDate[0]) { - if (MM > maxDate[1]) { - back = ["m", 1]; - } else if (MM == maxDate[1]) { - if (DD > maxDate[2]) { - back = ["d", 1]; - } + } + if (YY == maxDate[0]) { + if (MM > maxDate[1]) { + back = ["m", 1]; + } else if (MM == maxDate[1]) { + if (DD > maxDate[2]) { + back = ["d", 1]; } } } - return back; - }, - - checkDateLegal: function (str) { - var ar = str.match(/\d+/g); - var YY = ar[0] | 0, MM = ar[1] | 0, DD = ar[2] | 0; - if (ar.length <= 1) { - return true; - } - if (ar.length <= 2) { - return MM >= 1 && MM <= 12; - } - var MD = BI.Date._MD.slice(0); - MD[1] = BI.isLeapYear(YY) ? 29 : 28; - return MM >= 1 && MM <= 12 && DD <= MD[MM - 1]; - }, - - /** 解析日期时间字符串 - * - * @param str - * @param fmt - * @returns {Date|Date} - * 年月日缺省值为当前日期, 时分秒缺省值为0 - */ - parseDateTime: function (str, fmt) { - var today = BI.getDate(); - var y; - var m; - var d; - // wei : 对于fmt为‘YYYYMM’或者‘YYYYMMdd’的格式,str的值为类似'201111'的形式,因为年月之间没有分隔符,所以正则表达式分割无效,导致bug7376。 - var a = str.split(/\W+/); - if (fmt.toLowerCase() == "%y%x" || fmt.toLowerCase() == "%y%x%d") { - var yearlength = 4; - var otherlength = 2; - a[0] = str.substring(0, yearlength); - a[1] = str.substring(yearlength, yearlength + otherlength); - a[2] = str.substring(yearlength + otherlength, yearlength + otherlength * 2); - } - var b = fmt.match(/%./g); - var i = 0, j = 0; - var hr = 0; - var min = 0; - var sec = 0; - for (i = 0; i < a.length; ++i) { - switch (b[i]) { - case "%d": - case "%e": - d = parseInt(a[i], 10); - break; + } + return back; +} - case "%X": - m = parseInt(a[i], 10) - 1; - break; - case "%x": - m = parseInt(a[i], 10) - 1; - break; +export function checkDateLegal(str) { + const ar = str.match(/\d+/g); + const YY = ar[0] | 0, MM = ar[1] | 0, DD = ar[2] | 0; + if (ar.length <= 1) { + return true; + } + if (ar.length <= 2) { + return MM >= 1 && MM <= 12; + } + let MD = BI.Date._MD.slice(0); + MD[1] = isLeapYear(YY) ? 29 : 28; + return MM >= 1 && MM <= 12 && DD <= MD[MM - 1]; +} - case "%Y": - case "%y": - y = parseInt(a[i], 10); - (y < 100) && (y += (y > 29) ? 1900 : 2000); - break; +/** 解析日期时间字符串 + * + * @param str + * @param fmt + * @returns {Date|Date} + * 年月日缺省值为当前日期, 时分秒缺省值为0 + */ +export function parseDateTime(str, fmt) { + const today = BI.getDate(); + let y; + let m; + let d; + // wei : 对于fmt为‘YYYYMM’或者‘YYYYMMdd’的格式,str的值为类似'201111'的形式,因为年月之间没有分隔符,所以正则表达式分割无效,导致bug7376。 + let a = str.split(/\W+/); + if (fmt.toLowerCase() == "%y%x" || fmt.toLowerCase() == "%y%x%d") { + let yearlength = 4; + let otherlength = 2; + a[0] = str.substring(0, yearlength); + a[1] = str.substring(yearlength, yearlength + otherlength); + a[2] = str.substring(yearlength + otherlength, yearlength + otherlength * 2); + } + let b = fmt.match(/%./g); + let i = 0, j = 0; + let hr = 0; + let min = 0; + let sec = 0; + for (i = 0; i < a.length; ++i) { + switch (b[i]) { + case "%d": + case "%e": + d = _global.parseInt(a[i], 10); + break; - case "%b": - case "%B": - for (j = 0; j < 12; ++j) { - if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { - m = j; - break; - } - } - break; + case "%X": + m = _global.parseInt(a[i], 10) - 1; + break; + case "%x": + m = _global.parseInt(a[i], 10) - 1; + break; - case "%H": - case "%I": - case "%k": - case "%l": - hr = parseInt(a[i], 10); - break; + case "%Y": + case "%y": + y = _global.parseInt(a[i], 10); + (y < 100) && (y += (y > 29) ? 1900 : 2000); + break; - case "%P": - case "%p": - if (/pm/i.test(a[i]) && hr < 12) { - hr += 12; - } else if (/am/i.test(a[i]) && hr >= 12) { - hr -= 12; - } - break; - case "%Q": - case "%q": - m = (parseInt(a[i], 10) - 1) * 3; - break; - case "%M": - min = parseInt(a[i], 10); - break; - case "%S": - sec = parseInt(a[i], 10); - break; - } - } - // if (!a[i]) { - // continue; - // } - if (isNaN(y)) { - y = today.getFullYear(); - } - if (isNaN(m)) { - m = today.getMonth(); - } - if (isNaN(d)) { - d = today.getDate(); - } - if (isNaN(hr)) { - hr = today.getHours(); - } - if (isNaN(min)) { - min = today.getMinutes(); - } - if (isNaN(sec)) { - sec = today.getSeconds(); - } - if (y != 0) { - return BI.getDate(y, m, d, hr, min, sec); - } - y = 0; - m = -1; - d = 0; - for (i = 0; i < a.length; ++i) { - if (a[i].search(/[a-zA-Z]+/) != -1) { - var t = -1; + case "%b": + case "%B": for (j = 0; j < 12; ++j) { if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { - t = j; + m = j; break; } } - if (t != -1) { - if (m != -1) { - d = m + 1; - } - m = t; - } - } else if (parseInt(a[i], 10) <= 12 && m == -1) { - m = a[i] - 1; - } else if (parseInt(a[i], 10) > 31 && y == 0) { - y = parseInt(a[i], 10); - (y < 100) && (y += (y > 29) ? 1900 : 2000); - } else if (d == 0) { - d = a[i]; - } - } - if (y == 0) { - y = today.getFullYear(); - } - if (m === -1) { - m = today.getMonth(); - } - if (m != -1 && d != 0) { - return BI.getDate(y, m, d, hr, min, sec); - } - return today; - }, - - getDate: function () { - var length = arguments.length; - var args = arguments; - var dt; - switch (length) { - // new Date() - case 0: - dt = new Date(); - break; - // new Date(long) - case 1: - dt = new Date(args[0]); - break; - // new Date(year, month) - case 2: - dt = new Date(args[0], args[1]); - break; - // new Date(year, month, day) - case 3: - dt = new Date(args[0], args[1], args[2]); - break; - // new Date(year, month, day, hour) - case 4: - dt = new Date(args[0], args[1], args[2], args[3]); - break; - // new Date(year, month, day, hour, minute) - case 5: - dt = new Date(args[0], args[1], args[2], args[3], args[4]); - break; - // new Date(year, month, day, hour, minute, second) - case 6: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); break; - // new Date(year, month, day, hour, minute, second, millisecond) - case 7: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - break; - default: - dt = new Date(); - break; - } - if (BI.isNotNull(BI.timeZone) && (arguments.length === 0 || (arguments.length === 1 && BI.isNumber(arguments[0])))) { - var localTime = dt.getTime(); - // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 - var localOffset = dt.getTimezoneOffset() * 60000; // 获得当地时间偏移的毫秒数 - var utc = localTime + localOffset; // utc即GMT时间标准时区 - return new Date(utc + BI.timeZone);// + Pool.timeZone.offset); - } - return dt; - - }, - - getTime: function () { - var length = arguments.length; - var args = arguments; - var dt; - switch (length) { - // new Date() - case 0: - dt = new Date(); - break; - // new Date(long) - case 1: - dt = new Date(args[0]); - break; - // new Date(year, month) - case 2: - dt = new Date(args[0], args[1]); - break; - // new Date(year, month, day) - case 3: - dt = new Date(args[0], args[1], args[2]); - break; - // new Date(year, month, day, hour) - case 4: - dt = new Date(args[0], args[1], args[2], args[3]); + + case "%H": + case "%I": + case "%k": + case "%l": + hr = _global.parseInt(a[i], 10); break; - // new Date(year, month, day, hour, minute) - case 5: - dt = new Date(args[0], args[1], args[2], args[3], args[4]); + + case "%P": + case "%p": + if (/pm/i.test(a[i]) && hr < 12) { + hr += 12; + } else if (/am/i.test(a[i]) && hr >= 12) { + hr -= 12; + } break; - // new Date(year, month, day, hour, minute, second) - case 6: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); + case "%Q": + case "%q": + m = (_global.parseInt(a[i], 10) - 1) * 3; break; - // new Date(year, month, day, hour, minute, second, millisecond) - case 7: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + case "%M": + min = _global.parseInt(a[i], 10); break; - default: - dt = new Date(); + case "%S": + sec = _global.parseInt(a[i], 10); break; } - if (BI.isNotNull(BI.timeZone)) { - // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 - return dt.getTime() - BI.timeZone - new Date().getTimezoneOffset() * 60000; + } + // if (!a[i]) { + // continue; + // } + if (isNaN(y)) { + y = today.getFullYear(); + } + if (isNaN(m)) { + m = today.getMonth(); + } + if (isNaN(d)) { + d = today.getDate(); + } + if (isNaN(hr)) { + hr = today.getHours(); + } + if (isNaN(min)) { + min = today.getMinutes(); + } + if (isNaN(sec)) { + sec = today.getSeconds(); + } + if (y != 0) { + return BI.getDate(y, m, d, hr, min, sec); + } + y = 0; + m = -1; + d = 0; + for (i = 0; i < a.length; ++i) { + if (a[i].search(/[a-zA-Z]+/) != -1) { + let t = -1; + for (j = 0; j < 12; ++j) { + if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { + t = j; + break; + } + } + if (t != -1) { + if (m != -1) { + d = m + 1; + } + m = t; + } + } else if (_global.parseInt(a[i], 10) <= 12 && m == -1) { + m = a[i] - 1; + } else if (_global.parseInt(a[i], 10) > 31 && y == 0) { + y = _global.parseInt(a[i], 10); + (y < 100) && (y += (y > 29) ? 1900 : 2000); + } else if (d == 0) { + d = a[i]; } - return dt.getTime(); - } -}); + if (y == 0) { + y = today.getFullYear(); + } + if (m === -1) { + m = today.getMonth(); + } + if (m != -1 && d != 0) { + return BI.getDate(y, m, d, hr, min, sec); + } + return today; +} + +export function getDate() { + const length = arguments.length; + const args = arguments; + let dt; + switch (length) { + // new Date() + case 0: + dt = new Date(); + break; + // new Date(long) + case 1: + dt = new Date(args[0]); + break; + // new Date(year, month) + case 2: + dt = new Date(args[0], args[1]); + break; + // new Date(year, month, day) + case 3: + dt = new Date(args[0], args[1], args[2]); + break; + // new Date(year, month, day, hour) + case 4: + dt = new Date(args[0], args[1], args[2], args[3]); + break; + // new Date(year, month, day, hour, minute) + case 5: + dt = new Date(args[0], args[1], args[2], args[3], args[4]); + break; + // new Date(year, month, day, hour, minute, second) + case 6: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); + break; + // new Date(year, month, day, hour, minute, second, millisecond) + case 7: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + break; + default: + dt = new Date(); + break; + } + if (isNotNull(BI.timeZone) && (arguments.length === 0 || (arguments.length === 1 && isNumber(arguments[0])))) { + const localTime = dt.getTime(); + // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 + const localOffset = dt.getTimezoneOffset() * 60000; // 获得当地时间偏移的毫秒数 + const utc = localTime + localOffset; // utc即GMT时间标准时区 + return new Date(utc + BI.timeZone);// + Pool.timeZone.offset); + } + return dt; +} + +export function getTime() { + const length = arguments.length; + const args = arguments; + let dt; + switch (length) { + // new Date() + case 0: + dt = new Date(); + break; + // new Date(long) + case 1: + dt = new Date(args[0]); + break; + // new Date(year, month) + case 2: + dt = new Date(args[0], args[1]); + break; + // new Date(year, month, day) + case 3: + dt = new Date(args[0], args[1], args[2]); + break; + // new Date(year, month, day, hour) + case 4: + dt = new Date(args[0], args[1], args[2], args[3]); + break; + // new Date(year, month, day, hour, minute) + case 5: + dt = new Date(args[0], args[1], args[2], args[3], args[4]); + break; + // new Date(year, month, day, hour, minute, second) + case 6: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); + break; + // new Date(year, month, day, hour, minute, second, millisecond) + case 7: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + break; + default: + dt = new Date(); + break; + } + if (isNotNull(BI.timeZone)) { + // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 + return dt.getTime() - BI.timeZone - new Date().getTimezoneOffset() * 60000; + } + return dt.getTime(); -// TODO: 暂时先直接export全部,下一步拆function -export default BI; \ No newline at end of file +} + +// 日期相关方法 +BI._.extend(BI, { + isLeapYear, + checkDateVoid, + checkDateLegal, + parseDateTime, + getDate, + getTime, +}); \ No newline at end of file diff --git a/src/core/3.ob.js b/src/core/3.ob.js index f6e9396de..5d0e9f7fb 100644 --- a/src/core/3.ob.js +++ b/src/core/3.ob.js @@ -1,4 +1,4 @@ -import BI from "./2.base"; +import { isFunction, isArray, isObject, isArguments, reduce, bind } from "./2.base"; function extend() { let target = arguments[0] || {}, length = arguments.length, i = 1, name, copy; @@ -49,11 +49,11 @@ export default class OB { _initProps(config) { let props = this.props; - if (BI.isFunction(this.props)) { + if (isFunction(this.props)) { props = this.props(config); } const defaultProps = extend(this._defaultConfig(config), props); - const modifiedDefaultProps = (config && config.type && OB.configFunctions[config.type + ".props"]) ? BI.reduce(OB.configFunctions[config.type + ".props"], function (value, conf, index) { + const modifiedDefaultProps = (config && config.type && OB.configFunctions[config.type + ".props"]) ? reduce(OB.configFunctions[config.type + ".props"], function (value, conf, index) { return extend(conf, value.fn(defaultProps, config, value.opt)); }, {}) : null; this.options = extend(defaultProps, modifiedDefaultProps, config); @@ -67,19 +67,19 @@ export default class OB { _initListeners() { if (this.options.listeners !== null) { BI._.each(this.options.listeners, (lis, eventName) => { - if (BI._.isFunction(lis)) { + if (isFunction(lis)) { this.on(eventName, lis); return; } - if (BI._.isArray(lis)) { + if (isArray(lis)) { BI._.each(lis, (l) => { this.on(eventName, l); }); return; } - (lis.target ? lis.target : this)[lis.once ? "once" : "on"](lis.eventName, BI._.bind(lis.action, this)); + (lis.target ? lis.target : this)[lis.once ? "once" : "on"](lis.eventName, bind(lis.action, this)); }); delete this.options.listeners; } @@ -89,10 +89,10 @@ export default class OB { _initRef() { const o = this.options; if (o.__ref) { - BI.isFunction(o.__ref) ? o.__ref.call(this, this) : o.__ref.current = this; + isFunction(o.__ref) ? o.__ref.call(this, this) : o.__ref.current = this; } if (o.ref) { - BI.isFunction(o.ref) ? o.ref.call(this, this) : o.ref.current = this; + isFunction(o.ref) ? o.ref.call(this, this) : o.ref.current = this; } } @@ -100,17 +100,17 @@ export default class OB { _purgeRef() { const o = this.options; if (o.__ref) { - BI.isFunction(o.__ref) ? o.__ref.call(null, null) : o.__ref.current = null; + isFunction(o.__ref) ? o.__ref.call(null, null) : o.__ref.current = null; o.__ref = null; } if (o.ref) { - BI.isFunction(o.ref) ? o.ref.call(null, null) : o.ref.current = null; + isFunction(o.ref) ? o.ref.call(null, null) : o.ref.current = null; o.ref = null; } } _getEvents() { - if (!BI._.isObject(this.events)) { + if (!isObject(this.events)) { this.events = {}; } @@ -125,7 +125,7 @@ export default class OB { on(eventName, fn) { eventName = eventName.toLowerCase(); let fns = this._getEvents()[eventName]; - if (!BI._.isArray(fns)) { + if (!isArray(fns)) { fns = []; this._getEvents()[eventName] = fns; } @@ -160,7 +160,7 @@ export default class OB { delete this._getEvents()[eventName]; } else { const fns = this._getEvents()[eventName]; - if (BI._.isArray(fns)) { + if (isArray(fns)) { const newFns = []; BI._.each(fns, function (ifn) { if (ifn !== fn) { @@ -189,8 +189,8 @@ export default class OB { fireEvent() { const eventName = arguments[0].toLowerCase(); const fns = this._getEvents()[eventName]; - if (BI.isArray(fns)) { - if (BI.isArguments(arguments[1])) { + if (isArray(fns)) { + if (isArguments(arguments[1])) { for (let i = 0; i < fns.length; i++) { if (fns[i].apply(this, arguments[1]) === false) { return false; @@ -216,6 +216,4 @@ export default class OB { } } -// BI.OB = BI.OB || OB; - BI.extend(BI, { OB }); diff --git a/src/core/4.widget.js b/src/core/4.widget.js index 1e6c4b746..728e70dfa 100644 --- a/src/core/4.widget.js +++ b/src/core/4.widget.js @@ -1,12 +1,12 @@ /** * Widget超类 - * @class BI.Widget - * @extends BI.OB + * @class Widget + * @extends OB * * @cfg {JSON} options 配置属性 */ -import BI 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"; const cancelAnimationFrame = @@ -23,20 +23,20 @@ function callLifeHook(self, life) { let hooks = [], hook; hook = self[life]; if (hook) { - hooks = hooks.concat(BI.isArray(hook) ? hook : [hook]); + hooks = hooks.concat(isArray(hook) ? hook : [hook]); } hook = self.options[life]; if (hook) { - hooks = hooks.concat(BI.isArray(hook) ? hook : [hook]); + hooks = hooks.concat(isArray(hook) ? hook : [hook]); } - BI.each(hooks, function (i, hook) { + each(hooks, function (i, hook) { hook.call(self); }); } export default class Widget extends OB { _defaultConfig () { - return BI.extend(super._defaultConfig(), { + return extend(super._defaultConfig(), { root: false, tagName: "div", attributes: null, @@ -67,9 +67,9 @@ export default class Widget extends OB { if (this.setup) { pushTarget(this); const delegate = this.setup(this.options); - if (BI.isPlainObject(delegate)) { + if (isPlainObject(delegate)) { // 如果setup返回一个json,即对外暴露的方法 - BI.extend(this, delegate); + extend(this, delegate); } else { this.render = delegate; } @@ -208,7 +208,7 @@ export default class Widget extends OB { this.element.addClass((o._baseCls || "") + " " + (o.baseCls || "") + " " + (o.extraCls || "")); } if (o.cls) { - if (BI.isFunction(o.cls)) { + if (isFunction(o.cls)) { const cls = this.__watch(o.cls, (context, newValue) => { this.element.removeClass(cls).addClass(cls = newValue); }); @@ -227,10 +227,10 @@ export default class Widget extends OB { this.element.data(o.data); } if (o.css) { - if (BI.isFunction(o.css)) { + if (isFunction(o.css)) { const css = this.__watch(o.css, (context, newValue) => { for (const k in css) { - if (BI.isNull(newValue[k])) { + if (isNull(newValue[k])) { newValue[k] = ""; } } @@ -250,7 +250,7 @@ export default class Widget extends OB { return getter.call(this, this); }, (handler && ((v) => { handler.call(this, this, v); - })) || BI.emptyFn, BI.extend({ deep: true }, options)); + })) || BI.emptyFn, extend({ deep: true }, options)); this._watchers.push(() => { watcher.teardown(); }); @@ -266,18 +266,18 @@ export default class Widget extends OB { */ _initRoot() { const o = this.options; - this.widgetName = o.widgetName || BI.uniqueId("widget"); + this.widgetName = o.widgetName || uniqueId("widget"); this._isRoot = o.root; this._children = {}; - if (BI.isWidget(o.element)) { + if (isWidget(o.element)) { this.element = this.options.element.element; this._parent = o.element; this._parent._children && this._parent.addWidget(this.widgetName, this); } else if (o.element) { - this.element = BI.Widget._renderEngine.createElement(this); + this.element = Widget._renderEngine.createElement(this); this._isRoot = true; } else { - this.element = BI.Widget._renderEngine.createElement(this); + this.element = Widget._renderEngine.createElement(this); } this.element._isWidget = true; // const widgets = this.element.data("__widgets") || []; @@ -288,14 +288,14 @@ export default class Widget extends OB { _initElementWidth() { const o = this.options; - if (BI.isWidthOrHeight(o.width)) { + if (isWidthOrHeight(o.width)) { this.element.css("width", BI.pixFormat(o.width)); } } _initElementHeight() { const o = this.options; - if (BI.isWidthOrHeight(o.height)) { + if (isWidthOrHeight(o.height)) { this.element.css("height", BI.pixFormat(o.height)); } } @@ -303,7 +303,7 @@ export default class Widget extends OB { _initVisual() { const o = this.options; if (o.invisible) { - const invisible = o.invisible = BI.isFunction(o.invisible) ? this.__watch(o.invisible, (context, newValue) => { + const invisible = o.invisible = isFunction(o.invisible) ? this.__watch(o.invisible, (context, newValue) => { this.setVisible(!newValue); }) : o.invisible; if (invisible) { @@ -317,7 +317,7 @@ export default class Widget extends OB { const o = this.options; if (o.disabled || o.invalid) { if (this.options.disabled) { - const disabled = o.disabled = BI.isFunction(o.disabled) ? this.__watch(o.disabled, (context, newValue) => { + const disabled = o.disabled = isFunction(o.disabled) ? this.__watch(o.disabled, (context, newValue) => { this.setEnable(!newValue); }) : o.disabled; if (disabled) { @@ -325,7 +325,7 @@ export default class Widget extends OB { } } if (this.options.invalid) { - const invalid = o.invalid = BI.isFunction(o.invalid) ? this.__watch(o.invalid, (context, newValue) => { + const invalid = o.invalid = isFunction(o.invalid) ? this.__watch(o.invalid, (context, newValue) => { this.setValid(!newValue); }) : o.invalid; if (invalid) { @@ -334,9 +334,9 @@ export default class Widget extends OB { } } if (o.effect) { - if (BI.isArray(o.effect)) { - if (BI.isArray(o.effect[0])) { - BI.each(o.effect, (i, effect) => { + if (isArray(o.effect)) { + if (isArray(o.effect[0])) { + each(o.effect, (i, effect) => { this.__watch(effect[0], effect[1]); }); } else { @@ -361,16 +361,16 @@ export default class Widget extends OB { this.__isMounting = true; // 当开启worker模式时,可以通过$render来实现另一种效果 const workerMode = BI.Providers.getProvider("bi.provider.system").getWorkerMode(); - const render = BI.isFunction(this.options.render) ? this.options.render : (workerMode ? (this.$render || this.render) : this.render); + 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 = BI.Plugin.getRender(this.options.type, els); - if (BI.isPlainObject(els)) { + if (isPlainObject(els)) { els = [els]; } this.__initWatch(); - if (BI.isArray(els)) { - BI.each(els, (i, el) => { + if (isArray(els)) { + each(els, (i, el) => { if (el) { BI._lazyCreateWidget(el, { element: this @@ -475,7 +475,7 @@ export default class Widget extends OB { this.options._disabled = true; } // 递归将所有子组件使能 - BI.each(this._children, function (i, child) { + each(this._children, function (i, child) { !child._manualSetEnable && child._setEnable && child._setEnable(enable); }); } @@ -487,7 +487,7 @@ export default class Widget extends OB { this.options._invalid = true; } // 递归将所有子组件使有效 - BI.each(this._children, function (i, child) { + each(this._children, function (i, child) { !child._manualSetValid && child._setValid && child._setValid(valid); }); } @@ -581,7 +581,7 @@ export default class Widget extends OB { doBehavior() { const args = arguments; // 递归将所有子组件使有效 - BI.each(this._children, function (i, child) { + each(this._children, function (i, child) { child.doBehavior && child.doBehavior.apply(child, args); }); } @@ -596,32 +596,32 @@ export default class Widget extends OB { addWidget(name, widget) { const self = this; - if (name instanceof BI.Widget) { + if (name instanceof Widget) { widget = name; name = widget.getName(); } - if (BI.isKey(name)) { + if (isKey(name)) { name = name + ""; } - name = name || widget.getName() || BI.uniqueId("widget"); + name = name || widget.getName() || uniqueId("widget"); if (this._children[name]) { throw new Error("组件:组件名已存在,不能进行添加"); } widget._setParent && widget._setParent(this); widget.on(BI.Events.DESTROY, function () { // TODO: self待删 - BI.remove(self._children, this); + remove(self._children, this); }); return (this._children[name] = widget); } getWidgetByName(name) { - if (!BI.isKey(name) || name === this.getName()) { + if (!isKey(name) || name === this.getName()) { return this; } name = name + ""; let widget = void 0, other = {}; - BI.any(this._children, function (i, wi) { + any(this._children, function (i, wi) { if (i === name) { widget = wi; return true; @@ -629,7 +629,7 @@ export default class Widget extends OB { other[i] = wi; }); if (!widget) { - BI.any(other, function (i, wi) { + any(other, function (i, wi) { return (widget = wi.getWidgetByName(i)); }); } @@ -637,8 +637,8 @@ export default class Widget extends OB { } removeWidget(nameOrWidget) { - if (BI.isWidget(nameOrWidget)) { - BI.remove(this._children, nameOrWidget); + if (isWidget(nameOrWidget)) { + remove(this._children, nameOrWidget); } else { delete this._children[nameOrWidget]; } @@ -661,11 +661,11 @@ export default class Widget extends OB { } attr(key, value) { - if (BI.isPlainObject(key)) { - BI.each(key, (k, v) => this.attr(k, v)); + if (isPlainObject(key)) { + each(key, (k, v) => this.attr(k, v)); return; } - if (BI.isNotNull(value)) { + if (isNotNull(value)) { return this.options[key] = value; } return this.options[key]; @@ -728,7 +728,7 @@ export default class Widget extends OB { } __d() { - BI.each(this._children, function (i, widget) { + each(this._children, function (i, widget) { widget && widget._unMount && widget._unMount(); }); this._children = {}; @@ -766,7 +766,7 @@ export default class Widget extends OB { _empty () { this._assetMounted(); - BI.each(this._children, function (i, widget) { + each(this._children, function (i, widget) { widget && widget._unMount && widget._unMount(); }); this._children = {}; @@ -800,9 +800,9 @@ export default class Widget extends OB { // this.purgeListeners(); // 去掉组件绑定的watcher - BI.each(this._watchers, function (i, unwatches) { - unwatches = BI.isArray(unwatches) ? unwatches : [unwatches]; - BI.each(unwatches, function (j, unwatch) { + each(this._watchers, function (i, unwatches) { + unwatches = isArray(unwatches) ? unwatches : [unwatches]; + each(unwatches, function (j, unwatch) { unwatch(); }); }); @@ -840,39 +840,39 @@ export default class Widget extends OB { } }; -BI.extend(BI, { Widget }); +extend(BI, { Widget }); let context = null, current = null; const contextStack = [], currentStack = []; -BI.Widget.pushContext = function (_context) { +Widget.pushContext = function (_context) { if (context) contextStack.push(context); - BI.Widget.context = context = _context; + Widget.context = context = _context; }; -BI.Widget.popContext = function () { - BI.Widget.context = context = contextStack.pop(); +Widget.popContext = function () { + Widget.context = context = contextStack.pop(); }; -BI.Widget.execWithContext = function (context, execFunc) { - BI.Widget.pushContext(context); +Widget.execWithContext = function (context, execFunc) { + Widget.pushContext(context); try { execFunc(); } catch (e) { throw e; } finally { - BI.Widget.popContext(); + Widget.popContext(); } }; function pushTarget(_current) { if (current) currentStack.push(current); - BI.Widget.current = current = _current; + Widget.current = current = _current; } function popTarget() { - BI.Widget.current = current = currentStack.pop(); + Widget.current = current = currentStack.pop(); } BI.useStore = function (_store) { @@ -903,7 +903,7 @@ BI.useStore = function (_store) { } current._store = function () { const st = (_store || currentStore).apply(this, arguments); - BI.extend(delegate, st); + extend(delegate, st); return st; }; return current.$storeDelegate = delegate; @@ -912,7 +912,7 @@ BI.useStore = function (_store) { BI.useContext = function (inject) { // 通过组件找最近的store - const vm = BI.Widget.findStore(BI.Widget.current || BI.Widget.context); + const vm = Widget.findStore(Widget.current || Widget.context); if (vm) { if (inject) { if (vm.$$computed && inject in vm.$$computed) { @@ -938,17 +938,17 @@ BI.useContext = function (inject) { BI.watch = function (vm, watch, handler) { // 必须要保证组件当前环境存在 - if (BI.Widget.current) { + if (Widget.current) { if (vm instanceof BI.Model) { const watchers = []; - if (BI.isKey(watch)) { + if (isKey(watch)) { const k = watch; watch = {}; watch[k] = handler; } for (const key in watch) { const innerHandler = watch[key]; - if (BI.isArray(handler)) { + if (isArray(handler)) { for (let i = 0; i < handler.length; i++) { watchers.push(Fix.watch(vm.model, key, innerHandler, { store: vm @@ -961,14 +961,14 @@ BI.watch = function (vm, watch, handler) { } } // vm中一定有_widget - BI.Widget.current._watchers || (BI.Widget.current._watchers = []); - BI.Widget.current._watchers = BI.Widget.current._watchers.concat(watchers); + Widget.current._watchers || (Widget.current._watchers = []); + Widget.current._watchers = Widget.current._watchers.concat(watchers); return; } handler = watch; watch = vm; - BI.Widget.current.$watchDelayCallbacks || (BI.Widget.current.$watchDelayCallbacks = []); - BI.Widget.current.$watchDelayCallbacks.push([watch, handler]); + Widget.current.$watchDelayCallbacks || (Widget.current.$watchDelayCallbacks = []); + Widget.current.$watchDelayCallbacks.push([watch, handler]); } }; @@ -980,7 +980,7 @@ BI.onBeforeMount = function (beforeMount) { } if (!current.beforeMount) { current.beforeMount = []; - } else if (!BI.isArray(current.beforeMount)) { + } else if (!isArray(current.beforeMount)) { current.beforeMount = [current.beforeMount]; } current.beforeMount.push(beforeMount); @@ -994,7 +994,7 @@ BI.onMounted = function (mounted) { } if (!current.mounted) { current.mounted = []; - } else if (!BI.isArray(current.mounted)) { + } else if (!isArray(current.mounted)) { current.mounted = [current.mounted]; } current.mounted.push(mounted); @@ -1004,7 +1004,7 @@ BI.onBeforeUnmount = function (beforeDestroy) { if (current) { if (!current.beforeDestroy) { current.beforeDestroy = []; - } else if (!BI.isArray(current.beforeDestroy)) { + } else if (!isArray(current.beforeDestroy)) { current.beforeDestroy = [current.beforeDestroy]; } current.beforeDestroy.push(beforeDestroy); @@ -1014,19 +1014,19 @@ BI.onUnmounted = function (destroyed) { if (current) { if (!current.destroyed) { current.destroyed = []; - } else if (!BI.isArray(current.destroyed)) { + } else if (!isArray(current.destroyed)) { current.destroyed = [current.destroyed]; } current.destroyed.push(destroyed); } }; -BI.Widget.registerRenderEngine = function (engine) { - BI.Widget._renderEngine = engine; +Widget.registerRenderEngine = function (engine) { + Widget._renderEngine = engine; }; -BI.Widget.registerRenderEngine({ +Widget.registerRenderEngine({ createElement: function (widget) { - if (BI.isWidget(widget)) { + if (isWidget(widget)) { const o = widget.options; if (o.element) { return BI.$(o.element); @@ -1048,7 +1048,7 @@ BI.mount = function (widget, container, predicate, hydrate) { // 将widget的element元素都挂载好,并建立相互关系 widget.element.data("__widgets", [widget]); const res = widget._mount(true, false, false, function (w) { - BI.each(w._children, function (i, child) { + each(w._children, function (i, child) { const ws = child.element.data("__widgets"); if (!ws) { ws = []; @@ -1059,13 +1059,13 @@ BI.mount = function (widget, container, predicate, hydrate) { predicate && predicate.apply(this, arguments); }); // 将新的dom树属性(事件等)patch到已存在的dom上 - const c = BI.Widget._renderEngine.createElement; + const c = Widget._renderEngine.createElement; BI.DOM.patchProps(widget.element, c(c(container).children()[0])); const triggerLifeHook = function (w) { w.beforeMount && w.beforeMount(); w.mounted && w.mounted(); - BI.each(w._children, function (i, child) { + each(w._children, function (i, child) { triggerLifeHook(child); }); }; @@ -1074,7 +1074,7 @@ BI.mount = function (widget, container, predicate, hydrate) { return res; } if (container) { - BI.Widget._renderEngine.createElement(container).append(widget.element); + Widget._renderEngine.createElement(container).append(widget.element); } return widget._mount(true, false, false, predicate); }; diff --git a/src/core/index.js b/src/core/index.js index 3727548fc..0b0f014c0 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -56,4 +56,6 @@ export { ResizeController, TooltipsController, StyleLoaderManager, -} \ No newline at end of file +} + +export * from './2.base'; \ No newline at end of file From 3e98c47b71f2b1bb53482963134cb3af19055df2 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Tue, 3 Jan 2023 11:37:01 +0800 Subject: [PATCH 023/300] =?UTF-8?q?KERNEL-14001=20refactor:=20inject?= =?UTF-8?q?=E7=9A=84es6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/1.pane.js | 19 +- src/core/3.ob.js | 12 +- src/core/4.widget.js | 53 ++- src/core/5.inject.js | 994 +++++++++++++++++++++--------------------- src/core/decorator.js | 3 +- src/core/index.js | 8 +- 6 files changed, 555 insertions(+), 534 deletions(-) diff --git a/src/base/1.pane.js b/src/base/1.pane.js index 1f7f1cc59..51ceecfce 100644 --- a/src/base/1.pane.js +++ b/src/base/1.pane.js @@ -6,7 +6,8 @@ * @extends BI.Widget * @abstract */ -import { Widget, shortcut, isNotEmptyString, extend, isNull, isEmpty } from "../core"; +import { Widget, shortcut, isNotEmptyString, extend, isNull, isEmpty, createWidget, Providers } from "../core"; +import { Layers } from "./0.base"; @shortcut() export default class Pane extends Widget { @@ -27,7 +28,7 @@ export default class Pane extends Widget { _assertTip() { if (!this._tipText) { - BI.createWidget({ + createWidget({ type: "bi.absolute_center_adapt", element: this, items: [{ @@ -45,7 +46,7 @@ export default class Pane extends Widget { loading() { const o = this.options; - const loadingAnimation = BI.createWidget(BI.Providers.getProvider("bi.provider.system").getLoading({ + const loadingAnimation = createWidget(Providers.getProvider("bi.provider.system").getLoading({ loadingSize: o.loadingSize, context: this, })); @@ -53,18 +54,18 @@ export default class Pane extends Widget { // loading的异步情况下由loaded后对面板的populate的时机决定 this.setTipVisible(false); if (o.overlap === true) { - if (!BI.Layers.has(this.getName() + "-loading")) { - BI.createWidget({ + if (!Layers.has(this.getName() + "-loading")) { + createWidget({ type: "bi.center_adapt", cls: "loading-container", items: this._getLoadingTipItems(loadingAnimation), - element: BI.Layers.make(this.getName() + "-loading", this), + element: Layers.make(this.getName() + "-loading", this), }); } - BI.Layers.show(this.getName() + "-loading"); + Layers.show(this.getName() + "-loading"); } else if (isNull(this._loading)) { loadingAnimation.element.css("zIndex", 1); - BI.createWidget({ + createWidget({ type: "bi.center_adapt", element: this, cls: "loading-container", @@ -101,7 +102,7 @@ export default class Pane extends Widget { } loaded() { - BI.Layers.remove(this.getName() + "-loading"); + Layers.remove(this.getName() + "-loading"); this._loading && this._loading.destroy(); this.options.onLoaded(); this.fireEvent(Pane.EVENT_LOADED); diff --git a/src/core/3.ob.js b/src/core/3.ob.js index 5d0e9f7fb..f51a68f06 100644 --- a/src/core/3.ob.js +++ b/src/core/3.ob.js @@ -1,6 +1,6 @@ -import { isFunction, isArray, isObject, isArguments, reduce, bind } from "./2.base"; +import { isFunction, isArray, isObject, isArguments, reduce, bind, extend } from "./2.base"; -function extend() { +function obExtend() { let target = arguments[0] || {}, length = arguments.length, i = 1, name, copy; for (; i < length; i++) { // Only deal with non-null/undefined values @@ -52,11 +52,11 @@ export default class OB { if (isFunction(this.props)) { props = this.props(config); } - const defaultProps = extend(this._defaultConfig(config), props); + const defaultProps = obExtend(this._defaultConfig(config), props); const modifiedDefaultProps = (config && config.type && OB.configFunctions[config.type + ".props"]) ? reduce(OB.configFunctions[config.type + ".props"], function (value, conf, index) { - return extend(conf, value.fn(defaultProps, config, value.opt)); + return obExtend(conf, value.fn(defaultProps, config, value.opt)); }, {}) : null; - this.options = extend(defaultProps, modifiedDefaultProps, config); + this.options = obExtend(defaultProps, modifiedDefaultProps, config); } _init() { @@ -216,4 +216,4 @@ export default class OB { } } -BI.extend(BI, { OB }); +extend(BI, { OB }); diff --git a/src/core/4.widget.js b/src/core/4.widget.js index 728e70dfa..54e833b51 100644 --- a/src/core/4.widget.js +++ b/src/core/4.widget.js @@ -8,6 +8,7 @@ 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"; const cancelAnimationFrame = _global.cancelAnimationFrame || @@ -360,7 +361,7 @@ export default class Widget extends OB { _initElement() { this.__isMounting = true; // 当开启worker模式时,可以通过$render来实现另一种效果 - const workerMode = BI.Providers.getProvider("bi.provider.system").getWorkerMode(); + 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; @@ -372,7 +373,7 @@ export default class Widget extends OB { if (isArray(els)) { each(els, (i, el) => { if (el) { - BI._lazyCreateWidget(el, { + _lazyCreateWidget(el, { element: this }); } @@ -840,9 +841,6 @@ export default class Widget extends OB { } }; -extend(BI, { Widget }); - - let context = null, current = null; const contextStack = [], currentStack = []; @@ -875,7 +873,7 @@ function popTarget() { Widget.current = current = currentStack.pop(); } -BI.useStore = function (_store) { +export function useStore(_store) { if (current && current.store) { return current.store; } @@ -908,9 +906,9 @@ BI.useStore = function (_store) { }; return current.$storeDelegate = delegate; } -}; +} -BI.useContext = function (inject) { +export function useContext(inject) { // 通过组件找最近的store const vm = Widget.findStore(Widget.current || Widget.context); if (vm) { @@ -934,9 +932,9 @@ BI.useContext = function (inject) { } } return vm; -}; +} -BI.watch = function (vm, watch, handler) { +export function watch(vm, watch, handler) { // 必须要保证组件当前环境存在 if (Widget.current) { if (vm instanceof BI.Model) { @@ -970,9 +968,9 @@ BI.watch = function (vm, watch, handler) { Widget.current.$watchDelayCallbacks || (Widget.current.$watchDelayCallbacks = []); Widget.current.$watchDelayCallbacks.push([watch, handler]); } -}; +} -BI.onBeforeMount = function (beforeMount) { +export function onBeforeMount(beforeMount) { if (current) { if (current.__isMounting) { beforeMount(); @@ -985,8 +983,9 @@ BI.onBeforeMount = function (beforeMount) { } current.beforeMount.push(beforeMount); } -}; -BI.onMounted = function (mounted) { +} + +export function onMounted(mounted) { if (current) { if (current._isMounted && !this.__async) { mounted(); @@ -1000,7 +999,8 @@ BI.onMounted = function (mounted) { current.mounted.push(mounted); } }; -BI.onBeforeUnmount = function (beforeDestroy) { + +export function onBeforeUnmount(beforeDestroy) { if (current) { if (!current.beforeDestroy) { current.beforeDestroy = []; @@ -1009,8 +1009,9 @@ BI.onBeforeUnmount = function (beforeDestroy) { } current.beforeDestroy.push(beforeDestroy); } -}; -BI.onUnmounted = function (destroyed) { +} + +export function onUnmounted(destroyed) { if (current) { if (!current.destroyed) { current.destroyed = []; @@ -1019,7 +1020,7 @@ BI.onUnmounted = function (destroyed) { } current.destroyed.push(destroyed); } -}; +} Widget.registerRenderEngine = function (engine) { Widget._renderEngine = engine; @@ -1043,7 +1044,7 @@ Widget.registerRenderEngine({ } }); -BI.mount = function (widget, container, predicate, hydrate) { +export function mount(widget, container, predicate, hydrate) { if (hydrate === true) { // 将widget的element元素都挂载好,并建立相互关系 widget.element.data("__widgets", [widget]); @@ -1077,4 +1078,16 @@ BI.mount = function (widget, container, predicate, hydrate) { Widget._renderEngine.createElement(container).append(widget.element); } return widget._mount(true, false, false, predicate); -}; +} + +extend(BI, { + Widget, + useStore, + useContext, + watch, + onBeforeMount, + onMounted, + onBeforeUnmount, + onUnmounted, + mount, +}); diff --git a/src/core/5.inject.js b/src/core/5.inject.js index 9602deed9..a8ec6786d 100644 --- a/src/core/5.inject.js +++ b/src/core/5.inject.js @@ -1,526 +1,530 @@ -(function () { - var moduleInjection = {}, moduleInjectionMap = { - components: {}, - constants: {}, - stores: {}, - services: {}, - models: {}, - providers: {} - }; - BI.module = BI.module || function (xtype, cls) { - if (moduleInjection[xtype] != null) { - _global.console && console.error("module: [" + xtype + "] 已经注册过了"); - } else { - if (BI.isFunction(cls)) { - cls = cls(); - } - for (var k in moduleInjectionMap) { - if (cls[k]) { - for (var key in cls[k]) { - if (!moduleInjectionMap[k]) { - continue; - } - if (!moduleInjectionMap[k][key]) { - moduleInjectionMap[k][key] = []; - } - moduleInjectionMap[k][key].push({ - version: cls[k][key], - moduleId: xtype - }); +import { isFunction, isNull, isNotNull, isArray, each, isWidget, extend, init, isEmpty, remove } from "./2.base"; +import OB from "./3.ob"; +import Widget from "./4.widget" + +let moduleInjection = {}, moduleInjectionMap = { + components: {}, + constants: {}, + stores: {}, + services: {}, + models: {}, + providers: {} +}; + +export function module(xtype, cls) { + if (moduleInjection[xtype] != null) { + _global.console && console.error("module: [" + xtype + "] 已经注册过了"); + } else { + if (isFunction(cls)) { + cls = cls(); + } + for (const k in moduleInjectionMap) { + if (cls[k]) { + for (const key in cls[k]) { + if (!moduleInjectionMap[k]) { + continue; + } + if (!moduleInjectionMap[k][key]) { + moduleInjectionMap[k][key] = []; } + moduleInjectionMap[k][key].push({ + version: cls[k][key], + moduleId: xtype + }); } } - moduleInjection[xtype] = cls; - } - - return function () { - return BI.Modules.getModule(xtype); - }; - }; - - var constantInjection = {}; - BI.constant = BI.constant || function (xtype, cls) { - if (constantInjection[xtype] != null) { - _global.console && console.error("constant: [" + xtype + "]已经注册过了"); - } else { - constantInjection[xtype] = cls; - } - - return function () { - return BI.Constants.getConstant(xtype); - }; - }; - - var modelInjection = {}; - BI.model = BI.model || function (xtype, cls) { - if (modelInjection[xtype] != null) { - _global.console && console.error("model: [" + xtype + "] 已经注册过了"); - } else { - modelInjection[xtype] = cls; - } - - return function (config) { - return BI.Models.getModel(xtype, config); - }; - }; - - var storeInjection = {}; - BI.store = BI.store || function (xtype, cls) { - if (storeInjection[xtype] != null) { - _global.console && console.error("store: [" + xtype + "] 已经注册过了"); - } else { - storeInjection[xtype] = cls; - } - - return function (config) { - return BI.Stores.getStore(xtype, config); - }; - }; - - var serviceInjection = {}; - BI.service = BI.service || function (xtype, cls) { - if (serviceInjection[xtype] != null) { - _global.console && console.error("service: [" + xtype + "] 已经注册过了"); - } - - serviceInjection[xtype] = cls; - - return function (config) { - return BI.Services.getService(xtype, config); - }; - }; - - var providerInjection = {}; - BI.provider = BI.provider || function (xtype, cls) { - if (providerInjection[xtype] != null) { - _global.console && console.error("provider: [" + xtype + "] 已经注册过了"); - } else { - providerInjection[xtype] = cls; - } - - return function (config) { - return BI.Providers.getProvider(xtype, config); - }; - }; - - var configFunctions = BI.OB.configFunctions = {}; - var runConfigFunction = function (type, configFn) { - if (!type || !configFunctions[type]) { - return false; - } - - var queue = []; - if (configFn) { - queue = configFunctions[type].filter(function (conf) { - return conf.fn === configFn; - }); - configFunctions[type] = configFunctions[type].filter(function (conf) { - return conf.fn !== configFn; - }); - } else { - queue = configFunctions[type]; - delete configFunctions[type]; } - - var dependencies = BI.Providers.getProvider("bi.provider.system").getDependencies(); - var modules = moduleInjectionMap.components[type] - || moduleInjectionMap.constants[type] - || moduleInjectionMap.services[type] - || moduleInjectionMap.stores[type] - || moduleInjectionMap.models[type] - || moduleInjectionMap.providers[type]; - for (var i = 0; i < queue.length; i++) { - var conf = queue[i]; - var version = conf.opt.version; - var fn = conf.fn; - if (modules && version) { - var findVersion = false; - for (var j = 0; j < modules.length; j++) { - var module = modules[j]; - if (module && dependencies[module.moduleId] && module.version === version) { - var minVersion = dependencies[module.moduleId].minVersion, - maxVersion = dependencies[module.moduleId].maxVersion; - if (minVersion && (moduleInjection[module.moduleId].version || version) < minVersion) { - findVersion = true; - break; - } - if (maxVersion && (moduleInjection[module.moduleId].version || version) > maxVersion) { - findVersion = true; - break; - } + moduleInjection[xtype] = cls; + } + + return () => Modules.getModule(xtype); +} +BI.module = BI.module || module; + +let constantInjection = {}; +export function constant(xtype, cls) { + if (constantInjection[xtype] != null) { + _global.console && console.error("constant: [" + xtype + "]已经注册过了"); + } else { + constantInjection[xtype] = cls; + } + + return () => Constants.getConstant(xtype); +} +BI.constant = BI.constant || constant; + +let modelInjection = {}; +export function model(xtype, cls) { + if (modelInjection[xtype] != null) { + _global.console && console.error("model: [" + xtype + "] 已经注册过了"); + } else { + modelInjection[xtype] = cls; + } + + return (config) => Models.getModel(xtype, config); +} +BI.model = BI.model || model; + +let storeInjection = {}; +export function store(xtype, cls) { + if (storeInjection[xtype] != null) { + _global.console && console.error("store: [" + xtype + "] 已经注册过了"); + } else { + storeInjection[xtype] = cls; + } + + return (config) => Stores.getStore(xtype, config); +} +BI.store = BI.store || store; + +let serviceInjection = {}; +export function service(xtype, cls) { + if (serviceInjection[xtype] != null) { + _global.console && console.error("service: [" + xtype + "] 已经注册过了"); + } + + serviceInjection[xtype] = cls; + + return (config) => Services.getService(xtype, config); +} +BI.service = BI.service || service; + +let providerInjection = {}; +export function provider(xtype, cls) { + if (providerInjection[xtype] != null) { + _global.console && console.error("provider: [" + xtype + "] 已经注册过了"); + } else { + providerInjection[xtype] = cls; + } + + return (config) => Providers.getProvider(xtype, config); +} +BI.provider = BI.provider || provider; + +let configFunctions = OB.configFunctions = {}; +const runConfigFunction = function (type, configFn) { + if (!type || !configFunctions[type]) { + return false; + } + + let queue = []; + if (configFn) { + queue = configFunctions[type].filter((conf) => conf.fn === configFn); + configFunctions[type] = configFunctions[type].filter((conf) => conf.fn !== configFn); + } else { + queue = configFunctions[type]; + delete configFunctions[type]; + } + + const dependencies = Providers.getProvider("bi.provider.system").getDependencies(); + const modules = moduleInjectionMap.components[type] + || moduleInjectionMap.constants[type] + || moduleInjectionMap.services[type] + || moduleInjectionMap.stores[type] + || moduleInjectionMap.models[type] + || moduleInjectionMap.providers[type]; + for (let i = 0; i < queue.length; i++) { + const conf = queue[i]; + const version = conf.opt.version; + const fn = conf.fn; + if (modules && version) { + let findVersion = false; + let module; + for (let j = 0; j < modules.length; j++) { + module = modules[j]; + if (module && dependencies[module.moduleId] && module.version === version) { + const minVersion = dependencies[module.moduleId].minVersion, + maxVersion = dependencies[module.moduleId].maxVersion; + if (minVersion && (moduleInjection[module.moduleId].version || version) < minVersion) { + findVersion = true; + break; + } + if (maxVersion && (moduleInjection[module.moduleId].version || version) > maxVersion) { + findVersion = true; + break; } - } - if (findVersion === true) { - _global.console && console.error("moduleId: [" + module.moduleId + "] 接口: [" + type + "] 接口版本: [" + version + "] 已过期,版本要求为:", dependencies[module.moduleId], "=>", moduleInjection[module.moduleId]); - continue; } } - if (constantInjection[type]) { - constantInjection[type] = fn(constantInjection[type]); + if (findVersion === true) { + _global.console && console.error("moduleId: [" + module.moduleId + "] 接口: [" + type + "] 接口版本: [" + version + "] 已过期,版本要求为:", dependencies[module.moduleId], "=>", moduleInjection[module.moduleId]); continue; } - if (providerInjection[type]) { - if (!providers[type]) { - providers[type] = new providerInjection[type](); - } - if (providerInstance[type]) { - delete providerInstance[type]; - } - fn(providers[type]); - continue; - } - BI.Plugin.configWidget(type, fn, conf.opt); } - }; - BI.config = BI.config || function (type, configFn, opt) { - if (BI.isFunction(type)) { - opt = configFn; - configFn = type; - type = "bi.provider.system"; + if (constantInjection[type]) { + constantInjection[type] = fn(constantInjection[type]); + continue; } - opt = opt || {}; - - // 系统配置直接执行 - if ("bi.provider.system" === type) { + if (providerInjection[type]) { if (!providers[type]) { providers[type] = new providerInjection[type](); } - // 如果config被重新配置的话,需要删除掉之前的实例 if (providerInstance[type]) { delete providerInstance[type]; } - return configFn(providers[type]); - } - - if (!configFunctions[type]) { - configFunctions[type] = []; - } - configFunctions[type].push({ - fn: configFn, - opt: opt - }); - - if (opt.immediately) { - return runConfigFunction(type, configFn); - } - }; - - BI.getReference = BI.getReference || function (type, fn) { - return BI.Plugin.registerObject(type, fn); - }; - - var actions = {}; - var globalAction = []; - BI.action = BI.action || function (type, actionFn) { - if (BI.isFunction(type)) { - globalAction.push(type); - return function () { - BI.remove(globalAction, function (idx) { - return globalAction.indexOf(actionFn) === idx; - }); - }; - } - if (!actions[type]) { - actions[type] = []; - } - actions[type].push(actionFn); - return function () { - BI.remove(actions[type], function (idx) { - return actions[type].indexOf(actionFn) === idx; - }); - if (actions[type].length === 0) { - delete actions[type]; - } + fn(providers[type]); + continue; + } + BI.Plugin.configWidget(type, fn, conf.opt); + } +}; + +export function config(type, configFn, opt) { + if (isFunction(type)) { + opt = configFn; + configFn = type; + type = "bi.provider.system"; + } + opt = opt || {}; + + // 系统配置直接执行 + if ("bi.provider.system" === type) { + if (!providers[type]) { + providers[type] = new providerInjection[type](); + } + // 如果config被重新配置的话,需要删除掉之前的实例 + if (providerInstance[type]) { + delete providerInstance[type]; + } + return configFn(providers[type]); + } + + if (!configFunctions[type]) { + configFunctions[type] = []; + } + configFunctions[type].push({ + fn: configFn, + opt: opt + }); + + if (opt.immediately) { + return runConfigFunction(type, configFn); + } +} +BI.config = BI.config || config; + +export function getReference(type, fn) { + return BI.Plugin.registerObject(type, fn); +} +BI.getReference = BI.getReference || getReference; + +let actions = {}; +let globalAction = []; +export function action(type, actionFn) { + if (isFunction(type)) { + globalAction.push(type); + return () => { + remove(globalAction, (idx) => globalAction.indexOf(actionFn) === idx); }; - }; - - var points = {}; - BI.point = BI.point || function (type, action, pointFn, after) { - if (!points[type]) { - points[type] = {}; - } - if (!points[type][action]) { - points[type][action] = {}; - } - if (!points[type][action][after ? "after" : "before"]) { - points[type][action][after ? "after" : "before"] = []; + } + if (!actions[type]) { + actions[type] = []; + } + actions[type].push(actionFn); + return () => { + remove(actions[type], (idx) => actions[type].indexOf(actionFn) === idx); + if (actions[type].length === 0) { + delete actions[type]; } - points[type][action][after ? "after" : "before"].push(pointFn); }; - - BI.Modules = BI.Modules || { - getModule: function (type) { - if (!moduleInjection[type]) { - _global.console && console.error("module: [" + type + "] 未定义"); - } - return moduleInjection[type]; - }, - getAllModules: function () { - return moduleInjection; - } - }; - - BI.Constants = BI.Constants || { - getConstant: function (type) { - if (BI.isNull(constantInjection[type])) { - _global.console && console.error("constant: [" + type + "] 未定义"); - } - runConfigFunction(type); - return BI.isFunction(constantInjection[type]) ? constantInjection[type]() : constantInjection[type]; - } - }; - - var callPoint = function (inst, types) { - types = BI.isArray(types) ? types : [types]; - BI.each(types, function (idx, type) { - if (points[type]) { - for (var action in points[type]) { - var bfns = points[type][action].before; - if (bfns) { - BI.aspect.before(inst, action, function (bfns) { - return function () { - for (var i = 0, len = bfns.length; i < len; i++) { - try { - bfns[i].apply(inst, arguments); - } catch (e) { - _global.console && console.error(e); - } +} +BI.action = BI.action || action; + +let points = {}; +export function point(type, action, pointFn, after) { + if (!points[type]) { + points[type] = {}; + } + if (!points[type][action]) { + points[type][action] = {}; + } + if (!points[type][action][after ? "after" : "before"]) { + points[type][action][after ? "after" : "before"] = []; + } + points[type][action][after ? "after" : "before"].push(pointFn); +} +BI.point = BI.point || point; + +export const Modules = { + getModule: function (type) { + if (!moduleInjection[type]) { + _global.console && console.error("module: [" + type + "] 未定义"); + } + return moduleInjection[type]; + }, + getAllModules: function () { + return moduleInjection; + } +} +BI.Modules = BI.Modules || Modules; + +export const Constants = { + getConstant: function (type) { + if (isNull(constantInjection[type])) { + _global.console && console.error("constant: [" + type + "] 未定义"); + } + runConfigFunction(type); + return isFunction(constantInjection[type]) ? constantInjection[type]() : constantInjection[type]; + } +} +BI.Constants = BI.Constants || Constants; + +const callPoint = function (inst, types) { + types = isArray(types) ? types : [types]; + each(types, (idx, type) => { + if (points[type]) { + for (const action in points[type]) { + let bfns = points[type][action].before; + if (bfns) { + BI.aspect.before(inst, action, function (bfns) { + return function () { + for (let i = 0, len = bfns.length; i < len; i++) { + try { + bfns[i].apply(inst, arguments); + } catch (e) { + _global.console && console.error(e); } - }; - }(bfns)); - } - var afns = points[type][action].after; - if (afns) { - BI.aspect.after(inst, action, function (afns) { - return function () { - for (var i = 0, len = afns.length; i < len; i++) { - try { - afns[i].apply(inst, arguments); - } catch (e) { - _global.console && console.error(e); - } + } + }; + }(bfns)); + } + let afns = points[type][action].after; + if (afns) { + BI.aspect.after(inst, action, function (afns) { + return function () { + for (let i = 0, len = afns.length; i < len; i++) { + try { + afns[i].apply(inst, arguments); + } catch (e) { + _global.console && console.error(e); } - }; - }(afns)); - } + } + }; + }(afns)); } } - }); - }; - - BI.Models = BI.Models || { - getModel: function (type, config) { - if (!modelInjection[type]) { - _global.console && console.error("model: [" + type + "] 未定义"); - } - runConfigFunction(type); - var inst = new modelInjection[type](config); - inst._constructor && inst._constructor(config); - inst.mixins && callPoint(inst, inst.mixins); - callPoint(inst, type); - return inst; } - }; - - var stores = {}; - - BI.Stores = BI.Stores || { - getStore: function (type, config) { - if (!storeInjection[type]) { - _global.console && console.error("store: [" + type + "] 未定义"); - } - if (stores[type]) { - return stores[type]; - } - var inst = stores[type] = new storeInjection[type](config); - inst._constructor && inst._constructor(config, function () { - delete stores[type]; - }); - callPoint(inst, type); - return inst; - } - }; - - var services = {}; - - BI.Services = BI.Services || { - getService: function (type, config) { - if (!serviceInjection[type]) { - _global.console && console.error("service: [" + type + "] 未定义"); - } - if (services[type]) { - return services[type]; - } - services[type] = new serviceInjection[type](config); - callPoint(services[type], type); + }); +}; + +export const Models = { + getModel: function (type, config) { + if (!modelInjection[type]) { + _global.console && console.error("model: [" + type + "] 未定义"); + } + runConfigFunction(type); + var inst = new modelInjection[type](config); + inst._constructor && inst._constructor(config); + inst.mixins && callPoint(inst, inst.mixins); + callPoint(inst, type); + return inst; + } +} +BI.Models = BI.Models || Models; + +let stores = {}; +export const Stores = { + getStore: function (type, config) { + if (!storeInjection[type]) { + _global.console && console.error("store: [" + type + "] 未定义"); + } + if (stores[type]) { + return stores[type]; + } + const inst = stores[type] = new storeInjection[type](config); + inst._constructor && inst._constructor(config, function () { + delete stores[type]; + }); + callPoint(inst, type); + return inst; + } +} +BI.Stores = BI.Stores || Stores; + +let services = {}; +export const Services = { + getService: (type, config) => { + if (!serviceInjection[type]) { + _global.console && console.error("service: [" + type + "] 未定义"); + } + if (services[type]) { return services[type]; } - }; - - var providers = {}, - providerInstance = {}; - - BI.Providers = BI.Providers || { - getProvider: function (type, config) { - if (!providerInjection[type]) { - _global.console && console.error("provider: [" + type + "] 未定义"); + services[type] = new serviceInjection[type](config); + callPoint(services[type], type); + return services[type]; + } +} +BI.Services = BI.Services || Services; + +let providers = {}, + providerInstance = {}; +export const Providers = { + getProvider: (type, config) => { + if (!providerInjection[type]) { + _global.console && console.error("provider: [" + type + "] 未定义"); + } + runConfigFunction(type); + if (!providers[type]) { + providers[type] = new providerInjection[type](); + } + if (!providerInstance[type] && providers[type].$get) { + providerInstance[type] = new (providers[type].$get())(config); + } + return providerInstance[type]; + } +} +BI.Providers = BI.Providers || Providers; + +export const Actions = { + runAction: function (type, event, config) { + each(actions[type], (i, act) => { + try { + act(event, config); + } catch (e) { + _global.console && console.error(e); } - runConfigFunction(type); - if (!providers[type]) { - providers[type] = new providerInjection[type](); - } - if (!providerInstance[type] && providers[type].$get) { - providerInstance[type] = new (providers[type].$get())(config); + }); + }, + runGlobalAction: function () { + var args = [].slice.call(arguments); + each(globalAction, (i, act) => { + try { + act.apply(null, args); + } catch (e) { + _global.console && console.error(e); } - return providerInstance[type]; - } - }; - - BI.Actions = BI.Actions || { - runAction: function (type, event, config) { - BI.each(actions[type], function (i, act) { - try { - act(event, config); - } catch (e) { - _global.console && console.error(e); - } - }); - }, - runGlobalAction: function () { - var args = [].slice.call(arguments); - BI.each(globalAction, function (i, act) { - try { - act.apply(null, args); - } catch (e) { - _global.console && console.error(e); - } - }); - } - }; - - var kv = {}; - BI.shortcut = BI.component = BI.shortcut || function (xtype, cls) { - if (kv[xtype] != null) { - _global.console && console.error("组件: [" + xtype + "] 已经注册过了"); - } - if (cls) { - cls["xtype"] = xtype; - } - kv[xtype] = cls; - }; - - // 根据配置属性生成widget - var createWidget = function (config, context, lazy) { - var cls = BI.isFunction(config.type) ? config.type : kv[config.type]; - - if (!cls) { - throw new Error("组件: [" + config.type + "] 未定义"); - } - var pushed = false; - var widget = new cls(); - widget._context = BI.Widget.context || context; - if (!BI.Widget.context && context) { - pushed = true; - BI.Widget.pushContext(context); - } - callPoint(widget, config.type); - widget._initProps(config); - widget._initRoot(); - widget._constructed(); - // if (!lazy || config.element || config.root) { - widget._lazyConstructor(); - // } - pushed && BI.Widget.popContext(); - return widget; - }; - - BI.createWidget = BI.createWidget || function (item, options, context, lazy) { - item || (item = {}); - if (BI.isWidget(options)) { - context = options; - options = {}; - } else { - options || (options = {}); - } - - var el, w; - if (item.type || options.type) { - el = BI.extend({}, options, item); - } else if (item.el && (item.el.type || options.type)) { - el = BI.extend({}, options, item.el); - } - - if (el) { - var elType = (el.type && el.type.xtype) || el.type; - runConfigFunction(elType); - } - - // 先把准备环境准备好 - BI.init(); - - if (BI.isEmpty(item) && BI.isEmpty(options)) { - return BI.createWidget({ - type: "bi.layout" - }); - } - if (BI.isWidget(item)) { - return item; - } - if (el) { - w = BI.Plugin.getWidget(elType, el); - var wType = (w.type && w.type.xtype) || w.type; - if (wType === elType) { - if (BI.Plugin.hasObject(elType)) { - if (!w.listeners || BI.isArray(w.listeners)) { - w.listeners = (w.listeners || []).concat([{ - eventName: BI.Events.MOUNT, - action: function () { - BI.Plugin.getObject(elType, this); - } - }]); - } else { - w.listeners[BI.Events.MOUNT] = [ - function () { - BI.Plugin.getObject(elType, this); - } - ].concat(w.listeners[BI.Events.MOUNT] || []); - } + }); + } +} +BI.Actions = BI.Actions || Actions; + +let kv = {}; +export function shortcut(xtype, cls) { + if (kv[xtype] != null) { + _global.console && console.error("组件: [" + xtype + "] 已经注册过了"); + } + if (cls) { + cls["xtype"] = xtype; + } + kv[xtype] = cls; +} +BI.shortcut = BI.component = BI.shortcut || shortcut; + +// 根据配置属性生成widget +const createRealWidget = function (config, context, lazy) { + const cls = isFunction(config.type) ? config.type : kv[config.type]; + + if (!cls) { + throw new Error("组件: [" + config.type + "] 未定义"); + } + let pushed = false; + const widget = new cls(); + widget._context = Widget.context || context; + if (!Widget.context && context) { + pushed = true; + Widget.pushContext(context); + } + callPoint(widget, config.type); + widget._initProps(config); + widget._initRoot(); + widget._constructed(); + // if (!lazy || config.element || config.root) { + widget._lazyConstructor(); + // } + pushed && Widget.popContext(); + return widget; +}; + +export function createWidget(item, options, context, lazy) { + item || (item = {}); + if (isWidget(options)) { + context = options; + options = {}; + } else { + options || (options = {}); + } + + var el, w; + if (item.type || options.type) { + el = extend({}, options, item); + } else if (item.el && (item.el.type || options.type)) { + el = extend({}, options, item.el); + } + + if (el) { + var elType = (el.type && el.type.xtype) || el.type; + runConfigFunction(elType); + } + + // 先把准备环境准备好 + init(); + + if (isEmpty(item) && isEmpty(options)) { + return createWidget({ + type: "bi.layout" + }); + } + if (isWidget(item)) { + return item; + } + if (el) { + w = BI.Plugin.getWidget(elType, el); + var wType = (w.type && w.type.xtype) || w.type; + if (wType === elType) { + if (BI.Plugin.hasObject(elType)) { + if (!w.listeners || isArray(w.listeners)) { + w.listeners = (w.listeners || []).concat([{ + eventName: BI.Events.MOUNT, + action: () => { + BI.Plugin.getObject(elType, this); + } + }]); + } else { + w.listeners[BI.Events.MOUNT] = [ + () => { + BI.Plugin.getObject(elType, this); + } + ].concat(w.listeners[BI.Events.MOUNT] || []); } - return createWidget(w, context, lazy); } - return BI.createWidget(w, options, context, lazy); - } - if (BI.isWidget(item.el)) { - return item.el; - } - throw new Error("组件:无法根据item创建组件", item); - }; - - BI._lazyCreateWidget = BI._lazyCreateWidget || function (item, options, context) { - return BI.createWidget(item, options, context, true); - }; - - BI.createElement = BI.createElement || function () { - var widget = BI.createWidget.apply(this, arguments); - return widget.element; - }; - - BI.getResource = BI.getResource || function (type, config) { - if (BI.isNotNull(constantInjection[type])) { - return BI.Constants.getConstant(type); - } - if (modelInjection[type]) { - return BI.Models.getModel(type, config); - } - if (storeInjection[type]) { - return BI.Stores.getStore(type, config); - } - if (serviceInjection[type]) { - return BI.Services.getService(type, config); - } - if (providerInjection[type]) { - return BI.Providers.getProvider(type, config); - } - throw new Error("未知类型: [" + type + "] 未定义"); - }; -})(); + return createRealWidget(w, context, lazy); + } + return createWidget(w, options, context, lazy); + } + if (isWidget(item.el)) { + return item.el; + } + throw new Error("组件:无法根据item创建组件", item); +} +BI.createWidget = BI.createWidget || createWidget; + +export function _lazyCreateWidget (item, options, context) { + return createWidget(item, options, context, true); +} +BI._lazyCreateWidget = BI._lazyCreateWidget || _lazyCreateWidget; + +export function createElement() { + const widget = createWidget.apply(this, arguments); + return widget.element; +} +BI.createElement = BI.createElement || createElement; + +export function getResource(type, config) { + if (isNotNull(constantInjection[type])) { + return Constants.getConstant(type); + } + if (modelInjection[type]) { + return Models.getModel(type, config); + } + if (storeInjection[type]) { + return Stores.getStore(type, config); + } + if (serviceInjection[type]) { + return Services.getService(type, config); + } + if (providerInjection[type]) { + return Providers.getProvider(type, config); + } + throw new Error("未知类型: [" + type + "] 未定义"); +} +BI.getResource = BI.getResource || getResource; diff --git a/src/core/decorator.js b/src/core/decorator.js index 23215d701..af7a6e005 100644 --- a/src/core/decorator.js +++ b/src/core/decorator.js @@ -1,8 +1,9 @@ /** * 注册widget */ +import { shortcut as biShortcut } from "./5.inject"; export function shortcut() { return function decorator(Target) { - BI.shortcut(Target.xtype, Target); + biShortcut(Target.xtype, Target); }; } diff --git a/src/core/index.js b/src/core/index.js index 0b0f014c0..18b15a0f2 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -37,6 +37,10 @@ BI.extend(BI, { StyleLoaderManager, }); +export * from './2.base'; +export * from './4.widget'; +export * from './5.inject'; + export { shortcut, OB, @@ -56,6 +60,4 @@ export { ResizeController, TooltipsController, StyleLoaderManager, -} - -export * from './2.base'; \ No newline at end of file +} \ No newline at end of file From e06221784778fceebbd8b6275e5b02350e3b5c41 Mon Sep 17 00:00:00 2001 From: impact Date: Tue, 3 Jan 2023 16:53:20 +0800 Subject: [PATCH 024/300] =?UTF-8?q?KERNEL-13948=20docs:=20=E4=BF=AE?= =?UTF-8?q?=E5=A4=8Dcombo=5Fgroup=20demo=E6=8E=A5=E5=8F=A3=E9=94=99?= =?UTF-8?q?=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- demo/js/core/abstract/combination/demo.combo.js | 4 ++-- demo/js/core/abstract/combination/demo.combo_group.js | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/demo/js/core/abstract/combination/demo.combo.js b/demo/js/core/abstract/combination/demo.combo.js index 2ec3619b1..fd7765b85 100644 --- a/demo/js/core/abstract/combination/demo.combo.js +++ b/demo/js/core/abstract/combination/demo.combo.js @@ -29,7 +29,7 @@ Demo.Func = BI.inherit(BI.Widget, { iconCls1: "close-ha-font", iconCls2: "close-ha-font" }, - children: [{ + items: [{ type: "bi.single_select_item", height: 25, text: "一月", @@ -385,7 +385,7 @@ Demo.Func = BI.inherit(BI.Widget, { }, width: 200 }); - childCombo.setValue(BI.deepClone(this.child)[0].children[0].value); + childCombo.setValue(BI.deepClone(this.child)[0].items[0].value); var monthCombo = BI.createWidget({ type: "bi.combo", diff --git a/demo/js/core/abstract/combination/demo.combo_group.js b/demo/js/core/abstract/combination/demo.combo_group.js index aeb9a1936..2cd391b7d 100644 --- a/demo/js/core/abstract/combination/demo.combo_group.js +++ b/demo/js/core/abstract/combination/demo.combo_group.js @@ -12,7 +12,7 @@ Demo.Func = BI.inherit(BI.Widget, { height: 25, iconCls: "close-ha-font" }, - children: [{ + items: [{ type: "bi.single_select_item", height: 25, text: "一月", @@ -63,7 +63,7 @@ Demo.Func = BI.inherit(BI.Widget, { }, width: 200 }); - childCombo.setValue(BI.deepClone(this.child)[0].children[0].value); + childCombo.setValue(BI.deepClone(this.child)[0].items[0].value); return BI.createWidget({ type: "bi.left", From 4edb0d9b23139d38d3913765396c6c49d69d61b3 Mon Sep 17 00:00:00 2001 From: impact Date: Tue, 3 Jan 2023 17:09:42 +0800 Subject: [PATCH 025/300] =?UTF-8?q?KERNEL-13948=20refactor:=20base/combina?= =?UTF-8?q?tion=E6=96=87=E4=BB=B6=E5=A4=B9ES6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/0.base.js | 5 +- src/base/combination/bubble.js | 972 +++++++++++++------------- src/base/combination/combo.js | 682 +++++++++--------- src/base/combination/expander.js | 245 +++---- src/base/combination/group.button.js | 326 ++++----- src/base/combination/group.combo.js | 98 +-- src/base/combination/group.virtual.js | 130 ++-- src/base/combination/loader.js | 221 +++--- src/base/combination/navigation.js | 162 ++--- src/base/combination/searcher.js | 306 ++++---- src/base/combination/switcher.js | 278 ++++---- src/base/combination/tab.js | 177 ++--- src/base/combination/tree.button.js | 142 ++-- src/base/index.js | 40 +- src/core/index.js | 3 + src/core/listener/listener.show.js | 52 +- 16 files changed, 1965 insertions(+), 1874 deletions(-) diff --git a/src/base/0.base.js b/src/base/0.base.js index 3d342a8d3..2b4960808 100644 --- a/src/base/0.base.js +++ b/src/base/0.base.js @@ -7,7 +7,8 @@ import { PopoverController, ResizeController, TooltipsController, - StyleLoaderManager + StyleLoaderManager, + extend } from "../core"; const Resizers = new ResizeController(); @@ -20,7 +21,7 @@ const Drawers = new DrawerController(); const Broadcasts = new BroadcastController(); const StyleLoaders = new StyleLoaderManager(); -BI.extend(BI, { +extend(BI, { Resizers, Layers, Maskers, diff --git a/src/base/combination/bubble.js b/src/base/combination/bubble.js index 7b5f57736..5d9e9e86a 100644 --- a/src/base/combination/bubble.js +++ b/src/base/combination/bubble.js @@ -1,513 +1,515 @@ -!(function () { - /** - * @class BI.Bubble - * @extends BI.Widget - */ - BI.Bubble = BI.inherit(BI.Widget, { - _defaultConfig: function () { - var conf = BI.Bubble.superclass._defaultConfig.apply(this, arguments); - - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-popper", - attributes: { - tabIndex: -1, - }, - trigger: "click", // click || hover || click-hover || "hover-click" || "" - toggle: true, - direction: "", - placement: "bottom-start", // top-start/top/top-end/bottom-start/bottom/bottom-end/left-start/left/left-end/right-start/right/right-end - logic: { - dynamic: true, - }, - container: null, // popupview放置的容器,默认为this.element - isDefaultInit: false, - destroyWhenHide: false, - hideWhenClickOutside: true, - showArrow: true, - hideWhenBlur: false, - isNeedAdjustHeight: true, // 是否需要高度调整 - isNeedAdjustWidth: true, - stopEvent: false, - stopPropagation: false, - adjustLength: 0, // 调整的距离 - adjustXOffset: 0, - adjustYOffset: 0, - hideChecker: BI.emptyFn, - offsetStyle: "left", // left,right,center - el: {}, - popup: {}, - comboClass: "bi-combo-popup", - hoverClass: "bi-combo-hover", - }); - }, - - render: function () { - var self = this, o = this.options; - this._initCombo(); - // 延迟绑定事件,这样可以将自己绑定的事情优先执行 - BI.nextTick(() => { - !this.isDestroyed() && this._initPullDownAction(); - }); - this.combo.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - if (self.isEnabled() && self.isValid()) { - if (type === BI.Events.EXPAND) { - self._popupView(); - } - if (type === BI.Events.COLLAPSE) { - self._hideView(); - } - if (type === BI.Events.EXPAND) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - self.fireEvent(BI.Bubble.EVENT_EXPAND); - } - if (type === BI.Events.COLLAPSE) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - self.isViewVisible() && self.fireEvent(BI.Bubble.EVENT_COLLAPSE); - } - if (type === BI.Events.CLICK) { - self.fireEvent(BI.Bubble.EVENT_TRIGGER_CHANGE, obj); - } +/** + * @class BI.Bubble + * @extends BI.Widget + */ +import { shortcut, Widget, Controller, extend, nextTick, createWidget, each, defer, debounce, delay, isNull, isFunction, contains, bind } from "../../core"; + +@shortcut() +export default class Bubble extends Widget { + static xtype = "bi.bubble"; + + static EVENT_TRIGGER_CHANGE = "EVENT_TRIGGER_CHANGE"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_EXPAND = "EVENT_EXPAND"; + static EVENT_COLLAPSE = "EVENT_COLLAPSE"; + static EVENT_AFTER_INIT = "EVENT_AFTER_INIT"; + + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + static EVENT_AFTER_POPUPVIEW = "EVENT_AFTER_POPUPVIEW"; + static EVENT_BEFORE_HIDEVIEW = "EVENT_BEFORE_HIDEVIEW"; + static EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { + baseCls: (conf.baseCls || "") + " bi-popper", + attributes: { + tabIndex: -1, + }, + trigger: "click", // click || hover || click-hover || "hover-click" || "" + toggle: true, + direction: "", + placement: "bottom-start", // top-start/top/top-end/bottom-start/bottom/bottom-end/left-start/left/left-end/right-start/right/right-end + logic: { + dynamic: true, + }, + container: null, // popupview放置的容器,默认为this.element + isDefaultInit: false, + destroyWhenHide: false, + hideWhenClickOutside: true, + showArrow: true, + hideWhenBlur: false, + isNeedAdjustHeight: true, // 是否需要高度调整 + isNeedAdjustWidth: true, + stopEvent: false, + stopPropagation: false, + adjustLength: 0, // 调整的距离 + adjustXOffset: 0, + adjustYOffset: 0, + hideChecker: BI.emptyFn, + offsetStyle: "left", // left,right,center + el: {}, + popup: {}, + comboClass: "bi-combo-popup", + hoverClass: "bi-combo-hover", + }); + } + + render() { + const { hoverClass, logic, isDefaultInit } = this.options; + this._initCombo(); + // 延迟绑定事件,这样可以将自己绑定的事情优先执行 + nextTick(() => { + !this.isDestroyed() && this._initPullDownAction(); + }); + this.combo.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { + if (this.isEnabled() && this.isValid()) { + if (type === BI.Events.EXPAND) { + this._popupView(); } - }); - - self.element.on("mouseenter." + self.getName(), function (e) { - if (self.isEnabled() && self.isValid() && self.combo.isEnabled() && self.combo.isValid()) { - self.element.addClass(o.hoverClass); + if (type === BI.Events.COLLAPSE) { + this._hideView(); } - }); - self.element.on("mouseleave." + self.getName(), function (e) { - if (self.isEnabled() && self.isValid() && self.combo.isEnabled() && self.combo.isValid()) { - self.element.removeClass(o.hoverClass); + if (type === BI.Events.EXPAND) { + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); + this.fireEvent(Bubble.EVENT_EXPAND); } - }); - - BI.createWidget(BI.extend({ - element: this, - scrolly: false, - }, BI.LogicFactory.createLogic("vertical", BI.extend(o.logic, { - items: [ - { el: this.combo } - ], - })))); - o.isDefaultInit && (this._assertPopupView()); - }, - - _toggle: function (e) { - this._assertPopupViewRender(); - if (this.popupView.isVisible()) { - this._hideView(e); - } else { - if (this.isEnabled()) { - this._popupView(e); + if (type === BI.Events.COLLAPSE) { + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); + this.isViewVisible() && this.fireEvent(Bubble.EVENT_COLLAPSE); + } + if (type === BI.Events.CLICK) { + this.fireEvent(Bubble.EVENT_TRIGGER_CHANGE, obj); } } - }, + }); - _initPullDownAction: function () { - var self = this, o = this.options; - var evs = (this.options.trigger || "").split(","); - - function st(e) { - if (o.stopEvent) { - e.stopEvent(); - } - if (o.stopPropagation) { - e.stopPropagation(); - } + this.element.on("mouseenter." + this.getName(), (e) => { + if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid()) { + this.element.addClass(hoverClass); + } + }); + this.element.on("mouseleave." + this.getName(), (e) => { + if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid()) { + this.element.removeClass(hoverClass); + } + }); + + createWidget(extend({ + element: this, + scrolly: false, + }, BI.LogicFactory.createLogic("vertical", extend(logic, { + items: [ + { el: this.combo } + ], + })))); + isDefaultInit && (this._assertPopupView()); + } + + _toggle(e) { + this._assertPopupViewRender(); + if (this.popupView.isVisible()) { + this._hideView(e); + } else { + if (this.isEnabled()) { + this._popupView(e); } + } + } - var enterPopup = false; + _initPullDownAction() { + const { stopEvent, stopPropagation, toggle } = this.options; + const evs = (this.options.trigger || "").split(","); - function hide(e) { - if (self.isEnabled() && self.isValid() && self.combo.isEnabled() && self.combo.isValid() && o.toggle === true) { - self._hideView(e); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.combo); - self.fireEvent(BI.Bubble.EVENT_COLLAPSE); - } - self.popupView && self.popupView.element.off("mouseenter." + self.getName()).off("mouseleave." + self.getName()); - enterPopup = false; + const st = (e) => { + if (stopEvent) { + e.stopEvent(); } + if (stopPropagation) { + e.stopPropagation(); + } + } - BI.each(evs, function (i, ev) { - switch (ev) { - case "hover": - self.element.on("mouseenter." + self.getName(), function (e) { - if (self.isEnabled() && self.isValid() && self.combo.isEnabled() && self.combo.isValid()) { - self._popupView(e); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.combo); - self.fireEvent(BI.Bubble.EVENT_EXPAND); - } - }); - self.element.on("mouseleave." + self.getName(), function (e) { - if (self.popupView) { - self.popupView.element.on("mouseenter." + self.getName(), function (e) { - enterPopup = true; - self.popupView.element.on("mouseleave." + self.getName(), function (e) { - hide(e); - }); - self.popupView.element.off("mouseenter." + self.getName()); + let enterPopup = false; + + const hide = (e) => { + if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid() && toggle === true) { + this._hideView(e); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", this.combo); + this.fireEvent(Bubble.EVENT_COLLAPSE); + } + this.popupView && this.popupView.element.off("mouseenter." + this.getName()).off("mouseleave." + this.getName()); + enterPopup = false; + } + + each(evs, (i, ev) => { + let debounced; + switch (ev) { + case "hover": + this.element.on("mouseenter." + this.getName(), (e) => { + if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid()) { + this._popupView(e); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.combo); + this.fireEvent(Bubble.EVENT_EXPAND); + } + }); + this.element.on("mouseleave." + this.getName(), (e) => { + if (this.popupView) { + this.popupView.element.on("mouseenter." + this.getName(), (e) => { + enterPopup = true; + this.popupView.element.on("mouseleave." + this.getName(), (e) => { + hide(e); }); - BI.defer(function () { - if (!enterPopup) { - hide(e); - } - }, 50); - } - }); - break; - case "click": - var debounce = BI.debounce(function (e) { - if (self.combo.element.__isMouseInBounds__(e)) { - if (self.isEnabled() && self.isValid() && self.combo.isEnabled() && self.combo.isValid()) { - // if (!o.toggle && self.isViewVisible()) { - // return; - // } - o.toggle ? self._toggle(e) : self._popupView(e); - if (self.isViewVisible()) { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.combo); - self.fireEvent(BI.Bubble.EVENT_EXPAND); - } else { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.combo); - self.fireEvent(BI.Bubble.EVENT_COLLAPSE); - } + this.popupView.element.off("mouseenter." + this.getName()); + }); + defer(() => { + if (!enterPopup) { + hide(e); + } + }, 50); + } + }); + break; + case "click": + debounced = debounce((e) => { + if (this.combo.element.__isMouseInBounds__(e)) { + if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid()) { + // if (!o.toggle && this.isViewVisible()) { + // return; + // } + toggle ? this._toggle(e) : this._popupView(e); + if (this.isViewVisible()) { + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.combo); + this.fireEvent(Bubble.EVENT_EXPAND); + } else { + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", this.combo); + this.fireEvent(Bubble.EVENT_COLLAPSE); } } - }, BI.EVENT_RESPONSE_TIME, { - "leading": true, - "trailing": false, - }); - self.element.off(ev + "." + self.getName()).on(ev + "." + self.getName(), function (e) { - debounce(e); - st(e); - }); - break; - case "click-hover": - var debounce = BI.debounce(function (e) { - if (self.combo.element.__isMouseInBounds__(e)) { - if (self.isEnabled() && self.isValid() && self.combo.isEnabled() && self.combo.isValid()) { - // if (self.isViewVisible()) { - // return; - // } - self._popupView(e); - if (self.isViewVisible()) { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.combo); - self.fireEvent(BI.Bubble.EVENT_EXPAND); - } + } + }, BI.EVENT_RESPONSE_TIME, { + "leading": true, + "trailing": false, + }); + this.element.off(ev + "." + this.getName()).on(ev + "." + this.getName(), (e) => { + debounced(e); + st(e); + }); + break; + case "click-hover": + debounced = debounce((e) => { + if (this.combo.element.__isMouseInBounds__(e)) { + if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid()) { + // if (this.isViewVisible()) { + // return; + // } + this._popupView(e); + if (this.isViewVisible()) { + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.combo); + this.fireEvent(Bubble.EVENT_EXPAND); } } - }, BI.EVENT_RESPONSE_TIME, { - "leading": true, - "trailing": false, - }); - self.element.off("click." + self.getName()).on("click." + self.getName(), function (e) { - debounce(e); - st(e); - }); - self.element.on("mouseleave." + self.getName(), function (e) { - if (self.popupView) { - self.popupView.element.on("mouseenter." + self.getName(), function (e) { - enterPopup = true; - self.popupView.element.on("mouseleave." + self.getName(), function (e) { - hide(e); - }); - self.popupView.element.off("mouseenter." + self.getName()); + } + }, BI.EVENT_RESPONSE_TIME, { + "leading": true, + "trailing": false, + }); + this.element.off("click." + this.getName()).on("click." + this.getName(), (e) => { + debounced(e); + st(e); + }); + this.element.on("mouseleave." + this.getName(), (e) => { + if (this.popupView) { + this.popupView.element.on("mouseenter." + this.getName(), (e) => { + enterPopup = true; + this.popupView.element.on("mouseleave." + this.getName(), (e) => { + hide(e); }); - BI.delay(function () { - if (!enterPopup) { - hide(e); - } - }, 50); - } - }); - break; - case "hover-click": - self.element.on("mouseenter." + self.getName(), function (e) { - if (self.isEnabled() && self.isValid() && self.combo.isEnabled() && self.combo.isValid()) { - self._popupView(e); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.combo); - self.fireEvent(BI.Bubble.EVENT_EXPAND); - } - }); - break; - default: - break; + this.popupView.element.off("mouseenter." + this.getName()); + }); + delay(() => { + if (!enterPopup) { + hide(e); + } + }, 50); + } + }); + break; + case "hover-click": + this.element.on("mouseenter." + this.getName(), (e) => { + if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid()) { + this._popupView(e); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.combo); + this.fireEvent(Bubble.EVENT_EXPAND); + } + }); + break; + default: + break; + } + }); + } + + _initCombo() { + this.combo = createWidget(this.options.el, { + value: this.options.value, + }); + } + + _assertPopupView() { + const { showArrow, value } = this.options; + if (isNull(this.popupView)) { + this.popupView = createWidget(isFunction(this.options.popup) ? this.options.popup() : this.options.popup, { + type: "bi.bubble_popup_view", + showArrow, + value, + }, this); + this.popupView.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { + if (type === BI.Events.CLICK) { + this.combo.setValue(this.getValue()); + this.fireEvent(Bubble.EVENT_CHANGE, value, obj); } + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); }); - }, - - _initCombo: function () { - this.combo = BI.createWidget(this.options.el, { - value: this.options.value, + this.popupView.setVisible(false); + nextTick(() => { + this.fireEvent(Bubble.EVENT_AFTER_INIT); }); - }, - - _assertPopupView: function () { - var self = this, o = this.options; - if (BI.isNull(this.popupView)) { - this.popupView = BI.createWidget(BI.isFunction(this.options.popup) ? this.options.popup() : this.options.popup, { - type: "bi.bubble_popup_view", - showArrow: o.showArrow, - value: o.value, - }, this); - this.popupView.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - if (type === BI.Events.CLICK) { - self.combo.setValue(self.getValue()); - self.fireEvent(BI.Bubble.EVENT_CHANGE, value, obj); - } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }); - this.popupView.setVisible(false); - BI.nextTick(function () { - self.fireEvent(BI.Bubble.EVENT_AFTER_INIT); - }); - } - }, - - _assertPopupViewRender: function () { - this._assertPopupView(); - if (!this._rendered) { - BI.createWidget({ - type: "bi.vertical", - scrolly: false, - element: BI.isFunction(this.options.container) ? this.options.container() : (this.options.container || this), - items: [ - { el: this.popupView } - ], - }); - this._rendered = true; - } - }, - - _hideIf: function (e, skipTriggerChecker) { - // if (this.element.__isMouseInBounds__(e) || (this.popupView && this.popupView.element.__isMouseInBounds__(e))) { - // return; - // } - // BI-10290 公式combo双击公式内容会收起 - if (e && ((skipTriggerChecker !== true && this.element.find(e.target).length > 0) - || (this.popupView && this.popupView.element.find(e.target).length > 0) - || e.target.className === "CodeMirror-cursor" || BI.Widget._renderEngine.createElement(e.target).closest(".CodeMirror-hints").length > 0)) {// BI-9887 CodeMirror的公式弹框需要特殊处理下 - var directions = this.options.direction.split(","); - if (BI.contains(directions, "innerLeft") || BI.contains(directions, "innerRight")) { - // popup可以出现在trigger内部的combo,滚动时不需要消失,而是调整位置 - this.adjustWidth(); - this.adjustHeight(); - } - - return; - } - var isHide = this.options.hideChecker.apply(this, [e]); - if (isHide === false) { - return; - } - this._hideView(e); - - return true; - }, - - _hideView: function (e) { - var o = this.options; - this.fireEvent(BI.Bubble.EVENT_BEFORE_HIDEVIEW); - if (this.options.destroyWhenHide === true) { - this.popupView && this.popupView.destroy(); - this.popupView = null; - this._rendered = false; - } else { - this.popupView && this.popupView.invisible(); - } - - if (!e || !this.combo.element.__isMouseInBounds__(e)) { - this.element.removeClass(this.options.hoverClass); - // 应对bi-focus-shadow在收起时不失焦 - this.element.blur(); - } - - if (this.popper) { - this.popper.destroy(); - this.popper = null; + } + } + + _assertPopupViewRender() { + this._assertPopupView(); + if (!this._rendered) { + createWidget({ + type: "bi.vertical", + scrolly: false, + element: isFunction(this.options.container) ? this.options.container() : (this.options.container || this), + items: [ + { el: this.popupView } + ], + }); + this._rendered = true; + } + } + + _hideIf(e, skipTriggerChecker) { + // if (this.element.__isMouseInBounds__(e) || (this.popupView && this.popupView.element.__isMouseInBounds__(e))) { + // return; + // } + // BI-10290 公式combo双击公式内容会收起 + if (e && ((skipTriggerChecker !== true && this.element.find(e.target).length > 0) + || (this.popupView && this.popupView.element.find(e.target).length > 0) + || e.target.className === "CodeMirror-cursor" || Widget._renderEngine.createElement(e.target).closest(".CodeMirror-hints").length > 0)) {// BI-9887 CodeMirror的公式弹框需要特殊处理下 + const directions = this.options.direction.split(","); + if (contains(directions, "innerLeft") || contains(directions, "innerRight")) { + // popup可以出现在trigger内部的combo,滚动时不需要消失,而是调整位置 + this.adjustWidth(); + this.adjustHeight(); } - this.element.removeClass(this.options.comboClass); - - BI.Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()).unbind("mousewheel." + this.getName()); - BI.EVENT_BLUR && o.hideWhenBlur && BI.Widget._renderEngine.createElement(window).unbind("blur." + this.getName()); - this.fireEvent(BI.Bubble.EVENT_AFTER_HIDEVIEW); - }, - - _popupView: function (e) { - var o = this.options; - this._assertPopupViewRender(); - this.fireEvent(BI.Bubble.EVENT_BEFORE_POPUPVIEW); - // popupVisible是为了获取其宽高, 放到可视范围之外以防止在IE下闪一下 - // this.popupView.css({left: -999999999, top: -99999999}); - this.popupView.visible(); - this.adjustWidth(e); - - if (this.popper) { - this.popper.destroy(); - } - var modifiers = [ - { - name: "offset", - options: { - offset: function () { - return [o.adjustXOffset, (o.showArrow ? 12 : 0) + (o.adjustYOffset + o.adjustLength)]; - }, - }, - } - ]; - if (this.options.showArrow) { - modifiers.push({ - name: "arrow", - options: { - padding: 4, - element: this.popupView.arrow.element[0], + return; + } + const isHide = this.options.hideChecker.apply(this, [e]); + if (isHide === false) { + return; + } + this._hideView(e); + + return true; + } + + _hideView(e) { + const { hideWhenBlur } = this.options; + this.fireEvent(Bubble.EVENT_BEFORE_HIDEVIEW); + if (this.options.destroyWhenHide === true) { + this.popupView && this.popupView.destroy(); + this.popupView = null; + this._rendered = false; + } else { + this.popupView && this.popupView.invisible(); + } + + if (!e || !this.combo.element.__isMouseInBounds__(e)) { + this.element.removeClass(this.options.hoverClass); + // 应对bi-focus-shadow在收起时不失焦 + this.element.blur(); + } + + if (this.popper) { + this.popper.destroy(); + this.popper = null; + } + + this.element.removeClass(this.options.comboClass); + + Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()).unbind("mousewheel." + this.getName()); + BI.EVENT_BLUR && hideWhenBlur && Widget._renderEngine.createElement(window).unbind("blur." + this.getName()); + this.fireEvent(Bubble.EVENT_AFTER_HIDEVIEW); + } + + _popupView(e) { + const { adjustXOffset, showArrow, adjustYOffset, adjustLength, placement, hideWhenClickOutside, hideWhenBlur } = this.options; + this._assertPopupViewRender(); + this.fireEvent(Bubble.EVENT_BEFORE_POPUPVIEW); + // popupVisible是为了获取其宽高, 放到可视范围之外以防止在IE下闪一下 + // this.popupView.css({left: -999999999, top: -99999999}); + this.popupView.visible(); + this.adjustWidth(e); + + if (this.popper) { + this.popper.destroy(); + } + const modifiers = [ + { + name: "offset", + options: { + offset: () => { + return [adjustXOffset, (showArrow ? 12 : 0) + (adjustYOffset + adjustLength)]; }, - }); + }, } - this.popper = BI.Popper.createPopper(this.combo.element[0], this.popupView.element[0], { - placement: o.placement, - strategy: "fixed", - modifiers: modifiers, + ]; + if (this.options.showArrow) { + modifiers.push({ + name: "arrow", + options: { + padding: 4, + element: this.popupView.arrow.element[0], + }, }); - - // this.adjustHeight(e); - - this.element.addClass(this.options.comboClass); - o.hideWhenClickOutside && BI.Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()); - BI.EVENT_BLUR && o.hideWhenBlur && BI.Widget._renderEngine.createElement(window).unbind("blur." + this.getName()); - - o.hideWhenClickOutside && BI.Widget._renderEngine.createElement(document).bind("mousedown." + this.getName(), BI.bind(this._hideIf, this)); - BI.EVENT_BLUR && o.hideWhenBlur && BI.Widget._renderEngine.createElement(window).bind("blur." + this.getName(), BI.bind(this._hideIf, this)); - this.fireEvent(BI.Bubble.EVENT_AFTER_POPUPVIEW); - }, - - adjustWidth: function (e) { - var o = this.options; - if (!this.popupView) { - return; - } - if (o.isNeedAdjustWidth === true) { - this.resetListWidth(""); - var width = this.popupView.element.outerWidth(); - var maxW = this.element.outerWidth() || o.width; - // BI-93885 最大列宽算法调整 - if (maxW < 500) { - if (width >= 500) { - maxW = 500; - } else if (width > maxW) { - // 防止小数导致差那么一点 - maxW = width + 1; - } + } + this.popper = BI.Popper.createPopper(this.combo.element[0], this.popupView.element[0], { + placement, + strategy: "fixed", + modifiers, + }); + + // this.adjustHeight(e); + + this.element.addClass(this.options.comboClass); + hideWhenClickOutside && Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()); + BI.EVENT_BLUR && hideWhenBlur && Widget._renderEngine.createElement(window).unbind("blur." + this.getName()); + + hideWhenClickOutside && Widget._renderEngine.createElement(document).bind("mousedown." + this.getName(), bind(this._hideIf, this)); + BI.EVENT_BLUR && hideWhenBlur && Widget._renderEngine.createElement(window).bind("blur." + this.getName(), bind(this._hideIf, this)); + this.fireEvent(Bubble.EVENT_AFTER_POPUPVIEW); + } + + adjustWidth(e) { + const { isNeedAdjustWidth } = this.options; + if (!this.popupView) { + return; + } + if (isNeedAdjustWidth === true) { + this.resetListWidth(""); + const width = this.popupView.element.outerWidth(); + let maxW = this.element.outerWidth() || this.options.width; + // BI-93885 最大列宽算法调整 + if (maxW < 500) { + if (width >= 500) { + maxW = 500; + } else if (width > maxW) { + // 防止小数导致差那么一点 + maxW = width + 1; } - - // if (width > maxW + 80) { - // maxW = maxW + 80; - // } else if (width > maxW) { - // maxW = width; - // } - this.resetListWidth(maxW < 100 ? 100 : maxW); - } - }, - - adjustHeight: function () { - - }, - - resetListHeight: function (h) { - this._assertPopupView(); - this.popupView.resetHeight && this.popupView.resetHeight(h); - }, - - resetListWidth: function (w) { - this._assertPopupView(); - this.popupView.resetWidth && this.popupView.resetWidth(w); - }, - - populate: function (items) { - this._assertPopupView(); - this.popupView.populate.apply(this.popupView, arguments); - this.combo.populate && this.combo.populate.apply(this.combo, arguments); - }, - - _setEnable: function (arg) { - BI.Bubble.superclass._setEnable.apply(this, arguments); - if (arg === true) { - this.element.removeClass("base-disabled disabled"); - } else if (arg === false) { - this.element.addClass("base-disabled disabled"); - } - !arg && this.element.removeClass(this.options.hoverClass); - !arg && this.isViewVisible() && this._hideView(); - }, - - setValue: function (v) { - this.combo.setValue(v); - if (BI.isNull(this.popupView)) { - this.options.popup.value = v; - } else { - this.popupView.setValue(v); } - }, - getValue: function () { - if (BI.isNull(this.popupView)) { - return this.options.popup.value; - } else { - return this.popupView.getValue(); - } - }, - - isViewVisible: function () { - return this.isEnabled() && this.combo.isEnabled() && !!this.popupView && this.popupView.isVisible(); - }, - - showView: function (e) { - // 减少popup 调整宽高的次数 - if (this.isEnabled() && this.combo.isEnabled() && !this.isViewVisible()) { - this._popupView(e); - } - }, - - hideView: function (e) { - this._hideView(e); - }, - - getView: function () { - return this.popupView; - }, - - getPopupPosition: function () { - return this.position; - }, - - toggle: function () { - this._toggle(); - }, - - destroyed: function () { - BI.Widget._renderEngine.createElement(document) - .unbind("click." + this.getName()) - .unbind("mousedown." + this.getName()) - .unbind("mouseenter." + this.getName()) - .unbind("mouseleave." + this.getName()); - BI.Widget._renderEngine.createElement(window) - .unbind("blur." + this.getName()); - this.popper && this.popper.destroy(); - this.popper = null; - this.popupView && this.popupView._destroy(); - }, - }); - BI.Bubble.EVENT_TRIGGER_CHANGE = "EVENT_TRIGGER_CHANGE"; - BI.Bubble.EVENT_CHANGE = "EVENT_CHANGE"; - BI.Bubble.EVENT_EXPAND = "EVENT_EXPAND"; - BI.Bubble.EVENT_COLLAPSE = "EVENT_COLLAPSE"; - BI.Bubble.EVENT_AFTER_INIT = "EVENT_AFTER_INIT"; - - - BI.Bubble.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; - BI.Bubble.EVENT_AFTER_POPUPVIEW = "EVENT_AFTER_POPUPVIEW"; - BI.Bubble.EVENT_BEFORE_HIDEVIEW = "EVENT_BEFORE_HIDEVIEW"; - BI.Bubble.EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; - - BI.shortcut("bi.bubble", BI.Bubble); -}()); + // if (width > maxW + 80) { + // maxW = maxW + 80; + // } else if (width > maxW) { + // maxW = width; + // } + this.resetListWidth(maxW < 100 ? 100 : maxW); + } + } + + adjustHeight() { + + } + + resetListHeight(h) { + this._assertPopupView(); + this.popupView.resetHeight && this.popupView.resetHeight(h); + } + + resetListWidth(w) { + this._assertPopupView(); + this.popupView.resetWidth && this.popupView.resetWidth(w); + } + + populate(items) { + this._assertPopupView(); + this.popupView.populate.apply(this.popupView, arguments); + this.combo.populate && this.combo.populate.apply(this.combo, arguments); + } + + _setEnable(arg) { + super._setEnable(arguments); + if (arg === true) { + this.element.removeClass("base-disabled disabled"); + } else if (arg === false) { + this.element.addClass("base-disabled disabled"); + } + !arg && this.element.removeClass(this.options.hoverClass); + !arg && this.isViewVisible() && this._hideView(); + } + + setValue(v) { + this.combo.setValue(v); + if (isNull(this.popupView)) { + this.options.popup.value = v; + } else { + this.popupView.setValue(v); + } + } + + getValue() { + if (isNull(this.popupView)) { + return this.options.popup.value; + } else { + return this.popupView.getValue(); + } + } + + isViewVisible() { + return this.isEnabled() && this.combo.isEnabled() && !!this.popupView && this.popupView.isVisible(); + } + + showView(e) { + // 减少popup 调整宽高的次数 + if (this.isEnabled() && this.combo.isEnabled() && !this.isViewVisible()) { + this._popupView(e); + } + } + + hideView(e) { + this._hideView(e); + } + + getView() { + return this.popupView; + } + + getPopupPosition() { + return this.position; + } + + toggle() { + this._toggle(); + } + + destroyed() { + Widget._renderEngine.createElement(document) + .unbind("click." + this.getName()) + .unbind("mousedown." + this.getName()) + .unbind("mouseenter." + this.getName()) + .unbind("mouseleave." + this.getName()); + Widget._renderEngine.createElement(window) + .unbind("blur." + this.getName()); + this.popper && this.popper.destroy(); + this.popper = null; + this.popupView && this.popupView._destroy(); + } +} diff --git a/src/base/combination/combo.js b/src/base/combination/combo.js index 75c45a4fe..277e9e224 100644 --- a/src/base/combination/combo.js +++ b/src/base/combination/combo.js @@ -1,374 +1,374 @@ -!(function () { - var needHideWhenAnotherComboOpen = {}; - var currentOpenedCombos = {}; +/** + * @class BI.Combo + * @extends BI.Widget + */ - /** - * @class BI.Combo - * @extends BI.Widget - */ - BI.Combo = BI.inherit(BI.Bubble, { - _const: { - TRIANGLE_LENGTH: 12, - }, - _defaultConfig: function () { - var conf = BI.Combo.superclass._defaultConfig.apply(this, arguments); +import { shortcut, Widget, Controller, extend, createWidget, nextTick, bind, isNotNull, isNull, isFunction, each } from "../../core"; +import Bubble from "./bubble"; +import { Resizers } from "../0.base"; - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-combo" + (BI.isIE() ? " hack" : ""), - attributes: { - tabIndex: -1, - }, - trigger: "click", // click || hover || click-hover || "" - toggle: true, - direction: "bottom", // top||bottom||left||right||top,left||top,right||bottom,left||bottom,right||right,innerRight||right,innerLeft||innerRight||innerLeft - logic: { - dynamic: true, - }, - container: null, // popupview放置的容器,默认为this.element - isDefaultInit: false, - destroyWhenHide: false, - hideWhenBlur: true, - hideWhenAnotherComboOpen: false, - hideWhenClickOutside: true, - showArrow: false, - isNeedAdjustHeight: true, // 是否需要高度调整 - isNeedAdjustWidth: true, - stopEvent: false, - stopPropagation: false, - adjustLength: 0, // 调整的距离 - adjustXOffset: 0, - adjustYOffset: 0, - supportCSSTransform: true, - hideChecker: BI.emptyFn, - offsetStyle: "", // "",center,middle - el: {}, - popup: {}, - comboClass: "bi-combo-popup", - hoverClass: "bi-combo-hover", - belowMouse: false, - }); - }, +let needHideWhenAnotherComboOpen = {}; +let currentOpenedCombos = {}; - render: function () { - var self = this, o = this.options; - this._initCombo(); - // 延迟绑定事件,这样可以将自己绑定的事情优先执行 - BI.nextTick(() => { - !this.isDestroyed() && this._initPullDownAction(); - }); - this.combo.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - if (self.isEnabled() && self.isValid()) { - if (type === BI.Events.TOGGLE) { - self._toggle(); - } - if (type === BI.Events.EXPAND) { - self._popupView(); - } - if (type === BI.Events.COLLAPSE) { - self._hideView(); - } - if (type === BI.Events.EXPAND) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - self.fireEvent(BI.Combo.EVENT_EXPAND); - } - if (type === BI.Events.COLLAPSE) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - self.isViewVisible() && self.fireEvent(BI.Combo.EVENT_COLLAPSE); - } - if (type === BI.Events.CLICK) { - self.fireEvent(BI.Combo.EVENT_TRIGGER_CHANGE, obj); - } - } - }); +@shortcut() +export default class Combo extends Bubble { + static xtype = "bi.combo"; - self.element.on("mouseenter." + self.getName(), function (e) { - if (self.isEnabled() && self.isValid() && self.combo.isEnabled() && self.combo.isValid()) { - self.element.addClass(o.hoverClass); + static EVENT_TRIGGER_CHANGE = "EVENT_TRIGGER_CHANGE"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_EXPAND = "EVENT_EXPAND"; + static EVENT_COLLAPSE = "EVENT_COLLAPSE"; + static EVENT_AFTER_INIT = "EVENT_AFTER_INIT"; + + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + static EVENT_AFTER_POPUPVIEW = "EVENT_AFTER_POPUPVIEW"; + static EVENT_BEFORE_HIDEVIEW = "EVENT_BEFORE_HIDEVIEW"; + static EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { + baseCls: (conf.baseCls || "") + " bi-combo" + (BI.isIE() ? " hack" : ""), + attributes: { + tabIndex: -1, + }, + trigger: "click", // click || hover || click-hover || "" + toggle: true, + direction: "bottom", // top||bottom||left||right||top,left||top,right||bottom,left||bottom,right||right,innerRight||right,innerLeft||innerRight||innerLeft + logic: { + dynamic: true, + }, + container: null, // popupview放置的容器,默认为this.element + isDefaultInit: false, + destroyWhenHide: false, + hideWhenBlur: true, + hideWhenAnotherComboOpen: false, + hideWhenClickOutside: true, + showArrow: false, + isNeedAdjustHeight: true, // 是否需要高度调整 + isNeedAdjustWidth: true, + stopEvent: false, + stopPropagation: false, + adjustLength: 0, // 调整的距离 + adjustXOffset: 0, + adjustYOffset: 0, + supportCSSTransform: true, + hideChecker: BI.emptyFn, + offsetStyle: "", // "",center,middle + el: {}, + popup: {}, + comboClass: "bi-combo-popup", + hoverClass: "bi-combo-hover", + belowMouse: false, + }); + } + + render() { + const { hoverClass, logic, isDefaultInit } = this.options; + this._initCombo(); + // 延迟绑定事件,这样可以将自己绑定的事情优先执行 + nextTick(() => { + !this.isDestroyed() && this._initPullDownAction(); + }); + this.combo.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { + if (this.isEnabled() && this.isValid()) { + if (type === BI.Events.TOGGLE) { + this._toggle(); } - }); - self.element.on("mouseleave." + self.getName(), function (e) { - if (self.isEnabled() && self.isValid() && self.combo.isEnabled() && self.combo.isValid()) { - self.element.removeClass(o.hoverClass); + if (type === BI.Events.EXPAND) { + this._popupView(); } - }); - - BI.createWidget(BI.extend({ - element: this, - scrolly: false, - }, BI.LogicFactory.createLogic("vertical", BI.extend(o.logic, { - items: [ - { el: this.combo } - ], - })))); - o.isDefaultInit && (this._assertPopupView()); - BI.Resizers.add(this.getName(), BI.bind(function (e) { - // 如果resize对象是combo的子元素,则不应该收起,或交由hideChecker去处理 - if (this.isViewVisible()) { - BI.isNotNull(e) ? this._hideIf(e) : this._hideView(); + if (type === BI.Events.COLLAPSE) { + this._hideView(); + } + if (type === BI.Events.EXPAND) { + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); + this.fireEvent(Combo.EVENT_EXPAND); + } + if (type === BI.Events.COLLAPSE) { + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); + this.isViewVisible() && this.fireEvent(Combo.EVENT_COLLAPSE); + } + if (type === BI.Events.CLICK) { + this.fireEvent(Combo.EVENT_TRIGGER_CHANGE, obj); } - }, this)); - }, - - _assertPopupView: function () { - var self = this, o = this.options; - if (BI.isNull(this.popupView)) { - this.popupView = BI.createWidget(BI.isFunction(this.options.popup) ? this.options.popup() : this.options.popup, { - type: "bi.popup_view", - showArrow: o.showArrow, - value: o.value, - }, this); - this.popupView.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - if (type === BI.Events.CLICK) { - self.combo.setValue(self.getValue()); - self.fireEvent(BI.Bubble.EVENT_CHANGE, value, obj); - } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }); - this.popupView.setVisible(false); - BI.nextTick(function () { - self.fireEvent(BI.Bubble.EVENT_AFTER_INIT); - }); } - }, + }); - _hideView: function (e) { - var o = this.options; - this.fireEvent(BI.Combo.EVENT_BEFORE_HIDEVIEW); - if (this.options.destroyWhenHide === true) { - this.popupView && this.popupView.destroy(); - this.popupView = null; - this._rendered = false; - } else { - this.popupView && this.popupView.invisible(); + this.element.on("mouseenter." + this.getName(), (e) => { + if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid()) { + this.element.addClass(hoverClass); } - - if (!e || !this.combo.element.__isMouseInBounds__(e)) { - this.element.removeClass(this.options.hoverClass); - // 应对bi-focus-shadow在收起时不失焦 - this.element.blur(); + }); + this.element.on("mouseleave." + this.getName(), (e) => { + if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid()) { + this.element.removeClass(hoverClass); } + }); - this.element.removeClass(this.options.comboClass); - delete needHideWhenAnotherComboOpen[this.getName()]; - delete currentOpenedCombos[this.getName()]; - - o.hideWhenClickOutside && BI.Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()).unbind("mousewheel." + this.getName()); - BI.EVENT_BLUR && o.hideWhenBlur && BI.Widget._renderEngine.createElement(window).unbind("blur." + this.getName()); - this.fireEvent(BI.Combo.EVENT_AFTER_HIDEVIEW, e); - }, + createWidget(extend({ + element: this, + scrolly: false, + }, BI.LogicFactory.createLogic("vertical", extend(logic, { + items: [ + { el: this.combo } + ], + })))); + isDefaultInit && (this._assertPopupView()); + Resizers.add(this.getName(), bind((e) => { + // 如果resize对象是combo的子元素,则不应该收起,或交由hideChecker去处理 + if (this.isViewVisible()) { + isNotNull(e) ? this._hideIf(e) : this._hideView(); + } + }, this)); + } - _popupView: function (e) { - var self = this, o = this.options; - this._assertPopupViewRender(); - this.fireEvent(BI.Combo.EVENT_BEFORE_POPUPVIEW); - // popupVisible是为了获取其宽高, 放到可视范围之外以防止在IE下闪一下 - this.popupView.css({ left: -99999, top: -99999 }); - this.popupView.visible(); - BI.each(needHideWhenAnotherComboOpen, function (i, combo) { - if (i !== self.getName()) { - if (combo && combo._hideIf(e, true) === true) { - delete needHideWhenAnotherComboOpen[i]; - } + _assertPopupView() { + const { showArrow, value, hideWhenClickOutside, hideWhenBlur } = this.options; + if (isNull(this.popupView)) { + this.popupView = createWidget(isFunction(this.options.popup) ? this.options.popup() : this.options.popup, { + type: "bi.popup_view", + showArrow, + value, + }, this); + this.popupView.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { + if (type === BI.Events.CLICK) { + this.combo.setValue(this.getValue()); + this.fireEvent(Bubble.EVENT_CHANGE, value, obj); } + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); + }); + this.popupView.setVisible(false); + nextTick(() => { + this.fireEvent(Bubble.EVENT_AFTER_INIT); }); - currentOpenedCombos[this.getName()] = this; - this.options.hideWhenAnotherComboOpen && (needHideWhenAnotherComboOpen[this.getName()] = this); - this.adjustWidth(e); - this.adjustHeight(e); + } + } - this.element.addClass(this.options.comboClass); - o.hideWhenClickOutside && BI.Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()).unbind("mousewheel." + this.getName()); - o.hideWhenClickOutside && BI.Widget._renderEngine.createElement(document).unbind("mousewheel." + this.getName()); - BI.EVENT_BLUR && o.hideWhenBlur && BI.Widget._renderEngine.createElement(window).unbind("blur." + this.getName()); + _hideView(e) { + const { hideWhenClickOutside, hideWhenBlur } = this.options; + this.fireEvent(Combo.EVENT_BEFORE_HIDEVIEW); + if (this.options.destroyWhenHide === true) { + this.popupView && this.popupView.destroy(); + this.popupView = null; + this._rendered = false; + } else { + this.popupView && this.popupView.invisible(); + } - o.hideWhenClickOutside && BI.Widget._renderEngine.createElement(document).bind("mousedown." + this.getName(), BI.bind(this._hideIf, this)).bind("mousewheel." + this.getName(), BI.bind(this._hideIf, this)); - o.hideWhenClickOutside && BI.Widget._renderEngine.createElement(document).bind("mousewheel." + this.getName(), BI.bind(this._hideIf, this)); - BI.EVENT_BLUR && o.hideWhenBlur && BI.Widget._renderEngine.createElement(window).bind("blur." + this.getName(), BI.bind(this._hideIf, this)); - this.fireEvent(BI.Combo.EVENT_AFTER_POPUPVIEW); - }, + if (!e || !this.combo.element.__isMouseInBounds__(e)) { + this.element.removeClass(this.options.hoverClass); + // 应对bi-focus-shadow在收起时不失焦 + this.element.blur(); + } - adjustHeight: function (e) { - var o = this.options, p = {}; - if (!this.popupView) { - return; - } - var isVisible = this.popupView.isVisible(); - this.popupView.visible(); - var combo = (o.belowMouse && BI.isNotNull(e)) ? { - element: { - 0: BI.extend({}, e.target, { - getBoundingClientRect: function () { - return { - left: e.pageX, - top: e.pageY, - width: 0, - height: 0, - }; - } - }), - offset: function () { - return { - left: e.pageX, - top: e.pageY, - }; - }, - }, - } : this.combo; + this.element.removeClass(this.options.comboClass); + delete needHideWhenAnotherComboOpen[this.getName()]; + delete currentOpenedCombos[this.getName()]; - var positionRelativeElement = BI.DOM.getPositionRelativeContainingBlock( - BI.isNull(o.container) - ? this.element[0] - : BI.isWidget(o.container) - ? o.container.element[0] - : BI.Widget._renderEngine.createElement(BI.isFunction(o.container) ? o.container() : o.container)[0] - ); + hideWhenClickOutside && Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()).unbind("mousewheel." + this.getName()); + BI.EVENT_BLUR && hideWhenBlur && Widget._renderEngine.createElement(window).unbind("blur." + this.getName()); + this.fireEvent(Combo.EVENT_AFTER_HIDEVIEW, e); + } - switch (o.direction) { - case "bottom": - case "bottom,right": - p = BI.DOM.getComboPosition(combo, this.popupView, o.adjustXOffset, (o.adjustYOffset + o.adjustLength) + (o.showArrow ? this._const.TRIANGLE_LENGTH : 0), o.isNeedAdjustHeight, ["bottom", "top", "right", "left"], o.offsetStyle, positionRelativeElement); - break; - case "top": - case "top,right": - p = BI.DOM.getComboPosition(combo, this.popupView, o.adjustXOffset, (o.adjustYOffset + o.adjustLength) + (o.showArrow ? this._const.TRIANGLE_LENGTH : 0), o.isNeedAdjustHeight, ["top", "bottom", "right", "left"], o.offsetStyle, positionRelativeElement); - break; - case "left": - case "left,bottom": - p = BI.DOM.getComboPosition(combo, this.popupView, (o.adjustXOffset + o.adjustLength) + (o.showArrow ? this._const.TRIANGLE_LENGTH : 0), o.adjustYOffset, o.isNeedAdjustHeight, ["left", "right", "bottom", "top"], o.offsetStyle, positionRelativeElement); - break; - case "right": - case "right,bottom": - p = BI.DOM.getComboPosition(combo, this.popupView, (o.adjustXOffset + o.adjustLength) + (o.showArrow ? this._const.TRIANGLE_LENGTH : 0), o.adjustYOffset, o.isNeedAdjustHeight, ["right", "left", "bottom", "top"], o.offsetStyle, positionRelativeElement); - break; - case "top,left": - p = BI.DOM.getComboPosition(combo, this.popupView, o.adjustXOffset, (o.adjustYOffset + o.adjustLength) + (o.showArrow ? this._const.TRIANGLE_LENGTH : 0), o.isNeedAdjustHeight, ["top", "bottom", "left", "right"], o.offsetStyle, positionRelativeElement); - break; - case "bottom,left": - p = BI.DOM.getComboPosition(combo, this.popupView, o.adjustXOffset, (o.adjustYOffset + o.adjustLength) + (o.showArrow ? this._const.TRIANGLE_LENGTH : 0), o.isNeedAdjustHeight, ["bottom", "top", "left", "right"], o.offsetStyle, positionRelativeElement); - break; - case "left,top": - p = BI.DOM.getComboPosition(combo, this.popupView, (o.adjustXOffset + o.adjustLength) + (o.showArrow ? this._const.TRIANGLE_LENGTH : 0), o.adjustYOffset, o.isNeedAdjustHeight, ["left", "right", "top", "bottom"], o.offsetStyle, positionRelativeElement); - break; - case "right,top": - p = BI.DOM.getComboPosition(combo, this.popupView, (o.adjustXOffset + o.adjustLength) + (o.showArrow ? this._const.TRIANGLE_LENGTH : 0), o.adjustYOffset, o.isNeedAdjustHeight, ["right", "left", "top", "bottom"], o.offsetStyle, positionRelativeElement); - break; - case "right,innerRight": - p = BI.DOM.getComboPosition(combo, this.popupView, (o.adjustXOffset + o.adjustLength) + (o.showArrow ? this._const.TRIANGLE_LENGTH : 0), o.adjustYOffset, o.isNeedAdjustHeight, ["right", "left", "innerRight", "innerLeft", "bottom", "top"], o.offsetStyle, positionRelativeElement); - break; - case "right,innerLeft": - p = BI.DOM.getComboPosition(combo, this.popupView, (o.adjustXOffset + o.adjustLength) + (o.showArrow ? this._const.TRIANGLE_LENGTH : 0), o.adjustYOffset, o.isNeedAdjustHeight, ["right", "left", "innerLeft", "innerRight", "bottom", "top"], o.offsetStyle, positionRelativeElement); - break; - case "innerRight": - p = BI.DOM.getComboPosition(combo, this.popupView, (o.adjustXOffset + o.adjustLength) + (o.showArrow ? this._const.TRIANGLE_LENGTH : 0), o.adjustYOffset, o.isNeedAdjustHeight, ["innerRight", "innerLeft", "right", "left", "bottom", "top"], o.offsetStyle, positionRelativeElement); - break; - case "innerLeft": - p = BI.DOM.getComboPosition(combo, this.popupView, (o.adjustXOffset + o.adjustLength) + (o.showArrow ? this._const.TRIANGLE_LENGTH : 0), o.adjustYOffset, o.isNeedAdjustHeight, ["innerLeft", "innerRight", "left", "right", "bottom", "top"], o.offsetStyle, positionRelativeElement); - break; - case "top,custom": - case "custom,top": - p = BI.DOM.getTopAdaptPosition(combo, this.popupView, (o.adjustYOffset + o.adjustLength) + (o.showArrow ? this._const.TRIANGLE_LENGTH : 0), o.isNeedAdjustHeight); - p.dir = "top"; - break; - case "custom,bottom": - case "bottom,custom": - p = BI.DOM.getBottomAdaptPosition(combo, this.popupView, (o.adjustYOffset + o.adjustLength) + (o.showArrow ? this._const.TRIANGLE_LENGTH : 0), o.isNeedAdjustHeight); - p.dir = "bottom"; - break; - case "left,custom": - case "custom,left": - p = BI.DOM.getLeftAdaptPosition(combo, this.popupView, (o.adjustXOffset + o.adjustLength) + (o.showArrow ? this._const.TRIANGLE_LENGTH : 0)); - delete p.top; - delete p.adaptHeight; - p.dir = "left"; - break; - case "custom,right": - case "right,custom": - p = BI.DOM.getRightAdaptPosition(combo, this.popupView, (o.adjustXOffset + o.adjustLength) + (o.showArrow ? this._const.TRIANGLE_LENGTH : 0)); - delete p.top; - delete p.adaptHeight; - p.dir = "right"; - break; - default: - break; + _popupView(e) { + const { hideWhenClickOutside, hideWhenBlur } = this.options; + this._assertPopupViewRender(); + this.fireEvent(Combo.EVENT_BEFORE_POPUPVIEW); + // popupVisible是为了获取其宽高, 放到可视范围之外以防止在IE下闪一下 + this.popupView.css({ left: -99999, top: -99999 }); + this.popupView.visible(); + each(needHideWhenAnotherComboOpen, (i, combo) => { + if (i !== this.getName()) { + if (combo && combo._hideIf(e, true) === true) { + delete needHideWhenAnotherComboOpen[i]; + } } + }); + currentOpenedCombos[this.getName()] = this; + this.options.hideWhenAnotherComboOpen && (needHideWhenAnotherComboOpen[this.getName()] = this); + this.adjustWidth(e); + this.adjustHeight(e); - var width = this.combo.element.outerWidth(); - var height = this.combo.element.outerHeight(); - this.popupView.setDirection && this.popupView.setDirection(p.dir, { - width: width, - height: height, - offsetStyle: o.offsetStyle, - adjustXOffset: o.adjustXOffset, - adjustYOffset: o.adjustYOffset, - offset: this.combo.element.offset(), - }); + this.element.addClass(this.options.comboClass); + hideWhenClickOutside && Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()).unbind("mousewheel." + this.getName()); + hideWhenClickOutside && Widget._renderEngine.createElement(document).unbind("mousewheel." + this.getName()); + BI.EVENT_BLUR && hideWhenBlur && Widget._renderEngine.createElement(window).unbind("blur." + this.getName()); - if (o.supportCSSTransform) { + hideWhenClickOutside && Widget._renderEngine.createElement(document).bind("mousewheel." + this.getName(), bind(this._hideIf, this)); + hideWhenClickOutside && Widget._renderEngine.createElement(document).bind("mousedown." + this.getName(), bind(this._hideIf, this)).bind("mousewheel." + this.getName(), bind(this._hideIf, this)); + BI.EVENT_BLUR && hideWhenBlur && Widget._renderEngine.createElement(window).bind("blur." + this.getName(), bind(this._hideIf, this)); + this.fireEvent(Combo.EVENT_AFTER_POPUPVIEW); + } - var positonedRect = positionRelativeElement.getBoundingClientRect(); + adjustHeight(e) { + const { belowMouse, supportCSSTransform, container, direction, adjustXOffset, adjustYOffset, adjustLength, showArrow, isNeedAdjustHeight, offsetStyle } = this.options; + let p = {}; + if (!this.popupView) { + return; + } + const isVisible = this.popupView.isVisible(); + this.popupView.visible(); + const combo = (belowMouse && isNotNull(e)) ? { + element: { + 0: e.target, + offset: () => { + return { + left: e.pageX, + top: e.pageY, + }; + }, + bounds: () => { + // offset为其相对于父定位元素的偏移 + return { + x: e.offsetX, + y: e.offsetY, + width: 0, + height: 24, + }; + }, + outerWidth: () => { + return 0; + }, + outerHeight: () => { + return 24; + }, + }, + } : this.combo; + const positionRelativeElement = supportCSSTransform ? BI.DOM.getPositionRelativeContainingBlock(isNull(container) ? this.element[0] : Widget._renderEngine.createElement(isFunction(container) ? container() : container)[0]) : null; + const TRIANGLE_LENGTH = 12; + switch (direction) { + case "bottom": + case "bottom,right": + p = BI.DOM.getComboPosition(combo, this.popupView, adjustXOffset, (adjustYOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), isNeedAdjustHeight, ["bottom", "top", "right", "left"], offsetStyle, positionRelativeElement); + break; + case "top": + case "top,right": + p = BI.DOM.getComboPosition(combo, this.popupView, adjustXOffset, (adjustYOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), isNeedAdjustHeight, ["top", "bottom", "right", "left"], offsetStyle, positionRelativeElement); + break; + case "left": + case "left,bottom": + p = BI.DOM.getComboPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), adjustYOffset, isNeedAdjustHeight, ["left", "right", "bottom", "top"], offsetStyle, positionRelativeElement); + break; + case "right": + case "right,bottom": + p = BI.DOM.getComboPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), adjustYOffset, isNeedAdjustHeight, ["right", "left", "bottom", "top"], offsetStyle, positionRelativeElement); + break; + case "top,left": + p = BI.DOM.getComboPosition(combo, this.popupView, adjustXOffset, (adjustYOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), isNeedAdjustHeight, ["top", "bottom", "left", "right"], offsetStyle, positionRelativeElement); + break; + case "bottom,left": + p = BI.DOM.getComboPosition(combo, this.popupView, adjustXOffset, (adjustYOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), isNeedAdjustHeight, ["bottom", "top", "left", "right"], offsetStyle, positionRelativeElement); + break; + case "left,top": + p = BI.DOM.getComboPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), adjustYOffset, isNeedAdjustHeight, ["left", "right", "top", "bottom"], offsetStyle, positionRelativeElement); + break; + case "right,top": + p = BI.DOM.getComboPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), adjustYOffset, isNeedAdjustHeight, ["right", "left", "top", "bottom"], offsetStyle, positionRelativeElement); + break; + case "right,innerRight": + p = BI.DOM.getComboPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), adjustYOffset, isNeedAdjustHeight, ["right", "left", "innerRight", "innerLeft", "bottom", "top"], offsetStyle, positionRelativeElement); + break; + case "right,innerLeft": + p = BI.DOM.getComboPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), adjustYOffset, isNeedAdjustHeight, ["right", "left", "innerLeft", "innerRight", "bottom", "top"], offsetStyle, positionRelativeElement); + break; + case "innerRight": + p = BI.DOM.getComboPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), adjustYOffset, isNeedAdjustHeight, ["innerRight", "innerLeft", "right", "left", "bottom", "top"], offsetStyle, positionRelativeElement); + break; + case "innerLeft": + p = BI.DOM.getComboPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), adjustYOffset, isNeedAdjustHeight, ["innerLeft", "innerRight", "left", "right", "bottom", "top"], offsetStyle, positionRelativeElement); + break; + case "top,custom": + case "custom,top": + p = BI.DOM.getTopAdaptPosition(combo, this.popupView, (adjustYOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), isNeedAdjustHeight); + p.dir = "top"; + break; + case "custom,bottom": + case "bottom,custom": + p = BI.DOM.getBottomAdaptPosition(combo, this.popupView, (adjustYOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), isNeedAdjustHeight); + p.dir = "bottom"; + break; + case "left,custom": + case "custom,left": + p = BI.DOM.getLeftAdaptPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0)); + delete p.top; + delete p.adaptHeight; + p.dir = "left"; + break; + case "custom,right": + case "right,custom": + p = BI.DOM.getRightAdaptPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0)); + delete p.top; + delete p.adaptHeight; + p.dir = "right"; + break; + default: + break; + } - var scaleX = positonedRect.width / positionRelativeElement.offsetWidth; - var scaleY = positonedRect.height / positionRelativeElement.offsetHeight; + if ("adaptHeight" in p) { + this.resetListHeight(p.adaptHeight); + } - p.top && (p.top = Math.round(p.top / scaleY + positionRelativeElement.scrollTop)); - p.left && (p.left = Math.round(p.left / scaleX + positionRelativeElement.scrollLeft)); + const width = this.combo.element.outerWidth(); + const height = this.combo.element.outerHeight(); + this.popupView.setDirection && this.popupView.setDirection(p.dir, { + width, + height, + offsetStyle, + adjustXOffset, + adjustYOffset, + offset: this.combo.element.offset(), + }); - p.adaptHeight && (p.adaptHeight = Math.round(p.adaptHeight / scaleY)); - } + if (supportCSSTransform) { - if ("adaptHeight" in p) { - this.resetListHeight(p.adaptHeight); - } + const positonedRect = positionRelativeElement.getBoundingClientRect(); - if ("left" in p) { - this.popupView.element.css({ - left: p.left, - }); - } - if ("top" in p) { - this.popupView.element.css({ - top: p.top, - }); - } - this.position = p; - this.popupView.setVisible(isVisible); - }, + const scaleX = positonedRect.width / positionRelativeElement.offsetWidth; + const scaleY = positonedRect.height / positionRelativeElement.offsetHeight; - destroyed: function () { - BI.Widget._renderEngine.createElement(document) - .unbind("click." + this.getName()) - .unbind("mousedown." + this.getName()) - .unbind("mousewheel." + this.getName()) - .unbind("mouseenter." + this.getName()) - .unbind("mouseleave." + this.getName()); - BI.Widget._renderEngine.createElement(window) - .unbind("blur." + this.getName()); - BI.Resizers.remove(this.getName()); - this.popupView && this.popupView._destroy(); - delete needHideWhenAnotherComboOpen[this.getName()]; - delete currentOpenedCombos[this.getName()]; - }, - }); - BI.Combo.closeAll = function () { - BI.each(currentOpenedCombos, function (i, combo) { - if (combo) { - combo.hideView(); - } - }); - currentOpenedCombos = {}; - needHideWhenAnotherComboOpen = {}; - }; - BI.Combo.EVENT_TRIGGER_CHANGE = "EVENT_TRIGGER_CHANGE"; - BI.Combo.EVENT_CHANGE = "EVENT_CHANGE"; - BI.Combo.EVENT_EXPAND = "EVENT_EXPAND"; - BI.Combo.EVENT_COLLAPSE = "EVENT_COLLAPSE"; - BI.Combo.EVENT_AFTER_INIT = "EVENT_AFTER_INIT"; + p.top && (p.top = p.top / scaleY); + p.left && (p.left = p.left / scaleX); + } + if ("left" in p) { + this.popupView.element.css({ + left: p.left, + }); + } + if ("top" in p) { + this.popupView.element.css({ + top: p.top, + }); + } + this.position = p; + this.popupView.setVisible(isVisible); + } - BI.Combo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; - BI.Combo.EVENT_AFTER_POPUPVIEW = "EVENT_AFTER_POPUPVIEW"; - BI.Combo.EVENT_BEFORE_HIDEVIEW = "EVENT_BEFORE_HIDEVIEW"; - BI.Combo.EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; + destroyed() { + Widget._renderEngine.createElement(document) + .unbind("click." + this.getName()) + .unbind("mousedown." + this.getName()) + .unbind("mousewheel." + this.getName()) + .unbind("mouseenter." + this.getName()) + .unbind("mouseleave." + this.getName()); + Widget._renderEngine.createElement(window) + .unbind("blur." + this.getName()); + Resizers.remove(this.getName()); + this.popupView && this.popupView._destroy(); + delete needHideWhenAnotherComboOpen[this.getName()]; + delete currentOpenedCombos[this.getName()]; + } +} - BI.shortcut("bi.combo", BI.Combo); -}()); +Combo.closeAll = () => { + each(currentOpenedCombos, (i, combo) => { + if (combo) { + combo.hideView(); + } + }); + currentOpenedCombos = {}; + needHideWhenAnotherComboOpen = {}; +}; diff --git a/src/base/combination/expander.js b/src/base/combination/expander.js index 60b3dd471..3c7e9f8cb 100644 --- a/src/base/combination/expander.js +++ b/src/base/combination/expander.js @@ -6,9 +6,25 @@ * @class BI.Expander * @extends BI.Widget */ -BI.Expander = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.Expander.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, Widget, Controller, extend, nextTick, each, debounce, isNull, createWidget } from "../../core"; + +@shortcut() +export default class Expander extends Widget { + static xtype = "bi.expander"; + + static EVENT_EXPAND = "EVENT_EXPAND"; + static EVENT_COLLAPSE = "EVENT_COLLAPSE"; + static EVENT_TRIGGER_CHANGE = "EVENT_TRIGGER_CHANGE"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_AFTER_INIT = "EVENT_AFTER_INIT"; + + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + static EVENT_AFTER_POPUPVIEW = "EVENT_AFTER_POPUPVIEW"; + static EVENT_BEFORE_HIDEVIEW = "EVENT_BEFORE_HIDEVIEW"; + static EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { baseCls: "bi-expander", trigger: "click", toggle: true, @@ -19,48 +35,48 @@ BI.Expander = BI.inherit(BI.Widget, { expanderClass: "bi-expander-popup", hoverClass: "bi-expander-hover", }); - }, + } - render: function () { - var self = this, o = this.options; - this._expanded = !!o.el.open; + render() { + const { el, hoverClass, isDefaultInit } = this.options; + this._expanded = !!el.open; this._initExpander(); // 延迟绑定事件,这样可以将自己绑定的事情优先执行 - BI.nextTick(() => { + nextTick(() => { !this.isDestroyed() && this._initPullDownAction(); }); - this.expander.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - if (self.isEnabled() && self.isValid()) { + this.expander.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { + if (this.isEnabled() && this.isValid()) { if (type === BI.Events.EXPAND) { - self._popupView(); + this._popupView(); } if (type === BI.Events.COLLAPSE) { - self._hideView(); + this._hideView(); } if (type === BI.Events.EXPAND) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - self.fireEvent(BI.Expander.EVENT_EXPAND); + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); + this.fireEvent(Expander.EVENT_EXPAND); } if (type === BI.Events.COLLAPSE) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - self.isViewVisible() && self.fireEvent(BI.Expander.EVENT_COLLAPSE); + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); + this.isViewVisible() && this.fireEvent(Expander.EVENT_COLLAPSE); } if (type === BI.Events.CLICK) { - self.fireEvent(BI.Expander.EVENT_TRIGGER_CHANGE, value, obj); + this.fireEvent(Expander.EVENT_TRIGGER_CHANGE, value, obj); } } }); - this.element.hover(function () { - if (self.isEnabled() && self.isValid() && self.expander.isEnabled() && self.expander.isValid()) { - self.element.addClass(o.hoverClass); + this.element.hover(() => { + if (this.isEnabled() && this.isValid() && this.expander.isEnabled() && this.expander.isValid()) { + this.element.addClass(hoverClass); } - }, function () { - if (self.isEnabled() && self.isValid() && self.expander.isEnabled() && self.expander.isValid()) { - self.element.removeClass(o.hoverClass); + }, () => { + if (this.isEnabled() && this.isValid() && this.expander.isEnabled() && this.expander.isValid()) { + this.element.removeClass(hoverClass); } }); - BI.createWidget({ + createWidget({ type: "bi.vertical", scrolly: false, element: this, @@ -68,13 +84,13 @@ BI.Expander = BI.inherit(BI.Widget, { { el: this.expander } ], }); - o.isDefaultInit && this._assertPopupView(); + isDefaultInit && this._assertPopupView(); if (this.expander.isOpened() === true) { this._popupView(); } - }, + } - _toggle: function () { + _toggle() { this._assertPopupViewRender(); if (this.popupView.isVisible()) { this._hideView(); @@ -83,40 +99,40 @@ BI.Expander = BI.inherit(BI.Widget, { this._popupView(); } } - }, + } - _initPullDownAction: function () { - var self = this, o = this.options; - var evs = this.options.trigger.split(","); - BI.each(evs, function (i, e) { + _initPullDownAction() { + const { toggle } = this.options; + const evs = this.options.trigger.split(","); + each(evs, (i, e) => { switch (e) { case "hover": - self.element[e](function (e) { - if (self.isEnabled() && self.isValid() && self.expander.isEnabled() && self.expander.isValid()) { - self._popupView(); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.expander); - self.fireEvent(BI.Expander.EVENT_EXPAND); + this.element[e]((e) => { + if (this.isEnabled() && this.isValid() && this.expander.isEnabled() && this.expander.isValid()) { + this._popupView(); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.expander); + this.fireEvent(Expander.EVENT_EXPAND); } - }, function () { - if (self.isEnabled() && self.isValid() && self.expander.isEnabled() && self.expander.isValid() && o.toggle) { - self._hideView(); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.expander); - self.fireEvent(BI.Expander.EVENT_COLLAPSE); + }, () => { + if (this.isEnabled() && this.isValid() && this.expander.isEnabled() && this.expander.isValid() && toggle) { + this._hideView(); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", this.expander); + this.fireEvent(Expander.EVENT_COLLAPSE); } }); break; case "click": if (e) { - self.element.off(e + "." + self.getName()).on(e + "." + self.getName(), BI.debounce(function (e) { - if (self.expander.element.__isMouseInBounds__(e)) { - if (self.isEnabled() && self.isValid() && self.expander.isEnabled() && self.expander.isValid()) { - o.toggle ? self._toggle() : self._popupView(); - if (self.isExpanded()) { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.expander); - self.fireEvent(BI.Expander.EVENT_EXPAND); + this.element.off(e + "." + this.getName()).on(e + "." + this.getName(), debounce((e) => { + if (this.expander.element.__isMouseInBounds__(e)) { + if (this.isEnabled() && this.isValid() && this.expander.isEnabled() && this.expander.isValid()) { + toggle ? this._toggle() : this._popupView(); + if (this.isExpanded()) { + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.expander); + this.fireEvent(Expander.EVENT_EXPAND); } else { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.expander); - self.fireEvent(BI.Expander.EVENT_COLLAPSE); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", this.expander); + this.fireEvent(Expander.EVENT_COLLAPSE); } } } @@ -130,16 +146,16 @@ BI.Expander = BI.inherit(BI.Widget, { break; } }); - }, + } - _initExpander: function () { - this.expander = BI.createWidget(this.options.el); - }, + _initExpander() { + this.expander = createWidget(this.options.el); + } - _assertPopupView: function () { - var self = this, o = this.options; - if (BI.isNull(this.popupView)) { - this.popupView = BI.createWidget(this.options.popup, { + _assertPopupView() { + const { value } = this.options; + if (isNull(this.popupView)) { + this.popupView = createWidget(this.options.popup, { type: "bi.button_group", cls: "expander-popup", layouts: [{ @@ -147,26 +163,26 @@ BI.Expander = BI.inherit(BI.Widget, { hgap: 0, vgap: 0, }], - value: o.value, + value, }, this); - this.popupView.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.popupView.on(Controller.EVENT_CHANGE, (type, value, obj, ...args)=> { + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); if (type === BI.Events.CLICK) { // self.setValue(self.getValue()); - self.fireEvent(BI.Expander.EVENT_CHANGE, value, obj); + this.fireEvent(Expander.EVENT_CHANGE, value, obj); } }); this.popupView.setVisible(this.isExpanded()); - BI.nextTick(function () { - self.fireEvent(BI.Expander.EVENT_AFTER_INIT); + nextTick(() => { + this.fireEvent(Expander.EVENT_AFTER_INIT); }); } - }, + } - _assertPopupViewRender: function () { + _assertPopupViewRender() { this._assertPopupView(); if (!this._rendered) { - BI.createWidget({ + createWidget({ type: "bi.vertical", scrolly: false, element: this, @@ -176,113 +192,100 @@ BI.Expander = BI.inherit(BI.Widget, { }); this._rendered = true; } - }, + } - _hideView: function () { - this.fireEvent(BI.Expander.EVENT_BEFORE_HIDEVIEW); + _hideView() { + this.fireEvent(Expander.EVENT_BEFORE_HIDEVIEW); this._expanded = false; this.expander.setOpened(false); this.popupView && this.popupView.invisible(); this.element.removeClass(this.options.expanderClass); - this.fireEvent(BI.Expander.EVENT_AFTER_HIDEVIEW); - }, + this.fireEvent(Expander.EVENT_AFTER_HIDEVIEW); + } - _popupView: function () { + _popupView() { this._assertPopupViewRender(); - this.fireEvent(BI.Expander.EVENT_BEFORE_POPUPVIEW); + this.fireEvent(Expander.EVENT_BEFORE_POPUPVIEW); this._expanded = true; this.expander.setOpened(true); this.popupView.visible(); this.element.addClass(this.options.expanderClass); - this.fireEvent(BI.Expander.EVENT_AFTER_POPUPVIEW); - }, + this.fireEvent(Expander.EVENT_AFTER_POPUPVIEW); + } - populate: function (items) { + populate(items) { // this._assertPopupView(); this.popupView && this.popupView.populate.apply(this.popupView, arguments); this.expander.populate && this.expander.populate.apply(this.expander, arguments); - }, + } - _setEnable: function (arg) { - BI.Expander.superclass._setEnable.apply(this, arguments); + _setEnable(arg) { + super._setEnable(arguments); !arg && this.element.removeClass(this.options.hoverClass); !arg && this.isViewVisible() && this._hideView(); - }, + } - setValue: function (v) { + setValue(v) { this.expander.setValue(v); - if (BI.isNull(this.popupView)) { + if (isNull(this.popupView)) { this.options.popup.value = v; } else { this.popupView.setValue(v); } - }, + } - getValue: function () { - if (BI.isNull(this.popupView)) { + getValue() { + if (isNull(this.popupView)) { return this.options.popup.value; } else { return this.popupView.getValue(); } - }, + } - isViewVisible: function () { + isViewVisible() { return this.isEnabled() && this.expander.isEnabled() && !!this.popupView && this.popupView.isVisible(); - }, + } - isExpanded: function () { + isExpanded() { return this._expanded; - }, + } - showView: function () { + showView() { if (this.isEnabled() && this.expander.isEnabled()) { this._popupView(); } - }, + } - hideView: function () { + hideView() { this._hideView(); - }, + } - getView: function () { + getView() { return this.popupView; - }, + } - getAllLeaves: function () { + getAllLeaves() { return this.popupView && this.popupView.getAllLeaves(); - }, + } - getNodeById: function (id) { + getNodeById(id) { if (this.expander.options.id === id) { return this.expander; } return this.popupView && this.popupView.getNodeById(id); - }, + } - getNodeByValue: function (value) { + getNodeByValue(value) { if (this.expander.getValue() === value) { return this.expander; } return this.popupView && this.popupView.getNodeByValue(value); - }, - - destroy: function () { - BI.Expander.superclass.destroy.apply(this, arguments); - }, -}); -BI.Expander.EVENT_EXPAND = "EVENT_EXPAND"; -BI.Expander.EVENT_COLLAPSE = "EVENT_COLLAPSE"; -BI.Expander.EVENT_TRIGGER_CHANGE = "EVENT_TRIGGER_CHANGE"; -BI.Expander.EVENT_CHANGE = "EVENT_CHANGE"; -BI.Expander.EVENT_AFTER_INIT = "EVENT_AFTER_INIT"; - - -BI.Expander.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.Expander.EVENT_AFTER_POPUPVIEW = "EVENT_AFTER_POPUPVIEW"; -BI.Expander.EVENT_BEFORE_HIDEVIEW = "EVENT_BEFORE_HIDEVIEW"; -BI.Expander.EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; + } -BI.shortcut("bi.expander", BI.Expander); + destroy() { + super.destroy(arguments); + } +} diff --git a/src/base/combination/group.button.js b/src/base/combination/group.button.js index 02b044b17..22c110720 100644 --- a/src/base/combination/group.button.js +++ b/src/base/combination/group.button.js @@ -3,10 +3,16 @@ * @class BI.ButtonGroup * @extends BI.Widget */ +import { shortcut, Widget, Controller, extend, createWidget, createWidgets, each, isFunction, isKey, isNotEmptyArray, createItems, isArray, remove, map, stripEL, makeArrayByArray, clone, deepClone, formatEL, isEmpty, concat, removeAt, deepContains, has, any } from "../../core"; -BI.ButtonGroup = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.ButtonGroup.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export default class ButtonGroup extends Widget { + static xtype = "bi.button_group"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { baseCls: "bi-button-group", behaviors: {}, items: [], @@ -18,83 +24,84 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { vgap: 0, }], }); - }, + } - render: function () { - var self = this, o = this.options; - var behaviors = {}; - BI.each(o.behaviors, function (key, rule) { + render() { + const { behaviors: optionsBehaviors, items: optionsItems, value } = this.options; + const behaviors = {}; + each(optionsBehaviors, (key, rule) => { behaviors[key] = BI.BehaviorFactory.createBehavior(key, { rule: rule, }); }); this.behaviors = behaviors; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); - }) : o.items; + const items = isFunction(optionsItems) ? this.__watch(optionsItems, (context, newValue) => { + this.populate(newValue); + }) : optionsItems; this.populate(items); - o.value = BI.isFunction(o.value) ? this.__watch(o.value, function (context, newValue) { - self.setValue(newValue); - }) : o.value; - if (BI.isKey(o.value) || BI.isNotEmptyArray(o.value)) { - this.setValue(o.value); + this.options.value = isFunction(value) ? this.__watch(value, (context, newValue) => { + this.setValue(newValue); + }) : value; + if (isKey(value) || isNotEmptyArray(value)) { + this.setValue(value); } - }, + } - _createBtns: function (items) { - var btns; - BI.Widget.execWithContext(this, function () { - btns = BI.createWidgets(BI.createItems(items, { + _createBtns(items) { + let btns; + Widget.execWithContext(this, () => { + btns = createWidgets(createItems(items, { type: "bi.text_button", })); }); return btns; - }, + } - _btnsCreator: function (items) { - var self = this, args = Array.prototype.slice.call(arguments), o = this.options; - var buttons = this._createBtns(items); + _btnsCreator(items) { + const args = Array.prototype.slice.call(arguments); + const { chooseType } = this.options; + const buttons = this._createBtns(items); args[0] = buttons; - BI.each(this.behaviors, function (i, behavior) { + each(this.behaviors, (i, behavior) => { behavior.doBehavior.apply(behavior, args); }); - BI.each(buttons, function (i, btn) { - btn.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { + each(buttons, (i, btn) => { + btn.on(Controller.EVENT_CHANGE, (type, value, obj, ...arg) => { if (type === BI.Events.CLICK) { - switch (o.chooseType) { - case BI.ButtonGroup.CHOOSE_TYPE_SINGLE: - self.setValue(btn.getValue()); + switch (chooseType) { + case ButtonGroup.CHOOSE_TYPE_SINGLE: + this.setValue(btn.getValue()); break; - case BI.ButtonGroup.CHOOSE_TYPE_NONE: - self.setValue([]); + case ButtonGroup.CHOOSE_TYPE_NONE: + this.setValue([]); break; default: break; } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - self.fireEvent(BI.ButtonGroup.EVENT_CHANGE, value, obj); + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...arg); + this.fireEvent(ButtonGroup.EVENT_CHANGE, value, obj); } else { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...arg); } }); - btn.on(BI.Events.DESTROY, function () { - BI.remove(self.buttons, btn); + btn.on(BI.Events.DESTROY, () => { + remove(this.buttons, btn); }); }); return buttons; - }, - - _packageBtns: function (btns) { - var o = this.options; - var layouts = BI.isArray(o.layouts) ? o.layouts : [o.layouts]; - for (var i = layouts.length - 1; i > 0; i--) { - btns = BI.map(btns, function (k, it) { - return BI.extend({}, layouts[i], { + } + + _packageBtns(btns) { + const { layouts: optionsLayouts } = this.options; + const layouts = isArray(optionsLayouts) ? optionsLayouts : [optionsLayouts]; + for (let i = layouts.length - 1; i > 0; i--) { + btns = map(btns, (k, it) => { + return extend({}, layouts[i], { items: [ - BI.extend({}, layouts[i].el, { + extend({}, layouts[i].el, { el: it, }) ], @@ -103,56 +110,57 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { } return btns; - }, + } - _packageSimpleItems: function (btns) { - var o = this.options; + _packageSimpleItems(btns) { + const { items } = this.options; - return BI.map(o.items, function (i, item) { - if (BI.stripEL(item) === item) { + return map(items, (i, item) => { + if (stripEL(item) === item) { return btns[i]; } - return BI.extend({}, item, { + return extend({}, item, { el: btns[i], }); }); - }, + } - _packageItems: function (items, packBtns) { - return BI.createItems(BI.makeArrayByArray(items, {}), BI.clone(packBtns)); - }, + _packageItems(items, packBtns) { + return createItems(makeArrayByArray(items, {}), clone(packBtns)); + } - _packageLayout: function (items) { - var o = this.options, layout = BI.deepClone(BI.isArray(o.layouts) ? o.layouts[0] : o.layouts); + _packageLayout(items) { + const { layouts } = this.options; + const layout = deepClone(isArray(layouts) ? layouts[0] : layouts); - var lay = BI.formatEL(layout).el; - while (lay && lay.items && !BI.isEmpty(lay.items)) { - lay = BI.formatEL(lay.items[0]).el; + let lay = formatEL(layout).el; + while (lay && lay.items && !isEmpty(lay.items)) { + lay = formatEL(lay.items[0]).el; } lay.items = items; return layout; - }, + } // 如果是一个简单的layout - _isSimpleLayout: function () { - var o = this.options; + _isSimpleLayout() { + const { layouts, items } = this.options; - return BI.isArray(o.layouts) ? (o.layouts.length === 1 && !BI.isArray(o.items[0])) : true; - }, + return isArray(layouts) ? (layouts.length === 1 && !isArray(items[0])) : true; + } - doBehavior: function () { - var args = Array.prototype.slice.call(arguments); + doBehavior() { + const args = Array.prototype.slice.call(arguments); args.unshift(this.buttons); - BI.each(this.behaviors, function (i, behavior) { + each(this.behaviors, (i, behavior) => { behavior.doBehavior.apply(behavior, args); }); - }, + } - prependItems: function (items) { - var btns = this._btnsCreator.apply(this, arguments); - this.buttons = BI.concat(btns, this.buttons); + prependItems(items) { + const btns = this._btnsCreator.apply(this, arguments); + this.buttons = concat(btns, this.buttons); if (this._isSimpleLayout() && this.layouts && this.layouts.prependItems) { this.layouts.prependItems(btns); @@ -162,11 +170,11 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { items = this._packageItems(items, this._packageBtns(btns)); this.layouts.prependItems(this._packageLayout(items).items); - }, + } - addItems: function (items) { - var btns = this._btnsCreator.apply(this, arguments); - this.buttons = BI.concat(this.buttons, btns); + addItems(items) { + const btns = this._btnsCreator.apply(this, arguments); + this.buttons = concat(this.buttons, btns); // 如果是一个简单的layout if (this._isSimpleLayout() && this.layouts && this.layouts.addItems) { @@ -177,26 +185,26 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { items = this._packageItems(items, this._packageBtns(btns)); this.layouts.addItems(this._packageLayout(items).items); - }, + } - removeItemAt: function (indexes) { - BI.removeAt(this.buttons, indexes); + removeItemAt(indexes) { + removeAt(this.buttons, indexes); this.layouts.removeItemAt(indexes); - }, + } - removeItems: function (values) { - values = BI.isArray(values) ? values : [values]; - var deleted = []; - BI.each(this.buttons, function (i, button) { - if (BI.deepContains(values, button.getValue())) { + removeItems(values) { + values = isArray(values) ? values : [values]; + const deleted = []; + each(this.buttons, (i, button) => { + if (deepContains(values, button.getValue())) { deleted.push(i); } }); - BI.removeAt(this.buttons, deleted); + removeAt(this.buttons, deleted); this.layouts.removeItemAt(deleted); - }, + } - populate: function (items) { + populate(items) { items = items || []; this.empty(); this.options.items = items; @@ -208,114 +216,114 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { items = this._packageItems(items, this._packageBtns(this.buttons)); } - this.layouts = BI.createWidget(BI.extend({ element: this }, this._packageLayout(items))); - }, + this.layouts = createWidget(extend({ element: this }, this._packageLayout(items))); + } - setNotSelectedValue: function (v) { - v = BI.isArray(v) ? v : [v]; - BI.each(this.buttons, function (i, item) { - if (BI.deepContains(v, item.getValue())) { + setNotSelectedValue(v) { + v = isArray(v) ? v : [v]; + each(this.buttons, (i, item) => { + if (deepContains(v, item.getValue())) { item.setSelected && item.setSelected(false); } else { item.setSelected && item.setSelected(true); } }); - }, + } - setEnabledValue: function (v) { - v = BI.isArray(v) ? v : [v]; - BI.each(this.buttons, function (i, item) { - if (BI.deepContains(v, item.getValue())) { + setEnabledValue(v) { + v = isArray(v) ? v : [v]; + each(this.buttons, (i, item) => { + if (deepContains(v, item.getValue())) { item.setEnable(true); } else { item.setEnable(false); } }); - }, + } - setValue: function (v) { - v = BI.isArray(v) ? v : [v]; - BI.each(this.buttons, function (i, item) { - if (BI.deepContains(v, item.getValue())) { + setValue(v) { + v = isArray(v) ? v : [v]; + each(this.buttons, (i, item) => { + if (deepContains(v, item.getValue())) { item.setSelected && item.setSelected(true); } else { item.setSelected && item.setSelected(false); } }); - }, + } - setValueMap: function (map) { + setValueMap(map) { map = map || {}; - BI.each(this.buttons, function (i, item) { - if (BI.has(map, item.getValue())) { + each(this.buttons, (i, item) => { + if (has(map, item.getValue())) { item.setSelected && item.setSelected(true); } else { item.setSelected && item.setSelected(false); } }); - }, + } - setAllSelected: function (v) { - BI.each(this.getAllButtons(), function (i, btn) { + setAllSelected(v) { + each(this.getAllButtons(), (i, btn) => { (btn.setSelected || btn.setAllSelected).apply(btn, [v]); }); - }, + } - getNotSelectedValue: function () { - var v = []; - BI.each(this.buttons, function (i, item) { + getNotSelectedValue() { + const v = []; + each(this.buttons, (i, item) => { if (item.isEnabled() && !(item.isSelected && item.isSelected())) { v.push(item.getValue()); } }); return v; - }, + } - getValue: function () { - var v = []; - BI.each(this.buttons, function (i, item) { + getValue() { + const v = []; + each(this.buttons, (i, item) => { if (item.isEnabled() && item.isSelected && item.isSelected()) { v.push(item.getValue()); } }); return v; - }, + } - getAllButtons: function () { + getAllButtons() { return this.buttons; - }, + } - getAllLeaves: function () { + getAllLeaves() { return this.buttons; - }, + } - getSelectedButtons: function () { - var btns = []; - BI.each(this.buttons, function (i, item) { + getSelectedButtons() { + const btns = []; + each(this.buttons, (i, item) => { if (item.isSelected && item.isSelected()) { btns.push(item); } }); return btns; - }, + } - getNotSelectedButtons: function () { - var btns = []; - BI.each(this.buttons, function (i, item) { + getNotSelectedButtons() { + const btns = []; + each(this.buttons, (i, item) => { if (item.isSelected && !item.isSelected()) { btns.push(item); } }); return btns; - }, + } - getIndexByValue: function (value) { - var index = -1; - BI.any(this.buttons, function (i, item) { + getIndexByValue(value) { + let index = -1; + any(this.buttons, (i, item) => { if (item.isEnabled() && item.getValue() === value) { index = i; @@ -324,11 +332,11 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { }); return index; - }, + } - getNodeById: function (id) { - var node; - BI.any(this.buttons, function (i, item) { + getNodeById(id) { + let node; + any(this.buttons, (i, item) => { if (item.isEnabled() && item.options.id === id) { node = item; @@ -337,11 +345,11 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { }); return node; - }, + } - getNodeByValue: function (value) { - var node; - BI.any(this.buttons, function (i, item) { + getNodeByValue(value) { + let node; + any(this.buttons, (i, item) => { if (item.isEnabled() && item.getValue() === value) { node = item; @@ -350,35 +358,33 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { }); return node; - }, + } /** * 滚动到指定的节点 */ - scrollToValue: function (value, scrollIntoViewOptions) { - var node = this.getNodeByValue(value); + scrollToValue(value, scrollIntoViewOptions) { + const node = this.getNodeByValue(value); if (node) { node.element[0].scrollIntoView(scrollIntoViewOptions); } - }, + } - empty: function () { - BI.ButtonGroup.superclass.empty.apply(this, arguments); + empty() { + super.empty(arguments); this.options.items = []; - }, + } - destroy: function () { - BI.ButtonGroup.superclass.destroy.apply(this, arguments); + destroy() { + super.destroy(arguments); this.options.items = []; - }, -}); -BI.extend(BI.ButtonGroup, { + } +} + +extend(ButtonGroup, { CHOOSE_TYPE_SINGLE: BI.Selection.Single, CHOOSE_TYPE_MULTI: BI.Selection.Multi, CHOOSE_TYPE_ALL: BI.Selection.All, CHOOSE_TYPE_NONE: BI.Selection.None, CHOOSE_TYPE_DEFAULT: BI.Selection.Default, }); -BI.ButtonGroup.EVENT_CHANGE = "EVENT_CHANGE"; - -BI.shortcut("bi.button_group", BI.ButtonGroup); diff --git a/src/base/combination/group.combo.js b/src/base/combination/group.combo.js index 2f8b0c72e..97882f40f 100644 --- a/src/base/combination/group.combo.js +++ b/src/base/combination/group.combo.js @@ -2,9 +2,16 @@ * Created by GUY on 2015/8/10. */ -BI.ComboGroup = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.ComboGroup.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, Widget, Controller, extend, isEmpty, each, formatEL, clone, createWidget } from "../../core"; + +@shortcut() +export default class ComboGroup extends Widget { + static xtype = "bi.combo_group"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { baseCls: "bi-combo-group bi-list-item", // 以下这些属性对每一个combo都是公用的 @@ -28,69 +35,66 @@ BI.ComboGroup = BI.inherit(BI.Widget, { }, }, }); - }, + } - render: function () { + render() { this._populate(this.options.el); - }, + } - _populate: function (item) { - var self = this, o = this.options; - var children = o.items; - if (BI.isEmpty(children)) { + _populate(item) { + const { items, action, height, direction, isDefaultInit, isNeedAdjustHeight, isNeedAdjustWidth, adjustLength, popup, container, trigger } = this.options; + const children = items; + if (isEmpty(children)) { throw new Error("ComboGroup构造错误"); } - BI.each(children, function (i, ch) { - var son = BI.formatEL(ch).el.children; - ch = BI.formatEL(ch).el; - if (!BI.isEmpty(son)) { - ch.el = BI.clone(ch); + each(children, (i, ch) => { + const son = formatEL(ch).el.children; + ch = formatEL(ch).el; + if (!isEmpty(son)) { + ch.el = clone(ch); ch.items = son; ch.type = "bi.combo_group"; - ch.action = o.action; - ch.height = o.height; - ch.direction = o.direction; - ch.isDefaultInit = o.isDefaultInit; - ch.isNeedAdjustHeight = o.isNeedAdjustHeight; - ch.isNeedAdjustWidth = o.isNeedAdjustWidth; - ch.adjustLength = o.adjustLength; - ch.popup = o.popup; + ch.action = action; + ch.height = height; + ch.direction = direction; + ch.isDefaultInit = isDefaultInit; + ch.isNeedAdjustHeight = isNeedAdjustHeight; + ch.isNeedAdjustWidth = isNeedAdjustWidth; + ch.adjustLength = adjustLength; + ch.popup = popup; } }); - this.combo = BI.createWidget({ + this.combo = createWidget({ type: "bi.combo", element: this, - container: o.container, - height: o.height, - trigger: o.trigger, - direction: o.direction, - isDefaultInit: o.isDefaultInit, - isNeedAdjustWidth: o.isNeedAdjustWidth, - isNeedAdjustHeight: o.isNeedAdjustHeight, - adjustLength: o.adjustLength, + container, + height, + trigger, + direction, + isDefaultInit, + isNeedAdjustWidth, + isNeedAdjustHeight, + adjustLength, el: item, - popup: BI.extend({}, o.popup, { - el: BI.extend({ + popup: extend({}, popup, { + el: extend({ items: children, - }, o.popup.el), + }, popup.el), }), }); - this.combo.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.combo.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); if (type === BI.Events.CLICK) { - self.fireEvent(BI.ComboGroup.EVENT_CHANGE, obj); + this.fireEvent(ComboGroup.EVENT_CHANGE, obj); } }); - }, + } - getValue: function () { + getValue() { return this.combo.getValue(); - }, + } - setValue: function (v) { + setValue(v) { this.combo.setValue(v); - }, -}); -BI.ComboGroup.EVENT_CHANGE = "EVENT_CHANGE"; - -BI.shortcut("bi.combo_group", BI.ComboGroup); + } +} diff --git a/src/base/combination/group.virtual.js b/src/base/combination/group.virtual.js index 40e7c09f4..f757c4b4e 100644 --- a/src/base/combination/group.virtual.js +++ b/src/base/combination/group.virtual.js @@ -1,6 +1,13 @@ -BI.VirtualGroup = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.VirtualGroup.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, Widget, Controller, extend, isFunction, isKey, isArray, map, stripEL, deepClone, formatEL, isEmpty, each, createWidget } from "../../core"; + +@shortcut() +export default class VirtualGroup extends Widget { + static xtype = "bi.virtual_group"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { baseCls: "bi-virtual-group", items: [], layouts: [{ @@ -9,36 +16,36 @@ BI.VirtualGroup = BI.inherit(BI.Widget, { vgap: 0, }], }); - }, + } - render: function () { - var self = this, o = this.options; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); - }) : o.items; + render() { + const { items: optionsItems, value } = this.options; + const items = isFunction(optionsItems) ? this.__watch(optionsItems, (context, newValue) => { + this.populate(newValue); + }) : optionsItems; this.populate(items); - o.value = BI.isFunction(o.value) ? this.__watch(o.value, function (context, newValue) { - self.setValue(newValue); - }) : o.value; - if (BI.isKey(o.value)) { - this.setValue(o.value); + this.options.value = isFunction(value) ? this.__watch(value, (context, newValue) => { + this.setValue(newValue); + }) : value; + if (isKey(value)) { + this.setValue(value); } - }, + } - _packageBtns: function (items) { - var o = this.options; - var map = this.buttonMap = {}; - var layouts = BI.isArray(o.layouts) ? o.layouts : [o.layouts]; + _packageBtns(items) { + const o = this.options; + const map = this.buttonMap = {}; + const layouts = isArray(o.layouts) ? o.layouts : [o.layouts]; for (let i = layouts.length - 1; i > 0; i--) { - items = BI.map(items, function (k, it) { - var el = BI.stripEL(it); + items = map(items, (k, it) => { + const el = stripEL(it); - return BI.extend({}, layouts[i], { + return extend({}, layouts[i], { items: [ - BI.extend({}, layouts[i].el, { - el: BI.extend({ - ref: function (_ref) { - if (BI.isKey(map[el.value])) { + extend({}, layouts[i].el, { + el: extend({ + ref: (_ref) => { + if (isKey(map[el.value])) { map[el.value] = _ref; } }, @@ -50,33 +57,33 @@ BI.VirtualGroup = BI.inherit(BI.Widget, { } return items; - }, + } - _packageLayout: function (items) { - var o = this.options; - var layouts = BI.isArray(o.layouts) ? o.layouts : [o.layouts]; - var layout = BI.deepClone(layouts[0]); + _packageLayout(items) { + const o = this.options; + const layouts = isArray(o.layouts) ? o.layouts : [o.layouts]; + const layout = deepClone(layouts[0]); - var lay = BI.formatEL(layout).el; - while (lay && lay.items && !BI.isEmpty(lay.items)) { - lay = BI.formatEL(lay.items[0]).el; + let lay = formatEL(layout).el; + while (lay && lay.items && !isEmpty(lay.items)) { + lay = formatEL(lay.items[0]).el; } lay.items = items; return layout; - }, + } - addItems: function (items) { + addItems(items) { this.layouts.addItems(items, this); - }, + } - prependItems: function (items) { + prependItems(items) { this.layouts.prependItems(items, this); - }, + } - setValue: function (v) { - v = BI.isArray(v) ? v : [v]; - BI.each(this.buttonMap, function (key, item) { + setValue(v) { + v = isArray(v) ? v : [v]; + each(this.buttonMap, (key, item) => { if (item) { if (v.deepContains(key)) { item.setSelected && item.setSelected(true); @@ -85,11 +92,11 @@ BI.VirtualGroup = BI.inherit(BI.Widget, { } } }); - }, + } - getNotSelectedValue: function () { - var v = []; - BI.each(this.buttonMap, function (i, item) { + getNotSelectedValue() { + const v = []; + each(this.buttonMap, (i, item) => { if (item) { if (item.isEnabled() && !(item.isSelected && item.isSelected())) { v.push(item.getValue()); @@ -98,25 +105,25 @@ BI.VirtualGroup = BI.inherit(BI.Widget, { }); return v; - }, + } - getNodeByValue: function (value) { + getNodeByValue(value) { return this.buttonMap[value]; - }, + } /** * 滚动到指定的节点 */ - scrollToValue: function (value, scrollIntoViewOptions) { - var node = this.getNodeByValue(value); + scrollToValue(value, scrollIntoViewOptions) { + const node = this.getNodeByValue(value); if (node) { node.element[0].scrollIntoView(scrollIntoViewOptions); } - }, + } - getValue: function () { - var v = []; - BI.each(this.buttonMap, function (i, item) { + getValue() { + const v = []; + each(this.buttonMap, (i, item) => { if (item) { if (item.isEnabled() && item.isSelected && item.isSelected()) { v.push(item.getValue()); @@ -125,21 +132,18 @@ BI.VirtualGroup = BI.inherit(BI.Widget, { }); return v; - }, + } - populate: function (items) { + populate(items) { items = items || []; this.options.items = items; items = this._packageBtns(items); if (!this.layouts) { - this.layouts = BI.createWidget(BI.extend({ element: this }, this._packageLayout(items))); + this.layouts = createWidget(extend({ element: this }, this._packageLayout(items))); } else { this.layouts.populate(items, { context: this, }); } - }, -}); -BI.VirtualGroup.EVENT_CHANGE = "EVENT_CHANGE"; - -BI.shortcut("bi.virtual_group", BI.VirtualGroup); + } +} diff --git a/src/base/combination/loader.js b/src/base/combination/loader.js index cf548b024..0ebf26770 100644 --- a/src/base/combination/loader.js +++ b/src/base/combination/loader.js @@ -5,9 +5,16 @@ * @class BI.Loader * @extends BI.Widget */ -BI.Loader = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.Loader.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, Widget, Controller, extend, createWidget, isEmpty, nextTick, bind, isFunction, isNotEmptyArray, isNumber, isObject, each } from "../../core"; + +@shortcut() +export default class Loader extends Widget { + static xtype = "bi.loader"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { baseCls: "bi-loader", direction: "top", @@ -33,115 +40,115 @@ BI.Loader = BI.inherit(BI.Widget, { hasPrev: BI.emptyFn, hasNext: BI.emptyFn, }); - }, + } - _prevLoad: function () { - var self = this, o = this.options; + _prevLoad() { + const o = this.options; this.prev.setLoading(); - o.itemsCreator.apply(this, [{ times: --this.times }, function () { - self.prev.setLoaded(); - self.prependItems.apply(self, arguments); + o.itemsCreator.apply(this, [{ times: --this.times }, (...args) => { + this.prev.setLoaded(); + this.prependItems.apply(this, args); }]); - }, + } - _nextLoad: function () { - var self = this, o = this.options; + _nextLoad() { + const o = this.options; this.next.setLoading(); - o.itemsCreator.apply(this, [{ times: ++this.times }, function () { - self.next.setLoaded(); - self.addItems.apply(self, arguments); + o.itemsCreator.apply(this, [{ times: ++this.times }, (...args) => { + this.next.setLoaded(); + this.addItems.apply(this, args); }]); - }, + } - render: function () { - var self = this, o = this.options; - if (o.itemsCreator === false) { - o.prev = false; - o.next = false; + render() { + const { itemsCreator, prev, next, el, items: optionsItems, value, direction, logic, isDefaultInit } = this.options; + if (itemsCreator === false) { + prev = false; + next = false; } - if (o.prev !== false) { - this.prev = BI.createWidget(BI.extend({ + if (prev !== false) { + this.prev = createWidget(extend({ type: "bi.loading_bar", - }, o.prev)); - this.prev.on(BI.Controller.EVENT_CHANGE, function (type) { + }, prev)); + this.prev.on(Controller.EVENT_CHANGE, (type) => { if (type === BI.Events.CLICK) { - self._prevLoad(); + this._prevLoad(); } }); } - this.button_group = BI.createWidget(o.el, { + this.button_group = createWidget(el, { type: "bi.button_group", chooseType: 0, - items: o.items, + items: optionsItems, behaviors: {}, layouts: [{ type: "bi.vertical", }], - value: o.value, + value, }); - this.button_group.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.button_group.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); if (type === BI.Events.CLICK) { - self.fireEvent(BI.Loader.EVENT_CHANGE, obj); + this.fireEvent(Loader.EVENT_CHANGE, obj); } }); - if (o.next !== false) { - this.next = BI.createWidget(BI.extend({ + if (next !== false) { + this.next = createWidget(extend({ type: "bi.loading_bar", - }, o.next)); - this.next.on(BI.Controller.EVENT_CHANGE, function (type) { + }, next)); + this.next.on(Controller.EVENT_CHANGE, (type) => { if (type === BI.Events.CLICK) { - self._nextLoad(); + this._nextLoad(); } }); } - BI.createWidget(BI.extend({ + createWidget(extend({ element: this, - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend({ + }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(direction), extend({ scrolly: true, - }, o.logic, { - items: BI.LogicFactory.createLogicItemsByDirection(o.direction, this.prev, this.button_group, this.next), + }, logic, { + items: BI.LogicFactory.createLogicItemsByDirection(direction, this.prev, this.button_group, this.next), })))); - o.isDefaultInit && BI.isEmpty(o.items) && BI.nextTick(BI.bind(function () { - o.isDefaultInit && BI.isEmpty(o.items) && this._populate(); + isDefaultInit && isEmpty(optionsItems) && nextTick(bind(() => { + isDefaultInit && isEmpty(optionsItems) && this._populate(); }, this)); - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); - }) : o.items; - if (BI.isNotEmptyArray(items)) { + const items = isFunction(optionsItems) ? this.__watch(optionsItems, (context, newValue) => { + this.populate(newValue); + }) : optionsItems; + if (isNotEmptyArray(items)) { this._populate(items); } - }, + } - hasPrev: function () { - var o = this.options; - if (BI.isNumber(o.count)) { - return this.count < o.count; + hasPrev() { + const { count, hasPrev } = this.options; + if (isNumber(count)) { + return this.count < count; } - return !!o.hasPrev.apply(this, [{ + return !!hasPrev.apply(this, [{ times: this.times, count: this.count, }]); - }, + } - hasNext: function () { - var o = this.options; - if (BI.isNumber(o.count)) { - return this.count < o.count; + hasNext() { + const { count, hasNext } = this.options; + if (isNumber(count)) { + return this.count < count; } - return !!o.hasNext.apply(this, [{ + return !!hasNext.apply(this, [{ times: this.times, count: this.count, }]); - }, + } - prependItems: function (items) { + prependItems(items) { this.count += items.length; if (this.next !== false) { if (this.hasPrev()) { @@ -152,11 +159,11 @@ BI.Loader = BI.inherit(BI.Widget, { } } this.button_group.prependItems.apply(this.button_group, arguments); - }, + } - addItems: function (items) { + addItems(items) { this.count += items.length; - if (BI.isObject(this.next)) { + if (isObject(this.next)) { if (this.hasNext()) { this.options.items = this.options.items.concat(items); this.next.setLoaded(); @@ -165,16 +172,16 @@ BI.Loader = BI.inherit(BI.Widget, { } } this.button_group.addItems.apply(this.button_group, arguments); - }, + } - _populate: function (items) { - var self = this, o = this.options; - if (arguments.length === 0 && (BI.isFunction(o.itemsCreator))) { - o.itemsCreator.apply(this, [{ times: 1 }, function () { - if (arguments.length === 0) { + _populate(items) { + const o = this.options; + if (arguments.length === 0 && (isFunction(o.itemsCreator))) { + o.itemsCreator.apply(this, [{ times: 1 }, (...args) => { + if (args.length === 0) { throw new Error("参数不能为空"); } - self.populate.apply(self, arguments); + this.populate.apply(this, args); o.onLoaded(); }]); @@ -184,14 +191,14 @@ BI.Loader = BI.inherit(BI.Widget, { this.times = 1; this.count = 0; this.count += items.length; - if (BI.isObject(this.next)) { + if (isObject(this.next)) { if (this.hasNext()) { this.next.setLoaded(); } else { this.next.invisible(); } } - if (BI.isObject(this.prev)) { + if (isObject(this.prev)) { if (this.hasPrev()) { this.prev.setLoaded(); } else { @@ -200,66 +207,64 @@ BI.Loader = BI.inherit(BI.Widget, { } return true; - }, + } - populate: function () { + populate() { this._populate.apply(this, arguments) && this.button_group.populate.apply(this.button_group, arguments); - }, + } - setNotSelectedValue: function () { + setNotSelectedValue() { this.button_group.setNotSelectedValue.apply(this.button_group, arguments); - }, + } - getNotSelectedValue: function () { + getNotSelectedValue() { return this.button_group.getNotSelectedValue(); - }, + } - setValue: function () { + setValue() { this.button_group.setValue.apply(this.button_group, arguments); - }, + } - getValue: function () { + getValue() { return this.button_group.getValue.apply(this.button_group, arguments); - }, + } - getAllButtons: function () { + getAllButtons() { return this.button_group.getAllButtons(); - }, + } - getAllLeaves: function () { + getAllLeaves() { return this.button_group.getAllLeaves(); - }, + } - getSelectedButtons: function () { + getSelectedButtons() { return this.button_group.getSelectedButtons(); - }, + } - getNotSelectedButtons: function () { + getNotSelectedButtons() { return this.button_group.getNotSelectedButtons(); - }, + } - getIndexByValue: function (value) { + getIndexByValue(value) { return this.button_group.getIndexByValue(value); - }, + } - getNodeById: function (id) { + getNodeById(id) { return this.button_group.getNodeById(id); - }, + } - getNodeByValue: function (value) { + getNodeByValue(value) { return this.button_group.getNodeByValue(value); - }, + } - empty: function () { + empty() { this.button_group.empty(); - BI.each([this.prev, this.next], function (i, ob) { + each([this.prev, this.next], (i, ob) => { ob && ob.setVisible(false); }); - }, - - destroy: function () { - BI.Loader.superclass.destroy.apply(this, arguments); - }, -}); -BI.Loader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.loader", BI.Loader); + } + + destroy() { + super.destroy(arguments); + } +} diff --git a/src/base/combination/navigation.js b/src/base/combination/navigation.js index 1b347298e..febb44958 100644 --- a/src/base/combination/navigation.js +++ b/src/base/combination/navigation.js @@ -1,10 +1,16 @@ /** * Created by GUY on 2015/6/26. */ +import { shortcut, Widget, Controller, extend, createWidget, bind, ShowListener, isFunction, each, nextTick, isKey, values } from "../../core"; -BI.Navigation = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.Navigation.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export default class Navigation extends Widget { + static xtype = "bi.navigation"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { direction: "bottom", // top, bottom, left, right, custom logic: { dynamic: false, @@ -12,160 +18,158 @@ BI.Navigation = BI.inherit(BI.Widget, { single: false, showIndex: false, tab: false, - cardCreator: function (v) { - return BI.createWidget(); + cardCreator: (v) => { + return createWidget(); }, afterCardCreated: BI.emptyFn, afterCardShow: BI.emptyFn, }); - }, + } - render: function () { - var self = this, o = this.options; - this.tab = BI.createWidget(this.options.tab, { type: "bi.button_group" }); + render() { + const { direction, logic, cardCreator, showIndex } = this.options; + this.tab = createWidget(this.options.tab, { type: "bi.button_group" }); this.cardMap = {}; this.showIndex = 0; - this.layout = BI.createWidget({ + this.layout = createWidget({ type: "bi.card", }); - BI.createWidget(BI.extend({ + createWidget(extend({ element: this, - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend({}, o.logic, { - items: BI.LogicFactory.createLogicItemsByDirection(o.direction, this.tab, this.layout), + }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(direction), extend({}, logic, { + items: BI.LogicFactory.createLogicItemsByDirection(direction, this.tab, this.layout), })))); - new BI.ShowListener({ + new ShowListener({ eventObj: this.tab, cardLayout: this.layout, - cardNameCreator: function (v) { - return self.showIndex + v; + cardNameCreator: (v) => { + return this.showIndex + v; }, - cardCreator: function (v) { - BI.Widget.execWithContext(self, function () { - self.cardMap[v] = o.cardCreator(v); + cardCreator: (v) => { + Widget.execWithContext(this, () => { + this.cardMap[v] = cardCreator(v); }); - return self.cardMap[v]; + return this.cardMap[v]; }, - afterCardCreated: BI.bind(this.afterCardCreated, this), - afterCardShow: BI.bind(this.afterCardShow, this), + afterCardCreated: bind(this.afterCardCreated, this), + afterCardShow: bind(this.afterCardShow, this), }); - if (BI.isFunction(o.showIndex)) { - this.__watch(o.showIndex, function (context, newValue) { - self.setSelect(newValue); + if (isFunction(showIndex)) { + this.__watch(showIndex, (context, newValue) => { + this.setSelect(newValue); }); } - }, + } - created: function () { - var o = this.options; - if (o.showIndex !== false) { - this.setSelect(o.showIndex); + created() { + const { showIndex } = this.options; + if (showIndex !== false) { + this.setSelect(showIndex); } - }, + } - _deleteOtherCards: function (currCardName) { - var self = this, o = this.options; - if (o.single === true) { - BI.each(this.cardMap, function (name, card) { + _deleteOtherCards(currCardName) { + const { single } = this.options; + if (single === true) { + each(this.cardMap, (name, card) => { if (name !== (currCardName + "")) { - self.layout.deleteCardByName(name); - delete self.cardMap[name]; + this.layout.deleteCardByName(name); + delete this.cardMap[name]; } }); } - }, + } - afterCardCreated: function (v) { - var self = this; - this.cardMap[v].on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + afterCardCreated(v) { + this.cardMap[v].on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); if (type === BI.Events.CLICK) { - self.fireEvent(BI.Navigation.EVENT_CHANGE, obj); + this.fireEvent(Navigation.EVENT_CHANGE, obj); } }); this.options.afterCardCreated.apply(this, arguments); - }, + } - afterCardShow: function (v) { + afterCardShow(v) { this.showIndex = v; this._deleteOtherCards(v); this.options.afterCardShow.apply(this, arguments); - }, + } - populate: function () { - var card = this.layout.getShowingCard(); + populate() { + const card = this.layout.getShowingCard(); if (card) { return card.populate.apply(card, arguments); } - }, + } - _assertCard: function (v) { - var self = this, o = this.options; + _assertCard(v) { + const { cardCreator } = this.options; if (!this.layout.isCardExisted(v)) { - BI.Widget.execWithContext(self, function () { - self.cardMap[v] = o.cardCreator(v); + Widget.execWithContext(this, () => { + this.cardMap[v] = cardCreator(v); }); this.layout.addCardByName(v, this.cardMap[v]); this.afterCardCreated(v); } - }, + } - setSelect: function (v) { + setSelect(v) { this._assertCard(v); this.layout.showCardByName(v); this._deleteOtherCards(v); if (this.showIndex !== v) { this.showIndex = v; - BI.nextTick(BI.bind(this.afterCardShow, this, v)); + nextTick(bind(this.afterCardShow, this, v)); } - }, + } - getSelect: function () { + getSelect() { return this.showIndex; - }, + } - getSelectedCard: function () { - if (BI.isKey(this.showIndex)) { + getSelectedCard() { + if (isKey(this.showIndex)) { return this.cardMap[this.showIndex]; } - }, + } - getAllCard: function() { - return BI.values(this.cardMap); - }, + getAllCard() { + return values(this.cardMap); + } /** * @override */ - setValue: function (v) { - var card = this.layout.getShowingCard(); + setValue(v) { + const card = this.layout.getShowingCard(); if (card) { card.setValue(v); } - }, + } /** * @override */ - getValue: function () { - var card = this.layout.getShowingCard(); + getValue() { + const card = this.layout.getShowingCard(); if (card) { return card.getValue(); } - }, + } - empty: function () { + empty() { this.layout.deleteAllCard(); this.cardMap = {}; - }, + } + + destroy() { + super.destroy(arguments); + } - destroy: function () { - BI.Navigation.superclass.destroy.apply(this, arguments); - }, -}); -BI.Navigation.EVENT_CHANGE = "EVENT_CHANGE"; +} -BI.shortcut("bi.navigation", BI.Navigation); diff --git a/src/base/combination/searcher.js b/src/base/combination/searcher.js index 2098f4ce0..56b03f720 100644 --- a/src/base/combination/searcher.js +++ b/src/base/combination/searcher.js @@ -5,10 +5,23 @@ * @class BI.Searcher * @extends BI.Widget */ - -BI.Searcher = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.Searcher.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, Widget, Controller, extend, createWidget, debounce, bind, endWith, deepWithout, nextTick, isEmptyString, isNull } from "../../core"; +import ButtonGroup from "./group.button"; +import { Maskers } from "../0.base"; + +@shortcut() +export default class Searcher extends Widget { + static xtype = "bi.searcher"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_START = "EVENT_START"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_AFTER_INIT = "EVENT_AFTER_INIT"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { baseCls: "bi-searcher", lgap: 0, rgap: 0, @@ -20,10 +33,10 @@ BI.Searcher = BI.inherit(BI.Widget, { isDefaultInit: false, isAutoSearch: true, // 是否自动搜索 isAutoSync: true, // 是否自动同步数据, 即是否保持搜索面板和adapter面板状态值的统一 - chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, + chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, // isAutoSearch为false时启用 - onSearch: function (op, callback) { + onSearch: (op, callback) => { callback([]); }, @@ -40,190 +53,191 @@ BI.Searcher = BI.inherit(BI.Widget, { offset: {}, }, }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const { el, lgap, rgap, tgap, bgap, vgap, hgap, isDefaultInit } = this.options; - this.editor = BI.createWidget(o.el, { + this.editor = createWidget(el, { type: "bi.search_editor", }); - BI.createWidget({ + createWidget({ type: "bi.vertical", element: this, - lgap: o.lgap, - rgap: o.rgap, - tgap: o.tgap, - bgap: o.bgap, - vgap: o.vgap, - hgap: o.hgap, + lgap, + rgap, + tgap, + bgap, + vgap, + hgap, items: [this.editor], }); - o.isDefaultInit && (this._assertPopupView()); + isDefaultInit && (this._assertPopupView()); - var search = BI.debounce(BI.bind(this._search, this), BI.EVENT_RESPONSE_TIME, { + const search = debounce(bind(this._search, this), BI.EVENT_RESPONSE_TIME, { "leading": true, "trailing": false, }); - this.editor.on(BI.Controller.EVENT_CHANGE, function (type) { + this.editor.on(Controller.EVENT_CHANGE, (type) => { switch (type) { case BI.Events.STARTEDIT: - self._startSearch(); + this._startSearch(); break; case BI.Events.EMPTY: - self._stopSearch(); + this._stopSearch(); break; case BI.Events.CHANGE: search(); break; case BI.Events.PAUSE: - if (BI.endWith(this.getValue(), BI.BlankSplitChar)) { - self._pauseSearch(); + if (endWith(this.getValue(), BI.BlankSplitChar)) { + this._pauseSearch(); } break; default: break; } }); - }, + } - _assertPopupView: function () { - var self = this, o = this.options; - if ((o.masker && !BI.Maskers.has(this.getName())) || (o.masker === false && !this.popupView)) { - this.popupView = BI.createWidget(o.popup, { + _assertPopupView() { + const { masker, popup, chooseType, isAutoSync, adapter } = this.options; + if ((masker && !Maskers.has(this.getName())) || (masker === false && !this.popupView)) { + this.popupView = createWidget(popup, { type: "bi.searcher_view", - chooseType: o.chooseType, + chooseType: chooseType, }); - this.popupView.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.popupView.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); if (type === BI.Events.CLICK) { - if (o.isAutoSync) { - var values = o.adapter && o.adapter.getValue(); - switch (o.chooseType) { - case BI.ButtonGroup.CHOOSE_TYPE_SINGLE: - o.adapter && o.adapter.setValue([obj.getValue()]); + if (isAutoSync) { + const values = adapter && adapter.getValue(); + switch (chooseType) { + case ButtonGroup.CHOOSE_TYPE_SINGLE: + adapter && adapter.setValue([obj.getValue()]); break; - case BI.ButtonGroup.CHOOSE_TYPE_MULTI: + case ButtonGroup.CHOOSE_TYPE_MULTI: if (!obj.isSelected()) { - o.adapter && o.adapter.setValue(BI.deepWithout(values, obj.getValue())); + adapter && adapter.setValue(deepWithout(values, obj.getValue())); } values.push(obj.getValue()); - o.adapter && o.adapter.setValue(values); + adapter && adapter.setValue(values); break; default: break; } } - self.fireEvent(BI.Searcher.EVENT_CHANGE, value, obj); + this.fireEvent(Searcher.EVENT_CHANGE, value, obj); } }); - BI.nextTick(function () { - self.fireEvent(BI.Searcher.EVENT_AFTER_INIT); + nextTick(() => { + this.fireEvent(Searcher.EVENT_AFTER_INIT); }); } - if (o.masker && !BI.Maskers.has(this.getName())) { - BI.Maskers.create(this.getName(), o.adapter, BI.extend({ + if (masker && !Maskers.has(this.getName())) { + Maskers.create(this.getName(), adapter, extend({ container: this, render: this.popupView, - }, o.masker), this); + }, masker), this); } - }, + } - _startSearch: function () { + _startSearch() { this._assertPopupView(); this._stop = false; this._isSearching = true; - this.fireEvent(BI.Searcher.EVENT_START); + this.fireEvent(Searcher.EVENT_START); this.popupView.startSearch && this.popupView.startSearch(); // 搜索前先清空dom // BI.Maskers.get(this.getName()).empty(); - BI.nextTick(function (name) { - BI.Maskers.show(name); + nextTick((name) => { + Maskers.show(name); }, this.getName()); - }, + } - _pauseSearch: function () { + _pauseSearch() { this._stop = true; - BI.nextTick(function (name) { - BI.Maskers.hide(name); + nextTick((name) => { + Maskers.hide(name); }, this.getName()); if (this._isSearching === true) { this.popupView && this.popupView.pauseSearch && this.popupView.pauseSearch(); - this.fireEvent(BI.Searcher.EVENT_PAUSE); + this.fireEvent(Searcher.EVENT_PAUSE); } this._isSearching = false; - }, + } - _stopSearch: function () { - var name = this.getName(); + _stopSearch() { + const name = this.getName(); this._stop = true; - BI.Maskers.hide(name); + Maskers.hide(name); if (this._isSearching === true) { this.popupView && this.popupView.stopSearch && this.popupView.stopSearch(); - this.fireEvent(BI.Searcher.EVENT_STOP); + this.fireEvent(Searcher.EVENT_STOP); } this._isSearching = false; - }, + } - _search: function () { - var self = this, o = this.options, keyword = this.editor.getValue(); + _search() { + const { isAutoSearch, adapter, isAutoSync, onSearch } = this.options; + const keyword = this.editor.getValue(); if (keyword === "" || this._stop) { return; } - if (o.isAutoSearch) { - var items = (o.adapter && ((o.adapter.getItems && o.adapter.getItems()) || o.adapter.attr("items"))) || []; - var finding = BI.Func.getSearchResult(items, keyword); - var match = finding.match, find = finding.find; + if (isAutoSearch) { + const items = (adapter && ((adapter.getItems && adapter.getItems()) || adapter.attr("items"))) || []; + const finding = BI.Func.getSearchResult(items, keyword); + const match = finding.match, find = finding.find; this.popupView.populate(find, match, keyword); - o.isAutoSync && o.adapter && o.adapter.getValue && this.popupView.setValue(o.adapter.getValue()); - self.fireEvent(BI.Searcher.EVENT_SEARCHING); + isAutoSync && adapter && adapter.getValue && this.popupView.setValue(adapter.getValue()); + this.fireEvent(Searcher.EVENT_SEARCHING); return; } this.popupView.loading && this.popupView.loading(); - o.onSearch({ + onSearch({ times: 1, keyword: keyword, - selectedValues: o.adapter && o.adapter.getValue(), - }, function (searchResult, matchResult) { - if (!self._stop && keyword === self.editor.getValue()) { - var args = [].slice.call(arguments); + selectedValues: adapter && adapter.getValue(), + }, (searchResult, matchResult, ...arg) => { + if (!this._stop && keyword === this.editor.getValue()) { + const args = [searchResult, matchResult, ...arg]; if (args.length > 0) { args.push(keyword); } - BI.Maskers.show(self.getName()); - self.popupView.populate.apply(self.popupView, args); - o.isAutoSync && o.adapter && o.adapter.getValue && self.popupView.setValue(o.adapter.getValue()); - self.popupView.loaded && self.popupView.loaded(); - self.fireEvent(BI.Searcher.EVENT_SEARCHING); + Maskers.show(this.getName()); + this.popupView.populate.apply(this.popupView, args); + isAutoSync && adapter && adapter.getValue && this.popupView.setValue(adapter.getValue()); + this.popupView.loaded && this.popupView.loaded(); + this.fireEvent(Searcher.EVENT_SEARCHING); } }); - }, + } - _getLastSearchKeyword: function () { + _getLastSearchKeyword() { if (this.isValid()) { - var res = this.editor.getValue().split(/\u200b\s\u200b/); - if (BI.isEmptyString(res[res.length - 1])) { + const res = this.editor.getValue().split(/\u200b\s\u200b/); + if (isEmptyString(res[res.length - 1])) { res = res.slice(0, res.length - 1); } - return BI.isNull(res) ? "" : res[res.length - 1]; + return isNull(res) ? "" : res[res.length - 1]; } - }, + } - setAdapter: function (adapter) { + setAdapter(adapter) { this.options.adapter = adapter; - BI.Maskers.remove(this.getName()); - }, + Maskers.remove(this.getName()); + } - doSearch: function () { + doSearch() { if (this.isSearching()) { this._search(); } - }, + } - stopSearch: function () { + stopSearch() { this._stopSearch();// 先停止搜索,然后再去设置editor为空 // important:停止搜索必须退出编辑状态,这里必须加上try(input框不显示时blur会抛异常) try { @@ -235,103 +249,95 @@ BI.Searcher = BI.inherit(BI.Widget, { } finally { this.editor.setValue(""); } - }, + } - isSearching: function () { + isSearching() { return this._isSearching; - }, + } - isViewVisible: function () { - return this.editor.isEnabled() && BI.Maskers.isVisible(this.getName()); - }, + isViewVisible() { + return this.editor.isEnabled() && Maskers.isVisible(this.getName()); + } - getView: function () { + getView() { return this.popupView; - }, + } - hasMatched: function () { + hasMatched() { this._assertPopupView(); return this.popupView.hasMatched(); - }, + } - adjustHeight: function () { - if (BI.Maskers.has(this.getName()) && BI.Maskers.get(this.getName()).isVisible()) { - BI.Maskers.show(this.getName()); + adjustHeight() { + if (Maskers.has(this.getName()) && Maskers.get(this.getName()).isVisible()) { + Maskers.show(this.getName()); } - }, + } - adjustView: function () { - this.isViewVisible() && BI.Maskers.show(this.getName()); - }, + adjustView() { + this.isViewVisible() && Maskers.show(this.getName()); + } - setValue: function (v) { - if (BI.isNull(this.popupView)) { + setValue(v) { + if (isNull(this.popupView)) { this.options.popup.value = v; } else { this.popupView.setValue(v); } - }, + } - getKeyword: function () { + getKeyword() { return this._getLastSearchKeyword(); - }, + } - getKeywords: function () { + getKeywords() { return this.editor.getKeywords(); - }, + } - getValue: function () { - var o = this.options; - if (o.isAutoSync && o.adapter && o.adapter.getValue) { - return o.adapter.getValue(); + getValue() { + const { isAutoSync, adapter, popup } = this.options; + if (isAutoSync && adapter && adapter.getValue) { + return adapter.getValue(); } if (this.isSearching()) { return this.popupView.getValue(); - } else if (o.adapter && o.adapter.getValue) { - return o.adapter.getValue(); + } else if (adapter && adapter.getValue) { + return adapter.getValue(); } - if (BI.isNull(this.popupView)) { - return o.popup.value; + if (isNull(this.popupView)) { + return popup.value; } return this.popupView.getValue(); - }, + } - populate: function (result, searchResult, keyword) { - var o = this.options; + populate(result, searchResult, keyword) { + const { isAutoSync, adapter } = this.options; this._assertPopupView(); this.popupView.populate.apply(this.popupView, arguments); - if (o.isAutoSync && o.adapter && o.adapter.getValue) { - this.popupView.setValue(o.adapter.getValue()); + if (isAutoSync && adapter && adapter.getValue) { + this.popupView.setValue(adapter.getValue()); } - }, + } - empty: function () { + empty() { this.popupView && this.popupView.empty(); - }, + } - destroyed: function () { - BI.Maskers.remove(this.getName()); - }, + destroyed() { + Maskers.remove(this.getName()); + } - focus: function () { + focus() { this.editor.focus(); - }, + } - blur: function () { + blur() { this.editor.blur(); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.editor.setWaterMark(v); - }, -}); -BI.Searcher.EVENT_CHANGE = "EVENT_CHANGE"; -BI.Searcher.EVENT_START = "EVENT_START"; -BI.Searcher.EVENT_STOP = "EVENT_STOP"; -BI.Searcher.EVENT_PAUSE = "EVENT_PAUSE"; -BI.Searcher.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.Searcher.EVENT_AFTER_INIT = "EVENT_AFTER_INIT"; - -BI.shortcut("bi.searcher", BI.Searcher); + } +} diff --git a/src/base/combination/switcher.js b/src/base/combination/switcher.js index 419711595..e89b31314 100644 --- a/src/base/combination/switcher.js +++ b/src/base/combination/switcher.js @@ -6,9 +6,26 @@ * @class BI.Switcher * @extends BI.Widget */ -BI.Switcher = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.Switcher.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, Widget, Controller, extend, nextTick, createWidget, each, debounce, isNull } from "../../core"; +import { Maskers } from "../0.base"; + +@shortcut() +export default class Switcher extends Widget { + static xtype = "bi.switcher"; + + static EVENT_EXPAND = "EVENT_EXPAND"; + static EVENT_COLLAPSE = "EVENT_COLLAPSE"; + static EVENT_TRIGGER_CHANGE = "EVENT_TRIGGER_CHANGE"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_AFTER_INIT = "EVENT_AFTER_INIT"; + + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + static EVENT_AFTER_POPUPVIEW = "EVENT_AFTER_POPUPVIEW"; + static EVENT_BEFORE_HIDEVIEW = "EVENT_BEFORE_HIDEVIEW"; + static EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { baseCls: "bi-switcher", direction: BI.Direction.Top, trigger: "click", @@ -20,47 +37,47 @@ BI.Switcher = BI.inherit(BI.Widget, { switcherClass: "bi-switcher-popup", hoverClass: "bi-switcher-hover", }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const { hoverClass, isDefaultInit } = this.options; this._initSwitcher(); // 延迟绑定事件,这样可以将自己绑定的事情优先执行 - BI.nextTick(() => { + nextTick(() => { !this.isDestroyed() && this._initPullDownAction(); }); - this.switcher.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - if (self.isEnabled() && self.isValid()) { + this.switcher.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { + if (this.isEnabled() && this.isValid()) { if (type === BI.Events.EXPAND) { - self._popupView(); + this._popupView(); } if (type === BI.Events.COLLAPSE) { - self._hideView(); + this._hideView(); } if (type === BI.Events.EXPAND) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - self.fireEvent(BI.Switcher.EVENT_EXPAND); + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); + this.fireEvent(Switcher.EVENT_EXPAND); } if (type === BI.Events.COLLAPSE) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - self.isViewVisible() && self.fireEvent(BI.Switcher.EVENT_COLLAPSE); + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); + this.isViewVisible() && this.fireEvent(Switcher.EVENT_COLLAPSE); } if (type === BI.Events.CLICK) { - self.fireEvent(BI.Switcher.EVENT_TRIGGER_CHANGE, value, obj); + this.fireEvent(Switcher.EVENT_TRIGGER_CHANGE, value, obj); } } }); - this.element.hover(function () { - if (self.isEnabled() && self.switcher.isEnabled()) { - self.element.addClass(o.hoverClass); + this.element.hover(() => { + if (this.isEnabled() && this.switcher.isEnabled()) { + this.element.addClass(hoverClass); } - }, function () { - if (self.isEnabled() && self.switcher.isEnabled()) { - self.element.removeClass(o.hoverClass); + }, () => { + if (this.isEnabled() && this.switcher.isEnabled()) { + this.element.removeClass(hoverClass); } }); - BI.createWidget({ + createWidget({ type: "bi.vertical", scrolly: false, element: this, @@ -68,10 +85,10 @@ BI.Switcher = BI.inherit(BI.Widget, { { el: this.switcher } ], }); - o.isDefaultInit && (this._assertPopupView()); - }, + isDefaultInit && (this._assertPopupView()); + } - _toggle: function () { + _toggle() { this._assertPopupView(); if (this.isExpanded()) { this._hideView(); @@ -80,40 +97,40 @@ BI.Switcher = BI.inherit(BI.Widget, { this._popupView(); } } - }, + } - _initPullDownAction: function () { - var self = this, o = this.options; - var evs = this.options.trigger.split(","); - BI.each(evs, function (i, e) { + _initPullDownAction() { + const { toggle } = this.options; + const evs = this.options.trigger.split(","); + each(evs, (i, e) => { switch (e) { case "hover": - self.element[e](function (e) { - if (self.isEnabled() && self.switcher.isEnabled()) { - self._popupView(); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.switcher); - self.fireEvent(BI.Switcher.EVENT_EXPAND); + this.element[e]((e) => { + if (this.isEnabled() && this.switcher.isEnabled()) { + this._popupView(); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.switcher); + this.fireEvent(Switcher.EVENT_EXPAND); } - }, function () { - if (self.isEnabled() && self.switcher.isEnabled() && o.toggle) { - self._hideView(); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.switcher); - self.fireEvent(BI.Switcher.EVENT_COLLAPSE); + }, () => { + if (this.isEnabled() && this.switcher.isEnabled() && toggle) { + this._hideView(); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", this.switcher); + this.fireEvent(Switcher.EVENT_COLLAPSE); } }); break; default : if (e) { - self.element.off(e + "." + self.getName()).on(e + "." + self.getName(), BI.debounce(function (e) { - if (self.switcher.element.__isMouseInBounds__(e)) { - if (self.isEnabled() && self.switcher.isEnabled()) { - o.toggle ? self._toggle() : self._popupView(); - if (self.isExpanded()) { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.switcher); - self.fireEvent(BI.Switcher.EVENT_EXPAND); + this.element.off(e + "." + this.getName()).on(e + "." + this.getName(), debounce((e) => { + if (this.switcher.element.__isMouseInBounds__(e)) { + if (this.isEnabled() && this.switcher.isEnabled()) { + toggle ? this._toggle() : this._popupView(); + if (this.isExpanded()) { + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.switcher); + this.fireEvent(Switcher.EVENT_EXPAND); } else { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.switcher); - self.fireEvent(BI.Switcher.EVENT_COLLAPSE); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", this.switcher); + this.fireEvent(Switcher.EVENT_COLLAPSE); } } } @@ -125,36 +142,36 @@ BI.Switcher = BI.inherit(BI.Widget, { break; } }); - }, + } - _initSwitcher: function () { - this.switcher = BI.createWidget(this.options.el, { + _initSwitcher() { + this.switcher = createWidget(this.options.el, { value: this.options.value, }); - }, + } - _assertPopupView: function () { - var self = this, o = this.options; + _assertPopupView() { + const { popup, adapter, masker, value, direction } = this.options; if (!this._created) { - this.popupView = BI.createWidget(o.popup, { + this.popupView = createWidget(popup, { type: "bi.button_group", - element: o.adapter && BI.Maskers.create(this.getName(), o.adapter, BI.extend({ container: this }, o.masker)), + element: adapter && Maskers.create(this.getName(), adapter, extend({ container: this }, masker)), cls: "switcher-popup", layouts: [{ type: "bi.vertical", hgap: 0, vgap: 0, }], - value: o.value, + value, }, this); - this.popupView.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.popupView.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); if (type === BI.Events.CLICK) { - self.fireEvent(BI.Switcher.EVENT_CHANGE, value, obj); + this.fireEvent(Switcher.EVENT_CHANGE, value, obj); } }); - if (o.direction !== BI.Direction.Custom && !o.adapter) { - BI.createWidget({ + if (direction !== BI.Direction.Custom && !adapter) { + createWidget({ type: "bi.vertical", scrolly: false, element: this, @@ -164,133 +181,120 @@ BI.Switcher = BI.inherit(BI.Widget, { }); } this._created = true; - BI.nextTick(function () { - self.fireEvent(BI.Switcher.EVENT_AFTER_INIT); + nextTick(() => { + this.fireEvent(Switcher.EVENT_AFTER_INIT); }); } - }, + } - _hideView: function () { - this.fireEvent(BI.Switcher.EVENT_BEFORE_HIDEVIEW); - var self = this, o = this.options; - o.adapter ? BI.Maskers.hide(self.getName()) : (self.popupView && self.popupView.setVisible(false)); - BI.nextTick(function () { - o.adapter ? BI.Maskers.hide(self.getName()) : (self.popupView && self.popupView.setVisible(false)); - self.element.removeClass(o.switcherClass); - self.fireEvent(BI.Switcher.EVENT_AFTER_HIDEVIEW); + _hideView() { + this.fireEvent(Switcher.EVENT_BEFORE_HIDEVIEW); + const { adapter, switcherClass } = this.options; + adapter ? Maskers.hide(this.getName()) : (this.popupView && this.popupView.setVisible(false)); + nextTick(() => { + adapter ? Maskers.hide(this.getName()) : (this.popupView && this.popupView.setVisible(false)); + this.element.removeClass(switcherClass); + this.fireEvent(Switcher.EVENT_AFTER_HIDEVIEW); }); - }, + } - _popupView: function () { - var self = this, o = this.options; + _popupView() { + const { adapter, switcherClass } = this.options; this._assertPopupView(); - this.fireEvent(BI.Switcher.EVENT_BEFORE_POPUPVIEW); - o.adapter ? BI.Maskers.show(this.getName()) : self.popupView.setVisible(true); - BI.nextTick(function (name) { - o.adapter ? BI.Maskers.show(name) : self.popupView.setVisible(true); - self.element.addClass(o.switcherClass); - self.fireEvent(BI.Switcher.EVENT_AFTER_POPUPVIEW); + this.fireEvent(Switcher.EVENT_BEFORE_POPUPVIEW); + adapter ? Maskers.show(this.getName()) : this.popupView.setVisible(true); + nextTick((name) => { + adapter ? Maskers.show(name) : this.popupView.setVisible(true); + this.element.addClass(switcherClass); + this.fireEvent(Switcher.EVENT_AFTER_POPUPVIEW); }, this.getName()); - }, + } - _populate: function () { + _populate() { this._assertPopupView(); this.popupView.populate.apply(this.popupView, arguments); - }, + } - populate: function (items) { + populate(items) { this._populate.apply(this, arguments); this.switcher.populate && this.switcher.populate.apply(this.switcher, arguments); - }, + } - _setEnable: function (arg) { - BI.Switcher.superclass._setEnable.apply(this, arguments); + _setEnable(arg) { + super._setEnable(arguments); !arg && this.isViewVisible() && this._hideView(); - }, + } - setValue: function (v) { + setValue(v) { this.switcher.setValue(v); - if (BI.isNull(this.popupView)) { + if (isNull(this.popupView)) { this.options.popup.value = v; } else { this.popupView.setValue(v); } - }, + } - getValue: function () { - if (BI.isNull(this.popupView)) { + getValue() { + if (isNull(this.popupView)) { return this.options.popup.value; } else { return this.popupView.getValue(); } - }, + } - setAdapter: function (adapter) { + setAdapter(adapter) { this.options.adapter = adapter; - BI.Maskers.remove(this.getName()); - }, + Maskers.remove(this.getName()); + } - isViewVisible: function () { + isViewVisible() { return this.isEnabled() && this.switcher.isEnabled() && - (this.options.adapter ? BI.Maskers.isVisible(this.getName()) : (this.popupView && this.popupView.isVisible())); - }, + (this.options.adapter ? Maskers.isVisible(this.getName()) : (this.popupView && this.popupView.isVisible())); + } - isExpanded: function () { + isExpanded() { return this.isViewVisible(); - }, + } - showView: function () { + showView() { if (this.isEnabled() && this.switcher.isEnabled()) { this._popupView(); } - }, + } - hideView: function () { + hideView() { this._hideView(); - }, + } - getView: function () { + getView() { return this.popupView; - }, + } - adjustView: function () { - this.isViewVisible() && BI.Maskers.show(this.getName()); - }, + adjustView() { + this.isViewVisible() && Maskers.show(this.getName()); + } - getAllLeaves: function () { + getAllLeaves() { return this.popupView && this.popupView.getAllLeaves(); - }, + } - getNodeById: function (id) { + getNodeById(id) { if (this.switcher.attr("id") === id) { return this.switcher; } return this.popupView && this.popupView.getNodeById(id); - }, + } - getNodeByValue: function (value) { + getNodeByValue(value) { if (this.switcher.getValue() === value) { return this.switcher; } return this.popupView && this.popupView.getNodeByValue(value); - }, + } - empty: function () { + empty() { this.popupView && this.popupView.empty(); - }, -}); -BI.Switcher.EVENT_EXPAND = "EVENT_EXPAND"; -BI.Switcher.EVENT_COLLAPSE = "EVENT_COLLAPSE"; -BI.Switcher.EVENT_TRIGGER_CHANGE = "EVENT_TRIGGER_CHANGE"; -BI.Switcher.EVENT_CHANGE = "EVENT_CHANGE"; -BI.Switcher.EVENT_AFTER_INIT = "EVENT_AFTER_INIT"; - - -BI.Switcher.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.Switcher.EVENT_AFTER_POPUPVIEW = "EVENT_AFTER_POPUPVIEW"; -BI.Switcher.EVENT_BEFORE_HIDEVIEW = "EVENT_BEFORE_HIDEVIEW"; -BI.Switcher.EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; - -BI.shortcut("bi.switcher", BI.Switcher); + } +} diff --git a/src/base/combination/tab.js b/src/base/combination/tab.js index 933496004..7fcce06c4 100644 --- a/src/base/combination/tab.js +++ b/src/base/combination/tab.js @@ -1,10 +1,16 @@ /** * Created by GUY on 2015/6/26. */ +import { shortcut, Widget, Controller, ShowListener, extend, createWidget, isObject, each, isFunction, contains, any, isEqual } from "../../core"; -BI.Tab = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.Tab.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export default class Tab extends Widget { + static xtype = "bi.tab"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { baseCls: "bi-tab", direction: "top", // top, bottom, left, right, custom single: false, // 是不是单页面 @@ -13,87 +19,87 @@ BI.Tab = BI.inherit(BI.Widget, { }, showIndex: false, tab: false, - cardCreator: function (v) { - return BI.createWidget(); + cardCreator: (v) => { + return createWidget(); }, keepAlives: [], }); - }, - - render: function () { - var self = this, o = this.options; - if (BI.isObject(o.tab)) { - this.tab = BI.createWidget(this.options.tab, { type: "bi.button_group" }); - this.tab.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + } + + render() { + const { tab, direction, logic, cardCreator } = this.options; + if (isObject(tab)) { + this.tab = createWidget(this.options.tab, { type: "bi.button_group" }); + this.tab.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); }); } this.cardMap = {}; - this.layout = BI.createWidget({ + this.layout = createWidget({ type: "bi.card", }); - BI.createWidget(BI.extend({ + createWidget(extend({ element: this, - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend({}, o.logic, { - items: BI.LogicFactory.createLogicItemsByDirection(o.direction, this.tab, this.layout), + }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(direction), extend({}, logic, { + items: BI.LogicFactory.createLogicItemsByDirection(direction, this.tab, this.layout), })))); - var listener = new BI.ShowListener({ + const listener = new ShowListener({ eventObj: this.tab, cardLayout: this.layout, - cardCreator: function (v) { - BI.Widget.execWithContext(self, function () { - self.cardMap[v] = o.cardCreator(v); + cardCreator: (v) => { + Widget.execWithContext(this, () => { + this.cardMap[v] = cardCreator(v); }); - return self.cardMap[v]; + return this.cardMap[v]; }, - afterCardShow: function (v) { - self._deleteOtherCards(v); - self.curr = v; + afterCardShow: (v) => { + this._deleteOtherCards(v); + this.curr = v; }, }); - listener.on(BI.ShowListener.EVENT_CHANGE, function (value) { - self.fireEvent(BI.Tab.EVENT_CHANGE, value, self); + listener.on(ShowListener.EVENT_CHANGE, (value) => { + this.fireEvent(Tab.EVENT_CHANGE, value, this); }); - }, - - _deleteOtherCards: function (currCardName) { - var self = this, o = this.options; - if (o.single === true) { - BI.each(this.cardMap, function (name, card) { - if (name !== (currCardName + "") && self._keepAlive(name) !== true) { - self.layout.deleteCardByName(name); - delete self.cardMap[name]; + } + + _deleteOtherCards(currCardName) { + const { single } = this.options; + if (single === true) { + each(this.cardMap, (name, card) => { + if (name !== (currCardName + "") && this._keepAlive(name) !== true) { + this.layout.deleteCardByName(name); + delete this.cardMap[name]; } }); } - }, + } - _assertCard: function (v) { - var self = this, o = this.options; + _assertCard(v) { + const { cardCreator } = this.options; if (!this.layout.isCardExisted(v)) { - BI.Widget.execWithContext(this, function () { - self.cardMap[v] = o.cardCreator(v); + Widget.execWithContext(this, () => { + this.cardMap[v] = cardCreator(v); }); this.layout.addCardByName(v, this.cardMap[v]); } - }, + } - _keepAlive: function (v) { - var o = this.options; + _keepAlive(v) { + const { keepAlives } = this.options; - return BI.isFunction(o.keepAlives) ? o.keepAlives(v) : BI.contains(o.keepAlives, v); - }, + return isFunction(keepAlives) ? keepAlives(v) : contains(keepAlives, v); + } - created: function () { - var self = this, o = this.options; + created() { + const o = this.options; + let showIndex; - var showIndex; - if (BI.isFunction(o.showIndex)) { - showIndex = this.__watch(o.showIndex, function (context, newValue) { - self.setSelect(newValue); + if (isFunction(o.showIndex)) { + showIndex = this.__watch(o.showIndex, (context, newValue) => { + this.setSelect(newValue); }); } else { showIndex = o.showIndex; @@ -102,9 +108,9 @@ BI.Tab = BI.inherit(BI.Widget, { if (showIndex !== false) { this.setSelect(showIndex); } - }, + } - setSelect: function (v, action, callback) { + setSelect(v, action, callback) { this.tab && this.tab.setValue(v); this._assertCard(v); this.layout.showCardByName(v, action, callback); @@ -112,69 +118,66 @@ BI.Tab = BI.inherit(BI.Widget, { if (this.curr !== v) { this.curr = v; } - }, + } - removeTab: function (cardname) { - var self = this; - BI.any(this.cardMap, function (name, card) { - if (BI.isEqual(name, (cardname + ""))) { - self.layout.deleteCardByName(name); - delete self.cardMap[name]; + removeTab(cardname) { + any(this.cardMap, (name, card) => { + if (isEqual(name, (cardname + ""))) { + this.layout.deleteCardByName(name); + delete this.cardMap[name]; return true; } }); - }, + } - isCardExisted: function (cardName) { + isCardExisted(cardName) { return this.layout.isCardExisted(cardName); - }, + } - getSelect: function () { + getSelect() { return this.curr; - }, + } - getSelectedTab: function () { + getSelectedTab() { return this.layout.getShowingCard(); - }, + } - getTab: function (v) { + getTab(v) { this._assertCard(v); return this.layout.getCardByName(v); - }, + } - setValue: function (v) { - var card = this.layout.getShowingCard(); + setValue(v) { + const card = this.layout.getShowingCard(); if (card) { card.setValue(v); } - }, + } - getValue: function () { - var card = this.layout.getShowingCard(); + getValue() { + const card = this.layout.getShowingCard(); if (card) { return card.getValue(); } - }, + } - populate: function () { - var card = this.layout.getShowingCard(); + populate() { + const card = this.layout.getShowingCard(); if (card) { return card.populate && card.populate.apply(card, arguments); } - }, + } - empty: function () { + empty() { this.layout.deleteAllCard(); this.cardMap = {}; - }, + } - destroy: function () { + destroy() { this.cardMap = {}; - BI.Tab.superclass.destroy.apply(this, arguments); - }, -}); -BI.Tab.EVENT_CHANGE = "EVENT_CHANGE"; + super.destroy(arguments); + } -BI.shortcut("bi.tab", BI.Tab); +} diff --git a/src/base/combination/tree.button.js b/src/base/combination/tree.button.js index cfa9a3c3b..6ed1a1b3f 100644 --- a/src/base/combination/tree.button.js +++ b/src/base/combination/tree.button.js @@ -3,67 +3,74 @@ * @class BI.ButtonTree * @extends BI.ButtonGroup */ +import { shortcut, Widget, extend, isArray, each, isFunction, deepContains, concat, any, contains } from "../../core"; +import ButtonGroup from "./group.button"; -BI.ButtonTree = BI.inherit(BI.ButtonGroup, { - _defaultConfig: function () { - return BI.extend(BI.ButtonTree.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export default class ButtonTree extends ButtonGroup { + static xtype = "bi.button_tree"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { baseCls: "bi-button-tree", }); - }, + } - setNotSelectedValue: function (v) { - v = BI.isArray(v) ? v : [v]; - BI.each(this.buttons, function (i, item) { - if (!BI.isFunction(item.setSelected)) { + setNotSelectedValue(v) { + v = isArray(v) ? v : [v]; + each(this.buttons, (i, item) => { + if (!isFunction(item.setSelected)) { item.setNotSelectedValue(v); return; } - if (BI.deepContains(v, item.getValue())) { + if (deepContains(v, item.getValue())) { item.setSelected(false); } else { item.setSelected(true); } }); - }, + } - setEnabledValue: function (v) { - v = BI.isArray(v) ? v : [v]; - BI.each(this.buttons, function (i, item) { - if (BI.isFunction(item.setEnabledValue)) { + setEnabledValue(v) { + v = isArray(v) ? v : [v]; + each(this.buttons, (i, item) => { + if (isFunction(item.setEnabledValue)) { item.setEnabledValue(v); return; } - if (BI.deepContains(v, item.getValue())) { + if (deepContains(v, item.getValue())) { item.setEnable(true); } else { item.setEnable(false); } }); - }, + } - setValue: function (v) { - v = BI.isArray(v) ? v : [v]; - BI.each(this.buttons, function (i, item) { - if (!BI.isFunction(item.setSelected)) { + setValue(v) { + v = isArray(v) ? v : [v]; + each(this.buttons, (i, item) => { + if (!isFunction(item.setSelected)) { item.setValue(v); return; } - if (BI.deepContains(v, item.getValue())) { + if (deepContains(v, item.getValue())) { item.setSelected(true); } else { item.setSelected(false); } }); - }, + } - getNotSelectedValue: function () { - var v = []; - BI.each(this.buttons, function (i, item) { - if (item.isEnabled() && !BI.isFunction(item.setSelected)) { - v = BI.concat(v, item.getNotSelectedValue()); + getNotSelectedValue() { + let v = []; + each(this.buttons, (i, item) => { + if (item.isEnabled() && !isFunction(item.setSelected)) { + v = concat(v, item.getNotSelectedValue()); return; } @@ -73,13 +80,13 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, { }); return v; - }, + } - getValue: function () { - var v = []; - BI.each(this.buttons, function (i, item) { - if (item.isEnabled() && !BI.isFunction(item.setSelected)) { - v = BI.concat(v, item.getValue()); + getValue() { + let v = []; + each(this.buttons, (i, item) => { + if (item.isEnabled() && !isFunction(item.setSelected)) { + v = concat(v, item.getValue()); return; } @@ -89,12 +96,12 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, { }); return v; - }, + } - getSelectedButtons: function () { - var btns = []; - BI.each(this.buttons, function (i, item) { - if (item.isEnabled() && !BI.isFunction(item.setSelected)) { + getSelectedButtons() { + let btns = []; + each(this.buttons, (i, item) => { + if (item.isEnabled() && !isFunction(item.setSelected)) { btns = btns.concat(item.getSelectedButtons()); return; @@ -105,12 +112,12 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, { }); return btns; - }, + } - getNotSelectedButtons: function () { - var btns = []; - BI.each(this.buttons, function (i, item) { - if (item.isEnabled() && !BI.isFunction(item.setSelected)) { + getNotSelectedButtons() { + let btns = []; + each(this.buttons, (i, item) => { + if (item.isEnabled() && !isFunction(item.setSelected)) { btns = btns.concat(item.getNotSelectedButtons()); return; @@ -121,13 +128,13 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, { }); return btns; - }, + } // 获取所有的叶子节点 - getAllLeaves: function () { - var leaves = []; - BI.each(this.buttons, function (i, item) { - if (item.isEnabled() && !BI.isFunction(item.setSelected)) { + getAllLeaves() { + let leaves = []; + each(this.buttons, (i, item) => { + if (item.isEnabled() && !isFunction(item.setSelected)) { leaves = leaves.concat(item.getAllLeaves()); return; @@ -138,13 +145,13 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, { }); return leaves; - }, + } - getIndexByValue: function (value) { - var index = -1; - BI.any(this.buttons, function (i, item) { - var vs = item.getValue(); - if (item.isEnabled() && (vs === value || BI.contains(vs, value))) { + getIndexByValue(value) { + let index = -1; + any(this.buttons, (i, item) => { + const vs = item.getValue(); + if (item.isEnabled() && (vs === value || contains(vs, value))) { index = i; return true; @@ -152,17 +159,17 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, { }); return index; - }, + } - getNodeById: function (id) { - var node; - BI.any(this.buttons, function (i, item) { + getNodeById(id) { + let node; + any(this.buttons, (i, item) => { if (item.isEnabled()) { if (item.attr("id") === id) { node = item; return true; - } else if (BI.isFunction(item.getNodeById)) { + } else if (isFunction(item.getNodeById)) { node = item.getNodeById(id); if (node) { return true; @@ -172,13 +179,13 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, { }); return node; - }, + } - getNodeByValue: function (value) { - var node; - BI.any(this.buttons, function (i, item) { + getNodeByValue(value) { + let node; + any(this.buttons, (i, item) => { if (item.isEnabled()) { - if (BI.isFunction(item.getNodeByValue)) { + if (isFunction(item.getNodeByValue)) { node = item.getNodeByValue(value); if (node) { return true; @@ -192,8 +199,5 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, { }); return node; - }, -}); -BI.ButtonTree.EVENT_CHANGE = "EVENT_CHANGE"; - -BI.shortcut("bi.button_tree", BI.ButtonTree); + } +} diff --git a/src/base/index.js b/src/base/index.js index b5f9c4faa..723070d48 100644 --- a/src/base/index.js +++ b/src/base/index.js @@ -1,3 +1,4 @@ +import { extend } from "../core"; import Pane from "./1.pane"; import Single from "./single/0.single"; import Text from "./single/1.text"; @@ -14,9 +15,20 @@ import VirtualGroupList from "./list/virtualgrouplist"; import VirtualList from "./list/virtuallist"; import GridView from "./grid/grid"; import Pager from "./pager/pager"; +import Bubble from "./combination/bubble"; +import Combo from "./combination/combo"; +import Expander from "./combination/expander"; +import ButtonGroup from "./combination/group.button"; +import ComboGroup from "./combination/group.combo"; +import VirtualGroup from "./combination/group.virtual"; +import Loader from "./combination/loader"; +import Navigation from "./combination/navigation"; +import Searcher from "./combination/searcher"; +import Switcher from "./combination/switcher"; +import Tab from "./combination/tab"; +import ButtonTree from "./combination/tree.button"; - -BI.extend(BI, { +extend(BI, { Pane, Single, Text, @@ -34,6 +46,18 @@ BI.extend(BI, { VirtualList, GridView, Pager, + Bubble, + Combo, + Expander, + ButtonGroup, + ComboGroup, + VirtualGroup, + Loader, + Navigation, + Searcher, + Switcher, + Tab, + ButtonTree, }); export { @@ -54,4 +78,16 @@ export { VirtualList, GridView, Pager, + Bubble, + Combo, + Expander, + ButtonGroup, + ComboGroup, + VirtualGroup, + Loader, + Navigation, + Searcher, + Switcher, + Tab, + ButtonTree, } \ No newline at end of file diff --git a/src/core/index.js b/src/core/index.js index 18b15a0f2..8295b976b 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -16,6 +16,7 @@ import PopoverController from "./controller/controller.popover"; import ResizeController from "./controller/controller.resizer"; import TooltipsController from "./controller/controller.tooltips"; import StyleLoaderManager from "./loader/loader.style"; +import ShowListener from "./listener/listener.show"; BI.extend(BI, { OB, @@ -35,6 +36,7 @@ BI.extend(BI, { ResizeController, TooltipsController, StyleLoaderManager, + ShowListener, }); export * from './2.base'; @@ -60,4 +62,5 @@ export { ResizeController, TooltipsController, StyleLoaderManager, + ShowListener, } \ No newline at end of file diff --git a/src/core/listener/listener.show.js b/src/core/listener/listener.show.js index af2236578..1c9469473 100644 --- a/src/core/listener/listener.show.js +++ b/src/core/listener/listener.show.js @@ -5,44 +5,50 @@ * @class BI.ShowListener * @extends BI.OB */ -BI.ShowListener = BI.inherit(BI.OB, { - props: function () { +import OB from "../3.ob"; +import { isArray, isNull, nextTick, } from "../2.base"; +import { createWidget } from "../5.inject"; +import Controller from "../controller/0.controller"; + +export default class ShowListener extends OB { + static EVENT_CHANGE = "EVENT_CHANGE"; + + props() { return { - eventObj: BI.createWidget(), + eventObj: createWidget(), cardLayout: null, - cardNameCreator: function (v) { + cardNameCreator: (v) => { return v; }, cardCreator: BI.emptyFn, afterCardCreated: BI.emptyFn, afterCardShow: BI.emptyFn }; - }, + } - init: function () { - var self = this, o = this.options; - if (o.eventObj) { - o.eventObj.on(BI.Controller.EVENT_CHANGE, function (type, v, ob) { + init() { + const { eventObj, cardLayout, afterCardCreated, cardNameCreator, cardCreator, afterCardShow } = this.options; + if (eventObj) { + eventObj.on(Controller.EVENT_CHANGE, (type, v, ob) => { if (type === BI.Events.CLICK) { - v = v || o.eventObj.getValue(); - v = BI.isArray(v) ? (v.length > 1 ? v.toString() : v[0]) : v; - if (BI.isNull(v)) { + v = v || eventObj.getValue(); + v = isArray(v) ? (v.length > 1 ? v.toString() : v[0]) : v; + if (isNull(v)) { throw new Error("不能为null"); } - var cardName = o.cardNameCreator(v); - if (!o.cardLayout.isCardExisted(cardName)) { - var card = o.cardCreator(cardName); - o.cardLayout.addCardByName(cardName, card); - o.afterCardCreated(cardName); + var cardName = cardNameCreator(v); + if (!cardLayout.isCardExisted(cardName)) { + const card = cardCreator(cardName); + cardLayout.addCardByName(cardName, card); + afterCardCreated(cardName); } - o.cardLayout.showCardByName(cardName); - BI.nextTick(function () { - o.afterCardShow(cardName); - self.fireEvent(BI.ShowListener.EVENT_CHANGE, cardName); + cardLayout.showCardByName(cardName); + nextTick(() => { + afterCardShow(cardName); + this.fireEvent(ShowListener.EVENT_CHANGE, cardName); }); } }); } } -}); -BI.ShowListener.EVENT_CHANGE = "EVENT_CHANGE"; +} From 15b9445faed5444ba0904058eb53b9a9d6d811aa Mon Sep 17 00:00:00 2001 From: zsmj Date: Tue, 3 Jan 2023 20:19:03 +0800 Subject: [PATCH 026/300] =?UTF-8?q?KERNEL-13991=20feat:=20core/func?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=A4=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/2.base.js | 30 +- src/core/func/alias.js | 1654 +++++++++--------- src/core/func/array.js | 29 +- src/core/func/date.js | 615 ++++--- src/core/func/function.js | 300 ++-- src/core/func/index.js | 23 + src/core/func/number.js | 274 ++- src/core/func/string.js | 224 ++- src/core/index.js | 8 +- src/core/platform/web/detectElementResize.js | 123 +- src/core/utils/chinesePY.js | 863 ++++----- 11 files changed, 2125 insertions(+), 2018 deletions(-) create mode 100644 src/core/func/index.js diff --git a/src/core/2.base.js b/src/core/2.base.js index 46bf10e92..a4e8df688 100644 --- a/src/core/2.base.js +++ b/src/core/2.base.js @@ -157,8 +157,10 @@ BI._.extend(BI, { BI._.each(["where", "findWhere", "invoke", "pluck", "shuffle", "sample", "toArray", "size"], function (name) { BI[name] = _apply(name); }); -BI._.each(["get", "set", "each", "map", "reduce", "reduceRight", "find", "filter", "reject", "every", "all", "some", "any", "max", "min", - "sortBy", "groupBy", "indexBy", "countBy", "partition", "clamp"], function (name) { +BI._.each([ + "get", "set", "each", "map", "reduce", "reduceRight", "find", "filter", "reject", "every", "all", "some", "any", "max", "min", + "sortBy", "groupBy", "indexBy", "countBy", "partition", "clamp" +], function (name) { if (name === "any") { BI[name] = _applyFunc("some"); } else { @@ -404,8 +406,10 @@ BI._.extend(BI, { }); // 数组相关的方法 -BI._.each(["first", "initial", "last", "rest", "compact", "flatten", "without", "union", "intersection", - "difference", "zip", "unzip", "object", "indexOf", "lastIndexOf", "sortedIndex", "range", "take", "takeRight", "uniqBy"], function (name) { +BI._.each([ + "first", "initial", "last", "rest", "compact", "flatten", "without", "union", "intersection", + "difference", "zip", "unzip", "object", "indexOf", "lastIndexOf", "sortedIndex", "range", "take", "takeRight", "uniqBy" +], function (name) { BI[name] = _apply(name); }); BI._.each(["findIndex", "findLastIndex"], function (name) { @@ -497,10 +501,12 @@ BI._.extend(BI, { }); // 对象相关方法 -BI._.each(["keys", "allKeys", "values", "pairs", "invert", "create", "functions", "extend", "extendOwn", +BI._.each([ + "keys", "allKeys", "values", "pairs", "invert", "create", "functions", "extend", "extendOwn", "defaults", "clone", "property", "propertyOf", "matcher", "isEqual", "isMatch", "isEmpty", "isElement", "isNumber", "isString", "isArray", "isObject", "isPlainObject", "isArguments", "isFunction", "isFinite", - "isBoolean", "isDate", "isRegExp", "isError", "isNaN", "isUndefined", "zipObject", "cloneDeep"], function (name) { + "isBoolean", "isDate", "isRegExp", "isError", "isNaN", "isUndefined", "zipObject", "cloneDeep" +], function (name) { BI[name] = _apply(name); }); export const keys = BI.keys; @@ -666,6 +672,7 @@ BI._.extend(BI, { export const deepClone = BI._.cloneDeep; export const deepExtend = BI._.deepExtend; + export function isDeepMatch(object, attrs) { let attrsKeys = keys(attrs), length = attrsKeys.length; if (object == null) { @@ -886,7 +893,7 @@ export const nextTick = (function () { }; })(); -BI._.extend(BI, { nextTick }); +BI._.extend(BI, { nextTick }); // 数字相关方法 BI._.each(["random"], function (name) { @@ -1351,9 +1358,8 @@ export function parseDateTime(str, fmt) { return today; } -export function getDate() { - const length = arguments.length; - const args = arguments; +export function getDate(...args) { + const length = args.length; let dt; switch (length) { // new Date() @@ -1458,5 +1464,5 @@ BI._.extend(BI, { checkDateLegal, parseDateTime, getDate, - getTime, -}); \ No newline at end of file + getTime, +}); diff --git a/src/core/func/alias.js b/src/core/func/alias.js index 2884e492b..f7ba2f324 100644 --- a/src/core/func/alias.js +++ b/src/core/func/alias.js @@ -1,938 +1,930 @@ -(function () { - var _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 = {}; - } - - function isEmpty (value) { - // 判断是否为空值 - var result = value === "" || value === null || value === undefined; - return result; - } - - // 判断是否是无效的日期 - function isInvalidDate (date) { - return date == "Invalid Date" || date == "NaN"; - } +import {each, isFunction, isNull, isObject, isPlainObject, keys, leftPad, parseDateTime, values} from "../2.base"; +import {replaceAll} from "./string"; +import {getFullDayName, getMonthName, getTimezone} from "./date"; + +var _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 = {}; +} + +function isEmpty(value) { + // 判断是否为空值 + return value === "" || value === null || value === undefined; +} + +// 判断是否是无效的日期 +function isInvalidDate(date) { + return date === "Invalid Date" || date === "NaN"; +} + +/** + * CHART-1400 + * 使用数值计算的方式来获取任意数值的科学技术表示值。 + * 科学计数格式 + */ +function _eFormat(text, fmt) { + text = +text; + + return eFormat(text, fmt); /** - * CHART-1400 - * 使用数值计算的方式来获取任意数值的科学技术表示值。 - * 科学计数格式 + * 科学计数格式具体计算过程 + * @param num + * @param format {String}有两种形式, + * 1、"0.00E00"这样的字符串表示正常的科学计数表示,只不过规定了数值精确到百分位, + * 而数量级的绝对值如果是10以下的时候在前面补零。 + * 2、 "##0.0E0"这样的字符串则规定用科学计数法表示之后的数值的整数部分是三位,精确到十分位, + * 数量级没有规定,因为没见过实数里有用科学计数法表示之后E的后面会小于一位的情况(0无所谓)。 + * @returns {*} */ - function _eFormat (text, fmt) { - text = +text; - - return eFormat(text, fmt); - - /** - * 科学计数格式具体计算过程 - * @param num - * @param format {String}有两种形式, - * 1、"0.00E00"这样的字符串表示正常的科学计数表示,只不过规定了数值精确到百分位, - * 而数量级的绝对值如果是10以下的时候在前面补零。 - * 2、 "##0.0E0"这样的字符串则规定用科学计数法表示之后的数值的整数部分是三位,精确到十分位, - * 数量级没有规定,因为没见过实数里有用科学计数法表示之后E的后面会小于一位的情况(0无所谓)。 - * @returns {*} - */ - function eFormat (num, format) { - var neg = num < 0 ? (num *= -1, "-") : "", - magnitudeNeg = ""; + function eFormat(num, format) { + var neg = num < 0 ? (num *= -1, "-") : "", + magnitudeNeg = ""; - var funcName = num > 0 && num < 1 ? "floor" : "ceil"; // -0.9999->-1 - // 数量级 - var magnitude = Math[funcName](Math.log(num) / Math.log(10)); + var funcName = num > 0 && num < 1 ? "floor" : "ceil"; // -0.9999->-1 + // 数量级 + var magnitude = Math[funcName](Math.log(num) / Math.log(10)); - if (!isFinite(magnitude)) { - return format.replace(/#/ig, "").replace(/\.e/ig, "E"); - } + if (!isFinite(magnitude)) { + return format.replace(/#/ig, "").replace(/\.e/ig, "E"); + } - num = num / Math.pow(10, magnitude); + num = num / Math.pow(10, magnitude); - // 让num转化成[1, 10)区间上的数 - if (num > 0 && num < 1) { - num *= 10; - magnitude -= 1; - } + // 让num转化成[1, 10)区间上的数 + if (num > 0 && num < 1) { + num *= 10; + magnitude -= 1; + } - // 计算出format中需要显示的整数部分的位数,然后更新这个数值,也更新数量级 - var integerLen = getInteger(magnitude, format); - integerLen > 1 && (magnitude -= integerLen - 1, num *= Math.pow(10, integerLen - 1)); + // 计算出format中需要显示的整数部分的位数,然后更新这个数值,也更新数量级 + var integerLen = getInteger(magnitude, format); + integerLen > 1 && (magnitude -= integerLen - 1, num *= Math.pow(10, integerLen - 1)); - magnitude < 0 && (magnitudeNeg = "-", magnitude *= -1); + magnitude < 0 && (magnitudeNeg = "-", magnitude *= -1); - // 获取科学计数法精确到的位数 - var precision = getPrecision(format); - // 判断num经过四舍五入之后是否有进位 - var isValueCarry = isValueCarried(num); + // 获取科学计数法精确到的位数 + var precision = getPrecision(format); + // 判断num经过四舍五入之后是否有进位 + var isValueCarry = isValueCarried(num); - num *= Math.pow(10, precision); - num = Math.round(num); - // 如果出现进位的情况,将num除以10 - isValueCarry && (num /= 10, magnitude += magnitudeNeg === "-" ? -1 : 1); - num /= Math.pow(10, precision); + num *= Math.pow(10, precision); + num = Math.round(num); + // 如果出现进位的情况,将num除以10 + isValueCarry && (num /= 10, magnitude += magnitudeNeg === "-" ? -1 : 1); + num /= Math.pow(10, precision); - // 小数部分保留precision位 - num = num.toFixed(precision); - // 格式化指数的部分 - magnitude = formatExponential(format, magnitude, magnitudeNeg); + // 小数部分保留precision位 + num = num.toFixed(precision); + // 格式化指数的部分 + magnitude = formatExponential(format, magnitude, magnitudeNeg); - return neg + num + "E" + magnitude; + return neg + num + "E" + magnitude; + } + + // 获取format格式规定的数量级的形式 + function formatExponential(format, num, magnitudeNeg) { + num += ""; + if (!/e/ig.test(format)) { + return num; } + format = format.split(/e/ig)[1]; - // 获取format格式规定的数量级的形式 - function formatExponential (format, num, magnitudeNeg) { - num += ""; - if (!/e/ig.test(format)) { - return num; - } - format = format.split(/e/ig)[1]; + while (num.length < format.length) { + num = "0" + num; + } - while (num.length < format.length) { - num = "0" + num; + // 如果magnitudeNeg是一个"-",而且num正好全是0,那么就别显示负号了 + var isAllZero = true; + for (var i = 0, len = num.length; i < len; i++) { + if (!isAllZero) { + continue; } + isAllZero = num.charAt(i) === "0"; + } + magnitudeNeg = isAllZero ? "" : magnitudeNeg; - // 如果magnitudeNeg是一个"-",而且num正好全是0,那么就别显示负号了 - var isAllZero = true; - for (var i = 0, len = num.length; i < len; i++) { - if (!isAllZero) { - continue; - } - isAllZero = num.charAt(i) === "0"; - } - magnitudeNeg = isAllZero ? "" : magnitudeNeg; + return magnitudeNeg + num; + } - return magnitudeNeg + num; + // 获取format规定的科学计数法精确到的位数 + function getPrecision(format) { + if (!/e/ig.test(format)) { + return 0; } + var arr = format.split(/e/ig)[0].split("."); - // 获取format规定的科学计数法精确到的位数 - function getPrecision (format) { - if (!/e/ig.test(format)) { - return 0; - } - var arr = format.split(/e/ig)[0].split("."); + return arr.length > 1 ? arr[1].length : 0; + } - return arr.length > 1 ? arr[1].length : 0; + // 获取数值科学计数法表示之后整数的位数 + // 这边我们还需要考虑#和0的问题 + function getInteger(magnitude, format) { + if (!/e/ig.test(format)) { + return 0; } + // return format.split(/e/ig)[0].split(".")[0].length; - // 获取数值科学计数法表示之后整数的位数 - // 这边我们还需要考虑#和0的问题 - function getInteger (magnitude, format) { - if (!/e/ig.test(format)) { - return 0; - } - // return format.split(/e/ig)[0].split(".")[0].length; - - var formatLeft = format.split(/e/ig)[0].split(".")[0], i, f, len = formatLeft.length; - var valueLeftLen = 0; + var formatLeft = format.split(/e/ig)[0].split(".")[0], i, f, len = formatLeft.length; + var valueLeftLen = 0; - for (i = 0; i < len; i++) { - f = formatLeft.charAt(i); - // "#"所在的位置到末尾长度小于等于值的整数部分长度,那么这个#才可以占位 - if (f == 0 || (f == "#" && (len - i <= magnitude + 1))) { - valueLeftLen++; - } + for (i = 0; i < len; i++) { + f = formatLeft.charAt(i); + // "#"所在的位置到末尾长度小于等于值的整数部分长度,那么这个#才可以占位 + if (f == 0 || (f == "#" && (len - i <= magnitude + 1))) { + valueLeftLen++; } - - return valueLeftLen; } - // 判断num通过round函数之后是否有进位 - function isValueCarried (num) { - var roundNum = Math.round(num); - num = (num + "").split(".")[0]; - roundNum = (roundNum + "").split(".")[0]; - return num.length !== roundNum.length; - } + return valueLeftLen; } - //'#.##'之类的格式处理 1.324e-18 这种的科学数字 - function _dealNumberPrecision (text, fright) { - if (/[eE]/.test(text)) { - var precision = 0, i = 0, ch; + // 判断num通过round函数之后是否有进位 + function isValueCarried(num) { + var roundNum = Math.round(num); + num = (num + "").split(".")[0]; + roundNum = (roundNum + "").split(".")[0]; + return num.length !== roundNum.length; + } +} - if (/[%‰]$/.test(fright)) { - precision = /[%]$/.test(fright) ? 2 : 3; - } +//'#.##'之类的格式处理 1.324e-18 这种的科学数字 +function _dealNumberPrecision(text, fright) { + if (/[eE]/.test(text)) { + var precision = 0, i = 0, ch; - for (var len = fright.length; i < len; i++) { - if ((ch = fright.charAt(i)) == "0" || ch == "#") { - precision++; - } - } - return Number(text).toFixed(precision); + if (/[%‰]$/.test(fright)) { + precision = /[%]$/.test(fright) ? 2 : 3; } - return text; + for (var len = fright.length; i < len; i++) { + if ((ch = fright.charAt(i)) == "0" || ch == "#") { + precision++; + } + } + return Number(text).toFixed(precision); } - /** - * 数字格式 - */ - function _numberFormat (text, format) { - var text = text + ""; + return text; +} - //在调用数字格式的时候如果text里没有任何数字则不处理 - if (!(/[0-9]/.test(text)) || !format) { - return text; - } +/** + * 数字格式 + */ +function _numberFormat(text, format) { + var text = text + ""; - // 数字格式,区分正负数 - var numMod = format.indexOf(";"); - if (numMod > -1) { - if (text >= 0) { - return _numberFormat(text + "", format.substring(0, numMod)); - } - return _numberFormat((-text) + "", format.substr(numMod + 1)); + //在调用数字格式的时候如果text里没有任何数字则不处理 + if (!(/[0-9]/.test(text)) || !format) { + return text; + } - } else { - // 兼容格式处理负数的情况(copy:fr-jquery.format.js) - if (+text < 0 && format.charAt(0) !== "-") { - return _numberFormat((-text) + "", "-" + format); - } + // 数字格式,区分正负数 + var numMod = format.indexOf(";"); + if (numMod > -1) { + if (text >= 0) { + return _numberFormat(text + "", format.substring(0, numMod)); } + return _numberFormat((-text) + "", format.substring(numMod + 1)); - var fp = format.split("."), fleft = fp[0] || "", fright = fp[1] || ""; - text = _dealNumberPrecision(text, fright); - var tp = text.split("."), tleft = tp[0] || "", tright = tp[1] || ""; - - // 百分比,千分比的小数点移位处理 - if (/[%‰]$/.test(format)) { - var paddingZero = /[%]$/.test(format) ? "00" : "000"; - tright += paddingZero; - tleft += tright.substr(0, paddingZero.length); - tleft = tleft.replace(/^0+/gi, ""); - tright = tright.substr(paddingZero.length).replace(/0+$/gi, ""); + } else { + // 兼容格式处理负数的情况(copy:fr-jquery.format.js) + if (+text < 0 && format.charAt(0) !== "-") { + return _numberFormat((-text) + "", "-" + format); } - var right = _dealWithRight(tright, fright); - if (right.leftPlus) { - // 小数点后有进位 - tleft = parseInt(tleft) + 1 + ""; + } - tleft = isNaN(tleft) ? "1" : tleft; - } - right = right.num; - var left = _dealWithLeft(tleft, fleft); - if (!(/[0-9]/.test(left))) { - left = left + "0"; - } - if (!(/[0-9]/.test(right))) { - return left + right; - } else { - return left + "." + right; - } + var fp = format.split("."), fleft = fp[0] || "", fright = fp[1] || ""; + text = _dealNumberPrecision(text, fright); + var tp = text.split("."), tleft = tp[0] || "", tright = tp[1] || ""; + + // 百分比,千分比的小数点移位处理 + if (/[%‰]$/.test(format)) { + var paddingZero = /[%]$/.test(format) ? "00" : "000"; + tright += paddingZero; + tleft += tright.substring(0, paddingZero.length); + tleft = tleft.replace(/^0+/gi, ""); + tright = tright.substring(paddingZero.length).replace(/0+$/gi, ""); } + var right = _dealWithRight(tright, fright); + if (right.leftPlus) { + // 小数点后有进位 + tleft = parseInt(tleft) + 1 + ""; - /** - * 处理小数点右边小数部分 - * @param tright 右边内容 - * @param fright 右边格式 - * @returns {JSON} 返回处理结果和整数部分是否需要进位 - * @private - */ - function _dealWithRight (tright, fright) { - var right = "", j = 0, i = 0; - for (var len = fright.length; i < len; i++) { - var ch = fright.charAt(i); - var c = tright.charAt(j); - switch (ch) { - case "0": - if (isEmpty(c)) { - c = "0"; - } - right += c; - j++; - break; - case "#": - right += c; - j++; - break; - default : - right += ch; - break; - } - } - var rll = tright.substr(j); - var result = {}; - if (!isEmpty(rll) && rll.charAt(0) > 4) { - // 有多余字符,需要四舍五入 - result.leftPlus = true; - var numReg = right.match(/^[0-9]+/); - if (numReg) { - var num = numReg[0]; - var orilen = num.length; - var newnum = parseInt(num) + 1 + ""; - // 进位到整数部分 - if (newnum.length > orilen) { - newnum = newnum.substr(1); - } else { - newnum = BI.leftPad(newnum, orilen, "0"); - result.leftPlus = false; + tleft = isNaN(tleft) ? "1" : tleft; + } + right = right.num; + var left = _dealWithLeft(tleft, fleft); + if (!(/[0-9]/.test(left))) { + left = left + "0"; + } + if (!(/[0-9]/.test(right))) { + return left + right; + } else { + return left + "." + right; + } +} + +/** + * 处理小数点右边小数部分 + * @param tright 右边内容 + * @param fright 右边格式 + * @returns {JSON} 返回处理结果和整数部分是否需要进位 + * @private + */ +function _dealWithRight(tright, fright) { + var right = "", j = 0, i = 0; + for (var len = fright.length; i < len; i++) { + var ch = fright.charAt(i); + var c = tright.charAt(j); + switch (ch) { + case "0": + if (isEmpty(c)) { + c = "0"; } - right = right.replace(/^[0-9]+/, newnum); - } + right += c; + j++; + break; + case "#": + right += c; + j++; + break; + default : + right += ch; + break; } - result.num = right; - return result; } - - /** - * 处理小数点左边整数部分 - * @param tleft 左边内容 - * @param fleft 左边格式 - * @returns {string} 返回处理结果 - * @private - */ - function _dealWithLeft (tleft, fleft) { - var left = ""; - var j = tleft.length - 1; - var combo = -1, last = -1; - var i = fleft.length - 1; - for (; i >= 0; i--) { - var ch = fleft.charAt(i); - var c = tleft.charAt(j); - switch (ch) { - case "0": - if (isEmpty(c)) { - c = "0"; - } - last = -1; - left = c + left; - j--; - break; - case "#": - last = i; - left = c + left; - j--; - break; - case ",": - if (!isEmpty(c)) { - // 计算一个,分隔区间的长度 - var com = fleft.match(/,[#0]+/); - if (com) { - combo = com[0].length - 1; - } - left = "," + left; - } - break; - default : - left = ch + left; - break; + var rll = tright.substring(j); + var result = {}; + if (!isEmpty(rll) && rll.charAt(0) > 4) { + // 有多余字符,需要四舍五入 + result.leftPlus = true; + var numReg = right.match(/^[0-9]+/); + if (numReg) { + var num = numReg[0]; + var orilen = num.length; + var newnum = parseInt(num) + 1 + ""; + // 进位到整数部分 + if (newnum.length > orilen) { + newnum = newnum.substring(1); + } else { + newnum = leftPad(newnum, orilen, "0"); + result.leftPlus = false; } + right = right.replace(/^[0-9]+/, newnum); } - if (last > -1) { - // 处理剩余字符 - var tll = tleft.substr(0, j + 1); - left = left.substr(0, last) + tll + left.substr(last); - } - if (combo > 0) { - // 处理,分隔区间 - var res = left.match(/[0-9]+,/); - if (res) { - res = res[0]; - var newstr = "", n = res.length - 1 - combo; - for (; n >= 0; n = n - combo) { - newstr = res.substr(n, combo) + "," + newstr; + } + result.num = right; + return result; +} + +/** + * 处理小数点左边整数部分 + * @param tleft 左边内容 + * @param fleft 左边格式 + * @returns {string} 返回处理结果 + * @private + */ +function _dealWithLeft(tleft, fleft) { + var left = ""; + var j = tleft.length - 1; + var combo = -1, last = -1; + var i = fleft.length - 1; + for (; i >= 0; i--) { + var ch = fleft.charAt(i); + var c = tleft.charAt(j); + switch (ch) { + case "0": + if (isEmpty(c)) { + c = "0"; } - var lres = res.substr(0, n + combo); - if (!isEmpty(lres)) { - newstr = lres + "," + newstr; + last = -1; + left = c + left; + j--; + break; + case "#": + last = i; + left = c + left; + j--; + break; + case ",": + if (!isEmpty(c)) { + // 计算一个,分隔区间的长度 + var com = fleft.match(/,[#0]+/); + if (com) { + combo = com[0].length - 1; + } + left = "," + left; } + break; + default : + left = ch + left; + break; + } + } + if (last > -1) { + // 处理剩余字符 + var tll = tleft.substring(0, j + 1); + left = left.substring(0, last) + tll + left.substring(last); + } + if (combo > 0) { + // 处理,分隔区间 + var res = left.match(/[0-9]+,/); + if (res) { + res = res[0]; + var newstr = "", n = res.length - 1 - combo; + for (; n >= 0; n = n - combo) { + newstr = res.substring(n, combo) + "," + newstr; + } + var lres = res.substring(0, n + combo); + if (!isEmpty(lres)) { + newstr = lres + "," + newstr; } - left = left.replace(/[0-9]+,/, newstr); } - return left; + left = left.replace(/[0-9]+,/, newstr); } + return left; +} +export const cjkEncode = function (text) { + // alex:如果非字符串,返回其本身(cjkEncode(234) 返回 ""是不对的) + if (typeof text !== "string") { + return text; + } - BI.cjkEncode = function (text) { - // alex:如果非字符串,返回其本身(cjkEncode(234) 返回 ""是不对的) - if (typeof text !== "string") { - return text; - } - - var newText = ""; - for (var i = 0; i < text.length; i++) { - var code = text.charCodeAt(i); - if (code >= 128 || code === 91 || code === 93) {// 91 is "[", 93 is "]". - newText += "[" + code.toString(16) + "]"; - } else { - newText += text.charAt(i); - } + var newText = ""; + for (var i = 0; i < text.length; i++) { + var code = text.charCodeAt(i); + if (code >= 128 || code === 91 || code === 93) {// 91 is "[", 93 is "]". + newText += "[" + code.toString(16) + "]"; + } else { + newText += text.charAt(i); } + } - return newText; - }; - - /** - * 将cjkEncode处理过的字符串转化为原始字符串 - * - * @static - * @param text 需要做解码的字符串 - * @return {String} 解码后的字符串 - */ - BI.cjkDecode = function (text) { - if (text == null) { - return ""; - } - // 查找没有 "[", 直接返回. kunsnat:数字的时候, 不支持indexOf方法, 也是直接返回. - if (!isNaN(text) || text.indexOf("[") == -1) { - return text; - } - - var newText = ""; - for (var i = 0; i < text.length; i++) { - var ch = text.charAt(i); - if (ch == "[") { - var rightIdx = text.indexOf("]", i + 1); - if (rightIdx > i + 1) { - var subText = text.substring(i + 1, rightIdx); - // james:主要是考虑[CDATA[]]这样的值的出现 - if (subText.length > 0) { - ch = String.fromCharCode(eval("0x" + subText)); - } + return newText; +}; + +/** + * 将cjkEncode处理过的字符串转化为原始字符串 + * + * @static + * @param text 需要做解码的字符串 + * @return {String} 解码后的字符串 + */ +export const cjkDecode = function (text) { + if (text == null) { + return ""; + } + // 查找没有 "[", 直接返回. kunsnat:数字的时候, 不支持indexOf方法, 也是直接返回. + if (!isNaN(text) || text.indexOf("[") == -1) { + return text; + } - i = rightIdx; + var newText = ""; + for (var i = 0; i < text.length; i++) { + var ch = text.charAt(i); + if (ch == "[") { + var rightIdx = text.indexOf("]", i + 1); + if (rightIdx > i + 1) { + var subText = text.substring(i + 1, rightIdx); + // james:主要是考虑[CDATA[]]这样的值的出现 + if (subText.length > 0) { + ch = String.fromCharCode(eval("0x" + subText)); } - } - newText += ch; + i = rightIdx; + } } - return newText; - }; + newText += ch; + } - // replace the html special tags - var SPECIAL_TAGS = { - "&": "&", - "\"": """, - "<": "<", - ">": ">", - "\x20": " ", - "\n": " " - }; - BI.htmlEncode = function (text) { - return BI.isNull(text) ? "" : BI.replaceAll(text + "", BI.keys(SPECIAL_TAGS).join("|"), function (v) { - return SPECIAL_TAGS[v] ? SPECIAL_TAGS[v] : v; - }); - }; - // html decode - BI.htmlDecode = function (text) { - return BI.isNull(text) ? "" : BI.replaceAll(text + "", BI.values(SPECIAL_TAGS).join("|"), function (v) { - switch (v) { - case "&": - return "&"; - case """: - return "\""; - case "<": - return "<"; - case ">": - return ">"; - case " ": - return " "; - case " ": - return "\n"; - default: - return v; + return newText; +}; + +// replace the html special tags +const SPECIAL_TAGS = { + "&": "&", + "\"": """, + "<": "<", + ">": ">", + "\x20": " ", + "\n": " " +}; +export const htmlEncode = function (text) { + return isNull(text) ? "" : replaceAll(text + "", keys(SPECIAL_TAGS).join("|"), function (v) { + return SPECIAL_TAGS[v] ? SPECIAL_TAGS[v] : v; + }); +}; +// html decode +export const htmlDecode = function (text) { + return isNull(text) ? "" : replaceAll(text + "", values(SPECIAL_TAGS).join("|"), function (v) { + switch (v) { + case "&": + return "&"; + case """: + return "\""; + case "<": + return "<"; + case ">": + return ">"; + case " ": + return " "; + case " ": + return "\n"; + default: + return v; + } + }); +}; + +export const cjkEncodeDO = function (o) { + if (isPlainObject(o)) { + var result = {}; + each(o, function (v, k) { + if (!(typeof v === "string")) { + v = jsonEncode(v); } + // wei:bug 43338,如果key是中文,cjkencode后o的长度就加了1,ie9以下版本死循环,所以新建对象result。 + k = cjkEncode(k); + result[k] = cjkEncode(v); }); + return result; + } + return o; +}; + +export const jsonEncode = function (o) { + // james:这个Encode是抄的EXT的 + var useHasOwn = !!{}.hasOwnProperty; + + // crashes Safari in some instances + // var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/; + + var m = { + "\b": "\\b", + "\t": "\\t", + "\n": "\\n", + "\f": "\\f", + "\r": "\\r", + "\"": "\\\"", + "\\": "\\\\" }; - BI.cjkEncodeDO = function (o) { - if (BI.isPlainObject(o)) { - var result = {}; - BI._.each(o, function (v, k) { - if (!(typeof v === "string")) { - v = BI.jsonEncode(v); + var encodeString = function (s) { + if (/["\\\x00-\x1f]/.test(s)) { + return "\"" + s.replace(/([\x00-\x1f\\"])/g, function (a, b) { + var c = m[b]; + if (c) { + return c; } - // wei:bug 43338,如果key是中文,cjkencode后o的长度就加了1,ie9以下版本死循环,所以新建对象result。 - k = BI.cjkEncode(k); - result[k] = BI.cjkEncode(v); - }); - return result; + c = b.charCodeAt(); + return "\\u00" + + Math.floor(c / 16).toString(16) + + (c % 16).toString(16); + }) + "\""; } - return o; + return "\"" + s + "\""; }; - BI.jsonEncode = function (o) { - // james:这个Encode是抄的EXT的 - var useHasOwn = !!{}.hasOwnProperty; - - // crashes Safari in some instances - // var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/; - - var m = { - "\b": "\\b", - "\t": "\\t", - "\n": "\\n", - "\f": "\\f", - "\r": "\\r", - "\"": "\\\"", - "\\": "\\\\" - }; - - var encodeString = function (s) { - if (/["\\\x00-\x1f]/.test(s)) { - return "\"" + s.replace(/([\x00-\x1f\\"])/g, function (a, b) { - var c = m[b]; - if (c) { - return c; + var encodeArray = function (o) { + var a = ["["], b, i, l = o.length, v; + for (i = 0; i < l; i += 1) { + v = o[i]; + switch (typeof v) { + case "undefined": + case "function": + case "unknown": + break; + default: + if (b) { + a.push(","); } - c = b.charCodeAt(); - return "\\u00" + - Math.floor(c / 16).toString(16) + - (c % 16).toString(16); - }) + "\""; - } - return "\"" + s + "\""; - }; - - var encodeArray = function (o) { - var a = ["["], b, i, l = o.length, v; - for (i = 0; i < l; i += 1) { - v = o[i]; - switch (typeof v) { - case "undefined": - case "function": - case "unknown": - break; - default: - if (b) { - a.push(","); - } - a.push(v === null ? "null" : BI.jsonEncode(v)); - b = true; - } - } - a.push("]"); - return a.join(""); - }; - - if (typeof o === "undefined" || o === null) { - return "null"; - } else if (BI.isArray(o)) { - return encodeArray(o); - } else if (o instanceof Date) { - /* - * alex:原来只是把年月日时分秒简单地拼成一个String,无法decode - * 现在这么处理就可以decode了,但是JS.jsonDecode和Java.JSONObject也要跟着改一下 - */ - return BI.jsonEncode({ - __time__: o.getTime() - }); - } else if (typeof o === "string") { - return encodeString(o); - } else if (typeof o === "number") { - return isFinite(o) ? String(o) : "null"; - } else if (typeof o === "boolean") { - return String(o); - } else if (BI.isFunction(o)) { - return String(o); - } - var a = ["{"], b, i, v; - for (i in o) { - if (!useHasOwn || o.hasOwnProperty(i)) { - v = o[i]; - switch (typeof v) { - case "undefined": - case "unknown": - break; - default: - if (b) { - a.push(","); - } - a.push(BI.jsonEncode(i), ":", - v === null ? "null" : BI.jsonEncode(v)); - b = true; - } + a.push(v === null ? "null" : jsonEncode(v)); + b = true; } } - a.push("}"); + a.push("]"); return a.join(""); - - }; - - BI.jsonDecode = function (text) { - - try { - // 注意0啊 - // var jo = $.parseJSON(text) || {}; - var jo = BI.$ ? BI.$.parseJSON(text) : _global.JSON.parse(text); - if (jo == null) { - jo = {}; - } - } catch (e) { - /* - * richie:浏览器只支持标准的JSON字符串转换,而jQuery会默认调用浏览器的window.JSON.parse()函数进行解析 - * 比如:var str = "{'a':'b'}",这种形式的字符串转换为JSON就会抛异常 - */ - try { - jo = new Function("return " + text)() || {}; - } catch (e) { - // do nothing - } - if (jo == null) { - jo = []; - } - } - if (!_hasDateInJson(text)) { - return jo; - } - - function _hasDateInJson (json) { - if (!json || typeof json !== "string") { - return false; - } - return json.indexOf("__time__") != -1; - } - - return (function (o) { - if (typeof o === "string") { - return o; - } - if (o && o.__time__ != null) { - return new Date(o.__time__); - } - for (var a in o) { - if (o[a] == o || typeof o[a] === "object" || BI._.isFunction(o[a])) { - break; - } - o[a] = arguments.callee(o[a]); - } - - return o; - })(jo); }; - /** - * 获取编码后的url - * @param urlTemplate url模板 - * @param param 参数 - * @returns {*|String} - * @example - * BI.getEncodeURL("design/{tableName}/{fieldName}",{tableName: "A", fieldName: "a"}) // design/A/a - */ - BI.getEncodeURL = function (urlTemplate, param) { - return BI.replaceAll(urlTemplate, "\\{(.*?)\\}", function (ori, str) { - return BI.encodeURIComponent(BI.isObject(param) ? param[str] : param); + if (typeof o === "undefined" || o === null) { + return "null"; + } else if (isArray(o)) { + return encodeArray(o); + } else if (o instanceof Date) { + /* + * alex:原来只是把年月日时分秒简单地拼成一个String,无法decode + * 现在这么处理就可以decode了,但是JS.jsonDecode和Java.JSONObject也要跟着改一下 + */ + return jsonEncode({ + __time__: o.getTime() }); - }; - - BI.encodeURIComponent = function (url) { - BI.specialCharsMap = BI.specialCharsMap || {}; - url = url || ""; - url = BI.replaceAll(url + "", BI.keys(BI.specialCharsMap || []).join("|"), function (str) { - switch (str) { - case "\\": - return BI.specialCharsMap["\\\\"] || str; + } else if (typeof o === "string") { + return encodeString(o); + } else if (typeof o === "number") { + return isFinite(o) ? String(o) : "null"; + } else if (typeof o === "boolean") { + return String(o); + } else if (isFunction(o)) { + return String(o); + } + var a = ["{"], b, i, v; + for (i in o) { + if (!useHasOwn || o.hasOwnProperty(i)) { + v = o[i]; + switch (typeof v) { + case "undefined": + case "unknown": + break; default: - return BI.specialCharsMap[str] || str; + if (b) { + a.push(","); + } + a.push(jsonEncode(i), ":", + v === null ? "null" : jsonEncode(v)); + b = true; } - }); - return _global.encodeURIComponent(url); - }; + } + } + a.push("}"); + return a.join(""); - BI.decodeURIComponent = function (url) { - var reserveSpecialCharsMap = {}; - BI.each(BI.specialCharsMap, function (initialChar, encodeChar) { - reserveSpecialCharsMap[encodeChar] = initialChar === "\\\\" ? "\\" : initialChar; - }); - url = url || ""; - url = BI.replaceAll(url + "", BI.keys(reserveSpecialCharsMap || []).join("|"), function (str) { - return reserveSpecialCharsMap[str] || str; - }); - return _global.decodeURIComponent(url); - }; +}; - BI.contentFormat = function (cv, fmt) { - if (isEmpty(cv)) { - // 原值为空,返回空字符 - return ""; - } - var text = cv.toString(); - if (isEmpty(fmt)) { - // 格式为空,返回原字符 - return text; - } - if (fmt.match(/^T/)) { - // T - 文本格式 - return text; - } else if (fmt.match(/^D/)) { - // D - 日期(时间)格式 - if (!(cv instanceof Date)) { - if (typeof cv === "number") { - // 毫秒数类型 - cv = new Date(cv); - } else { - //字符串类型转化为date类型 - cv = new Date(Date.parse(("" + cv).replace(/-|\./g, "/"))); - } - } - if (!isInvalidDate(cv) && !BI.isNull(cv)) { - var needTrim = fmt.match(/^DT/); - text = BI.date2Str(cv, fmt.substring(needTrim ? 2 : 1)); - } - } else if (fmt.match(/E/)) { - // 科学计数格式 - text = _eFormat(text, fmt); - } else { - // 数字格式 - text = _numberFormat(text, fmt); - } - // ¤ - 货币格式 - text = text.replace(/¤/g, "¥"); - return text; - }; +export const jsonDecode = function (text) { - /** - * 将Java提供的日期格式字符串装换为JS识别的日期格式字符串 - * @class FR.parseFmt - * @param fmt 日期格式 - * @returns {String} - */ - BI.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(/a{1}/g, "%p"); - //天 - if (new RegExp("d{2,}", "g").test(fmt)) { - fmt = fmt.replace(/d{2,}/g, "%d");//dd的时候替换为d - } else { - fmt = fmt.replace(/d{1}/g, "%e");//d的时候替换为j + try { + var jo = JSON.parse(text); + if (jo == null) { + jo = {}; } - //时 - if (new RegExp("h{2,}", "g").test(fmt)) {//12小时制 - fmt = fmt.replace(/h{2,}/g, "%I"); - } else { - fmt = fmt.replace(/h{1}/g, "%I"); + } catch (e) { + /* + * richie:浏览器只支持标准的JSON字符串转换,而jQuery会默认调用浏览器的window.JSON.parse()函数进行解析 + * 比如:var str = "{'a':'b'}",这种形式的字符串转换为JSON就会抛异常 + */ + try { + jo = new Function("return " + text)() || {}; + } catch (e) { + // do nothing } - if (new RegExp("H{2,}", "g").test(fmt)) {//24小时制 - fmt = fmt.replace(/H{2,}/g, "%H"); - } else { - fmt = fmt.replace(/H{1}/g, "%H"); + if (jo == null) { + jo = []; } - fmt = fmt.replace(/m{2,}/g, "%M")//分 - //秒 - .replace(/s{2,}/g, "%S"); - - return fmt; - }; + } + if (!_hasDateInJson(text)) { + return jo; + } - /** - * 把字符串按照对应的格式转化成日期对象 - * - * @example - * var result = BI.str2Date('2013-12-12', 'yyyy-MM-dd');//Thu Dec 12 2013 00:00:00 GMT+0800 - * - * @class BI.str2Date - * @param str 字符串 - * @param format 日期格式 - * @returns {*} - */ - BI.str2Date = function (str, format) { - if (typeof str != "string" || typeof format != "string") { - return null; + function _hasDateInJson(json) { + if (!json || typeof json !== "string") { + return false; } - var fmt = BI.parseFmt(format); - return BI.parseDateTime(str, fmt); - }; + return json.indexOf("__time__") !== -1; + } - /** - * 把日期对象按照指定格式转化成字符串 - * - * @example - * var date = new Date('Thu Dec 12 2013 00:00:00 GMT+0800'); - * var result = BI.date2Str(date, 'yyyy-MM-dd');//2013-12-12 - * - * @class BI.date2Str - * @param date 日期 - * @param format 日期格式 - * @returns {String} - */ - BI.date2Str = function (date, format) { - if (!date) { - return ""; - } - // O(len(format)) - var len = format.length, result = ""; - if (len > 0) { - var flagch = format.charAt(0), start = 0, str = flagch; - for (var i = 1; i < len; i++) { - var ch = format.charAt(i); - if (flagch !== ch) { - result += compileJFmt({ - char: flagch, - str: str, - len: i - start - }, date); - flagch = ch; - start = i; - str = flagch; - } else { - str += ch; - } - } - result += compileJFmt({ - char: flagch, - str: str, - len: len - start - }, date); + return (function parse(o) { + if (typeof o === "string") { + return o; } - return result; - - function compileJFmt (jfmt, date) { - var str = jfmt.str, len = jfmt.len, ch = jfmt["char"]; - switch (ch) { - case "E": // 星期 - str = BI.getFullDayName(date.getDay()); - break; - case "y": // 年 - if (len <= 3) { - str = (date.getFullYear() + "").slice(2, 4); - } else { - str = date.getFullYear(); - } - break; - case "M": // 月 - if (len > 2) { - str = BI.getMonthName(date.getMonth()); - } else if (len < 2) { - str = date.getMonth() + 1; - } else { - str = BI.leftPad(date.getMonth() + 1 + "", 2, "0"); - } - break; - case "d": // 日 - if (len > 1) { - str = BI.leftPad(date.getDate() + "", 2, "0"); - } else { - str = date.getDate(); - } - break; - case "h": // 时(12) - var hour = date.getHours() % 12; - if (hour === 0) { - hour = 12; - } - if (len > 1) { - str = BI.leftPad(hour + "", 2, "0"); - } else { - str = hour; - } - break; - case "H": // 时(24) - if (len > 1) { - str = BI.leftPad(date.getHours() + "", 2, "0"); - } else { - str = date.getHours(); - } - break; - case "m": - if (len > 1) { - str = BI.leftPad(date.getMinutes() + "", 2, "0"); - } else { - str = date.getMinutes(); - } - break; - case "s": - if (len > 1) { - str = BI.leftPad(date.getSeconds() + "", 2, "0"); - } else { - str = date.getSeconds(); - } - break; - case "a": - str = date.getHours() < 12 ? "am" : "pm"; - break; - case "z": - str = BI.getTimezone(date); - break; - default: - str = jfmt.str; - break; + if (o && o.__time__ != null) { + return new Date(o.__time__); + } + for (var a in o) { + if (o[a] == o || typeof o[a] === "object" || isFunction(o[a])) { + break; } - return str; + o[a] = parse(o[a]); } - }; - BI.object2Number = function (value) { - if (value == null) { - return 0; + return o; + })(jo); +}; + +/** + * 获取编码后的url + * @param urlTemplate url模板 + * @param param 参数 + * @returns {*|String} + * @example + * 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); + }); +}; + +export const encodeURIComponent = function (url) { + BI.specialCharsMap = BI.specialCharsMap || {}; + url = url || ""; + url = replaceAll(url + "", keys(BI.specialCharsMap || []).join("|"), function (str) { + switch (str) { + case "\\": + return BI.specialCharsMap["\\\\"] || str; + default: + return BI.specialCharsMap[str] || str; + } + }); + return _global.encodeURIComponent(url); +}; + +export const decodeURIComponent = function (url) { + var reserveSpecialCharsMap = {}; + each(BI.specialCharsMap, function (initialChar, encodeChar) { + reserveSpecialCharsMap[encodeChar] = initialChar === "\\\\" ? "\\" : initialChar; + }); + url = url || ""; + url = replaceAll(url + "", keys(reserveSpecialCharsMap || []).join("|"), function (str) { + return reserveSpecialCharsMap[str] || str; + }); + return _global.decodeURIComponent(url); +}; + +export const contentFormat = function (cv, fmt) { + if (isEmpty(cv)) { + // 原值为空,返回空字符 + return ""; + } + var text = cv.toString(); + if (isEmpty(fmt)) { + // 格式为空,返回原字符 + return text; + } + if (fmt.match(/^T/)) { + // T - 文本格式 + return text; + } else if (fmt.match(/^D/)) { + // D - 日期(时间)格式 + if (!(cv instanceof Date)) { + if (typeof cv === "number") { + // 毫秒数类型 + cv = new Date(cv); + } else { + //字符串类型转化为date类型 + cv = new Date(Date.parse(("" + cv).replace(/-|\./g, "/"))); + } } - if (typeof value === "number") { - return value; + if (!isInvalidDate(cv) && !isNull(cv)) { + var needTrim = fmt.match(/^DT/); + text = date2Str(cv, fmt.substring(needTrim ? 2 : 1)); } - var str = value + ""; - if (str.indexOf(".") === -1) { - return parseInt(str); + } else if (fmt.match(/E/)) { + // 科学计数格式 + text = _eFormat(text, fmt); + } else { + // 数字格式 + text = _numberFormat(text, fmt); + } + // ¤ - 货币格式 + text = text.replace(/¤/g, "¥"); + return text; +}; + +/** + * 将Java提供的日期格式字符串装换为JS识别的日期格式字符串 + * @param fmt 日期格式 + * @returns {string} + */ +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(/a{1}/g, "%p"); + //天 + if (new RegExp("d{2,}", "g").test(fmt)) { + fmt = fmt.replace(/d{2,}/g, "%d");//dd的时候替换为d + } else { + fmt = fmt.replace(/d{1}/g, "%e");//d的时候替换为j + } + //时 + 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小时制 + fmt = fmt.replace(/H{2,}/g, "%H"); + } else { + fmt = fmt.replace(/H{1}/g, "%H"); + } + fmt = fmt.replace(/m{2,}/g, "%M")//分 + //秒 + .replace(/s{2,}/g, "%S"); + + return fmt; +}; + +/** + * 把字符串按照对应的格式转化成日期对象 + * + * @example + * var result = BI.str2Date('2013-12-12', 'yyyy-MM-dd');//Thu Dec 12 2013 00:00:00 GMT+0800 + * @param str 字符串 + * @param format 日期格式 + * @returns {Date} + */ +export const str2Date = function (str, format) { + if (typeof str != "string" || typeof format != "string") { + return null; + } + var fmt = parseFmt(format); + return parseDateTime(str, fmt); +}; + +/** + * 把日期对象按照指定格式转化成字符串 + *@example + * var date = new Date('Thu Dec 12 2013 00:00:00 GMT+0800'); + * var result = BI.date2Str(date, 'yyyy-MM-dd');//2013-12-12 + * @param date + * @param format + * @returns {string} + */ +export const date2Str = function (date, format) { + if (!date) { + return ""; + } + // O(len(format)) + var len = format.length, result = ""; + if (len > 0) { + var flagch = format.charAt(0), start = 0, str = flagch; + for (var i = 1; i < len; i++) { + var ch = format.charAt(i); + if (flagch !== ch) { + result += compileJFmt({ + char: flagch, + str: str, + len: i - start + }, date); + flagch = ch; + start = i; + str = flagch; + } else { + str += ch; + } } - return parseFloat(str); - }; + result += compileJFmt({ + char: flagch, + str: str, + len: len - start + }, date); + } + return result; + + function compileJFmt(jfmt, date) { + var 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); + } else { + str = date.getFullYear(); + } + break; + case "M": // 月 + if (len > 2) { + str = getMonthName(date.getMonth()); + } else if (len < 2) { + str = date.getMonth() + 1; + } else { + str = leftPad(date.getMonth() + 1 + "", 2, "0"); + } + break; + case "d": // 日 + if (len > 1) { + str = leftPad(date.getDate() + "", 2, "0"); + } else { + str = date.getDate(); + } + break; + case "h": // 时(12) + var hour = date.getHours() % 12; + if (hour === 0) { + hour = 12; + } + if (len > 1) { + str = leftPad(hour + "", 2, "0"); + } else { + str = hour; + } + break; + case "H": // 时(24) + if (len > 1) { + str = leftPad(date.getHours() + "", 2, "0"); + } else { + str = date.getHours(); + } + break; + case "m": + if (len > 1) { + str = leftPad(date.getMinutes() + "", 2, "0"); + } else { + str = date.getMinutes(); + } + break; + case "s": + if (len > 1) { + str = leftPad(date.getSeconds() + "", 2, "0"); + } else { + str = date.getSeconds(); + } + break; + case "a": + str = date.getHours() < 12 ? "am" : "pm"; + break; + case "z": + str = getTimezone(date); + break; + default: + str = jfmt.str; + break; + } + return str; + } +}; - BI.object2Date = function (obj) { - if (obj == null) { - return new Date(); - } - if (obj instanceof Date) { - return obj; - } else if (typeof obj === "number") { - return new Date(obj); - } - var str = obj + ""; - str = str.replace(/-/g, "/"); - var dt = new Date(str); - if (!isInvalidDate(dt)) { - return dt; - } +export const object2Number = function (value) { + if (value == null) { + return 0; + } + if (typeof value === "number") { + return value; + } + var str = value + ""; + if (str.indexOf(".") === -1) { + return parseInt(str); + } + return parseFloat(str); +}; +export const object2Date = function (obj) { + if (obj == null) { return new Date(); + } + if (obj instanceof Date) { + return obj; + } else if (typeof obj === "number") { + return new Date(obj); + } + var str = obj + ""; + str = str.replace(/-/g, "/"); + var dt = new Date(str); + if (!isInvalidDate(dt)) { + return dt; + } - }; + return new Date(); - BI.object2Time = function (obj) { - if (obj == null) { - return new Date(); - } - if (obj instanceof Date) { - return obj; - } - var str = obj + ""; - str = str.replace(/-/g, "/"); - var dt = new Date(str); - if (!isInvalidDate(dt)) { - return dt; - } - if (str.indexOf("/") === -1 && str.indexOf(":") !== -1) { - dt = new Date("1970/01/01 " + str); - if (!isInvalidDate(dt)) { - return dt; - } - } - dt = BI.parseDateTime(str, "HH:mm:ss"); +}; + +export const object2Time = function (obj) { + if (obj == null) { + return new Date(); + } + if (obj instanceof Date) { + return obj; + } + var str = obj + ""; + str = str.replace(/-/g, "/"); + var dt = new Date(str); + if (!isInvalidDate(dt)) { + return dt; + } + if (str.indexOf("/") === -1 && str.indexOf(":") !== -1) { + dt = new Date("1970/01/01 " + str); if (!isInvalidDate(dt)) { return dt; } - return new Date(); + } + dt = parseDateTime(str, "HH:mm:ss"); + if (!isInvalidDate(dt)) { + return dt; + } + return new Date(); - }; -})(); +}; diff --git a/src/core/func/array.js b/src/core/func/array.js index a96292352..98f7d3703 100644 --- a/src/core/func/array.js +++ b/src/core/func/array.js @@ -2,21 +2,18 @@ * 对数组对象的扩展 * @class Array */ -BI._.extend(BI, { +export function pushArray(sArray, array) { + sArray.push(...array); +} - pushArray: function (sArray, array) { - for (var i = 0; i < array.length; i++) { - sArray.push(array[i]); - } - }, - pushDistinct: function (sArray, obj) { - if (!BI.contains(sArray, obj)) { - sArray.push(obj); - } - }, - pushDistinctArray: function (sArray, array) { - for (var i = 0, len = array.length; i < len; i++) { - BI.pushDistinct(sArray, array[i]); - } +export function pushDistinct(sArray, obj) { + if (sArray.indexOf(obj) !== -1) { + sArray.push(obj); } -}); +} + +export function pushDistinctArray(sArray, array) { + for (let i = 0, len = array.length; i < len; i++) { + pushDistinct(sArray, array[i]); + } +} diff --git a/src/core/func/date.js b/src/core/func/date.js index d603d235c..0d6ea79d3 100644 --- a/src/core/func/date.js +++ b/src/core/func/date.js @@ -1,16 +1,14 @@ /** Constants used for time computations */ -BI.Date = BI.Date || {}; -BI.Date.SECOND = 1000; -BI.Date.MINUTE = 60 * BI.Date.SECOND; -BI.Date.HOUR = 60 * BI.Date.MINUTE; -BI.Date.DAY = 24 * BI.Date.HOUR; -BI.Date.WEEK = 7 * BI.Date.DAY; +import {getDate, getTime} from "../2.base"; -// Monday first, etc. -BI.Date._FD = 1; - -// short month names -BI.Date._SMN = [0, +const SECOND = 1000; +const MINUTE = 60 * SECOND; +const HOUR = 60 * MINUTE; +const DAY = 24 * HOUR; +const WEEK = 7 * DAY; +const _FD = 1; +const _SMN = [ + 0, 1, 2, 3, @@ -21,292 +19,361 @@ BI.Date._SMN = [0, 8, 9, 10, - 11]; + 11 +]; +const _MD = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +const _OFFSET = [0, -1, -2, -3, -4, -5, -6]; // 实际上无论周几作为一周的第一天,周初周末都是在-6-0间做偏移,用一个数组就可以 -/** Adds the number of days array to the Date object. */ -BI.Date._MD = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +export const Date = { + SECOND, + MINUTE, + HOUR, + DAY, + WEEK, + _FD, + _SMN, + _MD, + _OFFSET, +}; -// 实际上无论周几作为一周的第一天,周初周末都是在-6-0间做偏移,用一个数组就可以 -BI.Date._OFFSET = [0, -1, -2, -3, -4, -5, -6]; +/** + * 获取时区 + * @returns {String} + */ +export function getTimezone(date) { + return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, ""); +} -BI._.extend(BI, { - /** - * 获取时区 - * @returns {String} - */ - getTimezone: function (date) { - return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, ""); - }, +/** + * Returns the number of days in the current month + */ +export function getMonthDays(date, month = date.getMonth()) { + var year = date.getFullYear(); + if (((0 === (year % 4)) && ((0 !== (year % 100)) || (0 === (year % 400)))) && month === 1) { + return 29; + } + return _MD[month]; +} - /** Returns the number of days in the current month */ - getMonthDays: function (date, month) { - var year = date.getFullYear(); - if (typeof month === "undefined") { - month = date.getMonth(); - } - if (((0 == (year % 4)) && ((0 != (year % 100)) || (0 == (year % 400)))) && month == 1) { - return 29; - } - return BI.Date._MD[month]; +/** + * 获取每月的最后一天 + * @returns {Date} + */ +export function getLastDateOfMont(date) { + return getDate(date.getFullYear(), date.getMonth(), getMonthDays(date)); +} - }, +/** + * 获取每月的最后一天 + * @returns {Date} + */ +export function getLastDateOfMonth(date) { + return getDate(date.getFullYear(), date.getMonth(), getMonthDays(date)); +} - /** - * 获取每月的最后一天 - * @returns {Date} - */ - getLastDateOfMonth: function (date) { - return BI.getDate(date.getFullYear(), date.getMonth(), BI.getMonthDays(date)); - }, +/** + * Returns the number of day in the year. + * @param date + * @returns {number} + */ +export function getDayOfYear(date) { + var now = getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); + var then = getDate(date.getFullYear(), 0, 0, 0, 0, 0); + var time = now - then; + return Math.floor(time / DAY); +} - /** Returns the number of day in the year. */ - getDayOfYear: function (date) { - var now = BI.getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); - var then = BI.getDate(date.getFullYear(), 0, 0, 0, 0, 0); - var time = now - then; - return Math.floor(time / BI.Date.DAY); - }, - /** Returns the number of the week in year, as defined in ISO 8601. */ - getWeekNumber: function (date) { - var d = BI.getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); - var week = d.getDay(); - var startOfWeek = BI.StartOfWeek % 7; - var middleDay = (startOfWeek + 3) % 7; - middleDay = middleDay || 7; - // 偏移到周周首之前需要多少天 - var offsetWeekStartCount = week < startOfWeek ? (7 + week - startOfWeek) : (week - startOfWeek); - var offsetWeekMiddleCount = middleDay < startOfWeek ? (7 + middleDay - startOfWeek) : (middleDay - startOfWeek); - d.setDate(d.getDate() - offsetWeekStartCount + offsetWeekMiddleCount); - var ms = d.valueOf(); - d.setMonth(0); - d.setDate(1); - return Math.floor((ms - d.valueOf()) / (7 * 864e5)) + 1; - }, +/** + * Returns the number of the week in year, as defined in ISO 8601. + * @param date + * @returns {number} + */ +export function getWeekNumber(date) { + var d = getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); + var week = d.getDay(); + var startOfWeek = BI.StartOfWeek % 7; + var middleDay = (startOfWeek + 3) % 7; + middleDay = middleDay || 7; + // 偏移到周周首之前需要多少天 + var offsetWeekStartCount = week < startOfWeek ? (7 + week - startOfWeek) : (week - startOfWeek); + var offsetWeekMiddleCount = middleDay < startOfWeek ? (7 + middleDay - startOfWeek) : (middleDay - startOfWeek); + d.setDate(d.getDate() - offsetWeekStartCount + offsetWeekMiddleCount); + var ms = d.valueOf(); + d.setMonth(0); + d.setDate(1); + return Math.floor((ms - d.valueOf()) / (7 * 864e5)) + 1; +} - getQuarter: function (date) { - return Math.floor(date.getMonth() / 3) + 1; - }, +export function getQuarter(date) { + return Math.floor(date.getMonth() / 3) + 1; +} - // 离当前时间多少天的时间 - getOffsetDate: function (date, offset) { - return BI.getDate(BI.getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()) + offset * 864e5); - }, +/** + * 离当前时间多少天的时间 + * @param date + * @param offset + * @returns {Date} + */ +export function getOffsetDate(date, offset) { + return getDate(getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()) + offset * 864e5); +} - getOffsetQuarter: function (date, n) { - var dt = BI.getDate(BI.getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds())); - var day = dt.getDate(); - var monthDay = BI.getMonthDays(BI.getDate(dt.getFullYear(), dt.getMonth() + BI.parseInt(n) * 3, 1)); - if (day > monthDay) { - day = monthDay; - } - dt.setDate(day); - dt.setMonth(dt.getMonth() + parseInt(n) * 3); - return dt; - }, +export function getOffsetQuarter(date, n) { + var dt = getDate(getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds())); + var day = dt.getDate(); + var monthDay = BI.getMonthDays(getDate(dt.getFullYear(), dt.getMonth() + parseInt(n, 10) * 3, 1)); + if (day > monthDay) { + day = monthDay; + } + dt.setDate(day); + dt.setMonth(dt.getMonth() + parseInt(n, 10) * 3); + return dt; +} - // 得到本季度的起始月份 - getQuarterStartMonth: function (date) { - var quarterStartMonth = 0; - var nowMonth = date.getMonth(); - if (nowMonth < 3) { - quarterStartMonth = 0; - } - if (2 < nowMonth && nowMonth < 6) { - quarterStartMonth = 3; - } - if (5 < nowMonth && nowMonth < 9) { - quarterStartMonth = 6; - } - if (nowMonth > 8) { - quarterStartMonth = 9; - } - return quarterStartMonth; - }, - // 获得本季度的起始日期 - getQuarterStartDate: function (date) { - return BI.getDate(date.getFullYear(), BI.getQuarterStartMonth(date), 1); - }, - // 得到本季度的结束日期 - getQuarterEndDate: function (date) { - var quarterEndMonth = BI.getQuarterStartMonth(date) + 2; - return BI.getDate(date.getFullYear(), quarterEndMonth, BI.getMonthDays(date, quarterEndMonth)); - }, +/** + * 得到本季度的起始月份 + * @param date + * @returns {number} + */ +export function getQuarterStartMonth(date) { + var quarterStartMonth = 0; + var nowMonth = date.getMonth(); + if (nowMonth < 3) { + quarterStartMonth = 0; + } + if (2 < nowMonth && nowMonth < 6) { + quarterStartMonth = 3; + } + if (5 < nowMonth && nowMonth < 9) { + quarterStartMonth = 6; + } + if (nowMonth > 8) { + quarterStartMonth = 9; + } + return quarterStartMonth; +} - // 指定日期n个月之前或之后的日期 - getOffsetMonth: function (date, n) { - var dt = BI.getDate(BI.getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds())); - var day = dt.getDate(); - var monthDay = BI.getMonthDays(BI.getDate(dt.getFullYear(), dt.getMonth() + parseInt(n), 1)); - if (day > monthDay) { - day = monthDay; - } - dt.setDate(day); - dt.setMonth(dt.getMonth() + parseInt(n)); - return dt; - }, +/** + * 获得本季度的起始日期 + * @param date + * @returns {Date} + */ +export function getQuarterStartDate(date) { + return getDate(date.getFullYear(), getQuarterStartMonth(date), 1); +} - // 获得本周的起始日期 - getWeekStartDate: function (date) { - var w = date.getDay(); - var startOfWeek = BI.StartOfWeek % 7; - return BI.getOffsetDate(date, BI.Date._OFFSET[w < startOfWeek ? (7 + w - startOfWeek) : (w - startOfWeek)]); - }, - // 得到本周的结束日期 - getWeekEndDate: function (date) { - var w = date.getDay(); - var startOfWeek = BI.StartOfWeek % 7; - return BI.getOffsetDate(date, BI.Date._OFFSET[w < startOfWeek ? (7 + w - startOfWeek) : (w - startOfWeek)] + 6); - }, +/** + * 得到本季度的结束日期 + * @param date + * @returns {Date} + */ +export function getQuarterEndDate(date) { + var quarterEndMonth = getQuarterStartMonth(date) + 2; + return getDate(date.getFullYear(), quarterEndMonth, getMonthDays(date)); +} - getFullDayName: function (index) { - return [BI.i18nText("BI-Basic_Sunday"), - BI.i18nText("BI-Basic_Monday"), - BI.i18nText("BI-Basic_Tuesday"), - BI.i18nText("BI-Basic_Wednesday"), - BI.i18nText("BI-Basic_Thursday"), - BI.i18nText("BI-Basic_Friday"), - BI.i18nText("BI-Basic_Saturday"), - BI.i18nText("BI-Basic_Sunday")][index]; - }, +/** + * 指定日期n个月之前或之后的日期 + * @param date + * @param n + * @returns {Date} + */ +export function getOffsetMonth(date, n) { + var dt = getDate(getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds())); + var day = dt.getDate(); + var monthDay = getMonthDays(getDate(dt.getFullYear(), dt.getMonth() + parseInt(n, 10), 1)); + if (day > monthDay) { + day = monthDay; + } + dt.setDate(day); + dt.setMonth(dt.getMonth() + parseInt(n, 10)); + return dt; +} - getShortDayName: function (index) { - return [BI.i18nText("BI-Basic_Simple_Sunday"), - BI.i18nText("BI-Basic_Simple_Monday"), - BI.i18nText("BI-Basic_Simple_Tuesday"), - BI.i18nText("BI-Basic_Simple_Wednesday"), - BI.i18nText("BI-Basic_Simple_Thursday"), - BI.i18nText("BI-Basic_Simple_Friday"), - BI.i18nText("BI-Basic_Simple_Saturday"), - BI.i18nText("BI-Basic_Simple_Sunday")][index]; - }, +/** + * 获得本周的起始日期 + * @param date + * @returns {Date} + */ +export function getWeekStartDate(date) { + var w = date.getDay(); + var startOfWeek = BI.StartOfWeek % 7; + return getOffsetDate(date, _OFFSET[w < startOfWeek ? (7 + w - startOfWeek) : (w - startOfWeek)]); +} - getMonthName: function (index) { - return [BI.i18nText("BI-Basic_January"), - BI.i18nText("BI-Basic_February"), - BI.i18nText("BI-Basic_March"), - BI.i18nText("BI-Basic_April"), - BI.i18nText("BI-Basic_May"), - BI.i18nText("BI-Basic_June"), - BI.i18nText("BI-Basic_July"), - BI.i18nText("BI-Basic_August"), - BI.i18nText("BI-Basic_September"), - BI.i18nText("BI-Basic_October"), - BI.i18nText("BI-Basic_November"), - BI.i18nText("BI-Basic_December")][index] - }, +/** + * 得到本周的结束日期 + * @param date + * @returns {Date} + */ +export function getWeekEndDate(date) { + var w = date.getDay(); + var startOfWeek = BI.StartOfWeek % 7; + return getOffsetDate(date, _OFFSET[w < startOfWeek ? (7 + w - startOfWeek) : (w - startOfWeek)] + 6); +} - getQuarterName: function (index) { - return ["", BI.i18nText("BI-Quarter_1"), - BI.i18nText("BI-Quarter_2"), - BI.i18nText("BI-Quarter_3"), - BI.i18nText("BI-Quarter_4")][index]; - }, +export function getFullDayName(index) { + return [ + BI.i18nText("BI-Basic_Sunday"), + BI.i18nText("BI-Basic_Monday"), + BI.i18nText("BI-Basic_Tuesday"), + BI.i18nText("BI-Basic_Wednesday"), + BI.i18nText("BI-Basic_Thursday"), + BI.i18nText("BI-Basic_Friday"), + BI.i18nText("BI-Basic_Saturday"), + BI.i18nText("BI-Basic_Sunday") + ][index]; +} - // 格式化打印日期 - print: function (date, str) { - var m = date.getMonth(); - var d = date.getDate(); - var y = date.getFullYear(); - var yWith4number = y + ""; - while (yWith4number.length < 4) { - yWith4number = "0" + yWith4number; - } - var wn = BI.getWeekNumber(date); - var qr = BI.getQuarter(date); - var w = date.getDay(); - var s = {}; - var hr = date.getHours(); - var pm = (hr >= 12); - var ir = (pm) ? (hr - 12) : hr; - var dy = BI.getDayOfYear(date); - if (ir == 0) { - ir = 12; - } - var min = date.getMinutes(); - var sec = date.getSeconds(); - s["%a"] = BI.getShortDayName(w); // abbreviated weekday name [FIXME: I18N] - s["%A"] = BI.getFullDayName(w); // full weekday name - s["%b"] = BI.Date._SMN[m]; // abbreviated month name [FIXME: I18N] - s["%B"] = BI.getMonthName(m); // full month name - // FIXME: %c : preferred date and time representation for the current locale - s["%C"] = 1 + Math.floor(y / 100); // the century number - s["%d"] = (d < 10) ? ("0" + d) : d; // the day of the month (range 01 to 31) - s["%e"] = d; // the day of the month (range 1 to 31) - // FIXME: %D : american date style: %m/%d/%y - // FIXME: %E, %F, %G, %g, %h (man strftime) - s["%H"] = (hr < 10) ? ("0" + hr) : hr; // hour, range 00 to 23 (24h format) - s["%I"] = (ir < 10) ? ("0" + ir) : ir; // hour, range 01 to 12 (12h format) - s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; // day of the year (range 001 to 366) - s["%k"] = hr + ""; // hour, range 0 to 23 (24h format) - s["%l"] = ir + ""; // hour, range 1 to 12 (12h format) - s["%X"] = (m < 9) ? ("0" + (1 + m)) : (1 + m); // month, range 01 to 12 - s["%x"] = m + 1; // month, range 1 to 12 - s["%M"] = (min < 10) ? ("0" + min) : min; // minute, range 00 to 59 - s["%n"] = "\n"; // a newline character - s["%p"] = pm ? "PM" : "AM"; - s["%P"] = pm ? "pm" : "am"; - // FIXME: %r : the time in am/pm notation %I:%M:%S %p - // FIXME: %R : the time in 24-hour notation %H:%M - s["%s"] = Math.floor(date.getTime() / 1000); - s["%S"] = (sec < 10) ? ("0" + sec) : sec; // seconds, range 00 to 59 - s["%t"] = "\t"; // a tab character - // FIXME: %T : the time in 24-hour notation (%H:%M:%S) - s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn; - s["%u"] = w + 1; // the day of the week (range 1 to 7, 1 = MON) - s["%w"] = w; // the day of the week (range 0 to 6, 0 = SUN) - // FIXME: %x : preferred date representation for the current locale without the time - // FIXME: %X : preferred time representation for the current locale without the date - s["%y"] = yWith4number.substr(2, 2); // year without the century (range 00 to 99) - s["%Y"] = yWith4number; // year with the century - s["%%"] = "%"; // a literal '%' character - s["%q"] = "0" + qr; - s["%Q"] = qr; +export function getShortDayName(index) { + return [ + BI.i18nText("BI-Basic_Simple_Sunday"), + BI.i18nText("BI-Basic_Simple_Monday"), + BI.i18nText("BI-Basic_Simple_Tuesday"), + BI.i18nText("BI-Basic_Simple_Wednesday"), + BI.i18nText("BI-Basic_Simple_Thursday"), + BI.i18nText("BI-Basic_Simple_Friday"), + BI.i18nText("BI-Basic_Simple_Saturday"), + BI.i18nText("BI-Basic_Simple_Sunday") + ][index]; +} - var re = /%./g; - BI.isKhtml = BI.isKhtml || function () { - if(!_global.navigator) { - return false; - } - return /Konqueror|Safari|KHTML/i.test(navigator.userAgent); - }; +export function getMonthName(index) { + return [ + BI.i18nText("BI-Basic_January"), + BI.i18nText("BI-Basic_February"), + BI.i18nText("BI-Basic_March"), + BI.i18nText("BI-Basic_April"), + BI.i18nText("BI-Basic_May"), + BI.i18nText("BI-Basic_June"), + BI.i18nText("BI-Basic_July"), + BI.i18nText("BI-Basic_August"), + BI.i18nText("BI-Basic_September"), + BI.i18nText("BI-Basic_October"), + BI.i18nText("BI-Basic_November"), + BI.i18nText("BI-Basic_December") + ][index]; +} - // 包含年周的格式化,ISO8601标准周的计数会影响年 - if ((str.indexOf("%Y") !== -1 || str.indexOf("%y") !== -1) && (str.indexOf("%W") !== -1 || str.indexOf("%U") !== -1 || str.indexOf("%V") !== -1)) { - switch (wn) { - // 如果周数是1,但是当前却在12月,表示此周数为下一年的 - case 1: - if (m === 11) { - s["%y"] = parseInt(s["%y"]) + 1; - s["%Y"] = parseInt(s["%Y"]) + 1; - } - break; - // 如果周数是53,但是当前却在1月,表示此周数为上一年的 - case 53: - if (m === 0) { - s["%y"] = parseInt(s["%y"]) - 1; - s["%Y"] = parseInt(s["%Y"]) - 1; - } - break; - default: - break; - } - } +export function getQuarterName(index) { + return [ + "", + BI.i18nText("BI-Quarter_1"), + BI.i18nText("BI-Quarter_2"), + BI.i18nText("BI-Quarter_3"), + BI.i18nText("BI-Quarter_4") + ][index]; +} - if (!BI.isKhtml()) { - return str.replace(re, function (par) { - return s[par] || par; - }); +/** + * 格式化打印日期 + * @param date + * @param str + * @returns {*} + */ +export function print(date, str) { + var m = date.getMonth(); + var d = date.getDate(); + var y = date.getFullYear(); + var yWith4number = y + ""; + while (yWith4number.length < 4) { + yWith4number = "0" + yWith4number; + } + var wn = getWeekNumber(date); + var qr = getQuarter(date); + var w = date.getDay(); + var s = {}; + var hr = date.getHours(); + var pm = (hr >= 12); + var ir = (pm) ? (hr - 12) : hr; + var dy = getDayOfYear(date); + if (ir === 0) { + ir = 12; + } + var min = date.getMinutes(); + var sec = date.getSeconds(); + s["%a"] = getShortDayName(w); // abbreviated weekday name [FIXME: I18N] + s["%A"] = getFullDayName(w); // full weekday name + s["%b"] = _SMN[m]; // abbreviated month name [FIXME: I18N] + s["%B"] = getMonthName(m); // full month name + // FIXME: %c : preferred date and time representation for the current locale + s["%C"] = 1 + Math.floor(y / 100); // the century number + s["%d"] = (d < 10) ? ("0" + d) : d; // the day of the month (range 01 to 31) + s["%e"] = d; // the day of the month (range 1 to 31) + // FIXME: %D : american date style: %m/%d/%y + // FIXME: %E, %F, %G, %g, %h (man strftime) + s["%H"] = (hr < 10) ? ("0" + hr) : hr; // hour, range 00 to 23 (24h format) + s["%I"] = (ir < 10) ? ("0" + ir) : ir; // hour, range 01 to 12 (12h format) + s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; // day of the year (range 001 to 366) + s["%k"] = hr + ""; // hour, range 0 to 23 (24h format) + s["%l"] = ir + ""; // hour, range 1 to 12 (12h format) + s["%X"] = (m < 9) ? ("0" + (1 + m)) : (1 + m); // month, range 01 to 12 + s["%x"] = m + 1; // month, range 1 to 12 + s["%M"] = (min < 10) ? ("0" + min) : min; // minute, range 00 to 59 + s["%n"] = "\n"; // a newline character + s["%p"] = pm ? "PM" : "AM"; + s["%P"] = pm ? "pm" : "am"; + // FIXME: %r : the time in am/pm notation %I:%M:%S %p + // FIXME: %R : the time in 24-hour notation %H:%M + s["%s"] = Math.floor(date.getTime() / 1000); + s["%S"] = (sec < 10) ? ("0" + sec) : sec; // seconds, range 00 to 59 + s["%t"] = "\t"; // a tab character + // FIXME: %T : the time in 24-hour notation (%H:%M:%S) + s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn; + s["%u"] = w + 1; // the day of the week (range 1 to 7, 1 = MON) + s["%w"] = w; // the day of the week (range 0 to 6, 0 = SUN) + // FIXME: %x : preferred date representation for the current locale without the time + // FIXME: %X : preferred time representation for the current locale without the date + s["%y"] = yWith4number.substr(2, 2); // year without the century (range 00 to 99) + s["%Y"] = yWith4number; // year with the century + s["%%"] = "%"; // a literal '%' character + s["%q"] = "0" + qr; + s["%Q"] = qr; + + var re = /%./g; + BI.isKhtml = BI.isKhtml || function () { + if (!_global.navigator) { + return false; } - var a = str.match(re); - for (var i = 0; i < a.length; i++) { - var tmp = s[a[i]]; - if (tmp) { - re = new RegExp(a[i], "g"); - str = str.replace(re, tmp); - } + return /Konqueror|Safari|KHTML/i.test(navigator.userAgent); + }; + + // 包含年周的格式化,ISO8601标准周的计数会影响年 + if ((str.indexOf("%Y") !== -1 || str.indexOf("%y") !== -1) && (str.indexOf("%W") !== -1 || str.indexOf("%U") !== -1 || str.indexOf("%V") !== -1)) { + switch (wn) { + // 如果周数是1,但是当前却在12月,表示此周数为下一年的 + case 1: + if (m === 11) { + s["%y"] = parseInt(s["%y"]) + 1; + s["%Y"] = parseInt(s["%Y"]) + 1; + } + break; + // 如果周数是53,但是当前却在1月,表示此周数为上一年的 + case 53: + if (m === 0) { + s["%y"] = parseInt(s["%y"]) - 1; + s["%Y"] = parseInt(s["%Y"]) - 1; + } + break; + default: + break; } + } - return str; + if (!BI.isKhtml()) { + return str.replace(re, function (par) { + return s[par] || par; + }); } -}); + var a = str.match(re); + for (var i = 0; i < a.length; i++) { + var tmp = s[a[i]]; + if (tmp) { + re = new RegExp(a[i], "g"); + str = str.replace(re, tmp); + } + } + + return str; +} diff --git a/src/core/func/function.js b/src/core/func/function.js index 83d58c5ec..e66b54453 100644 --- a/src/core/func/function.js +++ b/src/core/func/function.js @@ -2,167 +2,173 @@ * 基本的函数 * Created by GUY on 2015/6/24. */ -BI.Func = BI.Func || {}; -BI._.extend(BI.Func, { - /** - * 创建唯一的名字 - * @param array - * @param name - * @returns {*} - */ - createDistinctName: function (array, name) { - var src = name, idx = 1; - name = name || ""; - while (true) { - if (BI.every(array, function (i, item) { - return BI.isKey(item) ? item !== name : item.name !== name; - })) { - break; - } - name = src + (idx++); +import {every, isKey, isArray, toUpperCase, each, stripEL, isNotNull, isNull, isObject} from "../2.base"; +import {makeFirstPY} from "../utils/chinesePY"; + +/** + * 创建唯一的名字 + * @param array + * @param name + * @returns {*} + */ +export function createDistinctName(array, name) { + var src = name, idx = 1; + name = name || ""; + while (true) { + if (every(array, function (i, item) { + return isKey(item) ? item !== name : item.name !== name; + })) { + break; } - return name; - }, + name = src + (idx++); + } + return name; +} - /** - * 获取字符宽度 - * @param str - * @return {number} - */ - getGBWidth: function (str) { - str = str + ""; - str = str.replace(/[^\x00-\xff]/g, "xx"); - return Math.ceil(str.length / 2); - }, +/** + * 获取字符宽度 + * @param str + * @return {number} + */ +export function getGBWidth(str) { + str = str + ""; + str = str.replace(/[^\x00-\xff]/g, "xx"); + return Math.ceil(str.length / 2); +} - /** - * 获取搜索结果 - * @param items - * @param keyword - * @param param 搜索哪个属性 - */ - getSearchResult: function (items, keyword, param) { - var isArray = BI.isArray(items); - items = isArray ? BI.flatten(items) : items; - param || (param = "text"); - if (!BI.isKey(keyword)) { - return { - find: items, - match: isArray ? [] : {} - }; +/** + * 获取搜索结果 + * @param items + * @param keyword + * @param param 搜索哪个属性 + */ +export function getSearchResult(items, keyword, param) { + var array = isArray(items); + items = array ? BI.flatten(items) : items; + param || (param = "text"); + if (!isKey(keyword)) { + return { + find: items, + match: array ? [] : {} + }; + } + var t, text, py; + keyword = toUpperCase(keyword); + var matched = array ? [] : {}, find = array ? [] : {}; + each(items, function (i, item) { + // 兼容item为null的处理 + if (isNull(item)) { + return; } - var t, text, py; - keyword = BI.toUpperCase(keyword); - var matched = isArray ? [] : {}, find = isArray ? [] : {}; - BI.each(items, function (i, item) { - // 兼容item为null的处理 - if (BI.isNull(item)) { - return; - } - t = BI.stripEL(item); - text = BI.find([t[param], t.text, t.value, t.name, t], function (index, val) { - return BI.isNotNull(val); - }); + t = stripEL(item); + text = [t[param], t.text, t.value, t.name, t].find(isNotNull); - if (BI.isNull(text) || BI.isObject(text)) return; + if (isNull(text) || isObject(text)) return; - py = BI.makeFirstPY(text, { - splitChar: "\u200b" - }); - text = BI.toUpperCase(text); - py = BI.toUpperCase(py); - var pidx; - if (text.indexOf(keyword) > -1) { - if (text === keyword) { - isArray ? matched.push(item) : (matched[i] = item); - } else { - isArray ? find.push(item) : (find[i] = item); - } - // BI-56386 这边两个pid / text.length是为了防止截取的首字符串不是完整的,但光这样做还不够,即时错位了,也不能说明就不符合条件 - } else if (pidx = py.indexOf(keyword), (pidx > -1)) { + py = makeFirstPY(text, { + splitChar: "\u200b" + }); + text = toUpperCase(text); + py = toUpperCase(py); + var pidx; + if (text.indexOf(keyword) > -1) { + if (text === keyword) { + array ? matched.push(item) : (matched[i] = item); + } else { + array ? find.push(item) : (find[i] = item); + } + } else { // BI-56386 这边两个pid / text.length是为了防止截取的首字符串不是完整的,但光这样做还不够,即时错位了,也不能说明就不符合条件 + pidx = py.indexOf(keyword); + if (pidx > -1) { if (text === keyword || keyword.length === text.length) { - isArray ? matched.push(item) : (matched[i] = item); + array ? matched.push(item) : (matched[i] = item); } else { - isArray ? find.push(item) : (find[i] = item); + array ? find.push(item) : (find[i] = item); } } - }); - return { - match: matched, - find: find - }; - }, - - /** - * 获取按GB2312排序的结果 - * @param items - * @param key - * @return {any[]} - */ - getSortedResult: function (items, key) { - var getTextOfItem = BI.isFunction(key) ? key : - function (item, key) { - if (BI.isNotNull(key)) { - return item[key]; - } - if (BI.isNotNull(item.text)) { - return item.text; - } - if (BI.isNotNull(item.value)) { - return item.value; - } - return item; - }; + } + }); + return { + match: matched, + find: find + }; +} - return items.sort(function (item1, item2) { - var str1 = getTextOfItem(item1, key); - var str2 = getTextOfItem(item2, key); - if (BI.isNull(str1) && BI.isNull(str2)) { - return 0; - } - if (BI.isNull(str1)) { - return -1; - } - if (BI.isNull(str2)) { - return 1; - } - if (str1 === str2) { - return 0; +/** + * 获取按GB2312排序的结果 + * @param items + * @param key + * @return {any[]} + */ +export function getSortedResult(items, key) { + var getTextOfItem = BI.isFunction(key) ? key : + function (item, key) { + if (BI.isNotNull(key)) { + return item[key]; } - var len1 = str1.length, len2 = str2.length; - for (var i = 0; i < len1 && i < len2; i++) { - var char1 = str1[i]; - var char2 = str2[i]; - if (char1 !== char2) { - // 找不到的字符都往后面放 - return (BI.isNull(BI.CODE_INDEX[char1]) ? BI.MAX : BI.CODE_INDEX[char1]) - (BI.isNull(BI.CODE_INDEX[char2]) ? BI.MAX : BI.CODE_INDEX[char2]); - } + if (BI.isNotNull(item.text)) { + return item.text; } - return len1 - len2; - }); - } -}); - -BI._.extend(BI, { - beforeFunc: function (sFunc, func) { - var __self = sFunc; - return function () { - if (func.apply(sFunc, arguments) === false) { - return false; + if (BI.isNotNull(item.value)) { + return item.value; } - return __self.apply(sFunc, arguments); + return item; }; - }, - afterFunc: function (sFunc, func) { - var __self = sFunc; - return function () { - var ret = __self.apply(sFunc, arguments); - if (ret === false) { - return false; + return items.sort(function (item1, item2) { + var str1 = getTextOfItem(item1, key); + var str2 = getTextOfItem(item2, key); + if (BI.isNull(str1) && BI.isNull(str2)) { + return 0; + } + if (BI.isNull(str1)) { + return -1; + } + if (BI.isNull(str2)) { + return 1; + } + if (str1 === str2) { + return 0; + } + var len1 = str1.length, len2 = str2.length; + for (var i = 0; i < len1 && i < len2; i++) { + var char1 = str1[i]; + var char2 = str2[i]; + if (char1 !== char2) { + // 找不到的字符都往后面放 + return (BI.isNull(BI.CODE_INDEX[char1]) ? BI.MAX : BI.CODE_INDEX[char1]) - (BI.isNull(BI.CODE_INDEX[char2]) ? BI.MAX : BI.CODE_INDEX[char2]); } - func.apply(sFunc, arguments); - return ret; - }; - } -}); + } + return len1 - len2; + }); +} + +export function beforeFunc(sFunc, func) { + var __self = sFunc; + return function () { + if (func.apply(sFunc, arguments) === false) { + return false; + } + return __self.apply(sFunc, arguments); + }; +} + +export function afterFunc(sFunc, func) { + var __self = sFunc; + return function () { + var ret = __self.apply(sFunc, arguments); + if (ret === false) { + return false; + } + func.apply(sFunc, arguments); + return ret; + }; +} + + +export const Func = { + createDistinctName, + getGBWidth, + getSearchResult, + getSortedResult, +}; diff --git a/src/core/func/index.js b/src/core/func/index.js new file mode 100644 index 000000000..3475bf8d6 --- /dev/null +++ b/src/core/func/index.js @@ -0,0 +1,23 @@ +export * from "./alias"; +export * from "./array"; +export * from "./date"; +export * from "./function"; +export * from "./number"; +export * from "./string"; + +// need delete +import * as _alias from "./alias"; +import * as _array from "./array"; +import * as _date from "./date"; +import * as _function from "./function"; +import * as _number from "./number"; +import * as _string from "./string"; + +Object.assign(BI, { + ..._alias, + ..._array, + ..._date, + ..._function, + ..._number, + ..._string +}); diff --git a/src/core/func/number.js b/src/core/func/number.js index 59021349f..73f9dbec6 100644 --- a/src/core/func/number.js +++ b/src/core/func/number.js @@ -1,156 +1,154 @@ -BI._.extend(BI, { - // 给Number类型增加一个add方法,调用起来更加方便。 - add: function (num, arg) { - return accAdd(arg, num); +// 给Number类型增加一个add方法,调用起来更加方便。 +export function add(num, arg) { + return accAdd(arg, num); - /** - ** 加法函数,用来得到精确的加法结果 - ** 说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。 - ** 调用:accAdd(arg1,arg2) - ** 返回值:arg1加上arg2的精确结果 - **/ - function accAdd (arg1, arg2) { - var r1, r2, m, c; - try { - r1 = arg1.toString().split(".")[1].length; - } catch (e) { - r1 = 0; - } - try { - r2 = arg2.toString().split(".")[1].length; - } catch (e) { - r2 = 0; - } - c = Math.abs(r1 - r2); - m = Math.pow(10, Math.max(r1, r2)); - if (c > 0) { - var cm = Math.pow(10, c); - if (r1 > r2) { - arg1 = Number(arg1.toString().replace(".", "")); - arg2 = Number(arg2.toString().replace(".", "")) * cm; - } else { - arg1 = Number(arg1.toString().replace(".", "")) * cm; - arg2 = Number(arg2.toString().replace(".", "")); - } - } else { + /** + ** 加法函数,用来得到精确的加法结果 + ** 说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。 + ** 调用:accAdd(arg1,arg2) + ** 返回值:arg1加上arg2的精确结果 + **/ + function accAdd(arg1, arg2) { + var r1, r2, m, c; + try { + r1 = arg1.toString().split(".")[1].length; + } catch (e) { + r1 = 0; + } + try { + r2 = arg2.toString().split(".")[1].length; + } catch (e) { + r2 = 0; + } + c = Math.abs(r1 - r2); + m = Math.pow(10, Math.max(r1, r2)); + if (c > 0) { + var cm = Math.pow(10, c); + if (r1 > r2) { arg1 = Number(arg1.toString().replace(".", "")); + arg2 = Number(arg2.toString().replace(".", "")) * cm; + } else { + arg1 = Number(arg1.toString().replace(".", "")) * cm; arg2 = Number(arg2.toString().replace(".", "")); } - return (arg1 + arg2) / m; + } else { + arg1 = Number(arg1.toString().replace(".", "")); + arg2 = Number(arg2.toString().replace(".", "")); } - }, + return (arg1 + arg2) / m; + } +} - // 给Number类型增加一个sub方法,调用起来更加方便。 - sub: function (num, arg) { - return accSub(num, arg); +// 给Number类型增加一个sub方法,调用起来更加方便。 +export function sub(num, arg) { + return accSub(num, arg); - /** - ** 减法函数,用来得到精确的减法结果 - ** 说明:javascript的减法结果会有误差,在两个浮点数相减的时候会比较明显。这个函数返回较为精确的减法结果。 - ** 调用:accSub(arg1,arg2) - ** 返回值:arg1加上arg2的精确结果 - **/ - function accSub (arg1, arg2) { - var r1, r2, m, n; - try { - r1 = arg1.toString().split(".")[1].length; - } catch (e) { - r1 = 0; - } - try { - r2 = arg2.toString().split(".")[1].length; - } catch (e) { - r2 = 0; - } - m = Math.pow(10, Math.max(r1, r2)); // last modify by deeka //动态控制精度长度 - n = (r1 >= r2) ? r1 : r2; - return ((arg1 * m - arg2 * m) / m).toFixed(n); + /** + ** 减法函数,用来得到精确的减法结果 + ** 说明:javascript的减法结果会有误差,在两个浮点数相减的时候会比较明显。这个函数返回较为精确的减法结果。 + ** 调用:accSub(arg1,arg2) + ** 返回值:arg1加上arg2的精确结果 + **/ + function accSub(arg1, arg2) { + var r1, r2, m, n; + try { + r1 = arg1.toString().split(".")[1].length; + } catch (e) { + r1 = 0; + } + try { + r2 = arg2.toString().split(".")[1].length; + } catch (e) { + r2 = 0; } - }, + m = Math.pow(10, Math.max(r1, r2)); // last modify by deeka //动态控制精度长度 + n = (r1 >= r2) ? r1 : r2; + return ((arg1 * m - arg2 * m) / m).toFixed(n); + } +} - // 给Number类型增加一个mul方法,调用起来更加方便。 - mul: function (num, arg) { - return accMul(arg, num); +// 给Number类型增加一个mul方法,调用起来更加方便。 +export function mul(num, arg) { + return accMul(arg, num); - /** - ** 乘法函数,用来得到精确的乘法结果 - ** 说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。 - ** 调用:accMul(arg1,arg2) - ** 返回值:arg1乘以 arg2的精确结果 - **/ - function accMul (arg1, arg2) { - var m = 0, s1 = arg1.toString(), s2 = arg2.toString(); - try { - m += s1.split(".")[1].length; - } catch (e) { - } - try { - m += s2.split(".")[1].length; - } catch (e) { - } - return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m); + /** + ** 乘法函数,用来得到精确的乘法结果 + ** 说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。 + ** 调用:accMul(arg1,arg2) + ** 返回值:arg1乘以 arg2的精确结果 + **/ + function accMul(arg1, arg2) { + var m = 0, s1 = arg1.toString(), s2 = arg2.toString(); + try { + m += s1.split(".")[1].length; + } catch (e) { } - }, - - // 给Number类型增加一个div方法,调用起来更加方便。 - div: function (num, arg) { - return accDivide(num, arg); - - /** - * Return digits length of a number - * @param {*number} num Input number - */ - function digitLength (num) { - // Get digit length of e - var eSplit = num.toString().split(/[eE]/); - var len = (eSplit[0].split(".")[1] || "").length - (+(eSplit[1] || 0)); - return len > 0 ? len : 0; - } - /** - * 把小数转成整数,支持科学计数法。如果是小数则放大成整数 - * @param {*number} num 输入数 - */ - function float2Fixed (num) { - if (num.toString().indexOf("e") === -1) { - return Number(num.toString().replace(".", "")); - } - var dLen = digitLength(num); - return dLen > 0 ? num * Math.pow(10, dLen) : num; + try { + m += s2.split(".")[1].length; + } catch (e) { } + return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m); + } +} - /** - * 精确乘法 - */ - function times (num1, num2) { - var others = []; - for (var _i = 2; _i < arguments.length; _i++) { - others[_i - 2] = arguments[_i]; - } - if (others.length > 0) { - return times.apply(void 0, [times(num1, num2), others[0]].concat(others.slice(1))); - } - var num1Changed = float2Fixed(num1); - var num2Changed = float2Fixed(num2); - var baseNum = digitLength(num1) + digitLength(num2); - var leftValue = num1Changed * num2Changed; - return leftValue / Math.pow(10, baseNum); +// 给Number类型增加一个div方法,调用起来更加方便。 +export function div(num, arg) { + return accDivide(num, arg); + + /** + * Return digits length of a number + * @param {*number} num Input number + */ + function digitLength(num) { + // Get digit length of e + var eSplit = num.toString().split(/[eE]/); + var len = (eSplit[0].split(".")[1] || "").length - (+(eSplit[1] || 0)); + return len > 0 ? len : 0; + } + + /** + * 把小数转成整数,支持科学计数法。如果是小数则放大成整数 + * @param {*number} num 输入数 + */ + function float2Fixed(num) { + if (num.toString().indexOf("e") === -1) { + return Number(num.toString().replace(".", "")); } + var dLen = digitLength(num); + return dLen > 0 ? num * Math.pow(10, dLen) : num; + } - /** - * 精确除法 - */ - function accDivide (num1, num2) { - var others = []; - for (var _i = 2; _i < arguments.length; _i++) { - others[_i - 2] = arguments[_i]; - } - if (others.length > 0) { - return accDivide.apply(void 0, [accDivide(num1, num2), others[0]].concat(others.slice(1))); - } - var num1Changed = float2Fixed(num1); - var num2Changed = float2Fixed(num2); - return times((num1Changed / num2Changed), Math.pow(10, digitLength(num2) - digitLength(num1))); + /** + * 精确乘法 + */ + function times(num1, num2) { + var others = []; + for (var _i = 2; _i < arguments.length; _i++) { + others[_i - 2] = arguments[_i]; + } + if (others.length > 0) { + return times.apply(void 0, [times(num1, num2), others[0]].concat(others.slice(1))); } + var num1Changed = float2Fixed(num1); + var num2Changed = float2Fixed(num2); + var baseNum = digitLength(num1) + digitLength(num2); + var leftValue = num1Changed * num2Changed; + return leftValue / Math.pow(10, baseNum); } -}); \ No newline at end of file + /** + * 精确除法 + */ + function accDivide(num1, num2) { + var others = []; + for (var _i = 2; _i < arguments.length; _i++) { + others[_i - 2] = arguments[_i]; + } + if (others.length > 0) { + return accDivide.apply(void 0, [accDivide(num1, num2), others[0]].concat(others.slice(1))); + } + var num1Changed = float2Fixed(num1); + var num2Changed = float2Fixed(num2); + return times((num1Changed / num2Changed), Math.pow(10, digitLength(num2) - digitLength(num1))); + } +} diff --git a/src/core/func/string.js b/src/core/func/string.js index 55a89e63f..de5b29628 100644 --- a/src/core/func/string.js +++ b/src/core/func/string.js @@ -1,123 +1,121 @@ +import {isString} from "../2.base"; + /** - * 对字符串对象的扩展 - * @class String + * 判断字符串是否已指定的字符串开始 + * @param str source字符串 + * @param {String} startTag 指定的开始字符串 + * @return {Boolean} 如果字符串以指定字符串开始则返回true,否则返回false */ -BI._.extend(BI, { +export function startWith(str, startTag) { + str = str || ""; + if (startTag == null || startTag == "" || str.length === 0 || startTag.length > str.length) { + return false; + } + return str.substr(0, startTag.length) == startTag; +} - /** - * 判断字符串是否已指定的字符串开始 - * @param str source字符串 - * @param {String} startTag 指定的开始字符串 - * @return {Boolean} 如果字符串以指定字符串开始则返回true,否则返回false - */ - startWith: function (str, startTag) { - str = str || ""; - if (startTag == null || startTag == "" || str.length === 0 || startTag.length > str.length) { - return false; - } - return str.substr(0, startTag.length) == startTag; - }, - /** - * 判断字符串是否以指定的字符串结束 - * @param str source字符串 - * @param {String} endTag 指定的字符串 - * @return {Boolean} 如果字符串以指定字符串结束则返回true,否则返回false - */ - endWith: function (str, endTag) { - if (endTag == null || endTag == "" || str.length === 0 || endTag.length > str.length) { - return false; - } - return str.substring(str.length - endTag.length) == endTag; - }, +/** + * 判断字符串是否以指定的字符串结束 + * @param str source字符串 + * @param {String} endTag 指定的字符串 + * @return {Boolean} 如果字符串以指定字符串结束则返回true,否则返回false + */ +export function endWith(str, endTag) { + if (endTag == null || endTag == "" || str.length === 0 || endTag.length > str.length) { + return false; + } + return str.substring(str.length - endTag.length) == endTag; +} - /** - * 获取url中指定名字的参数 - * @param str source字符串 - * @param {String} name 参数的名字 - * @return {String} 参数的值 - */ - getQuery: function (str, name) { - var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); - var r = str.substr(str.indexOf("?") + 1).match(reg); - if (r) { - return unescape(r[2]); - } - return null; - }, +/** + * 获取url中指定名字的参数 + * @param str source字符串 + * @param {String} name 参数的名字 + * @return {String} 参数的值 + */ +export function getQuery(str, name) { + var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); + var r = str.substr(str.indexOf("?") + 1).match(reg); + if (r) { + return unescape(r[2]); + } + return null; +} - /** - * 给url加上给定的参数 - * @param str source字符串 - * @param {Object} paras 参数对象,是一个键值对对象 - * @return {String} 添加了给定参数的url - */ - appendQuery: function (str, paras) { - if (!paras) { - return str; - } - var src = str; - // 没有问号说明还没有参数 - if (src.indexOf("?") === -1) { - src += "?"; - } - // 如果以问号结尾,说明没有其他参数 - if (BI.endWith(src, "?") !== false) { - } else { - src += "&"; - } - BI._.each(paras, function (value, name) { - if (typeof(name) === "string") { - src += name + "=" + value + "&"; - } - }); - src = src.substr(0, src.length - 1); - return src; - }, - /** - * 将所有符合第一个字符串所表示的字符串替换成为第二个字符串 - * @param str source字符串 - * @param {String} s1 要替换的字符串的正则表达式 - * @param {String} s2 替换的结果字符串 - * @returns {String} 替换后的字符串 - */ - replaceAll: function (str, s1, s2) { - return BI.isString(str) ? str.replace(new RegExp(s1, "gm"), s2) : str; - }, - /** - * 总是让字符串以指定的字符开头 - * @param str source字符串 - * @param {String} start 指定的字符 - * @returns {String} 以指定字符开头的字符串 - */ - perfectStart: function (str, start) { - if (BI.startWith(str, start)) { - return str; +/** + * 给url加上给定的参数 + * @param str source字符串 + * @param {Object} paras 参数对象,是一个键值对对象 + * @return {String} 添加了给定参数的url + */ +export function appendQuery(str, paras) { + if (!paras) { + return str; + } + var src = str; + // 没有问号说明还没有参数 + if (src.indexOf("?") === -1) { + src += "?"; + } + // 如果以问号结尾,说明没有其他参数 + if (BI.endWith(src, "?") !== false) { + } else { + src += "&"; + } + BI._.each(paras, function (value, name) { + if (typeof (name) === "string") { + src += name + "=" + value + "&"; } - return start + str; + }); + src = src.substr(0, src.length - 1); + return src; +} - }, +/** + * 将所有符合第一个字符串所表示的字符串替换成为第二个字符串 + * @param str source字符串 + * @param {String} s1 要替换的字符串的正则表达式 + * @param {String} s2 替换的结果字符串 + * @returns {String} 替换后的字符串 + */ +export function replaceAll(str, s1, s2) { + return isString(str) ? str.replace(new RegExp(s1, "gm"), s2) : str; +} - /** - * 获取字符串中某字符串的所有项位置数组 - * @param str source字符串 - * @param {String} sub 子字符串 - * @return {Number[]} 子字符串在父字符串中出现的所有位置组成的数组 - */ - allIndexOf: function (str, sub) { - if (typeof sub !== "string") { - return []; - } - var location = []; - var offset = 0; - while (str.length > 0) { - var loc = str.indexOf(sub); - if (loc === -1) { - break; - } - location.push(offset + loc); - str = str.substring(loc + sub.length, str.length); - offset += loc + sub.length; +/** + * 总是让字符串以指定的字符开头 + * @param str source字符串 + * @param {String} start 指定的字符 + * @returns {String} 以指定字符开头的字符串 + */ +export function perfectStart(str, start) { + if (BI.startWith(str, start)) { + return str; + } + return start + str; + +} + +/** + * 获取字符串中某字符串的所有项位置数组 + * @param str source字符串 + * @param {String} sub 子字符串 + * @return {Number[]} 子字符串在父字符串中出现的所有位置组成的数组 + */ +export function allIndexOf(str, sub) { + if (typeof sub !== "string") { + return []; + } + var location = []; + var offset = 0; + while (str.length > 0) { + var loc = str.indexOf(sub); + if (loc === -1) { + break; } - return location; + location.push(offset + loc); + str = str.substring(loc + sub.length, str.length); + offset += loc + sub.length; } -}); \ No newline at end of file + return location; +} diff --git a/src/core/index.js b/src/core/index.js index 0b0f014c0..dbcd9f509 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -1,4 +1,4 @@ -import { shortcut } from "./decorator"; +import {shortcut} from "./decorator"; import OB from "./3.ob"; import Widget from "./4.widget"; import Action from "./action/action"; @@ -16,6 +16,7 @@ import PopoverController from "./controller/controller.popover"; import ResizeController from "./controller/controller.resizer"; import TooltipsController from "./controller/controller.tooltips"; import StyleLoaderManager from "./loader/loader.style"; +import "./h"; BI.extend(BI, { OB, @@ -56,6 +57,7 @@ export { ResizeController, TooltipsController, StyleLoaderManager, -} +}; -export * from './2.base'; \ No newline at end of file +export * from './2.base'; +export * from "./func"; diff --git a/src/core/platform/web/detectElementResize.js b/src/core/platform/web/detectElementResize.js index 3183a57c4..502ebb0ee 100644 --- a/src/core/platform/web/detectElementResize.js +++ b/src/core/platform/web/detectElementResize.js @@ -323,7 +323,22 @@ var ResizeObserverPolyfill = (function (exports) { }; var CATCH_PERIOD = 250; var observerConfig = { attributes: true, characterData: true, childList: true, subtree: true }; - var events = ['resize', 'load', 'transitionend', 'animationend', 'animationstart', 'animationiteration', 'keyup', 'keydown', 'mouseup', 'mousedown', 'mouseover', 'mouseout', 'blur', 'focus']; + var events = [ + 'resize', + 'load', + 'transitionend', + 'animationend', + 'animationstart', + 'animationiteration', + 'keyup', + 'keydown', + 'mouseup', + 'mousedown', + 'mouseover', + 'mouseout', + 'blur', + 'focus' + ]; var time = function (timeout) { if (timeout === void 0) { timeout = 0; @@ -412,14 +427,17 @@ var ResizeObserverPolyfill = (function (exports) { }; var skipNotifyOnElement = function (target) { - return !isSVG(target) && !isReplacedElement(target) && getComputedStyle(target).display === 'inline'; + return !isSVG(target) + && !isReplacedElement(target) + && getComputedStyle(target).display === 'inline'; }; var ResizeObservation = (function () { function ResizeObservation(target, observedBox) { this.target = target; this.observedBox = observedBox || ResizeObserverBoxOptions.CONTENT_BOX; this.lastReportedSize = { - inlineSize: -1, blockSize: -1 + inlineSize: -1, + blockSize: -1 }; } @@ -428,7 +446,8 @@ var ResizeObserverPolyfill = (function (exports) { if (skipNotifyOnElement(this.target)) { this.lastReportedSize = size; } - if (this.lastReportedSize.inlineSize !== size.inlineSize || this.lastReportedSize.blockSize !== size.blockSize) { + if (this.lastReportedSize.inlineSize !== size.inlineSize + || this.lastReportedSize.blockSize !== size.blockSize) { return true; } return false; @@ -534,64 +553,58 @@ var ResizeObserverPolyfill = (function (exports) { return ResizeObserver; }()); - exports.ResizeObserver = ResizeObserver; - exports.ResizeObserverEntry = ResizeObserverEntry; - exports.ResizeObserverSize = ResizeObserverSize; - - Object.defineProperty(exports, '__esModule', { value: true }); - - return exports; - -})({}); - -var ResizeObserver = window.ResizeObserver || ResizeObserverPolyfill.ResizeObserver; + return ResizeObserver; +})(); -!(function () { +var ResizeObserver = window.ResizeObserver || ResizeObserverPolyfill; - var addResizeListener = function (element, fn) { - if (ResizeObserver) { - if (!element.__resizeObserver__) { - var resizeObserver = new ResizeObserver(function () { - element.__resizeListeners__.forEach(function (listener) { - BI.$(element).is(":visible") && listener(); - }); +var addResizeListener = function (element, fn) { + if (ResizeObserver) { + if (!element.__resizeObserver__) { + var resizeObserver = new ResizeObserver(function () { + element.__resizeListeners__.forEach(function (listener) { + BI.$(element).is(":visible") && listener(); }); - resizeObserver.observe(element); - element.__resizeObserver__ = resizeObserver; - } - if (!element.__resizeListeners__) { - element.__resizeListeners__ = []; - } - element.__resizeListeners__.push(fn); + }); + resizeObserver.observe(element); + element.__resizeObserver__ = resizeObserver; } - }; - var removeResizeListener = function (element, fn) { - if (ResizeObserver) { - if (BI.isNull(fn)) { - element.__resizeListeners__ = []; + if (!element.__resizeListeners__) { + element.__resizeListeners__ = []; + } + element.__resizeListeners__.push(fn); + } +}; +var removeResizeListener = function (element, fn) { + if (ResizeObserver) { + if (BI.isNull(fn)) { + element.__resizeListeners__ = []; + element.__resizeObserver__ && element.__resizeObserver__.unobserve(element); + element.__resizeObserver__ = null; + return; + } + var index = element.__resizeListeners__.indexOf(fn); + if (index >= 0) { + element.__resizeListeners__.splice(index, 1); + if (!element.__resizeListeners__.length) { element.__resizeObserver__ && element.__resizeObserver__.unobserve(element); element.__resizeObserver__ = null; - return; - } - var index = element.__resizeListeners__.indexOf(fn); - if (index >= 0) { - element.__resizeListeners__.splice(index, 1); - if (!element.__resizeListeners__.length) { - element.__resizeObserver__ && element.__resizeObserver__.unobserve(element); - element.__resizeObserver__ = null; - } } } - }; + } +}; - BI.ResizeDetector = { - addResizeListener: function (widget, fn) { - addResizeListener(widget.element[0], fn); - return function () { - removeResizeListener(widget.element[0], fn); - }; - }, removeResizeListener: function (widget, fn) { +export const ResizeDetector = { + addResizeListener: function (widget, fn) { + addResizeListener(widget.element[0], fn); + return function () { removeResizeListener(widget.element[0], fn); - } - }; -})(); + }; + }, removeResizeListener: function (widget, fn) { + removeResizeListener(widget.element[0], fn); + } +}; + +Object.assign(BI, { + ResizeDetector +}); diff --git a/src/core/utils/chinesePY.js b/src/core/utils/chinesePY.js index b22cd94cb..3ef5567db 100644 --- a/src/core/utils/chinesePY.js +++ b/src/core/utils/chinesePY.js @@ -2,439 +2,444 @@ * 汉字拼音索引 */ -!(function () { - var _ChineseFirstPY = "YDYQSXMWZSSXJBYMGCCZQPSSQBYCDSCDQLDYLYBSSJGYZZJJFKCCLZDHWDWZJLJPFYYNWJJTMYHZWZHFLZPPQHGSCYYYNJQYXXGJHHSDSJNKKTMOMLCRXYPSNQSECCQZGGLLYJLMYZZSECYKYYHQWJSSGGYXYZYJWWKDJHYCHMYXJTLXJYQBYXZLDWRDJRWYSRLDZJPCBZJJBRCFTLECZSTZFXXZHTRQHYBDLYCZSSYMMRFMYQZPWWJJYFCRWFDFZQPYDDWYXKYJAWJFFXYPSFTZYHHYZYSWCJYXSCLCXXWZZXNBGNNXBXLZSZSBSGPYSYZDHMDZBQBZCWDZZYYTZHBTSYYBZGNTNXQYWQSKBPHHLXGYBFMJEBJHHGQTJCYSXSTKZHLYCKGLYSMZXYALMELDCCXGZYRJXSDLTYZCQKCNNJWHJTZZCQLJSTSTBNXBTYXCEQXGKWJYFLZQLYHYXSPSFXLMPBYSXXXYDJCZYLLLSJXFHJXPJBTFFYABYXBHZZBJYZLWLCZGGBTSSMDTJZXPTHYQTGLJSCQFZKJZJQNLZWLSLHDZBWJNCJZYZSQQYCQYRZCJJWYBRTWPYFTWEXCSKDZCTBZHYZZYYJXZCFFZZMJYXXSDZZOTTBZLQWFCKSZSXFYRLNYJMBDTHJXSQQCCSBXYYTSYFBXDZTGBCNSLCYZZPSAZYZZSCJCSHZQYDXLBPJLLMQXTYDZXSQJTZPXLCGLQTZWJBHCTSYJSFXYEJJTLBGXSXJMYJQQPFZASYJNTYDJXKJCDJSZCBARTDCLYJQMWNQNCLLLKBYBZZSYHQQLTWLCCXTXLLZNTYLNEWYZYXCZXXGRKRMTCNDNJTSYYSSDQDGHSDBJGHRWRQLYBGLXHLGTGXBQJDZPYJSJYJCTMRNYMGRZJCZGJMZMGXMPRYXKJNYMSGMZJYMKMFXMLDTGFBHCJHKYLPFMDXLQJJSMTQGZSJLQDLDGJYCALCMZCSDJLLNXDJFFFFJCZFMZFFPFKHKGDPSXKTACJDHHZDDCRRCFQYJKQCCWJDXHWJLYLLZGCFCQDSMLZPBJJPLSBCJGGDCKKDEZSQCCKJGCGKDJTJDLZYCXKLQSCGJCLTFPCQCZGWPJDQYZJJBYJHSJDZWGFSJGZKQCCZLLPSPKJGQJHZZLJPLGJGJJTHJJYJZCZMLZLYQBGJWMLJKXZDZNJQSYZMLJLLJKYWXMKJLHSKJGBMCLYYMKXJQLBMLLKMDXXKWYXYSLMLPSJQQJQXYXFJTJDXMXXLLCXQBSYJBGWYMBGGBCYXPJYGPEPFGDJGBHBNSQJYZJKJKHXQFGQZKFHYGKHDKLLSDJQXPQYKYBNQSXQNSZSWHBSXWHXWBZZXDMNSJBSBKBBZKLYLXGWXDRWYQZMYWSJQLCJXXJXKJEQXSCYETLZHLYYYSDZPAQYZCMTLSHTZCFYZYXYLJSDCJQAGYSLCQLYYYSHMRQQKLDXZSCSSSYDYCJYSFSJBFRSSZQSBXXPXJYSDRCKGJLGDKZJZBDKTCSYQPYHSTCLDJDHMXMCGXYZHJDDTMHLTXZXYLYMOHYJCLTYFBQQXPFBDFHHTKSQHZYYWCNXXCRWHOWGYJLEGWDQCWGFJYCSNTMYTOLBYGWQWESJPWNMLRYDZSZTXYQPZGCWXHNGPYXSHMYQJXZTDPPBFYHZHTJYFDZWKGKZBLDNTSXHQEEGZZYLZMMZYJZGXZXKHKSTXNXXWYLYAPSTHXDWHZYMPXAGKYDXBHNHXKDPJNMYHYLPMGOCSLNZHKXXLPZZLBMLSFBHHGYGYYGGBHSCYAQTYWLXTZQCEZYDQDQMMHTKLLSZHLSJZWFYHQSWSCWLQAZYNYTLSXTHAZNKZZSZZLAXXZWWCTGQQTDDYZTCCHYQZFLXPSLZYGPZSZNGLNDQTBDLXGTCTAJDKYWNSYZLJHHZZCWNYYZYWMHYCHHYXHJKZWSXHZYXLYSKQYSPSLYZWMYPPKBYGLKZHTYXAXQSYSHXASMCHKDSCRSWJPWXSGZJLWWSCHSJHSQNHCSEGNDAQTBAALZZMSSTDQJCJKTSCJAXPLGGXHHGXXZCXPDMMHLDGTYBYSJMXHMRCPXXJZCKZXSHMLQXXTTHXWZFKHCCZDYTCJYXQHLXDHYPJQXYLSYYDZOZJNYXQEZYSQYAYXWYPDGXDDXSPPYZNDLTWRHXYDXZZJHTCXMCZLHPYYYYMHZLLHNXMYLLLMDCPPXHMXDKYCYRDLTXJCHHZZXZLCCLYLNZSHZJZZLNNRLWHYQSNJHXYNTTTKYJPYCHHYEGKCTTWLGQRLGGTGTYGYHPYHYLQYQGCWYQKPYYYTTTTLHYHLLTYTTSPLKYZXGZWGPYDSSZZDQXSKCQNMJJZZBXYQMJRTFFBTKHZKBXLJJKDXJTLBWFZPPTKQTZTGPDGNTPJYFALQMKGXBDCLZFHZCLLLLADPMXDJHLCCLGYHDZFGYDDGCYYFGYDXKSSEBDHYKDKDKHNAXXYBPBYYHXZQGAFFQYJXDMLJCSQZLLPCHBSXGJYNDYBYQSPZWJLZKSDDTACTBXZDYZYPJZQSJNKKTKNJDJGYYPGTLFYQKASDNTCYHBLWDZHBBYDWJRYGKZYHEYYFJMSDTYFZJJHGCXPLXHLDWXXJKYTCYKSSSMTWCTTQZLPBSZDZWZXGZAGYKTYWXLHLSPBCLLOQMMZSSLCMBJCSZZKYDCZJGQQDSMCYTZQQLWZQZXSSFPTTFQMDDZDSHDTDWFHTDYZJYQJQKYPBDJYYXTLJHDRQXXXHAYDHRJLKLYTWHLLRLLRCXYLBWSRSZZSYMKZZHHKYHXKSMDSYDYCJPBZBSQLFCXXXNXKXWYWSDZYQOGGQMMYHCDZTTFJYYBGSTTTYBYKJDHKYXBELHTYPJQNFXFDYKZHQKZBYJTZBXHFDXKDASWTAWAJLDYJSFHBLDNNTNQJTJNCHXFJSRFWHZFMDRYJYJWZPDJKZYJYMPCYZNYNXFBYTFYFWYGDBNZZZDNYTXZEMMQBSQEHXFZMBMFLZZSRXYMJGSXWZJSPRYDJSJGXHJJGLJJYNZZJXHGXKYMLPYYYCXYTWQZSWHWLYRJLPXSLSXMFSWWKLCTNXNYNPSJSZHDZEPTXMYYWXYYSYWLXJQZQXZDCLEEELMCPJPCLWBXSQHFWWTFFJTNQJHJQDXHWLBYZNFJLALKYYJLDXHHYCSTYYWNRJYXYWTRMDRQHWQCMFJDYZMHMYYXJWMYZQZXTLMRSPWWCHAQBXYGZYPXYYRRCLMPYMGKSJSZYSRMYJSNXTPLNBAPPYPYLXYYZKYNLDZYJZCZNNLMZHHARQMPGWQTZMXXMLLHGDZXYHXKYXYCJMFFYYHJFSBSSQLXXNDYCANNMTCJCYPRRNYTYQNYYMBMSXNDLYLYSLJRLXYSXQMLLYZLZJJJKYZZCSFBZXXMSTBJGNXYZHLXNMCWSCYZYFZLXBRNNNYLBNRTGZQYSATSWRYHYJZMZDHZGZDWYBSSCSKXSYHYTXXGCQGXZZSHYXJSCRHMKKBXCZJYJYMKQHZJFNBHMQHYSNJNZYBKNQMCLGQHWLZNZSWXKHLJHYYBQLBFCDSXDLDSPFZPSKJYZWZXZDDXJSMMEGJSCSSMGCLXXKYYYLNYPWWWGYDKZJGGGZGGSYCKNJWNJPCXBJJTQTJWDSSPJXZXNZXUMELPXFSXTLLXCLJXJJLJZXCTPSWXLYDHLYQRWHSYCSQYYBYAYWJJJQFWQCQQCJQGXALDBZZYJGKGXPLTZYFXJLTPADKYQHPMATLCPDCKBMTXYBHKLENXDLEEGQDYMSAWHZMLJTWYGXLYQZLJEEYYBQQFFNLYXRDSCTGJGXYYNKLLYQKCCTLHJLQMKKZGCYYGLLLJDZGYDHZWXPYSJBZKDZGYZZHYWYFQYTYZSZYEZZLYMHJJHTSMQWYZLKYYWZCSRKQYTLTDXWCTYJKLWSQZWBDCQYNCJSRSZJLKCDCDTLZZZACQQZZDDXYPLXZBQJYLZLLLQDDZQJYJYJZYXNYYYNYJXKXDAZWYRDLJYYYRJLXLLDYXJCYWYWNQCCLDDNYYYNYCKCZHXXCCLGZQJGKWPPCQQJYSBZZXYJSQPXJPZBSBDSFNSFPZXHDWZTDWPPTFLZZBZDMYYPQJRSDZSQZSQXBDGCPZSWDWCSQZGMDHZXMWWFYBPDGPHTMJTHZSMMBGZMBZJCFZWFZBBZMQCFMBDMCJXLGPNJBBXGYHYYJGPTZGZMQBQTCGYXJXLWZKYDPDYMGCFTPFXYZTZXDZXTGKMTYBBCLBJASKYTSSQYYMSZXFJEWLXLLSZBQJJJAKLYLXLYCCTSXMCWFKKKBSXLLLLJYXTYLTJYYTDPJHNHNNKBYQNFQYYZBYYESSESSGDYHFHWTCJBSDZZTFDMXHCNJZYMQWSRYJDZJQPDQBBSTJGGFBKJBXTGQHNGWJXJGDLLTHZHHYYYYYYSXWTYYYCCBDBPYPZYCCZYJPZYWCBDLFWZCWJDXXHYHLHWZZXJTCZLCDPXUJCZZZLYXJJTXPHFXWPYWXZPTDZZBDZCYHJHMLXBQXSBYLRDTGJRRCTTTHYTCZWMXFYTWWZCWJWXJYWCSKYBZSCCTZQNHXNWXXKHKFHTSWOCCJYBCMPZZYKBNNZPBZHHZDLSYDDYTYFJPXYNGFXBYQXCBHXCPSXTYZDMKYSNXSXLHKMZXLYHDHKWHXXSSKQYHHCJYXGLHZXCSNHEKDTGZXQYPKDHEXTYKCNYMYYYPKQYYYKXZLTHJQTBYQHXBMYHSQCKWWYLLHCYYLNNEQXQWMCFBDCCMLJGGXDQKTLXKGNQCDGZJWYJJLYHHQTTTNWCHMXCXWHWSZJYDJCCDBQCDGDNYXZTHCQRXCBHZTQCBXWGQWYYBXHMBYMYQTYEXMQKYAQYRGYZSLFYKKQHYSSQYSHJGJCNXKZYCXSBXYXHYYLSTYCXQTHYSMGSCPMMGCCCCCMTZTASMGQZJHKLOSQYLSWTMXSYQKDZLJQQYPLSYCZTCQQPBBQJZCLPKHQZYYXXDTDDTSJCXFFLLCHQXMJLWCJCXTSPYCXNDTJSHJWXDQQJSKXYAMYLSJHMLALYKXCYYDMNMDQMXMCZNNCYBZKKYFLMCHCMLHXRCJJHSYLNMTJZGZGYWJXSRXCWJGJQHQZDQJDCJJZKJKGDZQGJJYJYLXZXXCDQHHHEYTMHLFSBDJSYYSHFYSTCZQLPBDRFRZTZYKYWHSZYQKWDQZRKMSYNBCRXQBJYFAZPZZEDZCJYWBCJWHYJBQSZYWRYSZPTDKZPFPBNZTKLQYHBBZPNPPTYZZYBQNYDCPJMMCYCQMCYFZZDCMNLFPBPLNGQJTBTTNJZPZBBZNJKLJQYLNBZQHKSJZNGGQSZZKYXSHPZSNBCGZKDDZQANZHJKDRTLZLSWJLJZLYWTJNDJZJHXYAYNCBGTZCSSQMNJPJYTYSWXZFKWJQTKHTZPLBHSNJZSYZBWZZZZLSYLSBJHDWWQPSLMMFBJDWAQYZTCJTBNNWZXQXCDSLQGDSDPDZHJTQQPSWLYYJZLGYXYZLCTCBJTKTYCZJTQKBSJLGMGZDMCSGPYNJZYQYYKNXRPWSZXMTNCSZZYXYBYHYZAXYWQCJTLLCKJJTJHGDXDXYQYZZBYWDLWQCGLZGJGQRQZCZSSBCRPCSKYDZNXJSQGXSSJMYDNSTZTPBDLTKZWXQWQTZEXNQCZGWEZKSSBYBRTSSSLCCGBPSZQSZLCCGLLLZXHZQTHCZMQGYZQZNMCOCSZJMMZSQPJYGQLJYJPPLDXRGZYXCCSXHSHGTZNLZWZKJCXTCFCJXLBMQBCZZWPQDNHXLJCTHYZLGYLNLSZZPCXDSCQQHJQKSXZPBAJYEMSMJTZDXLCJYRYYNWJBNGZZTMJXLTBSLYRZPYLSSCNXPHLLHYLLQQZQLXYMRSYCXZLMMCZLTZSDWTJJLLNZGGQXPFSKYGYGHBFZPDKMWGHCXMSGDXJMCJZDYCABXJDLNBCDQYGSKYDQTXDJJYXMSZQAZDZFSLQXYJSJZYLBTXXWXQQZBJZUFBBLYLWDSLJHXJYZJWTDJCZFQZQZZDZSXZZQLZCDZFJHYSPYMPQZMLPPLFFXJJNZZYLSJEYQZFPFZKSYWJJJHRDJZZXTXXGLGHYDXCSKYSWMMZCWYBAZBJKSHFHJCXMHFQHYXXYZFTSJYZFXYXPZLCHMZMBXHZZSXYFYMNCWDABAZLXKTCSHHXKXJJZJSTHYGXSXYYHHHJWXKZXSSBZZWHHHCWTZZZPJXSNXQQJGZYZYWLLCWXZFXXYXYHXMKYYSWSQMNLNAYCYSPMJKHWCQHYLAJJMZXHMMCNZHBHXCLXTJPLTXYJHDYYLTTXFSZHYXXSJBJYAYRSMXYPLCKDUYHLXRLNLLSTYZYYQYGYHHSCCSMZCTZQXKYQFPYYRPFFLKQUNTSZLLZMWWTCQQYZWTLLMLMPWMBZSSTZRBPDDTLQJJBXZCSRZQQYGWCSXFWZLXCCRSZDZMCYGGDZQSGTJSWLJMYMMZYHFBJDGYXCCPSHXNZCSBSJYJGJMPPWAFFYFNXHYZXZYLREMZGZCYZSSZDLLJCSQFNXZKPTXZGXJJGFMYYYSNBTYLBNLHPFZDCYFBMGQRRSSSZXYSGTZRNYDZZCDGPJAFJFZKNZBLCZSZPSGCYCJSZLMLRSZBZZLDLSLLYSXSQZQLYXZLSKKBRXBRBZCYCXZZZEEYFGKLZLYYHGZSGZLFJHGTGWKRAAJYZKZQTSSHJJXDCYZUYJLZYRZDQQHGJZXSSZBYKJPBFRTJXLLFQWJHYLQTYMBLPZDXTZYGBDHZZRBGXHWNJTJXLKSCFSMWLSDQYSJTXKZSCFWJLBXFTZLLJZLLQBLSQMQQCGCZFPBPHZCZJLPYYGGDTGWDCFCZQYYYQYSSCLXZSKLZZZGFFCQNWGLHQYZJJCZLQZZYJPJZZBPDCCMHJGXDQDGDLZQMFGPSYTSDYFWWDJZJYSXYYCZCYHZWPBYKXRYLYBHKJKSFXTZJMMCKHLLTNYYMSYXYZPYJQYCSYCWMTJJKQYRHLLQXPSGTLYYCLJSCPXJYZFNMLRGJJTYZBXYZMSJYJHHFZQMSYXRSZCWTLRTQZSSTKXGQKGSPTGCZNJSJCQCXHMXGGZTQYDJKZDLBZSXJLHYQGGGTHQSZPYHJHHGYYGKGGCWJZZYLCZLXQSFTGZSLLLMLJSKCTBLLZZSZMMNYTPZSXQHJCJYQXYZXZQZCPSHKZZYSXCDFGMWQRLLQXRFZTLYSTCTMJCXJJXHJNXTNRZTZFQYHQGLLGCXSZSJDJLJCYDSJTLNYXHSZXCGJZYQPYLFHDJSBPCCZHJJJQZJQDYBSSLLCMYTTMQTBHJQNNYGKYRQYQMZGCJKPDCGMYZHQLLSLLCLMHOLZGDYYFZSLJCQZLYLZQJESHNYLLJXGJXLYSYYYXNBZLJSSZCQQCJYLLZLTJYLLZLLBNYLGQCHXYYXOXCXQKYJXXXYKLXSXXYQXCYKQXQCSGYXXYQXYGYTQOHXHXPYXXXULCYEYCHZZCBWQBBWJQZSCSZSSLZYLKDESJZWMYMCYTSDSXXSCJPQQSQYLYYZYCMDJDZYWCBTJSYDJKCYDDJLBDJJSODZYSYXQQYXDHHGQQYQHDYXWGMMMAJDYBBBPPBCMUUPLJZSMTXERXJMHQNUTPJDCBSSMSSSTKJTSSMMTRCPLZSZMLQDSDMJMQPNQDXCFYNBFSDQXYXHYAYKQYDDLQYYYSSZBYDSLNTFQTZQPZMCHDHCZCWFDXTMYQSPHQYYXSRGJCWTJTZZQMGWJJTJHTQJBBHWZPXXHYQFXXQYWYYHYSCDYDHHQMNMTMWCPBSZPPZZGLMZFOLLCFWHMMSJZTTDHZZYFFYTZZGZYSKYJXQYJZQBHMBZZLYGHGFMSHPZFZSNCLPBQSNJXZSLXXFPMTYJYGBXLLDLXPZJYZJYHHZCYWHJYLSJEXFSZZYWXKZJLUYDTMLYMQJPWXYHXSKTQJEZRPXXZHHMHWQPWQLYJJQJJZSZCPHJLCHHNXJLQWZJHBMZYXBDHHYPZLHLHLGFWLCHYYTLHJXCJMSCPXSTKPNHQXSRTYXXTESYJCTLSSLSTDLLLWWYHDHRJZSFGXTSYCZYNYHTDHWJSLHTZDQDJZXXQHGYLTZPHCSQFCLNJTCLZPFSTPDYNYLGMJLLYCQHYSSHCHYLHQYQTMZYPBYWRFQYKQSYSLZDQJMPXYYSSRHZJNYWTQDFZBWWTWWRXCWHGYHXMKMYYYQMSMZHNGCEPMLQQMTCWCTMMPXJPJJHFXYYZSXZHTYBMSTSYJTTQQQYYLHYNPYQZLCYZHZWSMYLKFJXLWGXYPJYTYSYXYMZCKTTWLKSMZSYLMPWLZWXWQZSSAQSYXYRHSSNTSRAPXCPWCMGDXHXZDZYFJHGZTTSBJHGYZSZYSMYCLLLXBTYXHBBZJKSSDMALXHYCFYGMQYPJYCQXJLLLJGSLZGQLYCJCCZOTYXMTMTTLLWTGPXYMZMKLPSZZZXHKQYSXCTYJZYHXSHYXZKXLZWPSQPYHJWPJPWXQQYLXSDHMRSLZZYZWTTCYXYSZZSHBSCCSTPLWSSCJCHNLCGCHSSPHYLHFHHXJSXYLLNYLSZDHZXYLSXLWZYKCLDYAXZCMDDYSPJTQJZLNWQPSSSWCTSTSZLBLNXSMNYYMJQBQHRZWTYYDCHQLXKPZWBGQYBKFCMZWPZLLYYLSZYDWHXPSBCMLJBSCGBHXLQHYRLJXYSWXWXZSLDFHLSLYNJLZYFLYJYCDRJLFSYZFSLLCQYQFGJYHYXZLYLMSTDJCYHBZLLNWLXXYGYYHSMGDHXXHHLZZJZXCZZZCYQZFNGWPYLCPKPYYPMCLQKDGXZGGWQBDXZZKZFBXXLZXJTPJPTTBYTSZZDWSLCHZHSLTYXHQLHYXXXYYZYSWTXZKHLXZXZPYHGCHKCFSYHUTJRLXFJXPTZTWHPLYXFCRHXSHXKYXXYHZQDXQWULHYHMJTBFLKHTXCWHJFWJCFPQRYQXCYYYQYGRPYWSGSUNGWCHKZDXYFLXXHJJBYZWTSXXNCYJJYMSWZJQRMHXZWFQSYLZJZGBHYNSLBGTTCSYBYXXWXYHXYYXNSQYXMQYWRGYQLXBBZLJSYLPSYTJZYHYZAWLRORJMKSCZJXXXYXCHDYXRYXXJDTSQFXLYLTSFFYXLMTYJMJUYYYXLTZCSXQZQHZXLYYXZHDNBRXXXJCTYHLBRLMBRLLAXKYLLLJLYXXLYCRYLCJTGJCMTLZLLCYZZPZPCYAWHJJFYBDYYZSMPCKZDQYQPBPCJPDCYZMDPBCYYDYCNNPLMTMLRMFMMGWYZBSJGYGSMZQQQZTXMKQWGXLLPJGZBQCDJJJFPKJKCXBLJMSWMDTQJXLDLPPBXCWRCQFBFQJCZAHZGMYKPHYYHZYKNDKZMBPJYXPXYHLFPNYYGXJDBKXNXHJMZJXSTRSTLDXSKZYSYBZXJLXYSLBZYSLHXJPFXPQNBYLLJQKYGZMCYZZYMCCSLCLHZFWFWYXZMWSXTYNXJHPYYMCYSPMHYSMYDYSHQYZCHMJJMZCAAGCFJBBHPLYZYLXXSDJGXDHKXXTXXNBHRMLYJSLTXMRHNLXQJXYZLLYSWQGDLBJHDCGJYQYCMHWFMJYBMBYJYJWYMDPWHXQLDYGPDFXXBCGJSPCKRSSYZJMSLBZZJFLJJJLGXZGYXYXLSZQYXBEXYXHGCXBPLDYHWETTWWCJMBTXCHXYQXLLXFLYXLLJLSSFWDPZSMYJCLMWYTCZPCHQEKCQBWLCQYDPLQPPQZQFJQDJHYMMCXTXDRMJWRHXCJZYLQXDYYNHYYHRSLSRSYWWZJYMTLTLLGTQCJZYABTCKZCJYCCQLJZQXALMZYHYWLWDXZXQDLLQSHGPJFJLJHJABCQZDJGTKHSSTCYJLPSWZLXZXRWGLDLZRLZXTGSLLLLZLYXXWGDZYGBDPHZPBRLWSXQBPFDWOFMWHLYPCBJCCLDMBZPBZZLCYQXLDOMZBLZWPDWYYGDSTTHCSQSCCRSSSYSLFYBFNTYJSZDFNDPDHDZZMBBLSLCMYFFGTJJQWFTMTPJWFNLBZCMMJTGBDZLQLPYFHYYMJYLSDCHDZJWJCCTLJCLDTLJJCPDDSQDSSZYBNDBJLGGJZXSXNLYCYBJXQYCBYLZCFZPPGKCXZDZFZTJJFJSJXZBNZYJQTTYJYHTYCZHYMDJXTTMPXSPLZCDWSLSHXYPZGTFMLCJTYCBPMGDKWYCYZCDSZZYHFLYCTYGWHKJYYLSJCXGYWJCBLLCSNDDBTZBSCLYZCZZSSQDLLMQYYHFSLQLLXFTYHABXGWNYWYYPLLSDLDLLBJCYXJZMLHLJDXYYQYTDLLLBUGBFDFBBQJZZMDPJHGCLGMJJPGAEHHBWCQXAXHHHZCHXYPHJAXHLPHJPGPZJQCQZGJJZZUZDMQYYBZZPHYHYBWHAZYJHYKFGDPFQSDLZMLJXKXGALXZDAGLMDGXMWZQYXXDXXPFDMMSSYMPFMDMMKXKSYZYSHDZKXSYSMMZZZMSYDNZZCZXFPLSTMZDNMXCKJMZTYYMZMZZMSXHHDCZJEMXXKLJSTLWLSQLYJZLLZJSSDPPMHNLZJCZYHMXXHGZCJMDHXTKGRMXFWMCGMWKDTKSXQMMMFZZYDKMSCLCMPCGMHSPXQPZDSSLCXKYXTWLWJYAHZJGZQMCSNXYYMMPMLKJXMHLMLQMXCTKZMJQYSZJSYSZHSYJZJCDAJZYBSDQJZGWZQQXFKDMSDJLFWEHKZQKJPEYPZYSZCDWYJFFMZZYLTTDZZEFMZLBNPPLPLPEPSZALLTYLKCKQZKGENQLWAGYXYDPXLHSXQQWQCQXQCLHYXXMLYCCWLYMQYSKGCHLCJNSZKPYZKCQZQLJPDMDZHLASXLBYDWQLWDNBQCRYDDZTJYBKBWSZDXDTNPJDTCTQDFXQQMGNXECLTTBKPWSLCTYQLPWYZZKLPYGZCQQPLLKCCYLPQMZCZQCLJSLQZDJXLDDHPZQDLJJXZQDXYZQKZLJCYQDYJPPYPQYKJYRMPCBYMCXKLLZLLFQPYLLLMBSGLCYSSLRSYSQTMXYXZQZFDZUYSYZTFFMZZSMZQHZSSCCMLYXWTPZGXZJGZGSJSGKDDHTQGGZLLBJDZLCBCHYXYZHZFYWXYZYMSDBZZYJGTSMTFXQYXQSTDGSLNXDLRYZZLRYYLXQHTXSRTZNGZXBNQQZFMYKMZJBZYMKBPNLYZPBLMCNQYZZZSJZHJCTZKHYZZJRDYZHNPXGLFZTLKGJTCTSSYLLGZRZBBQZZKLPKLCZYSSUYXBJFPNJZZXCDWXZYJXZZDJJKGGRSRJKMSMZJLSJYWQSKYHQJSXPJZZZLSNSHRNYPZTWCHKLPSRZLZXYJQXQKYSJYCZTLQZYBBYBWZPQDWWYZCYTJCJXCKCWDKKZXSGKDZXWWYYJQYYTCYTDLLXWKCZKKLCCLZCQQDZLQLCSFQCHQHSFSMQZZLNBJJZBSJHTSZDYSJQJPDLZCDCWJKJZZLPYCGMZWDJJBSJQZSYZYHHXJPBJYDSSXDZNCGLQMBTSFSBPDZDLZNFGFJGFSMPXJQLMBLGQCYYXBQKDJJQYRFKZTJDHCZKLBSDZCFJTPLLJGXHYXZCSSZZXSTJYGKGCKGYOQXJPLZPBPGTGYJZGHZQZZLBJLSQFZGKQQJZGYCZBZQTLDXRJXBSXXPZXHYZYCLWDXJJHXMFDZPFZHQHQMQGKSLYHTYCGFRZGNQXCLPDLBZCSCZQLLJBLHBZCYPZZPPDYMZZSGYHCKCPZJGSLJLNSCDSLDLXBMSTLDDFJMKDJDHZLZXLSZQPQPGJLLYBDSZGQLBZLSLKYYHZTTNTJYQTZZPSZQZTLLJTYYLLQLLQYZQLBDZLSLYYZYMDFSZSNHLXZNCZQZPBWSKRFBSYZMTHBLGJPMCZZLSTLXSHTCSYZLZBLFEQHLXFLCJLYLJQCBZLZJHHSSTBRMHXZHJZCLXFNBGXGTQJCZTMSFZKJMSSNXLJKBHSJXNTNLZDNTLMSJXGZJYJCZXYJYJWRWWQNZTNFJSZPZSHZJFYRDJSFSZJZBJFZQZZHZLXFYSBZQLZSGYFTZDCSZXZJBQMSZKJRHYJZCKMJKHCHGTXKXQGLXPXFXTRTYLXJXHDTSJXHJZJXZWZLCQSBTXWXGXTXXHXFTSDKFJHZYJFJXRZSDLLLTQSQQZQWZXSYQTWGWBZCGZLLYZBCLMQQTZHZXZXLJFRMYZFLXYSQXXJKXRMQDZDMMYYBSQBHGZMWFWXGMXLZPYYTGZYCCDXYZXYWGSYJYZNBHPZJSQSYXSXRTFYZGRHZTXSZZTHCBFCLSYXZLZQMZLMPLMXZJXSFLBYZMYQHXJSXRXSQZZZSSLYFRCZJRCRXHHZXQYDYHXSJJHZCXZBTYNSYSXJBQLPXZQPYMLXZKYXLXCJLCYSXXZZLXDLLLJJYHZXGYJWKJRWYHCPSGNRZLFZWFZZNSXGXFLZSXZZZBFCSYJDBRJKRDHHGXJLJJTGXJXXSTJTJXLYXQFCSGSWMSBCTLQZZWLZZKXJMLTMJYHSDDBXGZHDLBMYJFRZFSGCLYJBPMLYSMSXLSZJQQHJZFXGFQFQBPXZGYYQXGZTCQWYLTLGWSGWHRLFSFGZJMGMGBGTJFSYZZGZYZAFLSSPMLPFLCWBJZCLJJMZLPJJLYMQDMYYYFBGYGYZMLYZDXQYXRQQQHSYYYQXYLJTYXFSFSLLGNQCYHYCWFHCCCFXPYLYPLLZYXXXXXKQHHXSHJZCFZSCZJXCPZWHHHHHAPYLQALPQAFYHXDYLUKMZQGGGDDESRNNZLTZGCHYPPYSQJJHCLLJTOLNJPZLJLHYMHEYDYDSQYCDDHGZUNDZCLZYZLLZNTNYZGSLHSLPJJBDGWXPCDUTJCKLKCLWKLLCASSTKZZDNQNTTLYYZSSYSSZZRYLJQKCQDHHCRXRZYDGRGCWCGZQFFFPPJFZYNAKRGYWYQPQXXFKJTSZZXSWZDDFBBXTBGTZKZNPZZPZXZPJSZBMQHKCYXYLDKLJNYPKYGHGDZJXXEAHPNZKZTZCMXCXMMJXNKSZQNMNLWBWWXJKYHCPSTMCSQTZJYXTPCTPDTNNPGLLLZSJLSPBLPLQHDTNJNLYYRSZFFJFQWDPHZDWMRZCCLODAXNSSNYZRESTYJWJYJDBCFXNMWTTBYLWSTSZGYBLJPXGLBOCLHPCBJLTMXZLJYLZXCLTPNCLCKXTPZJSWCYXSFYSZDKNTLBYJCYJLLSTGQCBXRYZXBXKLYLHZLQZLNZCXWJZLJZJNCJHXMNZZGJZZXTZJXYCYYCXXJYYXJJXSSSJSTSSTTPPGQTCSXWZDCSYFPTFBFHFBBLZJCLZZDBXGCXLQPXKFZFLSYLTUWBMQJHSZBMDDBCYSCCLDXYCDDQLYJJWMQLLCSGLJJSYFPYYCCYLTJANTJJPWYCMMGQYYSXDXQMZHSZXPFTWWZQSWQRFKJLZJQQYFBRXJHHFWJJZYQAZMYFRHCYYBYQWLPEXCCZSTYRLTTDMQLYKMBBGMYYJPRKZNPBSXYXBHYZDJDNGHPMFSGMWFZMFQMMBCMZZCJJLCNUXYQLMLRYGQZCYXZLWJGCJCGGMCJNFYZZJHYCPRRCMTZQZXHFQGTJXCCJEAQCRJYHPLQLSZDJRBCQHQDYRHYLYXJSYMHZYDWLDFRYHBPYDTSSCNWBXGLPZMLZZTQSSCPJMXXYCSJYTYCGHYCJWYRXXLFEMWJNMKLLSWTXHYYYNCMMCWJDQDJZGLLJWJRKHPZGGFLCCSCZMCBLTBHBQJXQDSPDJZZGHGLFQYWBZYZJLTSTDHQHCTCBCHFLQMPWDSHYYTQWCNZZJTLBYMBPDYYYXSQKXWYYFLXXNCWCXYPMAELYKKJMZZZBRXYYQJFLJPFHHHYTZZXSGQQMHSPGDZQWBWPJHZJDYSCQWZKTXXSQLZYYMYSDZGRXCKKUJLWPYSYSCSYZLRMLQSYLJXBCXTLWDQZPCYCYKPPPNSXFYZJJRCEMHSZMSXLXGLRWGCSTLRSXBZGBZGZTCPLUJLSLYLYMTXMTZPALZXPXJTJWTCYYZLBLXBZLQMYLXPGHDSLSSDMXMBDZZSXWHAMLCZCPJMCNHJYSNSYGCHSKQMZZQDLLKABLWJXSFMOCDXJRRLYQZKJMYBYQLYHETFJZFRFKSRYXFJTWDSXXSYSQJYSLYXWJHSNLXYYXHBHAWHHJZXWMYLJCSSLKYDZTXBZSYFDXGXZJKHSXXYBSSXDPYNZWRPTQZCZENYGCXQFJYKJBZMLJCMQQXUOXSLYXXLYLLJDZBTYMHPFSTTQQWLHOKYBLZZALZXQLHZWRRQHLSTMYPYXJJXMQSJFNBXYXYJXXYQYLTHYLQYFMLKLJTMLLHSZWKZHLJMLHLJKLJSTLQXYLMBHHLNLZXQJHXCFXXLHYHJJGBYZZKBXSCQDJQDSUJZYYHZHHMGSXCSYMXFEBCQWWRBPYYJQTYZCYQYQQZYHMWFFHGZFRJFCDPXNTQYZPDYKHJLFRZXPPXZDBBGZQSTLGDGYLCQMLCHHMFYWLZYXKJLYPQHSYWMQQGQZMLZJNSQXJQSYJYCBEHSXFSZPXZWFLLBCYYJDYTDTHWZSFJMQQYJLMQXXLLDTTKHHYBFPWTYYSQQWNQWLGWDEBZWCMYGCULKJXTMXMYJSXHYBRWFYMWFRXYQMXYSZTZZTFYKMLDHQDXWYYNLCRYJBLPSXCXYWLSPRRJWXHQYPHTYDNXHHMMYWYTZCSQMTSSCCDALWZTCPQPYJLLQZYJSWXMZZMMYLMXCLMXCZMXMZSQTZPPQQBLPGXQZHFLJJHYTJSRXWZXSCCDLXTYJDCQJXSLQYCLZXLZZXMXQRJMHRHZJBHMFLJLMLCLQNLDXZLLLPYPSYJYSXCQQDCMQJZZXHNPNXZMEKMXHYKYQLXSXTXJYYHWDCWDZHQYYBGYBCYSCFGPSJNZDYZZJZXRZRQJJYMCANYRJTLDPPYZBSTJKXXZYPFDWFGZZRPYMTNGXZQBYXNBUFNQKRJQZMJEGRZGYCLKXZDSKKNSXKCLJSPJYYZLQQJYBZSSQLLLKJXTBKTYLCCDDBLSPPFYLGYDTZJYQGGKQTTFZXBDKTYYHYBBFYTYYBCLPDYTGDHRYRNJSPTCSNYJQHKLLLZSLYDXXWBCJQSPXBPJZJCJDZFFXXBRMLAZHCSNDLBJDSZBLPRZTSWSBXBCLLXXLZDJZSJPYLYXXYFTFFFBHJJXGBYXJPMMMPSSJZJMTLYZJXSWXTYLEDQPJMYGQZJGDJLQJWJQLLSJGJGYGMSCLJJXDTYGJQJQJCJZCJGDZZSXQGSJGGCXHQXSNQLZZBXHSGZXCXYLJXYXYYDFQQJHJFXDHCTXJYRXYSQTJXYEFYYSSYYJXNCYZXFXMSYSZXYYSCHSHXZZZGZZZGFJDLTYLNPZGYJYZYYQZPBXQBDZTZCZYXXYHHSQXSHDHGQHJHGYWSZTMZMLHYXGEBTYLZKQWYTJZRCLEKYSTDBCYKQQSAYXCJXWWGSBHJYZYDHCSJKQCXSWXFLTYNYZPZCCZJQTZWJQDZZZQZLJJXLSBHPYXXPSXSHHEZTXFPTLQYZZXHYTXNCFZYYHXGNXMYWXTZSJPTHHGYMXMXQZXTSBCZYJYXXTYYZYPCQLMMSZMJZZLLZXGXZAAJZYXJMZXWDXZSXZDZXLEYJJZQBHZWZZZQTZPSXZTDSXJJJZNYAZPHXYYSRNQDTHZHYYKYJHDZXZLSWCLYBZYECWCYCRYLCXNHZYDZYDYJDFRJJHTRSQTXYXJRJHOJYNXELXSFSFJZGHPZSXZSZDZCQZBYYKLSGSJHCZSHDGQGXYZGXCHXZJWYQWGYHKSSEQZZNDZFKWYSSTCLZSTSYMCDHJXXYWEYXCZAYDMPXMDSXYBSQMJMZJMTZQLPJYQZCGQHXJHHLXXHLHDLDJQCLDWBSXFZZYYSCHTYTYYBHECXHYKGJPXHHYZJFXHWHBDZFYZBCAPNPGNYDMSXHMMMMAMYNBYJTMPXYYMCTHJBZYFCGTYHWPHFTWZZEZSBZEGPFMTSKFTYCMHFLLHGPZJXZJGZJYXZSBBQSCZZLZCCSTPGXMJSFTCCZJZDJXCYBZLFCJSYZFGSZLYBCWZZBYZDZYPSWYJZXZBDSYUXLZZBZFYGCZXBZHZFTPBGZGEJBSTGKDMFHYZZJHZLLZZGJQZLSFDJSSCBZGPDLFZFZSZYZYZSYGCXSNXXCHCZXTZZLJFZGQSQYXZJQDCCZTQCDXZJYQJQCHXZTDLGSCXZSYQJQTZWLQDQZTQCHQQJZYEZZZPBWKDJFCJPZTYPQYQTTYNLMBDKTJZPQZQZZFPZSBNJLGYJDXJDZZKZGQKXDLPZJTCJDQBXDJQJSTCKNXBXZMSLYJCQMTJQWWCJQNJNLLLHJCWQTBZQYDZCZPZZDZYDDCYZZZCCJTTJFZDPRRTZTJDCQTQZDTJNPLZBCLLCTZSXKJZQZPZLBZRBTJDCXFCZDBCCJJLTQQPLDCGZDBBZJCQDCJWYNLLZYZCCDWLLXWZLXRXNTQQCZXKQLSGDFQTDDGLRLAJJTKUYMKQLLTZYTDYYCZGJWYXDXFRSKSTQTENQMRKQZHHQKDLDAZFKYPBGGPZREBZZYKZZSPEGJXGYKQZZZSLYSYYYZWFQZYLZZLZHWCHKYPQGNPGBLPLRRJYXCCSYYHSFZFYBZYYTGZXYLXCZWXXZJZBLFFLGSKHYJZEYJHLPLLLLCZGXDRZELRHGKLZZYHZLYQSZZJZQLJZFLNBHGWLCZCFJYSPYXZLZLXGCCPZBLLCYBBBBUBBCBPCRNNZCZYRBFSRLDCGQYYQXYGMQZWTZYTYJXYFWTEHZZJYWLCCNTZYJJZDEDPZDZTSYQJHDYMBJNYJZLXTSSTPHNDJXXBYXQTZQDDTJTDYYTGWSCSZQFLSHLGLBCZPHDLYZJYCKWTYTYLBNYTSDSYCCTYSZYYEBHEXHQDTWNYGYCLXTSZYSTQMYGZAZCCSZZDSLZCLZRQXYYELJSBYMXSXZTEMBBLLYYLLYTDQYSHYMRQWKFKBFXNXSBYCHXBWJYHTQBPBSBWDZYLKGZSKYHXQZJXHXJXGNLJKZLYYCDXLFYFGHLJGJYBXQLYBXQPQGZTZPLNCYPXDJYQYDYMRBESJYYHKXXSTMXRCZZYWXYQYBMCLLYZHQYZWQXDBXBZWZMSLPDMYSKFMZKLZCYQYCZLQXFZZYDQZPZYGYJYZMZXDZFYFYTTQTZHGSPCZMLCCYTZXJCYTJMKSLPZHYSNZLLYTPZCTZZCKTXDHXXTQCYFKSMQCCYYAZHTJPCYLZLYJBJXTPNYLJYYNRXSYLMMNXJSMYBCSYSYLZYLXJJQYLDZLPQBFZZBLFNDXQKCZFYWHGQMRDSXYCYTXNQQJZYYPFZXDYZFPRXEJDGYQBXRCNFYYQPGHYJDYZXGRHTKYLNWDZNTSMPKLBTHBPYSZBZTJZSZZJTYYXZPHSSZZBZCZPTQFZMYFLYPYBBJQXZMXXDJMTSYSKKBJZXHJCKLPSMKYJZCXTMLJYXRZZQSLXXQPYZXMKYXXXJCLJPRMYYGADYSKQLSNDHYZKQXZYZTCGHZTLMLWZYBWSYCTBHJHJFCWZTXWYTKZLXQSHLYJZJXTMPLPYCGLTBZZTLZJCYJGDTCLKLPLLQPJMZPAPXYZLKKTKDZCZZBNZDYDYQZJYJGMCTXLTGXSZLMLHBGLKFWNWZHDXUHLFMKYSLGXDTWWFRJEJZTZHYDXYKSHWFZCQSHKTMQQHTZHYMJDJSKHXZJZBZZXYMPAGQMSTPXLSKLZYNWRTSQLSZBPSPSGZWYHTLKSSSWHZZLYYTNXJGMJSZSUFWNLSOZTXGXLSAMMLBWLDSZYLAKQCQCTMYCFJBSLXCLZZCLXXKSBZQCLHJPSQPLSXXCKSLNHPSFQQYTXYJZLQLDXZQJZDYYDJNZPTUZDSKJFSLJHYLZSQZLBTXYDGTQFDBYAZXDZHZJNHHQBYKNXJJQCZMLLJZKSPLDYCLBBLXKLELXJLBQYCXJXGCNLCQPLZLZYJTZLJGYZDZPLTQCSXFDMNYCXGBTJDCZNBGBQYQJWGKFHTNPYQZQGBKPBBYZMTJDYTBLSQMPSXTBNPDXKLEMYYCJYNZCTLDYKZZXDDXHQSHDGMZSJYCCTAYRZLPYLTLKXSLZCGGEXCLFXLKJRTLQJAQZNCMBYDKKCXGLCZJZXJHPTDJJMZQYKQSECQZDSHHADMLZFMMZBGNTJNNLGBYJBRBTMLBYJDZXLCJLPLDLPCQDHLXZLYCBLCXZZJADJLNZMMSSSMYBHBSQKBHRSXXJMXSDZNZPXLGBRHWGGFCXGMSKLLTSJYYCQLTSKYWYYHYWXBXQYWPYWYKQLSQPTNTKHQCWDQKTWPXXHCPTHTWUMSSYHBWCRWXHJMKMZNGWTMLKFGHKJYLSYYCXWHYECLQHKQHTTQKHFZLDXQWYZYYDESBPKYRZPJFYYZJCEQDZZDLATZBBFJLLCXDLMJSSXEGYGSJQXCWBXSSZPDYZCXDNYXPPZYDLYJCZPLTXLSXYZYRXCYYYDYLWWNZSAHJSYQYHGYWWAXTJZDAXYSRLTDPSSYYFNEJDXYZHLXLLLZQZSJNYQYQQXYJGHZGZCYJCHZLYCDSHWSHJZYJXCLLNXZJJYYXNFXMWFPYLCYLLABWDDHWDXJMCXZTZPMLQZHSFHZYNZTLLDYWLSLXHYMMYLMBWWKYXYADTXYLLDJPYBPWUXJMWMLLSAFDLLYFLBHHHBQQLTZJCQJLDJTFFKMMMBYTHYGDCQRDDWRQJXNBYSNWZDBYYTBJHPYBYTTJXAAHGQDQTMYSTQXKBTZPKJLZRBEQQSSMJJBDJOTGTBXPGBKTLHQXJJJCTHXQDWJLWRFWQGWSHCKRYSWGFTGYGBXSDWDWRFHWYTJJXXXJYZYSLPYYYPAYXHYDQKXSHXYXGSKQHYWFDDDPPLCJLQQEEWXKSYYKDYPLTJTHKJLTCYYHHJTTPLTZZCDLTHQKZXQYSTEEYWYYZYXXYYSTTJKLLPZMCYHQGXYHSRMBXPLLNQYDQHXSXXWGDQBSHYLLPJJJTHYJKYPPTHYYKTYEZYENMDSHLCRPQFDGFXZPSFTLJXXJBSWYYSKSFLXLPPLBBBLBSFXFYZBSJSSYLPBBFFFFSSCJDSTZSXZRYYSYFFSYZYZBJTBCTSBSDHRTJJBYTCXYJEYLXCBNEBJDSYXYKGSJZBXBYTFZWGENYHHTHZHHXFWGCSTBGXKLSXYWMTMBYXJSTZSCDYQRCYTWXZFHMYMCXLZNSDJTTTXRYCFYJSBSDYERXJLJXBBDEYNJGHXGCKGSCYMBLXJMSZNSKGXFBNBPTHFJAAFXYXFPXMYPQDTZCXZZPXRSYWZDLYBBKTYQPQJPZYPZJZNJPZJLZZFYSBTTSLMPTZRTDXQSJEHBZYLZDHLJSQMLHTXTJECXSLZZSPKTLZKQQYFSYGYWPCPQFHQHYTQXZKRSGTTSQCZLPTXCDYYZXSQZSLXLZMYCPCQBZYXHBSXLZDLTCDXTYLZJYYZPZYZLTXJSJXHLPMYTXCQRBLZSSFJZZTNJYTXMYJHLHPPLCYXQJQQKZZSCPZKSWALQSBLCCZJSXGWWWYGYKTJBBZTDKHXHKGTGPBKQYSLPXPJCKBMLLXDZSTBKLGGQKQLSBKKTFXRMDKBFTPZFRTBBRFERQGXYJPZSSTLBZTPSZQZSJDHLJQLZBPMSMMSXLQQNHKNBLRDDNXXDHDDJCYYGYLXGZLXSYGMQQGKHBPMXYXLYTQWLWGCPBMQXCYZYDRJBHTDJYHQSHTMJSBYPLWHLZFFNYPMHXXHPLTBQPFBJWQDBYGPNZTPFZJGSDDTQSHZEAWZZYLLTYYBWJKXXGHLFKXDJTMSZSQYNZGGSWQSPHTLSSKMCLZXYSZQZXNCJDQGZDLFNYKLJCJLLZLMZZNHYDSSHTHZZLZZBBHQZWWYCRZHLYQQJBEYFXXXWHSRXWQHWPSLMSSKZTTYGYQQWRSLALHMJTQJSMXQBJJZJXZYZKXBYQXBJXSHZTSFJLXMXZXFGHKZSZGGYLCLSARJYHSLLLMZXELGLXYDJYTLFBHBPNLYZFBBHPTGJKWETZHKJJXZXXGLLJLSTGSHJJYQLQZFKCGNNDJSSZFDBCTWWSEQFHQJBSAQTGYPQLBXBMMYWXGSLZHGLZGQYFLZBYFZJFRYSFMBYZHQGFWZSYFYJJPHZBYYZFFWODGRLMFTWLBZGYCQXCDJYGZYYYYTYTYDWEGAZYHXJLZYYHLRMGRXXZCLHNELJJTJTPWJYBJJBXJJTJTEEKHWSLJPLPSFYZPQQBDLQJJTYYQLYZKDKSQJYYQZLDQTGJQYZJSUCMRYQTHTEJMFCTYHYPKMHYZWJDQFHYYXWSHCTXRLJHQXHCCYYYJLTKTTYTMXGTCJTZAYYOCZLYLBSZYWJYTSJYHBYSHFJLYGJXXTMZYYLTXXYPZLXYJZYZYYPNHMYMDYYLBLHLSYYQQLLNJJYMSOYQBZGDLYXYLCQYXTSZEGXHZGLHWBLJHEYXTWQMAKBPQCGYSHHEGQCMWYYWLJYJHYYZLLJJYLHZYHMGSLJLJXCJJYCLYCJPCPZJZJMMYLCQLNQLJQJSXYJMLSZLJQLYCMMHCFMMFPQQMFYLQMCFFQMMMMHMZNFHHJGTTHHKHSLNCHHYQDXTMMQDCYZYXYQMYQYLTDCYYYZAZZCYMZYDLZFFFMMYCQZWZZMABTBYZTDMNZZGGDFTYPCGQYTTSSFFWFDTZQSSYSTWXJHXYTSXXYLBYQHWWKXHZXWZNNZZJZJJQJCCCHYYXBZXZCYZTLLCQXYNJYCYYCYNZZQYYYEWYCZDCJYCCHYJLBTZYYCQWMPWPYMLGKDLDLGKQQBGYCHJXY"; +const _ChineseFirstPY = "YDYQSXMWZSSXJBYMGCCZQPSSQBYCDSCDQLDYLYBSSJGYZZJJFKCCLZDHWDWZJLJPFYYNWJJTMYHZWZHFLZPPQHGSCYYYNJQYXXGJHHSDSJNKKTMOMLCRXYPSNQSECCQZGGLLYJLMYZZSECYKYYHQWJSSGGYXYZYJWWKDJHYCHMYXJTLXJYQBYXZLDWRDJRWYSRLDZJPCBZJJBRCFTLECZSTZFXXZHTRQHYBDLYCZSSYMMRFMYQZPWWJJYFCRWFDFZQPYDDWYXKYJAWJFFXYPSFTZYHHYZYSWCJYXSCLCXXWZZXNBGNNXBXLZSZSBSGPYSYZDHMDZBQBZCWDZZYYTZHBTSYYBZGNTNXQYWQSKBPHHLXGYBFMJEBJHHGQTJCYSXSTKZHLYCKGLYSMZXYALMELDCCXGZYRJXSDLTYZCQKCNNJWHJTZZCQLJSTSTBNXBTYXCEQXGKWJYFLZQLYHYXSPSFXLMPBYSXXXYDJCZYLLLSJXFHJXPJBTFFYABYXBHZZBJYZLWLCZGGBTSSMDTJZXPTHYQTGLJSCQFZKJZJQNLZWLSLHDZBWJNCJZYZSQQYCQYRZCJJWYBRTWPYFTWEXCSKDZCTBZHYZZYYJXZCFFZZMJYXXSDZZOTTBZLQWFCKSZSXFYRLNYJMBDTHJXSQQCCSBXYYTSYFBXDZTGBCNSLCYZZPSAZYZZSCJCSHZQYDXLBPJLLMQXTYDZXSQJTZPXLCGLQTZWJBHCTSYJSFXYEJJTLBGXSXJMYJQQPFZASYJNTYDJXKJCDJSZCBARTDCLYJQMWNQNCLLLKBYBZZSYHQQLTWLCCXTXLLZNTYLNEWYZYXCZXXGRKRMTCNDNJTSYYSSDQDGHSDBJGHRWRQLYBGLXHLGTGXBQJDZPYJSJYJCTMRNYMGRZJCZGJMZMGXMPRYXKJNYMSGMZJYMKMFXMLDTGFBHCJHKYLPFMDXLQJJSMTQGZSJLQDLDGJYCALCMZCSDJLLNXDJFFFFJCZFMZFFPFKHKGDPSXKTACJDHHZDDCRRCFQYJKQCCWJDXHWJLYLLZGCFCQDSMLZPBJJPLSBCJGGDCKKDEZSQCCKJGCGKDJTJDLZYCXKLQSCGJCLTFPCQCZGWPJDQYZJJBYJHSJDZWGFSJGZKQCCZLLPSPKJGQJHZZLJPLGJGJJTHJJYJZCZMLZLYQBGJWMLJKXZDZNJQSYZMLJLLJKYWXMKJLHSKJGBMCLYYMKXJQLBMLLKMDXXKWYXYSLMLPSJQQJQXYXFJTJDXMXXLLCXQBSYJBGWYMBGGBCYXPJYGPEPFGDJGBHBNSQJYZJKJKHXQFGQZKFHYGKHDKLLSDJQXPQYKYBNQSXQNSZSWHBSXWHXWBZZXDMNSJBSBKBBZKLYLXGWXDRWYQZMYWSJQLCJXXJXKJEQXSCYETLZHLYYYSDZPAQYZCMTLSHTZCFYZYXYLJSDCJQAGYSLCQLYYYSHMRQQKLDXZSCSSSYDYCJYSFSJBFRSSZQSBXXPXJYSDRCKGJLGDKZJZBDKTCSYQPYHSTCLDJDHMXMCGXYZHJDDTMHLTXZXYLYMOHYJCLTYFBQQXPFBDFHHTKSQHZYYWCNXXCRWHOWGYJLEGWDQCWGFJYCSNTMYTOLBYGWQWESJPWNMLRYDZSZTXYQPZGCWXHNGPYXSHMYQJXZTDPPBFYHZHTJYFDZWKGKZBLDNTSXHQEEGZZYLZMMZYJZGXZXKHKSTXNXXWYLYAPSTHXDWHZYMPXAGKYDXBHNHXKDPJNMYHYLPMGOCSLNZHKXXLPZZLBMLSFBHHGYGYYGGBHSCYAQTYWLXTZQCEZYDQDQMMHTKLLSZHLSJZWFYHQSWSCWLQAZYNYTLSXTHAZNKZZSZZLAXXZWWCTGQQTDDYZTCCHYQZFLXPSLZYGPZSZNGLNDQTBDLXGTCTAJDKYWNSYZLJHHZZCWNYYZYWMHYCHHYXHJKZWSXHZYXLYSKQYSPSLYZWMYPPKBYGLKZHTYXAXQSYSHXASMCHKDSCRSWJPWXSGZJLWWSCHSJHSQNHCSEGNDAQTBAALZZMSSTDQJCJKTSCJAXPLGGXHHGXXZCXPDMMHLDGTYBYSJMXHMRCPXXJZCKZXSHMLQXXTTHXWZFKHCCZDYTCJYXQHLXDHYPJQXYLSYYDZOZJNYXQEZYSQYAYXWYPDGXDDXSPPYZNDLTWRHXYDXZZJHTCXMCZLHPYYYYMHZLLHNXMYLLLMDCPPXHMXDKYCYRDLTXJCHHZZXZLCCLYLNZSHZJZZLNNRLWHYQSNJHXYNTTTKYJPYCHHYEGKCTTWLGQRLGGTGTYGYHPYHYLQYQGCWYQKPYYYTTTTLHYHLLTYTTSPLKYZXGZWGPYDSSZZDQXSKCQNMJJZZBXYQMJRTFFBTKHZKBXLJJKDXJTLBWFZPPTKQTZTGPDGNTPJYFALQMKGXBDCLZFHZCLLLLADPMXDJHLCCLGYHDZFGYDDGCYYFGYDXKSSEBDHYKDKDKHNAXXYBPBYYHXZQGAFFQYJXDMLJCSQZLLPCHBSXGJYNDYBYQSPZWJLZKSDDTACTBXZDYZYPJZQSJNKKTKNJDJGYYPGTLFYQKASDNTCYHBLWDZHBBYDWJRYGKZYHEYYFJMSDTYFZJJHGCXPLXHLDWXXJKYTCYKSSSMTWCTTQZLPBSZDZWZXGZAGYKTYWXLHLSPBCLLOQMMZSSLCMBJCSZZKYDCZJGQQDSMCYTZQQLWZQZXSSFPTTFQMDDZDSHDTDWFHTDYZJYQJQKYPBDJYYXTLJHDRQXXXHAYDHRJLKLYTWHLLRLLRCXYLBWSRSZZSYMKZZHHKYHXKSMDSYDYCJPBZBSQLFCXXXNXKXWYWSDZYQOGGQMMYHCDZTTFJYYBGSTTTYBYKJDHKYXBELHTYPJQNFXFDYKZHQKZBYJTZBXHFDXKDASWTAWAJLDYJSFHBLDNNTNQJTJNCHXFJSRFWHZFMDRYJYJWZPDJKZYJYMPCYZNYNXFBYTFYFWYGDBNZZZDNYTXZEMMQBSQEHXFZMBMFLZZSRXYMJGSXWZJSPRYDJSJGXHJJGLJJYNZZJXHGXKYMLPYYYCXYTWQZSWHWLYRJLPXSLSXMFSWWKLCTNXNYNPSJSZHDZEPTXMYYWXYYSYWLXJQZQXZDCLEEELMCPJPCLWBXSQHFWWTFFJTNQJHJQDXHWLBYZNFJLALKYYJLDXHHYCSTYYWNRJYXYWTRMDRQHWQCMFJDYZMHMYYXJWMYZQZXTLMRSPWWCHAQBXYGZYPXYYRRCLMPYMGKSJSZYSRMYJSNXTPLNBAPPYPYLXYYZKYNLDZYJZCZNNLMZHHARQMPGWQTZMXXMLLHGDZXYHXKYXYCJMFFYYHJFSBSSQLXXNDYCANNMTCJCYPRRNYTYQNYYMBMSXNDLYLYSLJRLXYSXQMLLYZLZJJJKYZZCSFBZXXMSTBJGNXYZHLXNMCWSCYZYFZLXBRNNNYLBNRTGZQYSATSWRYHYJZMZDHZGZDWYBSSCSKXSYHYTXXGCQGXZZSHYXJSCRHMKKBXCZJYJYMKQHZJFNBHMQHYSNJNZYBKNQMCLGQHWLZNZSWXKHLJHYYBQLBFCDSXDLDSPFZPSKJYZWZXZDDXJSMMEGJSCSSMGCLXXKYYYLNYPWWWGYDKZJGGGZGGSYCKNJWNJPCXBJJTQTJWDSSPJXZXNZXUMELPXFSXTLLXCLJXJJLJZXCTPSWXLYDHLYQRWHSYCSQYYBYAYWJJJQFWQCQQCJQGXALDBZZYJGKGXPLTZYFXJLTPADKYQHPMATLCPDCKBMTXYBHKLENXDLEEGQDYMSAWHZMLJTWYGXLYQZLJEEYYBQQFFNLYXRDSCTGJGXYYNKLLYQKCCTLHJLQMKKZGCYYGLLLJDZGYDHZWXPYSJBZKDZGYZZHYWYFQYTYZSZYEZZLYMHJJHTSMQWYZLKYYWZCSRKQYTLTDXWCTYJKLWSQZWBDCQYNCJSRSZJLKCDCDTLZZZACQQZZDDXYPLXZBQJYLZLLLQDDZQJYJYJZYXNYYYNYJXKXDAZWYRDLJYYYRJLXLLDYXJCYWYWNQCCLDDNYYYNYCKCZHXXCCLGZQJGKWPPCQQJYSBZZXYJSQPXJPZBSBDSFNSFPZXHDWZTDWPPTFLZZBZDMYYPQJRSDZSQZSQXBDGCPZSWDWCSQZGMDHZXMWWFYBPDGPHTMJTHZSMMBGZMBZJCFZWFZBBZMQCFMBDMCJXLGPNJBBXGYHYYJGPTZGZMQBQTCGYXJXLWZKYDPDYMGCFTPFXYZTZXDZXTGKMTYBBCLBJASKYTSSQYYMSZXFJEWLXLLSZBQJJJAKLYLXLYCCTSXMCWFKKKBSXLLLLJYXTYLTJYYTDPJHNHNNKBYQNFQYYZBYYESSESSGDYHFHWTCJBSDZZTFDMXHCNJZYMQWSRYJDZJQPDQBBSTJGGFBKJBXTGQHNGWJXJGDLLTHZHHYYYYYYSXWTYYYCCBDBPYPZYCCZYJPZYWCBDLFWZCWJDXXHYHLHWZZXJTCZLCDPXUJCZZZLYXJJTXPHFXWPYWXZPTDZZBDZCYHJHMLXBQXSBYLRDTGJRRCTTTHYTCZWMXFYTWWZCWJWXJYWCSKYBZSCCTZQNHXNWXXKHKFHTSWOCCJYBCMPZZYKBNNZPBZHHZDLSYDDYTYFJPXYNGFXBYQXCBHXCPSXTYZDMKYSNXSXLHKMZXLYHDHKWHXXSSKQYHHCJYXGLHZXCSNHEKDTGZXQYPKDHEXTYKCNYMYYYPKQYYYKXZLTHJQTBYQHXBMYHSQCKWWYLLHCYYLNNEQXQWMCFBDCCMLJGGXDQKTLXKGNQCDGZJWYJJLYHHQTTTNWCHMXCXWHWSZJYDJCCDBQCDGDNYXZTHCQRXCBHZTQCBXWGQWYYBXHMBYMYQTYEXMQKYAQYRGYZSLFYKKQHYSSQYSHJGJCNXKZYCXSBXYXHYYLSTYCXQTHYSMGSCPMMGCCCCCMTZTASMGQZJHKLOSQYLSWTMXSYQKDZLJQQYPLSYCZTCQQPBBQJZCLPKHQZYYXXDTDDTSJCXFFLLCHQXMJLWCJCXTSPYCXNDTJSHJWXDQQJSKXYAMYLSJHMLALYKXCYYDMNMDQMXMCZNNCYBZKKYFLMCHCMLHXRCJJHSYLNMTJZGZGYWJXSRXCWJGJQHQZDQJDCJJZKJKGDZQGJJYJYLXZXXCDQHHHEYTMHLFSBDJSYYSHFYSTCZQLPBDRFRZTZYKYWHSZYQKWDQZRKMSYNBCRXQBJYFAZPZZEDZCJYWBCJWHYJBQSZYWRYSZPTDKZPFPBNZTKLQYHBBZPNPPTYZZYBQNYDCPJMMCYCQMCYFZZDCMNLFPBPLNGQJTBTTNJZPZBBZNJKLJQYLNBZQHKSJZNGGQSZZKYXSHPZSNBCGZKDDZQANZHJKDRTLZLSWJLJZLYWTJNDJZJHXYAYNCBGTZCSSQMNJPJYTYSWXZFKWJQTKHTZPLBHSNJZSYZBWZZZZLSYLSBJHDWWQPSLMMFBJDWAQYZTCJTBNNWZXQXCDSLQGDSDPDZHJTQQPSWLYYJZLGYXYZLCTCBJTKTYCZJTQKBSJLGMGZDMCSGPYNJZYQYYKNXRPWSZXMTNCSZZYXYBYHYZAXYWQCJTLLCKJJTJHGDXDXYQYZZBYWDLWQCGLZGJGQRQZCZSSBCRPCSKYDZNXJSQGXSSJMYDNSTZTPBDLTKZWXQWQTZEXNQCZGWEZKSSBYBRTSSSLCCGBPSZQSZLCCGLLLZXHZQTHCZMQGYZQZNMCOCSZJMMZSQPJYGQLJYJPPLDXRGZYXCCSXHSHGTZNLZWZKJCXTCFCJXLBMQBCZZWPQDNHXLJCTHYZLGYLNLSZZPCXDSCQQHJQKSXZPBAJYEMSMJTZDXLCJYRYYNWJBNGZZTMJXLTBSLYRZPYLSSCNXPHLLHYLLQQZQLXYMRSYCXZLMMCZLTZSDWTJJLLNZGGQXPFSKYGYGHBFZPDKMWGHCXMSGDXJMCJZDYCABXJDLNBCDQYGSKYDQTXDJJYXMSZQAZDZFSLQXYJSJZYLBTXXWXQQZBJZUFBBLYLWDSLJHXJYZJWTDJCZFQZQZZDZSXZZQLZCDZFJHYSPYMPQZMLPPLFFXJJNZZYLSJEYQZFPFZKSYWJJJHRDJZZXTXXGLGHYDXCSKYSWMMZCWYBAZBJKSHFHJCXMHFQHYXXYZFTSJYZFXYXPZLCHMZMBXHZZSXYFYMNCWDABAZLXKTCSHHXKXJJZJSTHYGXSXYYHHHJWXKZXSSBZZWHHHCWTZZZPJXSNXQQJGZYZYWLLCWXZFXXYXYHXMKYYSWSQMNLNAYCYSPMJKHWCQHYLAJJMZXHMMCNZHBHXCLXTJPLTXYJHDYYLTTXFSZHYXXSJBJYAYRSMXYPLCKDUYHLXRLNLLSTYZYYQYGYHHSCCSMZCTZQXKYQFPYYRPFFLKQUNTSZLLZMWWTCQQYZWTLLMLMPWMBZSSTZRBPDDTLQJJBXZCSRZQQYGWCSXFWZLXCCRSZDZMCYGGDZQSGTJSWLJMYMMZYHFBJDGYXCCPSHXNZCSBSJYJGJMPPWAFFYFNXHYZXZYLREMZGZCYZSSZDLLJCSQFNXZKPTXZGXJJGFMYYYSNBTYLBNLHPFZDCYFBMGQRRSSSZXYSGTZRNYDZZCDGPJAFJFZKNZBLCZSZPSGCYCJSZLMLRSZBZZLDLSLLYSXSQZQLYXZLSKKBRXBRBZCYCXZZZEEYFGKLZLYYHGZSGZLFJHGTGWKRAAJYZKZQTSSHJJXDCYZUYJLZYRZDQQHGJZXSSZBYKJPBFRTJXLLFQWJHYLQTYMBLPZDXTZYGBDHZZRBGXHWNJTJXLKSCFSMWLSDQYSJTXKZSCFWJLBXFTZLLJZLLQBLSQMQQCGCZFPBPHZCZJLPYYGGDTGWDCFCZQYYYQYSSCLXZSKLZZZGFFCQNWGLHQYZJJCZLQZZYJPJZZBPDCCMHJGXDQDGDLZQMFGPSYTSDYFWWDJZJYSXYYCZCYHZWPBYKXRYLYBHKJKSFXTZJMMCKHLLTNYYMSYXYZPYJQYCSYCWMTJJKQYRHLLQXPSGTLYYCLJSCPXJYZFNMLRGJJTYZBXYZMSJYJHHFZQMSYXRSZCWTLRTQZSSTKXGQKGSPTGCZNJSJCQCXHMXGGZTQYDJKZDLBZSXJLHYQGGGTHQSZPYHJHHGYYGKGGCWJZZYLCZLXQSFTGZSLLLMLJSKCTBLLZZSZMMNYTPZSXQHJCJYQXYZXZQZCPSHKZZYSXCDFGMWQRLLQXRFZTLYSTCTMJCXJJXHJNXTNRZTZFQYHQGLLGCXSZSJDJLJCYDSJTLNYXHSZXCGJZYQPYLFHDJSBPCCZHJJJQZJQDYBSSLLCMYTTMQTBHJQNNYGKYRQYQMZGCJKPDCGMYZHQLLSLLCLMHOLZGDYYFZSLJCQZLYLZQJESHNYLLJXGJXLYSYYYXNBZLJSSZCQQCJYLLZLTJYLLZLLBNYLGQCHXYYXOXCXQKYJXXXYKLXSXXYQXCYKQXQCSGYXXYQXYGYTQOHXHXPYXXXULCYEYCHZZCBWQBBWJQZSCSZSSLZYLKDESJZWMYMCYTSDSXXSCJPQQSQYLYYZYCMDJDZYWCBTJSYDJKCYDDJLBDJJSODZYSYXQQYXDHHGQQYQHDYXWGMMMAJDYBBBPPBCMUUPLJZSMTXERXJMHQNUTPJDCBSSMSSSTKJTSSMMTRCPLZSZMLQDSDMJMQPNQDXCFYNBFSDQXYXHYAYKQYDDLQYYYSSZBYDSLNTFQTZQPZMCHDHCZCWFDXTMYQSPHQYYXSRGJCWTJTZZQMGWJJTJHTQJBBHWZPXXHYQFXXQYWYYHYSCDYDHHQMNMTMWCPBSZPPZZGLMZFOLLCFWHMMSJZTTDHZZYFFYTZZGZYSKYJXQYJZQBHMBZZLYGHGFMSHPZFZSNCLPBQSNJXZSLXXFPMTYJYGBXLLDLXPZJYZJYHHZCYWHJYLSJEXFSZZYWXKZJLUYDTMLYMQJPWXYHXSKTQJEZRPXXZHHMHWQPWQLYJJQJJZSZCPHJLCHHNXJLQWZJHBMZYXBDHHYPZLHLHLGFWLCHYYTLHJXCJMSCPXSTKPNHQXSRTYXXTESYJCTLSSLSTDLLLWWYHDHRJZSFGXTSYCZYNYHTDHWJSLHTZDQDJZXXQHGYLTZPHCSQFCLNJTCLZPFSTPDYNYLGMJLLYCQHYSSHCHYLHQYQTMZYPBYWRFQYKQSYSLZDQJMPXYYSSRHZJNYWTQDFZBWWTWWRXCWHGYHXMKMYYYQMSMZHNGCEPMLQQMTCWCTMMPXJPJJHFXYYZSXZHTYBMSTSYJTTQQQYYLHYNPYQZLCYZHZWSMYLKFJXLWGXYPJYTYSYXYMZCKTTWLKSMZSYLMPWLZWXWQZSSAQSYXYRHSSNTSRAPXCPWCMGDXHXZDZYFJHGZTTSBJHGYZSZYSMYCLLLXBTYXHBBZJKSSDMALXHYCFYGMQYPJYCQXJLLLJGSLZGQLYCJCCZOTYXMTMTTLLWTGPXYMZMKLPSZZZXHKQYSXCTYJZYHXSHYXZKXLZWPSQPYHJWPJPWXQQYLXSDHMRSLZZYZWTTCYXYSZZSHBSCCSTPLWSSCJCHNLCGCHSSPHYLHFHHXJSXYLLNYLSZDHZXYLSXLWZYKCLDYAXZCMDDYSPJTQJZLNWQPSSSWCTSTSZLBLNXSMNYYMJQBQHRZWTYYDCHQLXKPZWBGQYBKFCMZWPZLLYYLSZYDWHXPSBCMLJBSCGBHXLQHYRLJXYSWXWXZSLDFHLSLYNJLZYFLYJYCDRJLFSYZFSLLCQYQFGJYHYXZLYLMSTDJCYHBZLLNWLXXYGYYHSMGDHXXHHLZZJZXCZZZCYQZFNGWPYLCPKPYYPMCLQKDGXZGGWQBDXZZKZFBXXLZXJTPJPTTBYTSZZDWSLCHZHSLTYXHQLHYXXXYYZYSWTXZKHLXZXZPYHGCHKCFSYHUTJRLXFJXPTZTWHPLYXFCRHXSHXKYXXYHZQDXQWULHYHMJTBFLKHTXCWHJFWJCFPQRYQXCYYYQYGRPYWSGSUNGWCHKZDXYFLXXHJJBYZWTSXXNCYJJYMSWZJQRMHXZWFQSYLZJZGBHYNSLBGTTCSYBYXXWXYHXYYXNSQYXMQYWRGYQLXBBZLJSYLPSYTJZYHYZAWLRORJMKSCZJXXXYXCHDYXRYXXJDTSQFXLYLTSFFYXLMTYJMJUYYYXLTZCSXQZQHZXLYYXZHDNBRXXXJCTYHLBRLMBRLLAXKYLLLJLYXXLYCRYLCJTGJCMTLZLLCYZZPZPCYAWHJJFYBDYYZSMPCKZDQYQPBPCJPDCYZMDPBCYYDYCNNPLMTMLRMFMMGWYZBSJGYGSMZQQQZTXMKQWGXLLPJGZBQCDJJJFPKJKCXBLJMSWMDTQJXLDLPPBXCWRCQFBFQJCZAHZGMYKPHYYHZYKNDKZMBPJYXPXYHLFPNYYGXJDBKXNXHJMZJXSTRSTLDXSKZYSYBZXJLXYSLBZYSLHXJPFXPQNBYLLJQKYGZMCYZZYMCCSLCLHZFWFWYXZMWSXTYNXJHPYYMCYSPMHYSMYDYSHQYZCHMJJMZCAAGCFJBBHPLYZYLXXSDJGXDHKXXTXXNBHRMLYJSLTXMRHNLXQJXYZLLYSWQGDLBJHDCGJYQYCMHWFMJYBMBYJYJWYMDPWHXQLDYGPDFXXBCGJSPCKRSSYZJMSLBZZJFLJJJLGXZGYXYXLSZQYXBEXYXHGCXBPLDYHWETTWWCJMBTXCHXYQXLLXFLYXLLJLSSFWDPZSMYJCLMWYTCZPCHQEKCQBWLCQYDPLQPPQZQFJQDJHYMMCXTXDRMJWRHXCJZYLQXDYYNHYYHRSLSRSYWWZJYMTLTLLGTQCJZYABTCKZCJYCCQLJZQXALMZYHYWLWDXZXQDLLQSHGPJFJLJHJABCQZDJGTKHSSTCYJLPSWZLXZXRWGLDLZRLZXTGSLLLLZLYXXWGDZYGBDPHZPBRLWSXQBPFDWOFMWHLYPCBJCCLDMBZPBZZLCYQXLDOMZBLZWPDWYYGDSTTHCSQSCCRSSSYSLFYBFNTYJSZDFNDPDHDZZMBBLSLCMYFFGTJJQWFTMTPJWFNLBZCMMJTGBDZLQLPYFHYYMJYLSDCHDZJWJCCTLJCLDTLJJCPDDSQDSSZYBNDBJLGGJZXSXNLYCYBJXQYCBYLZCFZPPGKCXZDZFZTJJFJSJXZBNZYJQTTYJYHTYCZHYMDJXTTMPXSPLZCDWSLSHXYPZGTFMLCJTYCBPMGDKWYCYZCDSZZYHFLYCTYGWHKJYYLSJCXGYWJCBLLCSNDDBTZBSCLYZCZZSSQDLLMQYYHFSLQLLXFTYHABXGWNYWYYPLLSDLDLLBJCYXJZMLHLJDXYYQYTDLLLBUGBFDFBBQJZZMDPJHGCLGMJJPGAEHHBWCQXAXHHHZCHXYPHJAXHLPHJPGPZJQCQZGJJZZUZDMQYYBZZPHYHYBWHAZYJHYKFGDPFQSDLZMLJXKXGALXZDAGLMDGXMWZQYXXDXXPFDMMSSYMPFMDMMKXKSYZYSHDZKXSYSMMZZZMSYDNZZCZXFPLSTMZDNMXCKJMZTYYMZMZZMSXHHDCZJEMXXKLJSTLWLSQLYJZLLZJSSDPPMHNLZJCZYHMXXHGZCJMDHXTKGRMXFWMCGMWKDTKSXQMMMFZZYDKMSCLCMPCGMHSPXQPZDSSLCXKYXTWLWJYAHZJGZQMCSNXYYMMPMLKJXMHLMLQMXCTKZMJQYSZJSYSZHSYJZJCDAJZYBSDQJZGWZQQXFKDMSDJLFWEHKZQKJPEYPZYSZCDWYJFFMZZYLTTDZZEFMZLBNPPLPLPEPSZALLTYLKCKQZKGENQLWAGYXYDPXLHSXQQWQCQXQCLHYXXMLYCCWLYMQYSKGCHLCJNSZKPYZKCQZQLJPDMDZHLASXLBYDWQLWDNBQCRYDDZTJYBKBWSZDXDTNPJDTCTQDFXQQMGNXECLTTBKPWSLCTYQLPWYZZKLPYGZCQQPLLKCCYLPQMZCZQCLJSLQZDJXLDDHPZQDLJJXZQDXYZQKZLJCYQDYJPPYPQYKJYRMPCBYMCXKLLZLLFQPYLLLMBSGLCYSSLRSYSQTMXYXZQZFDZUYSYZTFFMZZSMZQHZSSCCMLYXWTPZGXZJGZGSJSGKDDHTQGGZLLBJDZLCBCHYXYZHZFYWXYZYMSDBZZYJGTSMTFXQYXQSTDGSLNXDLRYZZLRYYLXQHTXSRTZNGZXBNQQZFMYKMZJBZYMKBPNLYZPBLMCNQYZZZSJZHJCTZKHYZZJRDYZHNPXGLFZTLKGJTCTSSYLLGZRZBBQZZKLPKLCZYSSUYXBJFPNJZZXCDWXZYJXZZDJJKGGRSRJKMSMZJLSJYWQSKYHQJSXPJZZZLSNSHRNYPZTWCHKLPSRZLZXYJQXQKYSJYCZTLQZYBBYBWZPQDWWYZCYTJCJXCKCWDKKZXSGKDZXWWYYJQYYTCYTDLLXWKCZKKLCCLZCQQDZLQLCSFQCHQHSFSMQZZLNBJJZBSJHTSZDYSJQJPDLZCDCWJKJZZLPYCGMZWDJJBSJQZSYZYHHXJPBJYDSSXDZNCGLQMBTSFSBPDZDLZNFGFJGFSMPXJQLMBLGQCYYXBQKDJJQYRFKZTJDHCZKLBSDZCFJTPLLJGXHYXZCSSZZXSTJYGKGCKGYOQXJPLZPBPGTGYJZGHZQZZLBJLSQFZGKQQJZGYCZBZQTLDXRJXBSXXPZXHYZYCLWDXJJHXMFDZPFZHQHQMQGKSLYHTYCGFRZGNQXCLPDLBZCSCZQLLJBLHBZCYPZZPPDYMZZSGYHCKCPZJGSLJLNSCDSLDLXBMSTLDDFJMKDJDHZLZXLSZQPQPGJLLYBDSZGQLBZLSLKYYHZTTNTJYQTZZPSZQZTLLJTYYLLQLLQYZQLBDZLSLYYZYMDFSZSNHLXZNCZQZPBWSKRFBSYZMTHBLGJPMCZZLSTLXSHTCSYZLZBLFEQHLXFLCJLYLJQCBZLZJHHSSTBRMHXZHJZCLXFNBGXGTQJCZTMSFZKJMSSNXLJKBHSJXNTNLZDNTLMSJXGZJYJCZXYJYJWRWWQNZTNFJSZPZSHZJFYRDJSFSZJZBJFZQZZHZLXFYSBZQLZSGYFTZDCSZXZJBQMSZKJRHYJZCKMJKHCHGTXKXQGLXPXFXTRTYLXJXHDTSJXHJZJXZWZLCQSBTXWXGXTXXHXFTSDKFJHZYJFJXRZSDLLLTQSQQZQWZXSYQTWGWBZCGZLLYZBCLMQQTZHZXZXLJFRMYZFLXYSQXXJKXRMQDZDMMYYBSQBHGZMWFWXGMXLZPYYTGZYCCDXYZXYWGSYJYZNBHPZJSQSYXSXRTFYZGRHZTXSZZTHCBFCLSYXZLZQMZLMPLMXZJXSFLBYZMYQHXJSXRXSQZZZSSLYFRCZJRCRXHHZXQYDYHXSJJHZCXZBTYNSYSXJBQLPXZQPYMLXZKYXLXCJLCYSXXZZLXDLLLJJYHZXGYJWKJRWYHCPSGNRZLFZWFZZNSXGXFLZSXZZZBFCSYJDBRJKRDHHGXJLJJTGXJXXSTJTJXLYXQFCSGSWMSBCTLQZZWLZZKXJMLTMJYHSDDBXGZHDLBMYJFRZFSGCLYJBPMLYSMSXLSZJQQHJZFXGFQFQBPXZGYYQXGZTCQWYLTLGWSGWHRLFSFGZJMGMGBGTJFSYZZGZYZAFLSSPMLPFLCWBJZCLJJMZLPJJLYMQDMYYYFBGYGYZMLYZDXQYXRQQQHSYYYQXYLJTYXFSFSLLGNQCYHYCWFHCCCFXPYLYPLLZYXXXXXKQHHXSHJZCFZSCZJXCPZWHHHHHAPYLQALPQAFYHXDYLUKMZQGGGDDESRNNZLTZGCHYPPYSQJJHCLLJTOLNJPZLJLHYMHEYDYDSQYCDDHGZUNDZCLZYZLLZNTNYZGSLHSLPJJBDGWXPCDUTJCKLKCLWKLLCASSTKZZDNQNTTLYYZSSYSSZZRYLJQKCQDHHCRXRZYDGRGCWCGZQFFFPPJFZYNAKRGYWYQPQXXFKJTSZZXSWZDDFBBXTBGTZKZNPZZPZXZPJSZBMQHKCYXYLDKLJNYPKYGHGDZJXXEAHPNZKZTZCMXCXMMJXNKSZQNMNLWBWWXJKYHCPSTMCSQTZJYXTPCTPDTNNPGLLLZSJLSPBLPLQHDTNJNLYYRSZFFJFQWDPHZDWMRZCCLODAXNSSNYZRESTYJWJYJDBCFXNMWTTBYLWSTSZGYBLJPXGLBOCLHPCBJLTMXZLJYLZXCLTPNCLCKXTPZJSWCYXSFYSZDKNTLBYJCYJLLSTGQCBXRYZXBXKLYLHZLQZLNZCXWJZLJZJNCJHXMNZZGJZZXTZJXYCYYCXXJYYXJJXSSSJSTSSTTPPGQTCSXWZDCSYFPTFBFHFBBLZJCLZZDBXGCXLQPXKFZFLSYLTUWBMQJHSZBMDDBCYSCCLDXYCDDQLYJJWMQLLCSGLJJSYFPYYCCYLTJANTJJPWYCMMGQYYSXDXQMZHSZXPFTWWZQSWQRFKJLZJQQYFBRXJHHFWJJZYQAZMYFRHCYYBYQWLPEXCCZSTYRLTTDMQLYKMBBGMYYJPRKZNPBSXYXBHYZDJDNGHPMFSGMWFZMFQMMBCMZZCJJLCNUXYQLMLRYGQZCYXZLWJGCJCGGMCJNFYZZJHYCPRRCMTZQZXHFQGTJXCCJEAQCRJYHPLQLSZDJRBCQHQDYRHYLYXJSYMHZYDWLDFRYHBPYDTSSCNWBXGLPZMLZZTQSSCPJMXXYCSJYTYCGHYCJWYRXXLFEMWJNMKLLSWTXHYYYNCMMCWJDQDJZGLLJWJRKHPZGGFLCCSCZMCBLTBHBQJXQDSPDJZZGHGLFQYWBZYZJLTSTDHQHCTCBCHFLQMPWDSHYYTQWCNZZJTLBYMBPDYYYXSQKXWYYFLXXNCWCXYPMAELYKKJMZZZBRXYYQJFLJPFHHHYTZZXSGQQMHSPGDZQWBWPJHZJDYSCQWZKTXXSQLZYYMYSDZGRXCKKUJLWPYSYSCSYZLRMLQSYLJXBCXTLWDQZPCYCYKPPPNSXFYZJJRCEMHSZMSXLXGLRWGCSTLRSXBZGBZGZTCPLUJLSLYLYMTXMTZPALZXPXJTJWTCYYZLBLXBZLQMYLXPGHDSLSSDMXMBDZZSXWHAMLCZCPJMCNHJYSNSYGCHSKQMZZQDLLKABLWJXSFMOCDXJRRLYQZKJMYBYQLYHETFJZFRFKSRYXFJTWDSXXSYSQJYSLYXWJHSNLXYYXHBHAWHHJZXWMYLJCSSLKYDZTXBZSYFDXGXZJKHSXXYBSSXDPYNZWRPTQZCZENYGCXQFJYKJBZMLJCMQQXUOXSLYXXLYLLJDZBTYMHPFSTTQQWLHOKYBLZZALZXQLHZWRRQHLSTMYPYXJJXMQSJFNBXYXYJXXYQYLTHYLQYFMLKLJTMLLHSZWKZHLJMLHLJKLJSTLQXYLMBHHLNLZXQJHXCFXXLHYHJJGBYZZKBXSCQDJQDSUJZYYHZHHMGSXCSYMXFEBCQWWRBPYYJQTYZCYQYQQZYHMWFFHGZFRJFCDPXNTQYZPDYKHJLFRZXPPXZDBBGZQSTLGDGYLCQMLCHHMFYWLZYXKJLYPQHSYWMQQGQZMLZJNSQXJQSYJYCBEHSXFSZPXZWFLLBCYYJDYTDTHWZSFJMQQYJLMQXXLLDTTKHHYBFPWTYYSQQWNQWLGWDEBZWCMYGCULKJXTMXMYJSXHYBRWFYMWFRXYQMXYSZTZZTFYKMLDHQDXWYYNLCRYJBLPSXCXYWLSPRRJWXHQYPHTYDNXHHMMYWYTZCSQMTSSCCDALWZTCPQPYJLLQZYJSWXMZZMMYLMXCLMXCZMXMZSQTZPPQQBLPGXQZHFLJJHYTJSRXWZXSCCDLXTYJDCQJXSLQYCLZXLZZXMXQRJMHRHZJBHMFLJLMLCLQNLDXZLLLPYPSYJYSXCQQDCMQJZZXHNPNXZMEKMXHYKYQLXSXTXJYYHWDCWDZHQYYBGYBCYSCFGPSJNZDYZZJZXRZRQJJYMCANYRJTLDPPYZBSTJKXXZYPFDWFGZZRPYMTNGXZQBYXNBUFNQKRJQZMJEGRZGYCLKXZDSKKNSXKCLJSPJYYZLQQJYBZSSQLLLKJXTBKTYLCCDDBLSPPFYLGYDTZJYQGGKQTTFZXBDKTYYHYBBFYTYYBCLPDYTGDHRYRNJSPTCSNYJQHKLLLZSLYDXXWBCJQSPXBPJZJCJDZFFXXBRMLAZHCSNDLBJDSZBLPRZTSWSBXBCLLXXLZDJZSJPYLYXXYFTFFFBHJJXGBYXJPMMMPSSJZJMTLYZJXSWXTYLEDQPJMYGQZJGDJLQJWJQLLSJGJGYGMSCLJJXDTYGJQJQJCJZCJGDZZSXQGSJGGCXHQXSNQLZZBXHSGZXCXYLJXYXYYDFQQJHJFXDHCTXJYRXYSQTJXYEFYYSSYYJXNCYZXFXMSYSZXYYSCHSHXZZZGZZZGFJDLTYLNPZGYJYZYYQZPBXQBDZTZCZYXXYHHSQXSHDHGQHJHGYWSZTMZMLHYXGEBTYLZKQWYTJZRCLEKYSTDBCYKQQSAYXCJXWWGSBHJYZYDHCSJKQCXSWXFLTYNYZPZCCZJQTZWJQDZZZQZLJJXLSBHPYXXPSXSHHEZTXFPTLQYZZXHYTXNCFZYYHXGNXMYWXTZSJPTHHGYMXMXQZXTSBCZYJYXXTYYZYPCQLMMSZMJZZLLZXGXZAAJZYXJMZXWDXZSXZDZXLEYJJZQBHZWZZZQTZPSXZTDSXJJJZNYAZPHXYYSRNQDTHZHYYKYJHDZXZLSWCLYBZYECWCYCRYLCXNHZYDZYDYJDFRJJHTRSQTXYXJRJHOJYNXELXSFSFJZGHPZSXZSZDZCQZBYYKLSGSJHCZSHDGQGXYZGXCHXZJWYQWGYHKSSEQZZNDZFKWYSSTCLZSTSYMCDHJXXYWEYXCZAYDMPXMDSXYBSQMJMZJMTZQLPJYQZCGQHXJHHLXXHLHDLDJQCLDWBSXFZZYYSCHTYTYYBHECXHYKGJPXHHYZJFXHWHBDZFYZBCAPNPGNYDMSXHMMMMAMYNBYJTMPXYYMCTHJBZYFCGTYHWPHFTWZZEZSBZEGPFMTSKFTYCMHFLLHGPZJXZJGZJYXZSBBQSCZZLZCCSTPGXMJSFTCCZJZDJXCYBZLFCJSYZFGSZLYBCWZZBYZDZYPSWYJZXZBDSYUXLZZBZFYGCZXBZHZFTPBGZGEJBSTGKDMFHYZZJHZLLZZGJQZLSFDJSSCBZGPDLFZFZSZYZYZSYGCXSNXXCHCZXTZZLJFZGQSQYXZJQDCCZTQCDXZJYQJQCHXZTDLGSCXZSYQJQTZWLQDQZTQCHQQJZYEZZZPBWKDJFCJPZTYPQYQTTYNLMBDKTJZPQZQZZFPZSBNJLGYJDXJDZZKZGQKXDLPZJTCJDQBXDJQJSTCKNXBXZMSLYJCQMTJQWWCJQNJNLLLHJCWQTBZQYDZCZPZZDZYDDCYZZZCCJTTJFZDPRRTZTJDCQTQZDTJNPLZBCLLCTZSXKJZQZPZLBZRBTJDCXFCZDBCCJJLTQQPLDCGZDBBZJCQDCJWYNLLZYZCCDWLLXWZLXRXNTQQCZXKQLSGDFQTDDGLRLAJJTKUYMKQLLTZYTDYYCZGJWYXDXFRSKSTQTENQMRKQZHHQKDLDAZFKYPBGGPZREBZZYKZZSPEGJXGYKQZZZSLYSYYYZWFQZYLZZLZHWCHKYPQGNPGBLPLRRJYXCCSYYHSFZFYBZYYTGZXYLXCZWXXZJZBLFFLGSKHYJZEYJHLPLLLLCZGXDRZELRHGKLZZYHZLYQSZZJZQLJZFLNBHGWLCZCFJYSPYXZLZLXGCCPZBLLCYBBBBUBBCBPCRNNZCZYRBFSRLDCGQYYQXYGMQZWTZYTYJXYFWTEHZZJYWLCCNTZYJJZDEDPZDZTSYQJHDYMBJNYJZLXTSSTPHNDJXXBYXQTZQDDTJTDYYTGWSCSZQFLSHLGLBCZPHDLYZJYCKWTYTYLBNYTSDSYCCTYSZYYEBHEXHQDTWNYGYCLXTSZYSTQMYGZAZCCSZZDSLZCLZRQXYYELJSBYMXSXZTEMBBLLYYLLYTDQYSHYMRQWKFKBFXNXSBYCHXBWJYHTQBPBSBWDZYLKGZSKYHXQZJXHXJXGNLJKZLYYCDXLFYFGHLJGJYBXQLYBXQPQGZTZPLNCYPXDJYQYDYMRBESJYYHKXXSTMXRCZZYWXYQYBMCLLYZHQYZWQXDBXBZWZMSLPDMYSKFMZKLZCYQYCZLQXFZZYDQZPZYGYJYZMZXDZFYFYTTQTZHGSPCZMLCCYTZXJCYTJMKSLPZHYSNZLLYTPZCTZZCKTXDHXXTQCYFKSMQCCYYAZHTJPCYLZLYJBJXTPNYLJYYNRXSYLMMNXJSMYBCSYSYLZYLXJJQYLDZLPQBFZZBLFNDXQKCZFYWHGQMRDSXYCYTXNQQJZYYPFZXDYZFPRXEJDGYQBXRCNFYYQPGHYJDYZXGRHTKYLNWDZNTSMPKLBTHBPYSZBZTJZSZZJTYYXZPHSSZZBZCZPTQFZMYFLYPYBBJQXZMXXDJMTSYSKKBJZXHJCKLPSMKYJZCXTMLJYXRZZQSLXXQPYZXMKYXXXJCLJPRMYYGADYSKQLSNDHYZKQXZYZTCGHZTLMLWZYBWSYCTBHJHJFCWZTXWYTKZLXQSHLYJZJXTMPLPYCGLTBZZTLZJCYJGDTCLKLPLLQPJMZPAPXYZLKKTKDZCZZBNZDYDYQZJYJGMCTXLTGXSZLMLHBGLKFWNWZHDXUHLFMKYSLGXDTWWFRJEJZTZHYDXYKSHWFZCQSHKTMQQHTZHYMJDJSKHXZJZBZZXYMPAGQMSTPXLSKLZYNWRTSQLSZBPSPSGZWYHTLKSSSWHZZLYYTNXJGMJSZSUFWNLSOZTXGXLSAMMLBWLDSZYLAKQCQCTMYCFJBSLXCLZZCLXXKSBZQCLHJPSQPLSXXCKSLNHPSFQQYTXYJZLQLDXZQJZDYYDJNZPTUZDSKJFSLJHYLZSQZLBTXYDGTQFDBYAZXDZHZJNHHQBYKNXJJQCZMLLJZKSPLDYCLBBLXKLELXJLBQYCXJXGCNLCQPLZLZYJTZLJGYZDZPLTQCSXFDMNYCXGBTJDCZNBGBQYQJWGKFHTNPYQZQGBKPBBYZMTJDYTBLSQMPSXTBNPDXKLEMYYCJYNZCTLDYKZZXDDXHQSHDGMZSJYCCTAYRZLPYLTLKXSLZCGGEXCLFXLKJRTLQJAQZNCMBYDKKCXGLCZJZXJHPTDJJMZQYKQSECQZDSHHADMLZFMMZBGNTJNNLGBYJBRBTMLBYJDZXLCJLPLDLPCQDHLXZLYCBLCXZZJADJLNZMMSSSMYBHBSQKBHRSXXJMXSDZNZPXLGBRHWGGFCXGMSKLLTSJYYCQLTSKYWYYHYWXBXQYWPYWYKQLSQPTNTKHQCWDQKTWPXXHCPTHTWUMSSYHBWCRWXHJMKMZNGWTMLKFGHKJYLSYYCXWHYECLQHKQHTTQKHFZLDXQWYZYYDESBPKYRZPJFYYZJCEQDZZDLATZBBFJLLCXDLMJSSXEGYGSJQXCWBXSSZPDYZCXDNYXPPZYDLYJCZPLTXLSXYZYRXCYYYDYLWWNZSAHJSYQYHGYWWAXTJZDAXYSRLTDPSSYYFNEJDXYZHLXLLLZQZSJNYQYQQXYJGHZGZCYJCHZLYCDSHWSHJZYJXCLLNXZJJYYXNFXMWFPYLCYLLABWDDHWDXJMCXZTZPMLQZHSFHZYNZTLLDYWLSLXHYMMYLMBWWKYXYADTXYLLDJPYBPWUXJMWMLLSAFDLLYFLBHHHBQQLTZJCQJLDJTFFKMMMBYTHYGDCQRDDWRQJXNBYSNWZDBYYTBJHPYBYTTJXAAHGQDQTMYSTQXKBTZPKJLZRBEQQSSMJJBDJOTGTBXPGBKTLHQXJJJCTHXQDWJLWRFWQGWSHCKRYSWGFTGYGBXSDWDWRFHWYTJJXXXJYZYSLPYYYPAYXHYDQKXSHXYXGSKQHYWFDDDPPLCJLQQEEWXKSYYKDYPLTJTHKJLTCYYHHJTTPLTZZCDLTHQKZXQYSTEEYWYYZYXXYYSTTJKLLPZMCYHQGXYHSRMBXPLLNQYDQHXSXXWGDQBSHYLLPJJJTHYJKYPPTHYYKTYEZYENMDSHLCRPQFDGFXZPSFTLJXXJBSWYYSKSFLXLPPLBBBLBSFXFYZBSJSSYLPBBFFFFSSCJDSTZSXZRYYSYFFSYZYZBJTBCTSBSDHRTJJBYTCXYJEYLXCBNEBJDSYXYKGSJZBXBYTFZWGENYHHTHZHHXFWGCSTBGXKLSXYWMTMBYXJSTZSCDYQRCYTWXZFHMYMCXLZNSDJTTTXRYCFYJSBSDYERXJLJXBBDEYNJGHXGCKGSCYMBLXJMSZNSKGXFBNBPTHFJAAFXYXFPXMYPQDTZCXZZPXRSYWZDLYBBKTYQPQJPZYPZJZNJPZJLZZFYSBTTSLMPTZRTDXQSJEHBZYLZDHLJSQMLHTXTJECXSLZZSPKTLZKQQYFSYGYWPCPQFHQHYTQXZKRSGTTSQCZLPTXCDYYZXSQZSLXLZMYCPCQBZYXHBSXLZDLTCDXTYLZJYYZPZYZLTXJSJXHLPMYTXCQRBLZSSFJZZTNJYTXMYJHLHPPLCYXQJQQKZZSCPZKSWALQSBLCCZJSXGWWWYGYKTJBBZTDKHXHKGTGPBKQYSLPXPJCKBMLLXDZSTBKLGGQKQLSBKKTFXRMDKBFTPZFRTBBRFERQGXYJPZSSTLBZTPSZQZSJDHLJQLZBPMSMMSXLQQNHKNBLRDDNXXDHDDJCYYGYLXGZLXSYGMQQGKHBPMXYXLYTQWLWGCPBMQXCYZYDRJBHTDJYHQSHTMJSBYPLWHLZFFNYPMHXXHPLTBQPFBJWQDBYGPNZTPFZJGSDDTQSHZEAWZZYLLTYYBWJKXXGHLFKXDJTMSZSQYNZGGSWQSPHTLSSKMCLZXYSZQZXNCJDQGZDLFNYKLJCJLLZLMZZNHYDSSHTHZZLZZBBHQZWWYCRZHLYQQJBEYFXXXWHSRXWQHWPSLMSSKZTTYGYQQWRSLALHMJTQJSMXQBJJZJXZYZKXBYQXBJXSHZTSFJLXMXZXFGHKZSZGGYLCLSARJYHSLLLMZXELGLXYDJYTLFBHBPNLYZFBBHPTGJKWETZHKJJXZXXGLLJLSTGSHJJYQLQZFKCGNNDJSSZFDBCTWWSEQFHQJBSAQTGYPQLBXBMMYWXGSLZHGLZGQYFLZBYFZJFRYSFMBYZHQGFWZSYFYJJPHZBYYZFFWODGRLMFTWLBZGYCQXCDJYGZYYYYTYTYDWEGAZYHXJLZYYHLRMGRXXZCLHNELJJTJTPWJYBJJBXJJTJTEEKHWSLJPLPSFYZPQQBDLQJJTYYQLYZKDKSQJYYQZLDQTGJQYZJSUCMRYQTHTEJMFCTYHYPKMHYZWJDQFHYYXWSHCTXRLJHQXHCCYYYJLTKTTYTMXGTCJTZAYYOCZLYLBSZYWJYTSJYHBYSHFJLYGJXXTMZYYLTXXYPZLXYJZYZYYPNHMYMDYYLBLHLSYYQQLLNJJYMSOYQBZGDLYXYLCQYXTSZEGXHZGLHWBLJHEYXTWQMAKBPQCGYSHHEGQCMWYYWLJYJHYYZLLJJYLHZYHMGSLJLJXCJJYCLYCJPCPZJZJMMYLCQLNQLJQJSXYJMLSZLJQLYCMMHCFMMFPQQMFYLQMCFFQMMMMHMZNFHHJGTTHHKHSLNCHHYQDXTMMQDCYZYXYQMYQYLTDCYYYZAZZCYMZYDLZFFFMMYCQZWZZMABTBYZTDMNZZGGDFTYPCGQYTTSSFFWFDTZQSSYSTWXJHXYTSXXYLBYQHWWKXHZXWZNNZZJZJJQJCCCHYYXBZXZCYZTLLCQXYNJYCYYCYNZZQYYYEWYCZDCJYCCHYJLBTZYYCQWMPWPYMLGKDLDLGKQQBGYCHJXY"; - // 此处收录了375个多音字,数据来自于http://www.51windows.net/pages/pinyin.asp - var oMultiDiff = { - 19969: "DZ", - 19975: "WM", - 19988: "QJ", - 20048: "YL", - 20056: "SC", - 20060: "NM", - 20094: "QG", - 20127: "QJ", - 20167: "QC", - 20193: "YG", - 20250: "KH", - 20256: "ZC", - 20282: "SC", - 20285: "QJG", - 20291: "TD", - 20314: "YD", - 20315: "BF", - 20340: "NE", - 20375: "TD", - 20389: "YJ", - 20391: "CZ", - 20415: "PB", - 20446: "YS", - 20447: "SQ", - 20504: "TC", - 20608: "KG", - 20854: "QJ", - 20857: "ZC", - 20911: "PF", - 20985: "AW", - 21032: "PB", - 21048: "XQ", - 21049: "SC", - 21089: "YS", - 21119: "JC", - 21242: "SB", - 21273: "SC", - 21305: "YP", - 21306: "QO", - 21330: "ZC", - 21333: "SDC", - 21345: "QK", - 21378: "CA", - 21397: "SC", - 21414: "XS", - 21442: "SC", - 21477: "JG", - 21480: "TD", - 21484: "ZS", - 21494: "YX", - 21505: "YX", - 21512: "HG", - 21523: "XH", - 21537: "PB", - 21542: "PF", - 21549: "KH", - 21571: "E", - 21574: "DA", - 21588: "TD", - 21589: "O", - 21618: "ZC", - 21621: "KHA", - 21632: "ZJ", - 21654: "KG", - 21679: "LKG", - 21683: "KH", - 21710: "A", - 21719: "YH", - 21734: "WOE", - 21769: "A", - 21780: "WN", - 21804: "XH", - 21834: "A", - 21899: "ZD", - 21903: "RN", - 21908: "WO", - 21939: "ZC", - 21956: "SA", - 21964: "YA", - 21970: "TD", - 22003: "A", - 22031: "JG", - 22040: "XS", - 22060: "ZC", - 22066: "ZC", - 22079: "MH", - 22129: "XJ", - 22179: "XA", - 22237: "NJ", - 22244: "TD", - 22280: "JQ", - 22300: "YH", - 22313: "XW", - 22331: "YQ", - 22343: "YJ", - 22351: "PH", - 22395: "DC", - 22412: "TD", - 22484: "PB", - 22500: "PB", - 22534: "ZD", - 22549: "DH", - 22561: "PB", - 22612: "TD", - 22771: "KQ", - 22831: "HB", - 22841: "JG", - 22855: "QJ", - 22865: "XQ", - 23013: "ML", - 23081: "WM", - 23487: "SX", - 23558: "QJ", - 23561: "YW", - 23586: "YW", - 23614: "YW", - 23615: "SN", - 23631: "PB", - 23646: "ZS", - 23663: "ZT", - 23673: "YG", - 23762: "TD", - 23769: "ZS", - 23780: "QJ", - 23884: "QK", - 24055: "XH", - 24113: "DC", - 24162: "ZC", - 24191: "GA", - 24273: "QJ", - 24324: "NL", - 24377: "TD", - 24378: "QJ", - 24439: "PF", - 24554: "ZS", - 24683: "TD", - 24694: "WE", - 24733: "LK", - 24925: "TN", - 25094: "ZG", - 25100: "XQ", - 25103: "XH", - 25153: "PB", - 25170: "PB", - 25179: "KG", - 25203: "PB", - 25240: "ZS", - 25282: "FB", - 25303: "NA", - 25324: "KG", - 25341: "ZY", - 25373: "WZ", - 25375: "XJ", - 25384: "A", - 25457: "A", - 25528: "SD", - 25530: "SC", - 25552: "TD", - 25774: "ZC", - 25874: "ZC", - 26044: "YW", - 26080: "WM", - 26292: "PB", - 26333: "PB", - 26355: "ZY", - 26366: "CZ", - 26397: "ZC", - 26399: "QJ", - 26415: "ZS", - 26451: "SB", - 26526: "ZC", - 26552: "JG", - 26561: "TD", - 26588: "JG", - 26597: "CZ", - 26629: "ZS", - 26638: "YL", - 26646: "XQ", - 26653: "KG", - 26657: "XJ", - 26727: "HG", - 26894: "ZC", - 26937: "ZS", - 26946: "ZC", - 26999: "KJ", - 27099: "KJ", - 27449: "YQ", - 27481: "XS", - 27542: "ZS", - 27663: "ZS", - 27748: "TS", - 27784: "SC", - 27788: "ZD", - 27795: "TD", - 27812: "O", - 27850: "PB", - 27852: "MB", - 27895: "SL", - 27898: "PL", - 27973: "QJ", - 27981: "KH", - 27986: "HX", - 27994: "XJ", - 28044: "YC", - 28065: "WG", - 28177: "SM", - 28267: "QJ", - 28291: "KH", - 28337: "ZQ", - 28463: "TL", - 28548: "DC", - 28601: "TD", - 28689: "PB", - 28805: "JG", - 28820: "QG", - 28846: "PB", - 28952: "TD", - 28975: "ZC", - 29100: "A", - 29325: "QJ", - 29575: "SL", - 29602: "FB", - 30010: "TD", - 30044: "CX", - 30058: "PF", - 30091: "YSP", - 30111: "YN", - 30229: "XJ", - 30427: "SC", - 30465: "SX", - 30631: "YQ", - 30655: "QJ", - 30684: "QJG", - 30707: "SD", - 30729: "XH", - 30796: "LG", - 30917: "PB", - 31074: "NM", - 31085: "JZ", - 31109: "SC", - 31181: "ZC", - 31192: "MLB", - 31293: "JQ", - 31400: "YX", - 31584: "YJ", - 31896: "ZN", - 31909: "ZY", - 31995: "XJ", - 32321: "PF", - 32327: "ZY", - 32418: "HG", - 32420: "XQ", - 32421: "HG", - 32438: "LG", - 32473: "GJ", - 32488: "TD", - 32521: "QJ", - 32527: "PB", - 32562: "ZSQ", - 32564: "JZ", - 32735: "ZD", - 32793: "PB", - 33071: "PF", - 33098: "XL", - 33100: "YA", - 33152: "PB", - 33261: "CX", - 33324: "BP", - 33333: "TD", - 33406: "YA", - 33426: "WM", - 33432: "PB", - 33445: "JG", - 33486: "ZN", - 33493: "TS", - 33507: "QJ", - 33540: "QJ", - 33544: "ZC", - 33564: "XQ", - 33617: "YT", - 33632: "QJ", - 33636: "XH", - 33637: "YX", - 33694: "WG", - 33705: "PF", - 33728: "YW", - 33882: "SR", - 34067: "WM", - 34074: "YW", - 34121: "QJ", - 34255: "ZC", - 34259: "XL", - 34425: "JH", - 34430: "XH", - 34485: "KH", - 34503: "YS", - 34532: "HG", - 34552: "XS", - 34558: "YE", - 34593: "ZL", - 34660: "YQ", - 34892: "XH", - 34928: "SC", - 34999: "QJ", - 35048: "PB", - 35059: "SC", - 35098: "ZC", - 35203: "TQ", - 35265: "JX", - 35299: "JX", - 35782: "SZ", - 35828: "YS", - 35830: "E", - 35843: "TD", - 35895: "YG", - 35977: "MH", - 36158: "JG", - 36228: "QJ", - 36426: "XQ", - 36466: "DC", - 36710: "CJ", - 36711: "ZYG", - 36767: "PB", - 36866: "SK", - 36951: "YW", - 37034: "YX", - 37063: "XH", - 37218: "ZC", - 37325: "ZC", - 38063: "PB", - 38079: "TD", - 38085: "QY", - 38107: "DC", - 38116: "TD", - 38123: "YD", - 38224: "HG", - 38241: "XTC", - 38271: "ZC", - 38415: "YE", - 38426: "KH", - 38461: "YD", - 38463: "AE", - 38466: "PB", - 38477: "XJ", - 38518: "YT", - 38551: "WK", - 38585: "ZC", - 38704: "XS", - 38739: "LJ", - 38761: "GJ", - 38808: "SQ", - 39048: "JG", - 39049: "XJ", - 39052: "HG", - 39076: "CZ", - 39271: "XT", - 39534: "TD", - 39552: "TD", - 39584: "PB", - 39647: "SB", - 39730: "LG", - 39748: "TPB", - 40109: "ZQ", - 40479: "ND", - 40516: "HG", - 40536: "HG", - 40583: "QJ", - 40765: "YQ", - 40784: "QJ", - 40840: "YK", - 40863: "QJG" - }; +// 此处收录了375个多音字,数据来自于http://www.51windows.net/pages/pinyin.asp +const oMultiDiff = { + 19969: "DZ", + 19975: "WM", + 19988: "QJ", + 20048: "YL", + 20056: "SC", + 20060: "NM", + 20094: "QG", + 20127: "QJ", + 20167: "QC", + 20193: "YG", + 20250: "KH", + 20256: "ZC", + 20282: "SC", + 20285: "QJG", + 20291: "TD", + 20314: "YD", + 20315: "BF", + 20340: "NE", + 20375: "TD", + 20389: "YJ", + 20391: "CZ", + 20415: "PB", + 20446: "YS", + 20447: "SQ", + 20504: "TC", + 20608: "KG", + 20854: "QJ", + 20857: "ZC", + 20911: "PF", + 20985: "AW", + 21032: "PB", + 21048: "XQ", + 21049: "SC", + 21089: "YS", + 21119: "JC", + 21242: "SB", + 21273: "SC", + 21305: "YP", + 21306: "QO", + 21330: "ZC", + 21333: "SDC", + 21345: "QK", + 21378: "CA", + 21397: "SC", + 21414: "XS", + 21442: "SC", + 21477: "JG", + 21480: "TD", + 21484: "ZS", + 21494: "YX", + 21505: "YX", + 21512: "HG", + 21523: "XH", + 21537: "PB", + 21542: "PF", + 21549: "KH", + 21571: "E", + 21574: "DA", + 21588: "TD", + 21589: "O", + 21618: "ZC", + 21621: "KHA", + 21632: "ZJ", + 21654: "KG", + 21679: "LKG", + 21683: "KH", + 21710: "A", + 21719: "YH", + 21734: "WOE", + 21769: "A", + 21780: "WN", + 21804: "XH", + 21834: "A", + 21899: "ZD", + 21903: "RN", + 21908: "WO", + 21939: "ZC", + 21956: "SA", + 21964: "YA", + 21970: "TD", + 22003: "A", + 22031: "JG", + 22040: "XS", + 22060: "ZC", + 22066: "ZC", + 22079: "MH", + 22129: "XJ", + 22179: "XA", + 22237: "NJ", + 22244: "TD", + 22280: "JQ", + 22300: "YH", + 22313: "XW", + 22331: "YQ", + 22343: "YJ", + 22351: "PH", + 22395: "DC", + 22412: "TD", + 22484: "PB", + 22500: "PB", + 22534: "ZD", + 22549: "DH", + 22561: "PB", + 22612: "TD", + 22771: "KQ", + 22831: "HB", + 22841: "JG", + 22855: "QJ", + 22865: "XQ", + 23013: "ML", + 23081: "WM", + 23487: "SX", + 23558: "QJ", + 23561: "YW", + 23586: "YW", + 23614: "YW", + 23615: "SN", + 23631: "PB", + 23646: "ZS", + 23663: "ZT", + 23673: "YG", + 23762: "TD", + 23769: "ZS", + 23780: "QJ", + 23884: "QK", + 24055: "XH", + 24113: "DC", + 24162: "ZC", + 24191: "GA", + 24273: "QJ", + 24324: "NL", + 24377: "TD", + 24378: "QJ", + 24439: "PF", + 24554: "ZS", + 24683: "TD", + 24694: "WE", + 24733: "LK", + 24925: "TN", + 25094: "ZG", + 25100: "XQ", + 25103: "XH", + 25153: "PB", + 25170: "PB", + 25179: "KG", + 25203: "PB", + 25240: "ZS", + 25282: "FB", + 25303: "NA", + 25324: "KG", + 25341: "ZY", + 25373: "WZ", + 25375: "XJ", + 25384: "A", + 25457: "A", + 25528: "SD", + 25530: "SC", + 25552: "TD", + 25774: "ZC", + 25874: "ZC", + 26044: "YW", + 26080: "WM", + 26292: "PB", + 26333: "PB", + 26355: "ZY", + 26366: "CZ", + 26397: "ZC", + 26399: "QJ", + 26415: "ZS", + 26451: "SB", + 26526: "ZC", + 26552: "JG", + 26561: "TD", + 26588: "JG", + 26597: "CZ", + 26629: "ZS", + 26638: "YL", + 26646: "XQ", + 26653: "KG", + 26657: "XJ", + 26727: "HG", + 26894: "ZC", + 26937: "ZS", + 26946: "ZC", + 26999: "KJ", + 27099: "KJ", + 27449: "YQ", + 27481: "XS", + 27542: "ZS", + 27663: "ZS", + 27748: "TS", + 27784: "SC", + 27788: "ZD", + 27795: "TD", + 27812: "O", + 27850: "PB", + 27852: "MB", + 27895: "SL", + 27898: "PL", + 27973: "QJ", + 27981: "KH", + 27986: "HX", + 27994: "XJ", + 28044: "YC", + 28065: "WG", + 28177: "SM", + 28267: "QJ", + 28291: "KH", + 28337: "ZQ", + 28463: "TL", + 28548: "DC", + 28601: "TD", + 28689: "PB", + 28805: "JG", + 28820: "QG", + 28846: "PB", + 28952: "TD", + 28975: "ZC", + 29100: "A", + 29325: "QJ", + 29575: "SL", + 29602: "FB", + 30010: "TD", + 30044: "CX", + 30058: "PF", + 30091: "YSP", + 30111: "YN", + 30229: "XJ", + 30427: "SC", + 30465: "SX", + 30631: "YQ", + 30655: "QJ", + 30684: "QJG", + 30707: "SD", + 30729: "XH", + 30796: "LG", + 30917: "PB", + 31074: "NM", + 31085: "JZ", + 31109: "SC", + 31181: "ZC", + 31192: "MLB", + 31293: "JQ", + 31400: "YX", + 31584: "YJ", + 31896: "ZN", + 31909: "ZY", + 31995: "XJ", + 32321: "PF", + 32327: "ZY", + 32418: "HG", + 32420: "XQ", + 32421: "HG", + 32438: "LG", + 32473: "GJ", + 32488: "TD", + 32521: "QJ", + 32527: "PB", + 32562: "ZSQ", + 32564: "JZ", + 32735: "ZD", + 32793: "PB", + 33071: "PF", + 33098: "XL", + 33100: "YA", + 33152: "PB", + 33261: "CX", + 33324: "BP", + 33333: "TD", + 33406: "YA", + 33426: "WM", + 33432: "PB", + 33445: "JG", + 33486: "ZN", + 33493: "TS", + 33507: "QJ", + 33540: "QJ", + 33544: "ZC", + 33564: "XQ", + 33617: "YT", + 33632: "QJ", + 33636: "XH", + 33637: "YX", + 33694: "WG", + 33705: "PF", + 33728: "YW", + 33882: "SR", + 34067: "WM", + 34074: "YW", + 34121: "QJ", + 34255: "ZC", + 34259: "XL", + 34425: "JH", + 34430: "XH", + 34485: "KH", + 34503: "YS", + 34532: "HG", + 34552: "XS", + 34558: "YE", + 34593: "ZL", + 34660: "YQ", + 34892: "XH", + 34928: "SC", + 34999: "QJ", + 35048: "PB", + 35059: "SC", + 35098: "ZC", + 35203: "TQ", + 35265: "JX", + 35299: "JX", + 35782: "SZ", + 35828: "YS", + 35830: "E", + 35843: "TD", + 35895: "YG", + 35977: "MH", + 36158: "JG", + 36228: "QJ", + 36426: "XQ", + 36466: "DC", + 36710: "CJ", + 36711: "ZYG", + 36767: "PB", + 36866: "SK", + 36951: "YW", + 37034: "YX", + 37063: "XH", + 37218: "ZC", + 37325: "ZC", + 38063: "PB", + 38079: "TD", + 38085: "QY", + 38107: "DC", + 38116: "TD", + 38123: "YD", + 38224: "HG", + 38241: "XTC", + 38271: "ZC", + 38415: "YE", + 38426: "KH", + 38461: "YD", + 38463: "AE", + 38466: "PB", + 38477: "XJ", + 38518: "YT", + 38551: "WK", + 38585: "ZC", + 38704: "XS", + 38739: "LJ", + 38761: "GJ", + 38808: "SQ", + 39048: "JG", + 39049: "XJ", + 39052: "HG", + 39076: "CZ", + 39271: "XT", + 39534: "TD", + 39552: "TD", + 39584: "PB", + 39647: "SB", + 39730: "LG", + 39748: "TPB", + 40109: "ZQ", + 40479: "ND", + 40516: "HG", + 40536: "HG", + 40583: "QJ", + 40765: "YQ", + 40784: "QJ", + 40840: "YK", + 40863: "QJG" +}; - var _checkPYCh = function (ch) { - var uni = ch.charCodeAt(0); - // 如果不在汉字处理范围之内,返回原字符,也可以调用自己的处理函数 - if (uni > 40869 || uni < 19968) {return ch;} // dealWithOthers(ch); - return (oMultiDiff[uni] ? oMultiDiff[uni] : (_ChineseFirstPY.charAt(uni - 19968))); - }; +const _checkPYCh = function (ch) { + var uni = ch.charCodeAt(0); + // 如果不在汉字处理范围之内,返回原字符,也可以调用自己的处理函数 + if (uni > 40869 || uni < 19968) { + return ch; + } // dealWithOthers(ch); + return (oMultiDiff[uni] ? oMultiDiff[uni] : (_ChineseFirstPY.charAt(uni - 19968))); +}; - var _mkPYRslt = function (arr, options) { - var ignoreMulti = options.ignoreMulti; - var splitChar = options.splitChar; - var arrRslt = [""], k, multiLen = 0; - for (var i = 0, len = arr.length; i < len; i++) { - var str = arr[i]; - var strlen = str.length; - // 多音字过多的情况下,指数增长会造成浏览器卡死,超过20完全卡死,18勉强能用,考虑到不同性能最好是16或者14 - // 超过14个多音字之后,后面的都用第一个拼音 - if (strlen == 1 || multiLen > 14 || ignoreMulti) { - var tmpStr = str.substring(0, 1); - for (k = 0; k < arrRslt.length; k++) { - arrRslt[k] += tmpStr; - } - } else { - var tmpArr = arrRslt.slice(0); - arrRslt = []; - multiLen ++; - for (k = 0; k < strlen; k++) { - // 复制一个相同的arrRslt - var tmp = tmpArr.slice(0); - // 把当前字符str[k]添加到每个元素末尾 - for (var j = 0; j < tmp.length; j++) { - tmp[j] += str.charAt(k); - } - // 把复制并修改后的数组连接到arrRslt上 - arrRslt = arrRslt.concat(tmp); +const _mkPYRslt = function (arr, options) { + var ignoreMulti = options.ignoreMulti; + var splitChar = options.splitChar; + var arrRslt = [""], k, multiLen = 0; + for (var i = 0, len = arr.length; i < len; i++) { + var str = arr[i]; + var strlen = str.length; + // 多音字过多的情况下,指数增长会造成浏览器卡死,超过20完全卡死,18勉强能用,考虑到不同性能最好是16或者14 + // 超过14个多音字之后,后面的都用第一个拼音 + if (strlen == 1 || multiLen > 14 || ignoreMulti) { + var tmpStr = str.substring(0, 1); + for (k = 0; k < arrRslt.length; k++) { + arrRslt[k] += tmpStr; + } + } else { + var tmpArr = arrRslt.slice(0); + arrRslt = []; + multiLen++; + for (k = 0; k < strlen; k++) { + // 复制一个相同的arrRslt + var tmp = tmpArr.slice(0); + // 把当前字符str[k]添加到每个元素末尾 + for (var j = 0; j < tmp.length; j++) { + tmp[j] += str.charAt(k); } + // 把复制并修改后的数组连接到arrRslt上 + arrRslt = arrRslt.concat(tmp); } } - // BI-56386 这边直接将所有多音字组合拼接是有风险的,因为丢失了每一组的起始索引信息, 外部使用indexOf等方法会造成错位 - // 一旦错位就可能认为不符合条件, 但实际上还是有可能符合条件的,故此处以一个无法搜索的不可见字符作为连接 - return arrRslt.join(splitChar || "").toLowerCase(); - }; + } + // BI-56386 这边直接将所有多音字组合拼接是有风险的,因为丢失了每一组的起始索引信息, 外部使用indexOf等方法会造成错位 + // 一旦错位就可能认为不符合条件, 但实际上还是有可能符合条件的,故此处以一个无法搜索的不可见字符作为连接 + return arrRslt.join(splitChar || "").toLowerCase(); +}; - BI._.extend(BI, { - makeFirstPY: function (str, options) { - options = options || {}; - if (typeof (str) !== "string") {return "" + str;} - var arrResult = []; // 保存中间结果的数组 - for (var i = 0, len = str.length; i < len; i++) { - // 获得unicode码 - var ch = str.charAt(i); - // 检查该unicode码是否在处理范围之内,在则返回该码对映汉字的拼音首字母,不在则调用其它函数处理 - arrResult.push(_checkPYCh(ch)); - } - // 处理arrResult,返回所有可能的拼音首字母串数组 - return _mkPYRslt(arrResult, options); - } - }); -})(); \ No newline at end of file + +export function makeFirstPY(str, options) { + options = options || {}; + if (typeof (str) !== "string") { + return "" + str; + } + var arrResult = []; // 保存中间结果的数组 + for (var i = 0, len = str.length; i < len; i++) { + // 获得unicode码 + var ch = str.charAt(i); + // 检查该unicode码是否在处理范围之内,在则返回该码对映汉字的拼音首字母,不在则调用其它函数处理 + arrResult.push(_checkPYCh(ch)); + } + // 处理arrResult,返回所有可能的拼音首字母串数组 + return _mkPYRslt(arrResult, options); +} + +Object.assign(BI, { + makeFirstPY +}); From 8ed5aaf502855bc4566b382896b7379480bcc2e7 Mon Sep 17 00:00:00 2001 From: zsmj Date: Wed, 4 Jan 2023 10:53:19 +0800 Subject: [PATCH 027/300] =?UTF-8?q?KERNEL-13991=20feat:=20core/func?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=A4=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/func/alias.js | 171 +++++++++++++++++++------------------- src/core/func/date.js | 84 +++++++++---------- src/core/func/function.js | 36 ++++---- src/core/func/number.js | 34 ++++---- src/core/func/string.js | 14 ++-- 5 files changed, 171 insertions(+), 168 deletions(-) diff --git a/src/core/func/alias.js b/src/core/func/alias.js index f7ba2f324..7de1e9f60 100644 --- a/src/core/func/alias.js +++ b/src/core/func/alias.js @@ -2,7 +2,7 @@ import {each, isFunction, isNull, isObject, isPlainObject, keys, leftPad, parseD import {replaceAll} from "./string"; import {getFullDayName, getMonthName, getTimezone} from "./date"; -var _global; +let _global; if (typeof window !== "undefined") { _global = window; } else if (typeof global !== "undefined") { @@ -47,12 +47,12 @@ function _eFormat(text, fmt) { * @returns {*} */ function eFormat(num, format) { - var neg = num < 0 ? (num *= -1, "-") : "", + let neg = num < 0 ? (num *= -1, "-") : "", magnitudeNeg = ""; - var funcName = num > 0 && num < 1 ? "floor" : "ceil"; // -0.9999->-1 + const funcName = num > 0 && num < 1 ? "floor" : "ceil"; // -0.9999->-1 // 数量级 - var magnitude = Math[funcName](Math.log(num) / Math.log(10)); + let magnitude = Math[funcName](Math.log(num) / Math.log(10)); if (!isFinite(magnitude)) { return format.replace(/#/ig, "").replace(/\.e/ig, "E"); @@ -67,15 +67,15 @@ function _eFormat(text, fmt) { } // 计算出format中需要显示的整数部分的位数,然后更新这个数值,也更新数量级 - var integerLen = getInteger(magnitude, format); + const integerLen = getInteger(magnitude, format); integerLen > 1 && (magnitude -= integerLen - 1, num *= Math.pow(10, integerLen - 1)); magnitude < 0 && (magnitudeNeg = "-", magnitude *= -1); // 获取科学计数法精确到的位数 - var precision = getPrecision(format); + const precision = getPrecision(format); // 判断num经过四舍五入之后是否有进位 - var isValueCarry = isValueCarried(num); + const isValueCarry = isValueCarried(num); num *= Math.pow(10, precision); num = Math.round(num); @@ -104,8 +104,8 @@ function _eFormat(text, fmt) { } // 如果magnitudeNeg是一个"-",而且num正好全是0,那么就别显示负号了 - var isAllZero = true; - for (var i = 0, len = num.length; i < len; i++) { + let isAllZero = true; + for (let i = 0, len = num.length; i < len; i++) { if (!isAllZero) { continue; } @@ -121,7 +121,7 @@ function _eFormat(text, fmt) { if (!/e/ig.test(format)) { return 0; } - var arr = format.split(/e/ig)[0].split("."); + const arr = format.split(/e/ig)[0].split("."); return arr.length > 1 ? arr[1].length : 0; } @@ -134,8 +134,8 @@ function _eFormat(text, fmt) { } // return format.split(/e/ig)[0].split(".")[0].length; - var formatLeft = format.split(/e/ig)[0].split(".")[0], i, f, len = formatLeft.length; - var valueLeftLen = 0; + let formatLeft = format.split(/e/ig)[0].split(".")[0], i, f, len = formatLeft.length; + let valueLeftLen = 0; for (i = 0; i < len; i++) { f = formatLeft.charAt(i); @@ -150,7 +150,7 @@ function _eFormat(text, fmt) { // 判断num通过round函数之后是否有进位 function isValueCarried(num) { - var roundNum = Math.round(num); + let roundNum = Math.round(num); num = (num + "").split(".")[0]; roundNum = (roundNum + "").split(".")[0]; return num.length !== roundNum.length; @@ -160,13 +160,13 @@ function _eFormat(text, fmt) { //'#.##'之类的格式处理 1.324e-18 这种的科学数字 function _dealNumberPrecision(text, fright) { if (/[eE]/.test(text)) { - var precision = 0, i = 0, ch; + let precision = 0, i = 0, ch; if (/[%‰]$/.test(fright)) { precision = /[%]$/.test(fright) ? 2 : 3; } - for (var len = fright.length; i < len; i++) { + for (let len = fright.length; i < len; i++) { if ((ch = fright.charAt(i)) == "0" || ch == "#") { precision++; } @@ -181,7 +181,7 @@ function _dealNumberPrecision(text, fright) { * 数字格式 */ function _numberFormat(text, format) { - var text = text + ""; + text = text + ""; //在调用数字格式的时候如果text里没有任何数字则不处理 if (!(/[0-9]/.test(text)) || !format) { @@ -189,7 +189,7 @@ function _numberFormat(text, format) { } // 数字格式,区分正负数 - var numMod = format.indexOf(";"); + const numMod = format.indexOf(";"); if (numMod > -1) { if (text >= 0) { return _numberFormat(text + "", format.substring(0, numMod)); @@ -203,19 +203,19 @@ function _numberFormat(text, format) { } } - var fp = format.split("."), fleft = fp[0] || "", fright = fp[1] || ""; + const fp = format.split("."), fleft = fp[0] || "", fright = fp[1] || ""; text = _dealNumberPrecision(text, fright); - var tp = text.split("."), tleft = tp[0] || "", tright = tp[1] || ""; + let tp = text.split("."), tleft = tp[0] || "", tright = tp[1] || ""; // 百分比,千分比的小数点移位处理 if (/[%‰]$/.test(format)) { - var paddingZero = /[%]$/.test(format) ? "00" : "000"; + let paddingZero = /[%]$/.test(format) ? "00" : "000"; tright += paddingZero; tleft += tright.substring(0, paddingZero.length); tleft = tleft.replace(/^0+/gi, ""); tright = tright.substring(paddingZero.length).replace(/0+$/gi, ""); } - var right = _dealWithRight(tright, fright); + let right = _dealWithRight(tright, fright); if (right.leftPlus) { // 小数点后有进位 tleft = parseInt(tleft) + 1 + ""; @@ -223,7 +223,7 @@ function _numberFormat(text, format) { tleft = isNaN(tleft) ? "1" : tleft; } right = right.num; - var left = _dealWithLeft(tleft, fleft); + let left = _dealWithLeft(tleft, fleft); if (!(/[0-9]/.test(left))) { left = left + "0"; } @@ -242,10 +242,10 @@ function _numberFormat(text, format) { * @private */ function _dealWithRight(tright, fright) { - var right = "", j = 0, i = 0; - for (var len = fright.length; i < len; i++) { - var ch = fright.charAt(i); - var c = tright.charAt(j); + let right = "", j = 0, i = 0; + for (let len = fright.length; i < len; i++) { + const ch = fright.charAt(i); + let c = tright.charAt(j); switch (ch) { case "0": if (isEmpty(c)) { @@ -263,16 +263,16 @@ function _dealWithRight(tright, fright) { break; } } - var rll = tright.substring(j); - var result = {}; + const rll = tright.substring(j); + const result = {}; if (!isEmpty(rll) && rll.charAt(0) > 4) { // 有多余字符,需要四舍五入 result.leftPlus = true; - var numReg = right.match(/^[0-9]+/); + const numReg = right.match(/^[0-9]+/); if (numReg) { - var num = numReg[0]; - var orilen = num.length; - var newnum = parseInt(num) + 1 + ""; + const num = numReg[0]; + const orilen = num.length; + let newnum = parseInt(num) + 1 + ""; // 进位到整数部分 if (newnum.length > orilen) { newnum = newnum.substring(1); @@ -295,13 +295,14 @@ function _dealWithRight(tright, fright) { * @private */ function _dealWithLeft(tleft, fleft) { - var left = ""; - var j = tleft.length - 1; - var combo = -1, last = -1; - var i = fleft.length - 1; + let newstr; + let left = ""; + let j = tleft.length - 1; + let combo = -1, last = -1; + let i = fleft.length - 1; for (; i >= 0; i--) { - var ch = fleft.charAt(i); - var c = tleft.charAt(j); + const ch = fleft.charAt(i); + let c = tleft.charAt(j); switch (ch) { case "0": if (isEmpty(c)) { @@ -319,7 +320,7 @@ function _dealWithLeft(tleft, fleft) { case ",": if (!isEmpty(c)) { // 计算一个,分隔区间的长度 - var com = fleft.match(/,[#0]+/); + const com = fleft.match(/,[#0]+/); if (com) { combo = com[0].length - 1; } @@ -333,19 +334,20 @@ function _dealWithLeft(tleft, fleft) { } if (last > -1) { // 处理剩余字符 - var tll = tleft.substring(0, j + 1); + const tll = tleft.substring(0, j + 1); left = left.substring(0, last) + tll + left.substring(last); } if (combo > 0) { // 处理,分隔区间 - var res = left.match(/[0-9]+,/); + let res = left.match(/[0-9]+,/); if (res) { res = res[0]; - var newstr = "", n = res.length - 1 - combo; + newstr = ""; + let n = res.length - 1 - combo; for (; n >= 0; n = n - combo) { newstr = res.substring(n, combo) + "," + newstr; } - var lres = res.substring(0, n + combo); + const lres = res.substring(0, n + combo); if (!isEmpty(lres)) { newstr = lres + "," + newstr; } @@ -361,9 +363,9 @@ export const cjkEncode = function (text) { return text; } - var newText = ""; - for (var i = 0; i < text.length; i++) { - var code = text.charCodeAt(i); + let newText = ""; + 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) + "]"; } else { @@ -386,17 +388,17 @@ export const cjkDecode = function (text) { return ""; } // 查找没有 "[", 直接返回. kunsnat:数字的时候, 不支持indexOf方法, 也是直接返回. - if (!isNaN(text) || text.indexOf("[") == -1) { + if (!isNaN(text) || text.indexOf("[") === -1) { return text; } - var newText = ""; - for (var i = 0; i < text.length; i++) { - var ch = text.charAt(i); - if (ch == "[") { - var rightIdx = text.indexOf("]", i + 1); + let newText = ""; + for (let i = 0; i < text.length; i++) { + let ch = text.charAt(i); + if (ch === "[") { + const rightIdx = text.indexOf("]", i + 1); if (rightIdx > i + 1) { - var subText = text.substring(i + 1, rightIdx); + let subText = text.substring(i + 1, rightIdx); // james:主要是考虑[CDATA[]]这样的值的出现 if (subText.length > 0) { ch = String.fromCharCode(eval("0x" + subText)); @@ -419,7 +421,7 @@ const SPECIAL_TAGS = { "<": "<", ">": ">", "\x20": " ", - "\n": " " + "\n": " ", }; export const htmlEncode = function (text) { return isNull(text) ? "" : replaceAll(text + "", keys(SPECIAL_TAGS).join("|"), function (v) { @@ -450,7 +452,7 @@ export const htmlDecode = function (text) { export const cjkEncodeDO = function (o) { if (isPlainObject(o)) { - var result = {}; + let result = {}; each(o, function (v, k) { if (!(typeof v === "string")) { v = jsonEncode(v); @@ -466,25 +468,25 @@ export const cjkEncodeDO = function (o) { export const jsonEncode = function (o) { // james:这个Encode是抄的EXT的 - var useHasOwn = !!{}.hasOwnProperty; + let useHasOwn = !!{}.hasOwnProperty; // crashes Safari in some instances // var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/; - var m = { + let m = { "\b": "\\b", "\t": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", "\"": "\\\"", - "\\": "\\\\" + "\\": "\\\\", }; - var encodeString = function (s) { + let encodeString = function (s) { if (/["\\\x00-\x1f]/.test(s)) { return "\"" + s.replace(/([\x00-\x1f\\"])/g, function (a, b) { - var c = m[b]; + let c = m[b]; if (c) { return c; } @@ -497,8 +499,8 @@ export const jsonEncode = function (o) { return "\"" + s + "\""; }; - var encodeArray = function (o) { - var a = ["["], b, i, l = o.length, v; + let encodeArray = function (o) { + let a = ["["], b, i, l = o.length, v; for (i = 0; i < l; i += 1) { v = o[i]; switch (typeof v) { @@ -528,7 +530,7 @@ export const jsonEncode = function (o) { * 现在这么处理就可以decode了,但是JS.jsonDecode和Java.JSONObject也要跟着改一下 */ return jsonEncode({ - __time__: o.getTime() + __time__: o.getTime(), }); } else if (typeof o === "string") { return encodeString(o); @@ -539,7 +541,7 @@ export const jsonEncode = function (o) { } else if (isFunction(o)) { return String(o); } - var a = ["{"], b, i, v; + let a = ["{"], b, i, v; for (i in o) { if (!useHasOwn || o.hasOwnProperty(i)) { v = o[i]; @@ -564,8 +566,9 @@ export const jsonEncode = function (o) { export const jsonDecode = function (text) { + let jo; try { - var jo = JSON.parse(text); + jo = JSON.parse(text); if (jo == null) { jo = {}; } @@ -601,8 +604,8 @@ export const jsonDecode = function (text) { if (o && o.__time__ != null) { return new Date(o.__time__); } - for (var a in o) { - if (o[a] == o || typeof o[a] === "object" || isFunction(o[a])) { + for (const a in o) { + if (o[a] === o || typeof o[a] === "object" || isFunction(o[a])) { break; } o[a] = parse(o[a]); @@ -641,7 +644,7 @@ export const encodeURIComponent = function (url) { }; export const decodeURIComponent = function (url) { - var reserveSpecialCharsMap = {}; + const reserveSpecialCharsMap = {}; each(BI.specialCharsMap, function (initialChar, encodeChar) { reserveSpecialCharsMap[encodeChar] = initialChar === "\\\\" ? "\\" : initialChar; }); @@ -657,7 +660,7 @@ export const contentFormat = function (cv, fmt) { // 原值为空,返回空字符 return ""; } - var text = cv.toString(); + let text = cv.toString(); if (isEmpty(fmt)) { // 格式为空,返回原字符 return text; @@ -677,7 +680,7 @@ export const contentFormat = function (cv, fmt) { } } if (!isInvalidDate(cv) && !isNull(cv)) { - var needTrim = fmt.match(/^DT/); + const needTrim = fmt.match(/^DT/); text = date2Str(cv, fmt.substring(needTrim ? 2 : 1)); } } else if (fmt.match(/E/)) { @@ -749,7 +752,7 @@ export const str2Date = function (str, format) { if (typeof str != "string" || typeof format != "string") { return null; } - var fmt = parseFmt(format); + const fmt = parseFmt(format); return parseDateTime(str, fmt); }; @@ -767,16 +770,16 @@ export const date2Str = function (date, format) { return ""; } // O(len(format)) - var len = format.length, result = ""; + let len = format.length, result = ""; if (len > 0) { - var flagch = format.charAt(0), start = 0, str = flagch; - for (var i = 1; i < len; i++) { - var ch = format.charAt(i); + let flagch = format.charAt(0), start = 0, str = flagch; + for (let i = 1; i < len; i++) { + const ch = format.charAt(i); if (flagch !== ch) { result += compileJFmt({ char: flagch, str: str, - len: i - start + len: i - start, }, date); flagch = ch; start = i; @@ -788,13 +791,13 @@ export const date2Str = function (date, format) { result += compileJFmt({ char: flagch, str: str, - len: len - start + len: len - start, }, date); } return result; function compileJFmt(jfmt, date) { - var 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()); @@ -823,7 +826,7 @@ export const date2Str = function (date, format) { } break; case "h": // 时(12) - var hour = date.getHours() % 12; + let hour = date.getHours() % 12; if (hour === 0) { hour = 12; } @@ -875,7 +878,7 @@ export const object2Number = function (value) { if (typeof value === "number") { return value; } - var str = value + ""; + const str = value + ""; if (str.indexOf(".") === -1) { return parseInt(str); } @@ -891,9 +894,9 @@ export const object2Date = function (obj) { } else if (typeof obj === "number") { return new Date(obj); } - var str = obj + ""; + let str = obj + ""; str = str.replace(/-/g, "/"); - var dt = new Date(str); + const dt = new Date(str); if (!isInvalidDate(dt)) { return dt; } @@ -909,9 +912,9 @@ export const object2Time = function (obj) { if (obj instanceof Date) { return obj; } - var str = obj + ""; + let str = obj + ""; str = str.replace(/-/g, "/"); - var dt = new Date(str); + let dt = new Date(str); if (!isInvalidDate(dt)) { return dt; } diff --git a/src/core/func/date.js b/src/core/func/date.js index 0d6ea79d3..8ef71e9e7 100644 --- a/src/core/func/date.js +++ b/src/core/func/date.js @@ -48,7 +48,7 @@ export function getTimezone(date) { * Returns the number of days in the current month */ export function getMonthDays(date, month = date.getMonth()) { - var year = date.getFullYear(); + const year = date.getFullYear(); if (((0 === (year % 4)) && ((0 !== (year % 100)) || (0 === (year % 400)))) && month === 1) { return 29; } @@ -77,9 +77,9 @@ export function getLastDateOfMonth(date) { * @returns {number} */ export function getDayOfYear(date) { - var now = getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); - var then = getDate(date.getFullYear(), 0, 0, 0, 0, 0); - var time = now - then; + const now = getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); + const then = getDate(date.getFullYear(), 0, 0, 0, 0, 0); + const time = now - then; return Math.floor(time / DAY); } @@ -90,16 +90,16 @@ export function getDayOfYear(date) { * @returns {number} */ export function getWeekNumber(date) { - var d = getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); - var week = d.getDay(); - var startOfWeek = BI.StartOfWeek % 7; - var middleDay = (startOfWeek + 3) % 7; + const d = getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); + const week = d.getDay(); + const startOfWeek = BI.StartOfWeek % 7; + let middleDay = (startOfWeek + 3) % 7; middleDay = middleDay || 7; // 偏移到周周首之前需要多少天 - var offsetWeekStartCount = week < startOfWeek ? (7 + week - startOfWeek) : (week - startOfWeek); - var offsetWeekMiddleCount = middleDay < startOfWeek ? (7 + middleDay - startOfWeek) : (middleDay - startOfWeek); + const offsetWeekStartCount = week < startOfWeek ? (7 + week - startOfWeek) : (week - startOfWeek); + const offsetWeekMiddleCount = middleDay < startOfWeek ? (7 + middleDay - startOfWeek) : (middleDay - startOfWeek); d.setDate(d.getDate() - offsetWeekStartCount + offsetWeekMiddleCount); - var ms = d.valueOf(); + const ms = d.valueOf(); d.setMonth(0); d.setDate(1); return Math.floor((ms - d.valueOf()) / (7 * 864e5)) + 1; @@ -120,9 +120,9 @@ export function getOffsetDate(date, offset) { } export function getOffsetQuarter(date, n) { - var dt = getDate(getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds())); - var day = dt.getDate(); - var monthDay = BI.getMonthDays(getDate(dt.getFullYear(), dt.getMonth() + parseInt(n, 10) * 3, 1)); + const dt = getDate(getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds())); + let day = dt.getDate(); + const monthDay = BI.getMonthDays(getDate(dt.getFullYear(), dt.getMonth() + parseInt(n, 10) * 3, 1)); if (day > monthDay) { day = monthDay; } @@ -137,8 +137,8 @@ export function getOffsetQuarter(date, n) { * @returns {number} */ export function getQuarterStartMonth(date) { - var quarterStartMonth = 0; - var nowMonth = date.getMonth(); + let quarterStartMonth = 0; + const nowMonth = date.getMonth(); if (nowMonth < 3) { quarterStartMonth = 0; } @@ -169,7 +169,7 @@ export function getQuarterStartDate(date) { * @returns {Date} */ export function getQuarterEndDate(date) { - var quarterEndMonth = getQuarterStartMonth(date) + 2; + const quarterEndMonth = getQuarterStartMonth(date) + 2; return getDate(date.getFullYear(), quarterEndMonth, getMonthDays(date)); } @@ -180,9 +180,9 @@ export function getQuarterEndDate(date) { * @returns {Date} */ export function getOffsetMonth(date, n) { - var dt = getDate(getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds())); - var day = dt.getDate(); - var monthDay = getMonthDays(getDate(dt.getFullYear(), dt.getMonth() + parseInt(n, 10), 1)); + const dt = getDate(getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds())); + let day = dt.getDate(); + const monthDay = getMonthDays(getDate(dt.getFullYear(), dt.getMonth() + parseInt(n, 10), 1)); if (day > monthDay) { day = monthDay; } @@ -197,8 +197,8 @@ export function getOffsetMonth(date, n) { * @returns {Date} */ export function getWeekStartDate(date) { - var w = date.getDay(); - var startOfWeek = BI.StartOfWeek % 7; + const w = date.getDay(); + const startOfWeek = BI.StartOfWeek % 7; return getOffsetDate(date, _OFFSET[w < startOfWeek ? (7 + w - startOfWeek) : (w - startOfWeek)]); } @@ -208,8 +208,8 @@ export function getWeekStartDate(date) { * @returns {Date} */ export function getWeekEndDate(date) { - var w = date.getDay(); - var startOfWeek = BI.StartOfWeek % 7; + const w = date.getDay(); + const startOfWeek = BI.StartOfWeek % 7; return getOffsetDate(date, _OFFSET[w < startOfWeek ? (7 + w - startOfWeek) : (w - startOfWeek)] + 6); } @@ -273,26 +273,26 @@ export function getQuarterName(index) { * @returns {*} */ export function print(date, str) { - var m = date.getMonth(); - var d = date.getDate(); - var y = date.getFullYear(); - var yWith4number = y + ""; + const m = date.getMonth(); + const d = date.getDate(); + const y = date.getFullYear(); + let yWith4number = y + ""; while (yWith4number.length < 4) { yWith4number = "0" + yWith4number; } - var wn = getWeekNumber(date); - var qr = getQuarter(date); - var w = date.getDay(); - var s = {}; - var hr = date.getHours(); - var pm = (hr >= 12); - var ir = (pm) ? (hr - 12) : hr; - var dy = getDayOfYear(date); + const wn = getWeekNumber(date); + const qr = getQuarter(date); + const w = date.getDay(); + const s = {}; + const hr = date.getHours(); + const pm = (hr >= 12); + let ir = (pm) ? (hr - 12) : hr; + const dy = getDayOfYear(date); if (ir === 0) { ir = 12; } - var min = date.getMinutes(); - var sec = date.getSeconds(); + const min = date.getMinutes(); + const sec = date.getSeconds(); s["%a"] = getShortDayName(w); // abbreviated weekday name [FIXME: I18N] s["%A"] = getFullDayName(w); // full weekday name s["%b"] = _SMN[m]; // abbreviated month name [FIXME: I18N] @@ -331,7 +331,7 @@ export function print(date, str) { s["%q"] = "0" + qr; s["%Q"] = qr; - var re = /%./g; + let re = /%./g; BI.isKhtml = BI.isKhtml || function () { if (!_global.navigator) { return false; @@ -366,9 +366,9 @@ export function print(date, str) { return s[par] || par; }); } - var a = str.match(re); - for (var i = 0; i < a.length; i++) { - var tmp = s[a[i]]; + const a = str.match(re); + for (let i = 0; i < a.length; i++) { + const tmp = s[a[i]]; if (tmp) { re = new RegExp(a[i], "g"); str = str.replace(re, tmp); diff --git a/src/core/func/function.js b/src/core/func/function.js index e66b54453..f8fc3cdca 100644 --- a/src/core/func/function.js +++ b/src/core/func/function.js @@ -12,7 +12,7 @@ import {makeFirstPY} from "../utils/chinesePY"; * @returns {*} */ export function createDistinctName(array, name) { - var src = name, idx = 1; + let src = name, idx = 1; name = name || ""; while (true) { if (every(array, function (i, item) { @@ -43,18 +43,18 @@ export function getGBWidth(str) { * @param param 搜索哪个属性 */ export function getSearchResult(items, keyword, param) { - var array = isArray(items); + let array = isArray(items); items = array ? BI.flatten(items) : items; param || (param = "text"); if (!isKey(keyword)) { return { find: items, - match: array ? [] : {} + match: array ? [] : {}, }; } - var t, text, py; + let t, text, py; keyword = toUpperCase(keyword); - var matched = array ? [] : {}, find = array ? [] : {}; + let matched = array ? [] : {}, find = array ? [] : {}; each(items, function (i, item) { // 兼容item为null的处理 if (isNull(item)) { @@ -66,11 +66,11 @@ export function getSearchResult(items, keyword, param) { if (isNull(text) || isObject(text)) return; py = makeFirstPY(text, { - splitChar: "\u200b" + splitChar: "\u200b", }); text = toUpperCase(text); py = toUpperCase(py); - var pidx; + let pidx; if (text.indexOf(keyword) > -1) { if (text === keyword) { array ? matched.push(item) : (matched[i] = item); @@ -90,7 +90,7 @@ export function getSearchResult(items, keyword, param) { }); return { match: matched, - find: find + find: find, }; } @@ -101,7 +101,7 @@ export function getSearchResult(items, keyword, param) { * @return {any[]} */ export function getSortedResult(items, key) { - var getTextOfItem = BI.isFunction(key) ? key : + let getTextOfItem = BI.isFunction(key) ? key : function (item, key) { if (BI.isNotNull(key)) { return item[key]; @@ -116,8 +116,8 @@ export function getSortedResult(items, key) { }; return items.sort(function (item1, item2) { - var str1 = getTextOfItem(item1, key); - var str2 = getTextOfItem(item2, key); + let str1 = getTextOfItem(item1, key); + let str2 = getTextOfItem(item2, key); if (BI.isNull(str1) && BI.isNull(str2)) { return 0; } @@ -130,10 +130,10 @@ export function getSortedResult(items, key) { if (str1 === str2) { return 0; } - var len1 = str1.length, len2 = str2.length; - for (var i = 0; i < len1 && i < len2; i++) { - var char1 = str1[i]; - var char2 = str2[i]; + let len1 = str1.length, len2 = str2.length; + for (let i = 0; i < len1 && i < len2; i++) { + let char1 = str1[i]; + let char2 = str2[i]; if (char1 !== char2) { // 找不到的字符都往后面放 return (BI.isNull(BI.CODE_INDEX[char1]) ? BI.MAX : BI.CODE_INDEX[char1]) - (BI.isNull(BI.CODE_INDEX[char2]) ? BI.MAX : BI.CODE_INDEX[char2]); @@ -144,7 +144,7 @@ export function getSortedResult(items, key) { } export function beforeFunc(sFunc, func) { - var __self = sFunc; + let __self = sFunc; return function () { if (func.apply(sFunc, arguments) === false) { return false; @@ -154,9 +154,9 @@ export function beforeFunc(sFunc, func) { } export function afterFunc(sFunc, func) { - var __self = sFunc; + let __self = sFunc; return function () { - var ret = __self.apply(sFunc, arguments); + let ret = __self.apply(sFunc, arguments); if (ret === false) { return false; } diff --git a/src/core/func/number.js b/src/core/func/number.js index 73f9dbec6..9f9640f66 100644 --- a/src/core/func/number.js +++ b/src/core/func/number.js @@ -9,7 +9,7 @@ export function add(num, arg) { ** 返回值:arg1加上arg2的精确结果 **/ function accAdd(arg1, arg2) { - var r1, r2, m, c; + let r1, r2, m, c; try { r1 = arg1.toString().split(".")[1].length; } catch (e) { @@ -23,7 +23,7 @@ export function add(num, arg) { c = Math.abs(r1 - r2); m = Math.pow(10, Math.max(r1, r2)); if (c > 0) { - var cm = Math.pow(10, c); + let cm = Math.pow(10, c); if (r1 > r2) { arg1 = Number(arg1.toString().replace(".", "")); arg2 = Number(arg2.toString().replace(".", "")) * cm; @@ -50,7 +50,7 @@ export function sub(num, arg) { ** 返回值:arg1加上arg2的精确结果 **/ function accSub(arg1, arg2) { - var r1, r2, m, n; + let r1, r2, m, n; try { r1 = arg1.toString().split(".")[1].length; } catch (e) { @@ -78,7 +78,7 @@ export function mul(num, arg) { ** 返回值:arg1乘以 arg2的精确结果 **/ function accMul(arg1, arg2) { - var m = 0, s1 = arg1.toString(), s2 = arg2.toString(); + let m = 0, s1 = arg1.toString(), s2 = arg2.toString(); try { m += s1.split(".")[1].length; } catch (e) { @@ -101,8 +101,8 @@ export function div(num, arg) { */ function digitLength(num) { // Get digit length of e - var eSplit = num.toString().split(/[eE]/); - var len = (eSplit[0].split(".")[1] || "").length - (+(eSplit[1] || 0)); + let eSplit = num.toString().split(/[eE]/); + let len = (eSplit[0].split(".")[1] || "").length - (+(eSplit[1] || 0)); return len > 0 ? len : 0; } @@ -114,7 +114,7 @@ export function div(num, arg) { if (num.toString().indexOf("e") === -1) { return Number(num.toString().replace(".", "")); } - var dLen = digitLength(num); + let dLen = digitLength(num); return dLen > 0 ? num * Math.pow(10, dLen) : num; } @@ -122,17 +122,17 @@ export function div(num, arg) { * 精确乘法 */ function times(num1, num2) { - var others = []; - for (var _i = 2; _i < arguments.length; _i++) { + let others = []; + for (let _i = 2; _i < arguments.length; _i++) { others[_i - 2] = arguments[_i]; } if (others.length > 0) { return times.apply(void 0, [times(num1, num2), others[0]].concat(others.slice(1))); } - var num1Changed = float2Fixed(num1); - var num2Changed = float2Fixed(num2); - var baseNum = digitLength(num1) + digitLength(num2); - var leftValue = num1Changed * num2Changed; + let num1Changed = float2Fixed(num1); + let num2Changed = float2Fixed(num2); + let baseNum = digitLength(num1) + digitLength(num2); + let leftValue = num1Changed * num2Changed; return leftValue / Math.pow(10, baseNum); } @@ -140,15 +140,15 @@ export function div(num, arg) { * 精确除法 */ function accDivide(num1, num2) { - var others = []; - for (var _i = 2; _i < arguments.length; _i++) { + let others = []; + for (let _i = 2; _i < arguments.length; _i++) { others[_i - 2] = arguments[_i]; } if (others.length > 0) { return accDivide.apply(void 0, [accDivide(num1, num2), others[0]].concat(others.slice(1))); } - var num1Changed = float2Fixed(num1); - var num2Changed = float2Fixed(num2); + let num1Changed = float2Fixed(num1); + let num2Changed = float2Fixed(num2); return times((num1Changed / num2Changed), Math.pow(10, digitLength(num2) - digitLength(num1))); } } diff --git a/src/core/func/string.js b/src/core/func/string.js index de5b29628..8b5d5ceba 100644 --- a/src/core/func/string.js +++ b/src/core/func/string.js @@ -11,7 +11,7 @@ export function startWith(str, startTag) { if (startTag == null || startTag == "" || str.length === 0 || startTag.length > str.length) { return false; } - return str.substr(0, startTag.length) == startTag; + return str.substring(0, startTag.length) == startTag; } /** @@ -34,8 +34,8 @@ export function endWith(str, endTag) { * @return {String} 参数的值 */ export function getQuery(str, name) { - var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); - var r = str.substr(str.indexOf("?") + 1).match(reg); + let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); + let r = str.substr(str.indexOf("?") + 1).match(reg); if (r) { return unescape(r[2]); } @@ -52,7 +52,7 @@ export function appendQuery(str, paras) { if (!paras) { return str; } - var src = str; + let src = str; // 没有问号说明还没有参数 if (src.indexOf("?") === -1) { src += "?"; @@ -106,10 +106,10 @@ export function allIndexOf(str, sub) { if (typeof sub !== "string") { return []; } - var location = []; - var offset = 0; + let location = []; + let offset = 0; while (str.length > 0) { - var loc = str.indexOf(sub); + let loc = str.indexOf(sub); if (loc === -1) { break; } From df41ae3b784e874d30427f262365059fb8967581 Mon Sep 17 00:00:00 2001 From: zsmj Date: Wed, 4 Jan 2023 11:21:06 +0800 Subject: [PATCH 028/300] =?UTF-8?q?KERNEL-13991=20feat:=20core/func?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=A4=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/func/__test__/function.test.js | 6 +++--- src/core/func/alias.js | 14 +++++++------- src/core/func/function.js | 22 +++++++++++----------- src/core/func/index.js | 2 +- src/core/func/number.js | 24 ++++++++++++------------ src/core/func/string.js | 8 ++++---- 6 files changed, 38 insertions(+), 38 deletions(-) diff --git a/src/core/func/__test__/function.test.js b/src/core/func/__test__/function.test.js index 388af5fe6..db6901582 100644 --- a/src/core/func/__test__/function.test.js +++ b/src/core/func/__test__/function.test.js @@ -8,7 +8,7 @@ describe("core-function-test", function () { * test_author_lei.wang */ it("createDistinctName-支持字符串数组", function () { - var names = ["name", "name1"]; + const names = ["name", "name1"]; expect(BI.Func.createDistinctName(names, "name")).to.equal("name2"); expect(BI.Func.createDistinctName(names, "name2")).to.equal("name2"); }); @@ -17,8 +17,8 @@ describe("core-function-test", function () { * test_author_lei.wang */ it("createDistinctName-支持对象数组数组", function () { - var names = [{ name: "name" }, { name: "name1" }]; + const names = [{ name: "name" }, { name: "name1" }]; expect(BI.Func.createDistinctName(names, "name")).to.equal("name2"); expect(BI.Func.createDistinctName(names, "name2")).to.equal("name2"); }); -}); \ No newline at end of file +}); diff --git a/src/core/func/alias.js b/src/core/func/alias.js index 7de1e9f60..b8596e7cf 100644 --- a/src/core/func/alias.js +++ b/src/core/func/alias.js @@ -209,7 +209,7 @@ function _numberFormat(text, format) { // 百分比,千分比的小数点移位处理 if (/[%‰]$/.test(format)) { - let paddingZero = /[%]$/.test(format) ? "00" : "000"; + const paddingZero = /[%]$/.test(format) ? "00" : "000"; tright += paddingZero; tleft += tright.substring(0, paddingZero.length); tleft = tleft.replace(/^0+/gi, ""); @@ -398,7 +398,7 @@ export const cjkDecode = function (text) { if (ch === "[") { const rightIdx = text.indexOf("]", i + 1); if (rightIdx > i + 1) { - let subText = text.substring(i + 1, rightIdx); + const subText = text.substring(i + 1, rightIdx); // james:主要是考虑[CDATA[]]这样的值的出现 if (subText.length > 0) { ch = String.fromCharCode(eval("0x" + subText)); @@ -452,7 +452,7 @@ export const htmlDecode = function (text) { export const cjkEncodeDO = function (o) { if (isPlainObject(o)) { - let result = {}; + const result = {}; each(o, function (v, k) { if (!(typeof v === "string")) { v = jsonEncode(v); @@ -468,12 +468,12 @@ export const cjkEncodeDO = function (o) { export const jsonEncode = function (o) { // james:这个Encode是抄的EXT的 - let useHasOwn = !!{}.hasOwnProperty; + const useHasOwn = !!{}.hasOwnProperty; // crashes Safari in some instances // var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/; - let m = { + const m = { "\b": "\\b", "\t": "\\t", "\n": "\\n", @@ -483,7 +483,7 @@ export const jsonEncode = function (o) { "\\": "\\\\", }; - let encodeString = function (s) { + const encodeString = function (s) { if (/["\\\x00-\x1f]/.test(s)) { return "\"" + s.replace(/([\x00-\x1f\\"])/g, function (a, b) { let c = m[b]; @@ -499,7 +499,7 @@ export const jsonEncode = function (o) { return "\"" + s + "\""; }; - let encodeArray = function (o) { + const encodeArray = function (o) { let a = ["["], b, i, l = o.length, v; for (i = 0; i < l; i += 1) { v = o[i]; diff --git a/src/core/func/function.js b/src/core/func/function.js index f8fc3cdca..ecbd78f2d 100644 --- a/src/core/func/function.js +++ b/src/core/func/function.js @@ -43,7 +43,7 @@ export function getGBWidth(str) { * @param param 搜索哪个属性 */ export function getSearchResult(items, keyword, param) { - let array = isArray(items); + const array = isArray(items); items = array ? BI.flatten(items) : items; param || (param = "text"); if (!isKey(keyword)) { @@ -54,7 +54,7 @@ export function getSearchResult(items, keyword, param) { } let t, text, py; keyword = toUpperCase(keyword); - let matched = array ? [] : {}, find = array ? [] : {}; + const matched = array ? [] : {}, find = array ? [] : {}; each(items, function (i, item) { // 兼容item为null的处理 if (isNull(item)) { @@ -101,7 +101,7 @@ export function getSearchResult(items, keyword, param) { * @return {any[]} */ export function getSortedResult(items, key) { - let getTextOfItem = BI.isFunction(key) ? key : + const getTextOfItem = BI.isFunction(key) ? key : function (item, key) { if (BI.isNotNull(key)) { return item[key]; @@ -116,8 +116,8 @@ export function getSortedResult(items, key) { }; return items.sort(function (item1, item2) { - let str1 = getTextOfItem(item1, key); - let str2 = getTextOfItem(item2, key); + const str1 = getTextOfItem(item1, key); + const str2 = getTextOfItem(item2, key); if (BI.isNull(str1) && BI.isNull(str2)) { return 0; } @@ -130,10 +130,10 @@ export function getSortedResult(items, key) { if (str1 === str2) { return 0; } - let len1 = str1.length, len2 = str2.length; + const len1 = str1.length, len2 = str2.length; for (let i = 0; i < len1 && i < len2; i++) { - let char1 = str1[i]; - let char2 = str2[i]; + const char1 = str1[i]; + const char2 = str2[i]; if (char1 !== char2) { // 找不到的字符都往后面放 return (BI.isNull(BI.CODE_INDEX[char1]) ? BI.MAX : BI.CODE_INDEX[char1]) - (BI.isNull(BI.CODE_INDEX[char2]) ? BI.MAX : BI.CODE_INDEX[char2]); @@ -144,7 +144,7 @@ export function getSortedResult(items, key) { } export function beforeFunc(sFunc, func) { - let __self = sFunc; + const __self = sFunc; return function () { if (func.apply(sFunc, arguments) === false) { return false; @@ -154,9 +154,9 @@ export function beforeFunc(sFunc, func) { } export function afterFunc(sFunc, func) { - let __self = sFunc; + const __self = sFunc; return function () { - let ret = __self.apply(sFunc, arguments); + const ret = __self.apply(sFunc, arguments); if (ret === false) { return false; } diff --git a/src/core/func/index.js b/src/core/func/index.js index 3475bf8d6..9b24275bf 100644 --- a/src/core/func/index.js +++ b/src/core/func/index.js @@ -19,5 +19,5 @@ Object.assign(BI, { ..._date, ..._function, ..._number, - ..._string + ..._string, }); diff --git a/src/core/func/number.js b/src/core/func/number.js index 9f9640f66..d7a4f31f5 100644 --- a/src/core/func/number.js +++ b/src/core/func/number.js @@ -23,7 +23,7 @@ export function add(num, arg) { c = Math.abs(r1 - r2); m = Math.pow(10, Math.max(r1, r2)); if (c > 0) { - let cm = Math.pow(10, c); + const cm = Math.pow(10, c); if (r1 > r2) { arg1 = Number(arg1.toString().replace(".", "")); arg2 = Number(arg2.toString().replace(".", "")) * cm; @@ -101,8 +101,8 @@ export function div(num, arg) { */ function digitLength(num) { // Get digit length of e - let eSplit = num.toString().split(/[eE]/); - let len = (eSplit[0].split(".")[1] || "").length - (+(eSplit[1] || 0)); + const eSplit = num.toString().split(/[eE]/); + const len = (eSplit[0].split(".")[1] || "").length - (+(eSplit[1] || 0)); return len > 0 ? len : 0; } @@ -114,7 +114,7 @@ export function div(num, arg) { if (num.toString().indexOf("e") === -1) { return Number(num.toString().replace(".", "")); } - let dLen = digitLength(num); + const dLen = digitLength(num); return dLen > 0 ? num * Math.pow(10, dLen) : num; } @@ -122,17 +122,17 @@ export function div(num, arg) { * 精确乘法 */ function times(num1, num2) { - let others = []; + const others = []; for (let _i = 2; _i < arguments.length; _i++) { others[_i - 2] = arguments[_i]; } if (others.length > 0) { return times.apply(void 0, [times(num1, num2), others[0]].concat(others.slice(1))); } - let num1Changed = float2Fixed(num1); - let num2Changed = float2Fixed(num2); - let baseNum = digitLength(num1) + digitLength(num2); - let leftValue = num1Changed * num2Changed; + const num1Changed = float2Fixed(num1); + const num2Changed = float2Fixed(num2); + const baseNum = digitLength(num1) + digitLength(num2); + const leftValue = num1Changed * num2Changed; return leftValue / Math.pow(10, baseNum); } @@ -140,15 +140,15 @@ export function div(num, arg) { * 精确除法 */ function accDivide(num1, num2) { - let others = []; + const others = []; for (let _i = 2; _i < arguments.length; _i++) { others[_i - 2] = arguments[_i]; } if (others.length > 0) { return accDivide.apply(void 0, [accDivide(num1, num2), others[0]].concat(others.slice(1))); } - let num1Changed = float2Fixed(num1); - let num2Changed = float2Fixed(num2); + const num1Changed = float2Fixed(num1); + const num2Changed = float2Fixed(num2); return times((num1Changed / num2Changed), Math.pow(10, digitLength(num2) - digitLength(num1))); } } diff --git a/src/core/func/string.js b/src/core/func/string.js index 8b5d5ceba..d273db525 100644 --- a/src/core/func/string.js +++ b/src/core/func/string.js @@ -34,8 +34,8 @@ export function endWith(str, endTag) { * @return {String} 参数的值 */ export function getQuery(str, name) { - let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); - let r = str.substr(str.indexOf("?") + 1).match(reg); + const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); + const r = str.substr(str.indexOf("?") + 1).match(reg); if (r) { return unescape(r[2]); } @@ -106,10 +106,10 @@ export function allIndexOf(str, sub) { if (typeof sub !== "string") { return []; } - let location = []; + const location = []; let offset = 0; while (str.length > 0) { - let loc = str.indexOf(sub); + const loc = str.indexOf(sub); if (loc === -1) { break; } From c645f52ac8e54668cb6a5d1c074d2f128275fbc4 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Wed, 4 Jan 2023 14:02:18 +0800 Subject: [PATCH 029/300] =?UTF-8?q?=E6=97=A0JIRA=E4=BB=BB=E5=8A=A1=20chore?= =?UTF-8?q?:=20=E9=87=8D=E6=96=B0=E6=95=B4=E7=90=86=E4=B8=80=E4=B8=8Bimpor?= =?UTF-8?q?t=E5=92=8Cexport=E5=92=8C=E6=8C=82=E8=BD=BD=E5=88=B0BI=E7=9A=84?= =?UTF-8?q?=E8=A7=84=E8=8C=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/0.base.js | 13 --- src/base/1.pane.js | 2 +- src/base/combination/bubble.js | 2 +- src/base/combination/combo.js | 4 +- src/base/combination/expander.js | 2 +- src/base/combination/group.button.js | 2 +- src/base/combination/group.combo.js | 2 +- src/base/combination/group.virtual.js | 2 +- src/base/combination/index.js | 12 ++ src/base/combination/loader.js | 2 +- src/base/combination/navigation.js | 2 +- src/base/combination/searcher.js | 4 +- src/base/combination/switcher.js | 2 +- src/base/combination/tab.js | 2 +- src/base/combination/tree.button.js | 4 +- src/base/foundation/message.js | 54 ++++----- src/base/index.js | 98 +++------------- src/base/layer/index.js | 4 + src/base/layer/layer.drawer.js | 2 +- src/base/layer/layer.popup.js | 2 +- src/base/layer/layer.searcher.js | 4 +- src/base/list/index.js | 3 + src/base/list/listview.js | 2 +- src/base/list/virtualgrouplist.js | 2 +- src/base/list/virtuallist.js | 2 +- src/base/single/0.single.js | 2 +- src/base/single/1.text.js | 6 +- src/base/single/a/a.js | 4 +- src/base/single/index.js | 4 + src/base/single/tip/0.tip.js | 4 +- src/base/single/tip/index.js | 3 + src/base/single/tip/tip.toast.js | 4 +- src/base/single/tip/tip.tooltip.js | 4 +- src/core/2.base.js | 121 -------------------- src/core/3.ob.js | 6 +- src/core/4.widget.js | 16 +-- src/core/5.inject.js | 26 +---- src/core/action/action.js | 4 +- src/core/action/action.show.js | 4 +- src/core/action/index.js | 2 + src/core/behavior/0.behavior.js | 4 +- src/core/behavior/behavior.highlight.js | 4 +- src/core/behavior/behavior.redmark.js | 4 +- src/core/behavior/index.js | 3 + src/core/controller/0.controller.js | 4 +- src/core/controller/controller.broadcast.js | 4 +- src/core/controller/controller.bubbles.js | 4 +- src/core/controller/controller.drawer.js | 4 +- src/core/controller/controller.layer.js | 4 +- src/core/controller/controller.masker.js | 4 +- src/core/controller/controller.popover.js | 4 +- src/core/controller/controller.resizer.js | 4 +- src/core/controller/controller.tooltips.js | 4 +- src/core/controller/index.js | 9 ++ src/core/index.js | 89 +++++--------- src/core/listener/listener.show.js | 6 +- src/core/loader/loader.style.js | 4 +- 57 files changed, 190 insertions(+), 409 deletions(-) create mode 100644 src/base/combination/index.js create mode 100644 src/base/layer/index.js create mode 100644 src/base/list/index.js create mode 100644 src/base/single/index.js create mode 100644 src/base/single/tip/index.js create mode 100644 src/core/action/index.js create mode 100644 src/core/behavior/index.js create mode 100644 src/core/controller/index.js diff --git a/src/base/0.base.js b/src/base/0.base.js index 2b4960808..e4daef1cf 100644 --- a/src/base/0.base.js +++ b/src/base/0.base.js @@ -8,7 +8,6 @@ import { ResizeController, TooltipsController, StyleLoaderManager, - extend } from "../core"; const Resizers = new ResizeController(); @@ -21,18 +20,6 @@ const Drawers = new DrawerController(); const Broadcasts = new BroadcastController(); const StyleLoaders = new StyleLoaderManager(); -extend(BI, { - Resizers, - Layers, - Maskers, - Bubbles, - Tooltips, - Popovers, - Drawers, - Broadcasts, - StyleLoaders -}); - export { Resizers, Layers, diff --git a/src/base/1.pane.js b/src/base/1.pane.js index 51ceecfce..ebbaac636 100644 --- a/src/base/1.pane.js +++ b/src/base/1.pane.js @@ -10,7 +10,7 @@ import { Widget, shortcut, isNotEmptyString, extend, isNull, isEmpty, createWidg import { Layers } from "./0.base"; @shortcut() -export default class Pane extends Widget { +export class Pane extends Widget { static xtype = "bi.pane"; static EVENT_LOADED = "EVENT_LOADED"; static EVENT_LOADING = "EVENT_LOADING"; diff --git a/src/base/combination/bubble.js b/src/base/combination/bubble.js index 5d9e9e86a..49bc6d176 100644 --- a/src/base/combination/bubble.js +++ b/src/base/combination/bubble.js @@ -5,7 +5,7 @@ import { shortcut, Widget, Controller, extend, nextTick, createWidget, each, defer, debounce, delay, isNull, isFunction, contains, bind } from "../../core"; @shortcut() -export default class Bubble extends Widget { +export class Bubble extends Widget { static xtype = "bi.bubble"; static EVENT_TRIGGER_CHANGE = "EVENT_TRIGGER_CHANGE"; diff --git a/src/base/combination/combo.js b/src/base/combination/combo.js index 277e9e224..6f16862e2 100644 --- a/src/base/combination/combo.js +++ b/src/base/combination/combo.js @@ -4,14 +4,14 @@ */ import { shortcut, Widget, Controller, extend, createWidget, nextTick, bind, isNotNull, isNull, isFunction, each } from "../../core"; -import Bubble from "./bubble"; +import { Bubble } from "./bubble"; import { Resizers } from "../0.base"; let needHideWhenAnotherComboOpen = {}; let currentOpenedCombos = {}; @shortcut() -export default class Combo extends Bubble { +export class Combo extends Bubble { static xtype = "bi.combo"; static EVENT_TRIGGER_CHANGE = "EVENT_TRIGGER_CHANGE"; diff --git a/src/base/combination/expander.js b/src/base/combination/expander.js index 3c7e9f8cb..fe04aec7a 100644 --- a/src/base/combination/expander.js +++ b/src/base/combination/expander.js @@ -9,7 +9,7 @@ import { shortcut, Widget, Controller, extend, nextTick, each, debounce, isNull, createWidget } from "../../core"; @shortcut() -export default class Expander extends Widget { +export class Expander extends Widget { static xtype = "bi.expander"; static EVENT_EXPAND = "EVENT_EXPAND"; diff --git a/src/base/combination/group.button.js b/src/base/combination/group.button.js index 22c110720..57c2e47e2 100644 --- a/src/base/combination/group.button.js +++ b/src/base/combination/group.button.js @@ -6,7 +6,7 @@ import { shortcut, Widget, Controller, extend, createWidget, createWidgets, each, isFunction, isKey, isNotEmptyArray, createItems, isArray, remove, map, stripEL, makeArrayByArray, clone, deepClone, formatEL, isEmpty, concat, removeAt, deepContains, has, any } from "../../core"; @shortcut() -export default class ButtonGroup extends Widget { +export class ButtonGroup extends Widget { static xtype = "bi.button_group"; static EVENT_CHANGE = "EVENT_CHANGE"; diff --git a/src/base/combination/group.combo.js b/src/base/combination/group.combo.js index 97882f40f..e2c0d1f6f 100644 --- a/src/base/combination/group.combo.js +++ b/src/base/combination/group.combo.js @@ -5,7 +5,7 @@ import { shortcut, Widget, Controller, extend, isEmpty, each, formatEL, clone, createWidget } from "../../core"; @shortcut() -export default class ComboGroup extends Widget { +export class ComboGroup extends Widget { static xtype = "bi.combo_group"; static EVENT_CHANGE = "EVENT_CHANGE"; diff --git a/src/base/combination/group.virtual.js b/src/base/combination/group.virtual.js index f757c4b4e..a9f069ea7 100644 --- a/src/base/combination/group.virtual.js +++ b/src/base/combination/group.virtual.js @@ -1,7 +1,7 @@ import { shortcut, Widget, Controller, extend, isFunction, isKey, isArray, map, stripEL, deepClone, formatEL, isEmpty, each, createWidget } from "../../core"; @shortcut() -export default class VirtualGroup extends Widget { +export class VirtualGroup extends Widget { static xtype = "bi.virtual_group"; static EVENT_CHANGE = "EVENT_CHANGE"; diff --git a/src/base/combination/index.js b/src/base/combination/index.js new file mode 100644 index 000000000..0a3b52bd1 --- /dev/null +++ b/src/base/combination/index.js @@ -0,0 +1,12 @@ +export { Bubble } from "./bubble"; +export { Combo } from "./combo"; +export { Expander } from "./expander"; +export { ButtonGroup } from "./group.button"; +export { ComboGroup } from "./group.combo"; +export { VirtualGroup } from "./group.virtual"; +export { Loader } from "./loader"; +export { Navigation } from "./navigation"; +export { Searcher } from "./searcher"; +export { Switcher } from "./switcher"; +export { Tab } from "./tab"; +export { ButtonTree } from "./tree.button"; \ No newline at end of file diff --git a/src/base/combination/loader.js b/src/base/combination/loader.js index 0ebf26770..744f2bb12 100644 --- a/src/base/combination/loader.js +++ b/src/base/combination/loader.js @@ -8,7 +8,7 @@ import { shortcut, Widget, Controller, extend, createWidget, isEmpty, nextTick, bind, isFunction, isNotEmptyArray, isNumber, isObject, each } from "../../core"; @shortcut() -export default class Loader extends Widget { +export class Loader extends Widget { static xtype = "bi.loader"; static EVENT_CHANGE = "EVENT_CHANGE"; diff --git a/src/base/combination/navigation.js b/src/base/combination/navigation.js index febb44958..671459d5c 100644 --- a/src/base/combination/navigation.js +++ b/src/base/combination/navigation.js @@ -4,7 +4,7 @@ import { shortcut, Widget, Controller, extend, createWidget, bind, ShowListener, isFunction, each, nextTick, isKey, values } from "../../core"; @shortcut() -export default class Navigation extends Widget { +export class Navigation extends Widget { static xtype = "bi.navigation"; static EVENT_CHANGE = "EVENT_CHANGE"; diff --git a/src/base/combination/searcher.js b/src/base/combination/searcher.js index 56b03f720..acf316e76 100644 --- a/src/base/combination/searcher.js +++ b/src/base/combination/searcher.js @@ -6,11 +6,11 @@ * @extends BI.Widget */ import { shortcut, Widget, Controller, extend, createWidget, debounce, bind, endWith, deepWithout, nextTick, isEmptyString, isNull } from "../../core"; -import ButtonGroup from "./group.button"; +import { ButtonGroup } from "./group.button"; import { Maskers } from "../0.base"; @shortcut() -export default class Searcher extends Widget { +export class Searcher extends Widget { static xtype = "bi.searcher"; static EVENT_CHANGE = "EVENT_CHANGE"; diff --git a/src/base/combination/switcher.js b/src/base/combination/switcher.js index e89b31314..b19f75404 100644 --- a/src/base/combination/switcher.js +++ b/src/base/combination/switcher.js @@ -10,7 +10,7 @@ import { shortcut, Widget, Controller, extend, nextTick, createWidget, each, deb import { Maskers } from "../0.base"; @shortcut() -export default class Switcher extends Widget { +export class Switcher extends Widget { static xtype = "bi.switcher"; static EVENT_EXPAND = "EVENT_EXPAND"; diff --git a/src/base/combination/tab.js b/src/base/combination/tab.js index 7fcce06c4..f7a7e2038 100644 --- a/src/base/combination/tab.js +++ b/src/base/combination/tab.js @@ -4,7 +4,7 @@ import { shortcut, Widget, Controller, ShowListener, extend, createWidget, isObject, each, isFunction, contains, any, isEqual } from "../../core"; @shortcut() -export default class Tab extends Widget { +export class Tab extends Widget { static xtype = "bi.tab"; static EVENT_CHANGE = "EVENT_CHANGE"; diff --git a/src/base/combination/tree.button.js b/src/base/combination/tree.button.js index 6ed1a1b3f..be25898f9 100644 --- a/src/base/combination/tree.button.js +++ b/src/base/combination/tree.button.js @@ -4,10 +4,10 @@ * @extends BI.ButtonGroup */ import { shortcut, Widget, extend, isArray, each, isFunction, deepContains, concat, any, contains } from "../../core"; -import ButtonGroup from "./group.button"; +import { ButtonGroup } from "./group.button"; @shortcut() -export default class ButtonTree extends ButtonGroup { +export class ButtonTree extends ButtonGroup { static xtype = "bi.button_tree"; static EVENT_CHANGE = "EVENT_CHANGE"; diff --git a/src/base/foundation/message.js b/src/base/foundation/message.js index 380e12039..add1060ba 100644 --- a/src/base/foundation/message.js +++ b/src/base/foundation/message.js @@ -3,12 +3,14 @@ * 弹出提示消息框,用于模拟阻塞操作(通过回调函数实现) * @class BI.Msg */ -BI.Msg = ((function () { - var $mask, $pop; +import { Widget, isString, isNull, isFunction, createWidget, remove, each } from "../../core" - var messageShows = []; +export const Msg = ((() => { + let $mask, $pop; - var toastStack = []; + let messageShows = []; + + let toastStack = []; return { alert: function (title, message, callback) { @@ -21,13 +23,13 @@ BI.Msg = ((function () { // BI.Msg.prompt(title, message, value, callback, min_width); }, toast: function (message, options, context) { - BI.isString(options) && (options = { level: options }); + isString(options) && (options = { level: options }); options = options || {}; - context = context || BI.Widget._renderEngine.createElement("body"); - var level = options.level || "common"; - var autoClose = BI.isNull(options.autoClose) ? true : options.autoClose; - var callback = BI.isFunction(options.callback) ? options.callback : BI.emptyFn; - var toast = BI.createWidget({ + context = context || Widget._renderEngine.createElement("body"); + const level = options.level || "common"; + const autoClose = isNull(options.autoClose) ? true : options.autoClose; + const callback = isFunction(options.callback) ? options.callback : BI.emptyFn; + const toast = createWidget({ type: "bi.toast", cls: "bi-message-animate bi-message-leave", level: level, @@ -37,9 +39,9 @@ BI.Msg = ((function () { listeners: [{ eventName: BI.Toast.EVENT_DESTORY, action: function () { - BI.remove(toastStack, toast.element); - var _height = BI.SIZE_CONSANTS.TOAST_TOP; - BI.each(toastStack, function (i, element) { + remove(toastStack, toast.element); + let _height = BI.SIZE_CONSANTS.TOAST_TOP; + each(toastStack, function (i, element) { element.css({ "top": _height }); _height += element.outerHeight() + 10; }); @@ -47,11 +49,11 @@ BI.Msg = ((function () { }, }], }); - var height = BI.SIZE_CONSANTS.TOAST_TOP; - BI.each(toastStack, function (i, element) { + const height = BI.SIZE_CONSANTS.TOAST_TOP; + each(toastStack, function (i, element) { height += element.outerHeight() + 10; }); - BI.createWidget({ + createWidget({ type: "bi.absolute", element: context, items: [{ @@ -75,7 +77,7 @@ BI.Msg = ((function () { }; }, _show: function (hasCancel, title, message, callback) { - BI.isNull($mask) && ($mask = BI.Widget._renderEngine.createElement("
").css({ + isNull($mask) && ($mask = Widget._renderEngine.createElement("
").css({ position: "absolute", zIndex: BI.zIndex_tip - 2, top: 0, @@ -84,7 +86,7 @@ BI.Msg = ((function () { bottom: 0, opacity: 0.5, }).appendTo("body")); - $pop = BI.Widget._renderEngine.createElement("
").css({ + $pop = Widget._renderEngine.createElement("
").css({ position: "absolute", zIndex: BI.zIndex_tip - 1, top: 0, @@ -100,7 +102,7 @@ BI.Msg = ((function () { $mask = null; } } - var controlItems = []; + let controlItems = []; if (hasCancel === true) { controlItems.push({ el: { @@ -109,7 +111,7 @@ BI.Msg = ((function () { level: "ignore", handler: function () { close(); - if (BI.isFunction(callback)) { + if (isFunction(callback)) { callback.apply(null, [false]); } }, @@ -122,13 +124,13 @@ BI.Msg = ((function () { text: BI.i18nText("BI-Basic_OK"), handler: function () { close(); - if (BI.isFunction(callback)) { + if (isFunction(callback)) { callback.apply(null, [true]); } }, }, }); - var conf = { + const conf = { element: $pop, type: "bi.center_adapt", items: [ @@ -141,13 +143,13 @@ BI.Msg = ((function () { this.element.keyup(function (e) { if (e.keyCode === BI.KeyCode.ENTER) { close(); - if (BI.isFunction(callback)) { + if (isFunction(callback)) { callback.apply(null, [true]); } } else if (e.keyCode === BI.KeyCode.ESCAPE) { close(); if (hasCancel === true) { - if (BI.isFunction(callback)) { + if (isFunction(callback)) { callback.apply(null, [false]); } } @@ -183,7 +185,7 @@ BI.Msg = ((function () { // height: 50, handler: function () { close(); - if (BI.isFunction(callback)) { + if (isFunction(callback)) { callback.apply(null, [false]); } }, @@ -228,7 +230,7 @@ BI.Msg = ((function () { ], }; - messageShows[messageShows.length] = BI.createWidget(conf); + messageShows[messageShows.length] = createWidget(conf); }, }; })()); diff --git a/src/base/index.js b/src/base/index.js index 723070d48..2c1dc228c 100644 --- a/src/base/index.js +++ b/src/base/index.js @@ -1,93 +1,31 @@ -import { extend } from "../core"; -import Pane from "./1.pane"; -import Single from "./single/0.single"; -import Text from "./single/1.text"; -import A from "./single/a/a"; -import Tip from "./single/tip/0.tip"; -import Toast from "./single/tip/tip.toast"; -import Tooltip from "./single/tip/tip.tooltip"; -import Drawer from "./layer/layer.drawer"; -import { Popover, BarPopover } from "./layer/layer.popover"; -import PopupView from "./layer/layer.popup"; -import SearcherView from "./layer/layer.searcher"; -import ListView from "./list/listview"; -import VirtualGroupList from "./list/virtualgrouplist"; -import VirtualList from "./list/virtuallist"; +import { Pane } from "./1.pane"; +import * as single from "./single"; +import * as layer from "./layer"; +import * as list from "./list"; import GridView from "./grid/grid"; import Pager from "./pager/pager"; -import Bubble from "./combination/bubble"; -import Combo from "./combination/combo"; -import Expander from "./combination/expander"; -import ButtonGroup from "./combination/group.button"; -import ComboGroup from "./combination/group.combo"; -import VirtualGroup from "./combination/group.virtual"; -import Loader from "./combination/loader"; -import Navigation from "./combination/navigation"; -import Searcher from "./combination/searcher"; -import Switcher from "./combination/switcher"; -import Tab from "./combination/tab"; -import ButtonTree from "./combination/tree.button"; +import * as combination from "./combination"; +import { Msg } from "./foundation/message"; -extend(BI, { +Object.assign(BI, { Pane, - Single, - Text, - A, - Tip, - Toast, - Tooltip, - Drawer, - Popover, - BarPopover, - PopupView, - SearcherView, - ListView, - VirtualGroupList, - VirtualList, + ...layer, + ...list, + ...single, GridView, Pager, - Bubble, - Combo, - Expander, - ButtonGroup, - ComboGroup, - VirtualGroup, - Loader, - Navigation, - Searcher, - Switcher, - Tab, - ButtonTree, + ...combination, + Msg, }); +export * from "./0.base"; +export * from "./combination"; +export * from "./layer"; +export * from "./list"; +export * from "./single"; export { Pane, - Single, - Text, - A, - Tip, - Toast, - Tooltip, - Drawer, - Popover, - BarPopover, - PopupView, - SearcherView, - ListView, - VirtualGroupList, - VirtualList, GridView, Pager, - Bubble, - Combo, - Expander, - ButtonGroup, - ComboGroup, - VirtualGroup, - Loader, - Navigation, - Searcher, - Switcher, - Tab, - ButtonTree, + Msg, } \ No newline at end of file diff --git a/src/base/layer/index.js b/src/base/layer/index.js new file mode 100644 index 000000000..8f04625d9 --- /dev/null +++ b/src/base/layer/index.js @@ -0,0 +1,4 @@ +export { Drawer } from "./layer.drawer"; +export { Popover, BarPopover } from "./layer.popover"; +export { PopupView } from "./layer.popup"; +export { SearcherView } from "./layer.searcher"; \ No newline at end of file diff --git a/src/base/layer/layer.drawer.js b/src/base/layer/layer.drawer.js index 890981d0e..75ef6b04b 100644 --- a/src/base/layer/layer.drawer.js +++ b/src/base/layer/layer.drawer.js @@ -6,7 +6,7 @@ import { Widget, shortcut } from "../../core"; @shortcut() -export default class Drawer extends Widget { +export class Drawer extends Widget { SIZE = { SMALL: "small", NORMAL: "normal", diff --git a/src/base/layer/layer.popup.js b/src/base/layer/layer.popup.js index ea4a35196..fd79d015f 100644 --- a/src/base/layer/layer.popup.js +++ b/src/base/layer/layer.popup.js @@ -6,7 +6,7 @@ import { Widget, shortcut } from "../../core"; @shortcut() -export default class PopupView extends Widget { +export class PopupView extends Widget { _const = { TRIANGLE_LENGTH: 12, } diff --git a/src/base/layer/layer.searcher.js b/src/base/layer/layer.searcher.js index f76aa7a17..9d4cfbb0e 100644 --- a/src/base/layer/layer.searcher.js +++ b/src/base/layer/layer.searcher.js @@ -7,10 +7,10 @@ */ import { shortcut } from "../../core"; -import Pane from "../1.pane"; +import { Pane } from "../1.pane"; @shortcut() -export default class SearcherView extends Pane { +export class SearcherView extends Pane { static xtype = "bi.searcher_view"; static EVENT_CHANGE = "EVENT_CHANGE"; diff --git a/src/base/list/index.js b/src/base/list/index.js new file mode 100644 index 000000000..0a1c500cd --- /dev/null +++ b/src/base/list/index.js @@ -0,0 +1,3 @@ +export { ListView } from "./listview"; +export { VirtualGroupList } from "./virtualgrouplist"; +export { VirtualList } from "./virtuallist"; \ No newline at end of file diff --git a/src/base/list/listview.js b/src/base/list/listview.js index 3ec9dc162..ce2870e75 100644 --- a/src/base/list/listview.js +++ b/src/base/list/listview.js @@ -7,7 +7,7 @@ */ import { Widget, shortcut } from "../../core"; @shortcut() -export default class ListView extends Widget { +export class ListView extends Widget { props() { return { baseCls: "bi-list-view", diff --git a/src/base/list/virtualgrouplist.js b/src/base/list/virtualgrouplist.js index be9845cc1..d89cb32a0 100644 --- a/src/base/list/virtualgrouplist.js +++ b/src/base/list/virtualgrouplist.js @@ -8,7 +8,7 @@ import { Widget, shortcut } from "../../core"; @shortcut() -export default class VirtualGroupList extends Widget { +export class VirtualGroupList extends Widget { props() { return { baseCls: "bi-virtual-group-list", diff --git a/src/base/list/virtuallist.js b/src/base/list/virtuallist.js index ed788acdd..d2ce62311 100644 --- a/src/base/list/virtuallist.js +++ b/src/base/list/virtuallist.js @@ -8,7 +8,7 @@ import { Widget, shortcut } from "../../core"; @shortcut() -export default class VirtualList extends Widget { +export class VirtualList extends Widget { props() { return { baseCls: "bi-virtual-list", diff --git a/src/base/single/0.single.js b/src/base/single/0.single.js index 845e8c33d..cd6ec00b0 100644 --- a/src/base/single/0.single.js +++ b/src/base/single/0.single.js @@ -14,7 +14,7 @@ import { Widget, shortcut } from "../../core"; import { Tooltips } from "../0.base"; @shortcut() -export default class Single extends Widget { +export class Single extends Widget { static xtype = "bi.single"; _defaultConfig() { diff --git a/src/base/single/1.text.js b/src/base/single/1.text.js index 33001a7bd..294a2aaec 100644 --- a/src/base/single/1.text.js +++ b/src/base/single/1.text.js @@ -3,11 +3,11 @@ * @class BI.Text * @extends BI.Single */ -import { shortcut } from "../../core/decorator"; -import { Single } from "../index"; +import { shortcut } from "../../core"; +import { Single } from "./0.single"; @shortcut() -export default class Text extends Single { +export class Text extends Single { static xtype = "bi.text"; props = { diff --git a/src/base/single/a/a.js b/src/base/single/a/a.js index 7acf03231..c52006dd3 100644 --- a/src/base/single/a/a.js +++ b/src/base/single/a/a.js @@ -7,9 +7,9 @@ * @abstract */ import { shortcut } from "../../../core"; -import Text from "../1.text"; +import { Text } from "../1.text"; @shortcut() -export default class A extends Text { +export class A extends Text { static xtype = "bi.a"; _defaultConfig() { diff --git a/src/base/single/index.js b/src/base/single/index.js new file mode 100644 index 000000000..748788816 --- /dev/null +++ b/src/base/single/index.js @@ -0,0 +1,4 @@ +export { Single } from "./0.single"; +export { Text } from "./1.text"; +export { A } from "./a/a"; +export * from "./tip"; \ No newline at end of file diff --git a/src/base/single/tip/0.tip.js b/src/base/single/tip/0.tip.js index d9ac9fee7..a4b93f4e5 100644 --- a/src/base/single/tip/0.tip.js +++ b/src/base/single/tip/0.tip.js @@ -7,8 +7,8 @@ * @abstract */ -import Single from "../0.single"; -export default class Tip extends Single { +import { Single } from "../0.single"; +export class Tip extends Single { _defaultConfig() { const conf = super._defaultConfig(arguments); return BI.extend(conf, { diff --git a/src/base/single/tip/index.js b/src/base/single/tip/index.js new file mode 100644 index 000000000..509c6be4c --- /dev/null +++ b/src/base/single/tip/index.js @@ -0,0 +1,3 @@ +export { Tip } from "./0.tip"; +export { Toast } from "./tip.toast"; +export { Tooltip } from "./tip.tooltip"; \ No newline at end of file diff --git a/src/base/single/tip/tip.toast.js b/src/base/single/tip/tip.toast.js index e93b3627a..2dce887e5 100644 --- a/src/base/single/tip/tip.toast.js +++ b/src/base/single/tip/tip.toast.js @@ -7,9 +7,9 @@ */ import { shortcut } from "../../../core"; -import Tip from "./0.tip"; +import { Tip } from "./0.tip"; @shortcut() -export default class Toast extends Tip { +export class Toast extends Tip { _const= { closableMinWidth: 146, minWidth: 100, diff --git a/src/base/single/tip/tip.tooltip.js b/src/base/single/tip/tip.tooltip.js index d50a52c19..d101bcab8 100644 --- a/src/base/single/tip/tip.tooltip.js +++ b/src/base/single/tip/tip.tooltip.js @@ -7,9 +7,9 @@ */ import { shortcut } from "../../../core"; -import Tip from "./0.tip"; +import { Tip } from "./0.tip"; @shortcut() -export default class Tooltip extends Tip { +export class Tooltip extends Tip { _const = { hgap: 8, vgap: 4, diff --git a/src/core/2.base.js b/src/core/2.base.js index a4e8df688..01814415b 100644 --- a/src/core/2.base.js +++ b/src/core/2.base.js @@ -139,20 +139,6 @@ export function trans2Element(widgets) { return map(widgets, (i, wi) => wi.element); } -// Utility -BI._.extend(BI, { - assert, - warn, - UUID, - isWidget, - createWidgets, - createItems, - packageItems, - formatEL, - stripEL, - trans2Element, -}); - // 集合相关方法 BI._.each(["where", "findWhere", "invoke", "pluck", "shuffle", "sample", "toArray", "size"], function (name) { BI[name] = _apply(name); @@ -384,27 +370,6 @@ export function int2Abc(num) { return str; } -BI._.extend(BI, { - count, - inverse, - firstKey, - lastKey, - firstObject, - lastObject, - concat, - backEach, - backAny, - backEvery, - backFindKey, - backFind, - remove, - removeAt, - string2Array, - array2String, - abc2Int, - int2Abc, -}); - // 数组相关的方法 BI._.each([ "first", "initial", "last", "rest", "compact", "flatten", "without", "union", "intersection", @@ -493,13 +458,6 @@ export function uniq(array, isSorted, iteratee, context) { return uniq.call(BI._, array, isSorted, iteratee, context); } -BI._.extend(BI, { - makeArray, - makeObject, - makeArrayByArray, - uniq, -}); - // 对象相关方法 BI._.each([ "keys", "allKeys", "values", "pairs", "invert", "create", "functions", "extend", "extendOwn", @@ -652,24 +610,6 @@ export function isPromise(obj) { return !!obj && (isObject(obj) || isFunction(obj)) && isFunction(obj.then); } -BI._.extend(BI, { - inherit, - init, - has, - freeze, - isKey, - isCapitalEqual, - isWidthOrHeight, - isNotNull, - isNull, - isEmptyArray, - isNotEmptyArray, - isEmptyObject, - isNotEmptyObject, - isWindow, - isPromise, -}); - export const deepClone = BI._.cloneDeep; export const deepExtend = BI._.deepExtend; @@ -781,20 +721,6 @@ export function deepDiff(object, other) { return result; } -// deep方法 -BI._.extend(BI, { - deepClone: BI._.cloneDeep, - deepExtend: BI._.merge, - isDeepMatch, - contains, - deepContains, - deepIndexOf, - deepRemove, - deepWithout, - deepUnique, - deepDiff, -}); - // 通用方法 BI._.each(["uniqueId", "result", "chain", "iteratee", "unescape", "before", "after", "chunk"], function (name) { BI[name] = function () { @@ -893,8 +819,6 @@ export const nextTick = (function () { }; })(); -BI._.extend(BI, { nextTick }); - // 数字相关方法 BI._.each(["random"], function (name) { BI[name] = _apply(name); @@ -985,22 +909,6 @@ export function average(array, iteratee, context) { return sumResult / array.length; } -BI._.extend(BI, { - parseInt, - parseSafeInt, - parseFloat, - isNaturalNumber, - isPositiveInteger, - isNegativeInteger, - isInteger, - isNumeric, - isFloat, - isOdd, - isEven, - sum, - average, -}); - export function trim() { return BI._.trim.apply(BI._, arguments); } @@ -1126,25 +1034,6 @@ export function format(format) { return format.replace(/\{(\d+)\}/g, (m, i) => args[i]); } -// 字符串相关方法 -BI._.extend(BI, { - trim, - toUpperCase, - toLowerCase, - isEndWithBlank, - isLiteral, - stripQuotes, - camelize, - hyphenate, - isNotEmptyString, - isEmptyString, - encrypt, - decrypt, - escape, - leftPad, - format, -}); - /** * 是否是闰年 * @param year @@ -1454,15 +1343,5 @@ export function getTime() { return dt.getTime() - BI.timeZone - new Date().getTimezoneOffset() * 60000; } return dt.getTime(); - } -// 日期相关方法 -BI._.extend(BI, { - isLeapYear, - checkDateVoid, - checkDateLegal, - parseDateTime, - getDate, - getTime, -}); diff --git a/src/core/3.ob.js b/src/core/3.ob.js index f51a68f06..fcd9db92a 100644 --- a/src/core/3.ob.js +++ b/src/core/3.ob.js @@ -1,4 +1,4 @@ -import { isFunction, isArray, isObject, isArguments, reduce, bind, extend } from "./2.base"; +import { isFunction, isArray, isObject, isArguments, reduce, bind } from "./2.base"; function obExtend() { let target = arguments[0] || {}, length = arguments.length, i = 1, name, copy; @@ -26,7 +26,7 @@ function obExtend() { return target; } -export default class OB { +export class OB { // props = {}; // init = null; @@ -215,5 +215,3 @@ export default class OB { this.purgeListeners(); } } - -extend(BI, { OB }); diff --git a/src/core/4.widget.js b/src/core/4.widget.js index 54e833b51..e67bdb4dc 100644 --- a/src/core/4.widget.js +++ b/src/core/4.widget.js @@ -7,7 +7,7 @@ */ 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"; const cancelAnimationFrame = @@ -35,7 +35,7 @@ function callLifeHook(self, life) { }); } -export default class Widget extends OB { +export class Widget extends OB { _defaultConfig () { return extend(super._defaultConfig(), { root: false, @@ -1079,15 +1079,3 @@ export function mount(widget, container, predicate, hydrate) { } return widget._mount(true, false, false, predicate); } - -extend(BI, { - Widget, - useStore, - useContext, - watch, - onBeforeMount, - onMounted, - onBeforeUnmount, - onUnmounted, - mount, -}); diff --git a/src/core/5.inject.js b/src/core/5.inject.js index a8ec6786d..77faa02f3 100644 --- a/src/core/5.inject.js +++ b/src/core/5.inject.js @@ -1,6 +1,6 @@ import { isFunction, isNull, isNotNull, isArray, each, isWidget, extend, init, isEmpty, remove } from "./2.base"; -import OB from "./3.ob"; -import Widget from "./4.widget" +import { OB } from "./3.ob"; +import { Widget } from "./4.widget" let moduleInjection = {}, moduleInjectionMap = { components: {}, @@ -39,7 +39,6 @@ export function module(xtype, cls) { return () => Modules.getModule(xtype); } -BI.module = BI.module || module; let constantInjection = {}; export function constant(xtype, cls) { @@ -51,7 +50,6 @@ export function constant(xtype, cls) { return () => Constants.getConstant(xtype); } -BI.constant = BI.constant || constant; let modelInjection = {}; export function model(xtype, cls) { @@ -63,7 +61,6 @@ export function model(xtype, cls) { return (config) => Models.getModel(xtype, config); } -BI.model = BI.model || model; let storeInjection = {}; export function store(xtype, cls) { @@ -75,7 +72,6 @@ export function store(xtype, cls) { return (config) => Stores.getStore(xtype, config); } -BI.store = BI.store || store; let serviceInjection = {}; export function service(xtype, cls) { @@ -87,7 +83,6 @@ export function service(xtype, cls) { return (config) => Services.getService(xtype, config); } -BI.service = BI.service || service; let providerInjection = {}; export function provider(xtype, cls) { @@ -99,7 +94,6 @@ export function provider(xtype, cls) { return (config) => Providers.getProvider(xtype, config); } -BI.provider = BI.provider || provider; let configFunctions = OB.configFunctions = {}; const runConfigFunction = function (type, configFn) { @@ -200,12 +194,10 @@ export function config(type, configFn, opt) { return runConfigFunction(type, configFn); } } -BI.config = BI.config || config; export function getReference(type, fn) { return BI.Plugin.registerObject(type, fn); } -BI.getReference = BI.getReference || getReference; let actions = {}; let globalAction = []; @@ -227,7 +219,6 @@ export function action(type, actionFn) { } }; } -BI.action = BI.action || action; let points = {}; export function point(type, action, pointFn, after) { @@ -242,7 +233,6 @@ export function point(type, action, pointFn, after) { } points[type][action][after ? "after" : "before"].push(pointFn); } -BI.point = BI.point || point; export const Modules = { getModule: function (type) { @@ -255,7 +245,6 @@ export const Modules = { return moduleInjection; } } -BI.Modules = BI.Modules || Modules; export const Constants = { getConstant: function (type) { @@ -266,7 +255,6 @@ export const Constants = { return isFunction(constantInjection[type]) ? constantInjection[type]() : constantInjection[type]; } } -BI.Constants = BI.Constants || Constants; const callPoint = function (inst, types) { types = isArray(types) ? types : [types]; @@ -319,7 +307,6 @@ export const Models = { return inst; } } -BI.Models = BI.Models || Models; let stores = {}; export const Stores = { @@ -338,7 +325,6 @@ export const Stores = { return inst; } } -BI.Stores = BI.Stores || Stores; let services = {}; export const Services = { @@ -354,7 +340,6 @@ export const Services = { return services[type]; } } -BI.Services = BI.Services || Services; let providers = {}, providerInstance = {}; @@ -373,7 +358,6 @@ export const Providers = { return providerInstance[type]; } } -BI.Providers = BI.Providers || Providers; export const Actions = { runAction: function (type, event, config) { @@ -396,7 +380,6 @@ export const Actions = { }); } } -BI.Actions = BI.Actions || Actions; let kv = {}; export function shortcut(xtype, cls) { @@ -408,7 +391,6 @@ export function shortcut(xtype, cls) { } kv[xtype] = cls; } -BI.shortcut = BI.component = BI.shortcut || shortcut; // 根据配置属性生成widget const createRealWidget = function (config, context, lazy) { @@ -496,18 +478,15 @@ export function createWidget(item, options, context, lazy) { } throw new Error("组件:无法根据item创建组件", item); } -BI.createWidget = BI.createWidget || createWidget; export function _lazyCreateWidget (item, options, context) { return createWidget(item, options, context, true); } -BI._lazyCreateWidget = BI._lazyCreateWidget || _lazyCreateWidget; export function createElement() { const widget = createWidget.apply(this, arguments); return widget.element; } -BI.createElement = BI.createElement || createElement; export function getResource(type, config) { if (isNotNull(constantInjection[type])) { @@ -527,4 +506,3 @@ export function getResource(type, config) { } throw new Error("未知类型: [" + type + "] 未定义"); } -BI.getResource = BI.getResource || getResource; diff --git a/src/core/action/action.js b/src/core/action/action.js index e582778ea..b87ea1e21 100644 --- a/src/core/action/action.js +++ b/src/core/action/action.js @@ -5,8 +5,8 @@ * @extends BI.OB * @abstract */ -import OB from "../3.ob"; -export default class Action extends OB { +import { OB } from "../3.ob"; +export class Action extends OB { props = { src: null, tar: null diff --git a/src/core/action/action.show.js b/src/core/action/action.show.js index 6ab3b7e1c..1084ec542 100644 --- a/src/core/action/action.show.js +++ b/src/core/action/action.show.js @@ -4,8 +4,8 @@ * @class BI.ShowAction * @extends BI.Action */ -import Action from "./action"; -export default class ShowAction extends Action { +import { Action } from "./action"; +export class ShowAction extends Action { actionPerformed(src, tar, callback) { tar = tar || this.options.tar; tar.setVisible(true); diff --git a/src/core/action/index.js b/src/core/action/index.js new file mode 100644 index 000000000..f82304e43 --- /dev/null +++ b/src/core/action/index.js @@ -0,0 +1,2 @@ +export { Action } from "./action"; +export { ShowAction } from "./action.show"; \ No newline at end of file diff --git a/src/core/behavior/0.behavior.js b/src/core/behavior/0.behavior.js index 25d82b529..5adc59d3d 100644 --- a/src/core/behavior/0.behavior.js +++ b/src/core/behavior/0.behavior.js @@ -20,8 +20,8 @@ BI.BehaviorFactory = { * @extends BI.OB */ -import OB from "../3.ob"; -export default class Behavior extends OB { +import { OB } from "../3.ob"; +export class Behavior extends OB { _defaultConfig() { return BI.extend(super._defaultConfig(arguments), { rule: () => true diff --git a/src/core/behavior/behavior.highlight.js b/src/core/behavior/behavior.highlight.js index 6ba710da0..1c0676b90 100644 --- a/src/core/behavior/behavior.highlight.js +++ b/src/core/behavior/behavior.highlight.js @@ -4,8 +4,8 @@ * @class BI.HighlightBehavior * @extends BI.Behavior */ -import Behavior from "./0.behavior"; -export default class HighlightBehavior extends Behavior { +import { Behavior } from "./0.behavior"; +export class HighlightBehavior extends Behavior { doBehavior(items) { const args = Array.prototype.slice.call(arguments, 1), o = this.options; diff --git a/src/core/behavior/behavior.redmark.js b/src/core/behavior/behavior.redmark.js index 1b2b349cf..5beb0797f 100644 --- a/src/core/behavior/behavior.redmark.js +++ b/src/core/behavior/behavior.redmark.js @@ -4,8 +4,8 @@ * @class BI.RedMarkBehavior * @extends BI.Behavior */ -import Behavior from "./0.behavior"; -export default class RedMarkBehavior extends Behavior { +import { Behavior } from "./0.behavior"; +export class RedMarkBehavior extends Behavior { doBehavior(items) { const args = Array.prototype.slice.call(arguments, 1), o = this.options; diff --git a/src/core/behavior/index.js b/src/core/behavior/index.js new file mode 100644 index 000000000..ee2ae69ed --- /dev/null +++ b/src/core/behavior/index.js @@ -0,0 +1,3 @@ +export { Behavior } from "./0.behavior"; +export { HighlightBehavior } from "./behavior.highlight"; +export { RedMarkBehavior } from "./behavior.redmark"; \ No newline at end of file diff --git a/src/core/controller/0.controller.js b/src/core/controller/0.controller.js index 0b5bd7b09..0841a9358 100644 --- a/src/core/controller/0.controller.js +++ b/src/core/controller/0.controller.js @@ -6,7 +6,7 @@ * @extends BI.OB * @abstract */ -import OB from "../3.ob"; -export default class Controller extends OB { +import { OB } from "../3.ob"; +export class Controller extends OB { static EVENT_CHANGE = "__EVENT_CHANGE__"; } diff --git a/src/core/controller/controller.broadcast.js b/src/core/controller/controller.broadcast.js index f6d7b8951..f0cc90c8d 100644 --- a/src/core/controller/controller.broadcast.js +++ b/src/core/controller/controller.broadcast.js @@ -4,8 +4,8 @@ * Created by GUY on 2015/12/23. * @class */ -import Controller from "./0.controller"; -export default class BroadcastController extends Controller { +import { Controller } from "./0.controller"; +export class BroadcastController extends Controller { init() { this._broadcasts = {}; } diff --git a/src/core/controller/controller.bubbles.js b/src/core/controller/controller.bubbles.js index 815b94728..e596eac60 100644 --- a/src/core/controller/controller.bubbles.js +++ b/src/core/controller/controller.bubbles.js @@ -5,8 +5,8 @@ * Created by GUY on 2015/8/21. * @class */ -import Controller from "./0.controller"; -export default class BubblesController extends Controller { +import { Controller } from "./0.controller"; +export class BubblesController extends Controller { init() { this.storeBubbles = {}; this.storePoppers = {}; diff --git a/src/core/controller/controller.drawer.js b/src/core/controller/controller.drawer.js index c288d019f..51a80b734 100644 --- a/src/core/controller/controller.drawer.js +++ b/src/core/controller/controller.drawer.js @@ -4,8 +4,8 @@ * @class BI.popoverController * @extends BI.Controller */ -import Controller from "./0.controller"; -export default class DrawerController extends Controller { +import { Controller } from "./0.controller"; +export class DrawerController extends Controller { constructor() { super(); this._constructor(); diff --git a/src/core/controller/controller.layer.js b/src/core/controller/controller.layer.js index 54273957b..6356588ab 100644 --- a/src/core/controller/controller.layer.js +++ b/src/core/controller/controller.layer.js @@ -4,8 +4,8 @@ * Created by GUY on 2015/6/24. * @class */ -import Controller from "./0.controller"; -export default class LayerController extends Controller { +import { Controller } from "./0.controller"; +export class LayerController extends Controller { constructor() { super(); this._constructor(); diff --git a/src/core/controller/controller.masker.js b/src/core/controller/controller.masker.js index 33bffef75..7ff0532bc 100644 --- a/src/core/controller/controller.masker.js +++ b/src/core/controller/controller.masker.js @@ -4,8 +4,8 @@ * Created by GUY on 2015/6/24. * @class */ -import LayerController from "./controller.layer"; -export default class MaskersController extends LayerController { +import { LayerController } from "./controller.layer"; +export class MaskersController extends LayerController { init() { super.init(arguments); this.zindex = BI.zIndex_masker; diff --git a/src/core/controller/controller.popover.js b/src/core/controller/controller.popover.js index 0c48b68ec..dc8e6a14d 100644 --- a/src/core/controller/controller.popover.js +++ b/src/core/controller/controller.popover.js @@ -4,8 +4,8 @@ * @class BI.popoverController * @extends BI.Controller */ -import Controller from "./0.controller"; -export default class PopoverController extends Controller { +import { Controller } from "./0.controller"; +export class PopoverController extends Controller { constructor() { super(); this._constructor(); diff --git a/src/core/controller/controller.resizer.js b/src/core/controller/controller.resizer.js index 3a6dcd31a..5b8c400b8 100644 --- a/src/core/controller/controller.resizer.js +++ b/src/core/controller/controller.resizer.js @@ -4,8 +4,8 @@ * Created by GUY on 2015/6/24. * @class */ -import Controller from "./0.controller"; -export default class ResizeController extends Controller { +import { Controller } from "./0.controller"; +export class ResizeController extends Controller { init() { this.resizerManger = {}; diff --git a/src/core/controller/controller.tooltips.js b/src/core/controller/controller.tooltips.js index 0e397aa33..e084caba9 100644 --- a/src/core/controller/controller.tooltips.js +++ b/src/core/controller/controller.tooltips.js @@ -6,8 +6,8 @@ * @class BI.TooltipsController * @extends BI.Controller */ -import Controller from "./0.controller"; -export default class TooltipsController extends Controller { +import { Controller } from "./0.controller"; +export class TooltipsController extends Controller { init() { this.tooltipsManager = {}; this.showingTips = {};// 存储正在显示的tooltip diff --git a/src/core/controller/index.js b/src/core/controller/index.js new file mode 100644 index 000000000..91701e15f --- /dev/null +++ b/src/core/controller/index.js @@ -0,0 +1,9 @@ +export { Controller } from "./0.controller"; +export { BroadcastController } from "./controller.broadcast"; +export { BubblesController } from "./controller.bubbles"; +export { DrawerController } from "./controller.drawer"; +export { LayerController } from "./controller.layer"; +export { MaskersController } from "./controller.masker"; +export { PopoverController } from "./controller.popover"; +export { ResizeController } from "./controller.resizer"; +export { TooltipsController } from "./controller.tooltips"; \ No newline at end of file diff --git a/src/core/index.js b/src/core/index.js index 3c660e1de..397017380 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -1,68 +1,39 @@ -import {shortcut} from "./decorator"; -import OB from "./3.ob"; -import Widget from "./4.widget"; -import Action from "./action/action"; -import ShowAction from "./action/action.show"; -import Behavior from "./behavior/0.behavior"; -import HighlightBehavior from "./behavior/behavior.highlight"; -import RedMarkBehavior from "./behavior/behavior.redmark"; -import Controller from "./controller/0.controller"; -import BroadcastController from "./controller/controller.broadcast"; -import BubblesController from "./controller/controller.bubbles"; -import DrawerController from "./controller/controller.drawer"; -import LayerController from "./controller/controller.layer"; -import MaskersController from "./controller/controller.masker"; -import PopoverController from "./controller/controller.popover"; -import ResizeController from "./controller/controller.resizer"; -import TooltipsController from "./controller/controller.tooltips"; -import StyleLoaderManager from "./loader/loader.style"; -import "./h"; -import ShowListener from "./listener/listener.show"; -BI.extend(BI, { - OB, - Widget, - Action, - ShowAction, - Behavior, - HighlightBehavior, - RedMarkBehavior, - Controller, - BroadcastController, - BubblesController, - DrawerController, - LayerController, - MaskersController, - PopoverController, - ResizeController, - TooltipsController, - StyleLoaderManager, - ShowListener, -}); +import * as base from "./2.base"; +import * as ob from "./3.ob"; +import * as widget from "./4.widget"; +import * as inject from "./5.inject"; +import * as action from "./action"; +import * as behavior from "./behavior"; +import * as controllers from "./controller"; +import { StyleLoaderManager } from "./loader/loader.style"; +import "./h"; +import { ShowListener } from "./listener/listener.show"; +import { shortcut } from "./decorator"; export * from "./2.base"; +export * from "./3.ob"; export * from "./4.widget"; export * from "./5.inject"; -export * from "./func"; +export * from "./action"; +export * from "./behavior"; +export * from "./controller"; export { + StyleLoaderManager, + ShowListener, shortcut, - OB, - Widget, - Action, - ShowAction, - Behavior, - HighlightBehavior, - RedMarkBehavior, - Controller, - BroadcastController, - BubblesController, - DrawerController, - LayerController, - MaskersController, - PopoverController, - ResizeController, - TooltipsController, +} + +Object.assign(BI, { + ...base, + ...ob, + ...widget, + ...inject, + ...behavior, + component: inject.shortcut, + ...action, + ...controllers, StyleLoaderManager, - ShowListener -}; + ShowListener, +}); diff --git a/src/core/listener/listener.show.js b/src/core/listener/listener.show.js index 1c9469473..25ddc7ea2 100644 --- a/src/core/listener/listener.show.js +++ b/src/core/listener/listener.show.js @@ -5,12 +5,12 @@ * @class BI.ShowListener * @extends BI.OB */ -import OB from "../3.ob"; +import { OB } from "../3.ob"; import { isArray, isNull, nextTick, } from "../2.base"; import { createWidget } from "../5.inject"; -import Controller from "../controller/0.controller"; +import { Controller } from "../controller/0.controller"; -export default class ShowListener extends OB { +export class ShowListener extends OB { static EVENT_CHANGE = "EVENT_CHANGE"; props() { diff --git a/src/core/loader/loader.style.js b/src/core/loader/loader.style.js index e10007cc3..1c65a2ede 100644 --- a/src/core/loader/loader.style.js +++ b/src/core/loader/loader.style.js @@ -4,9 +4,9 @@ * Created by GUY on 2015/9/7. * @class */ -import OB from "../3.ob"; +import { OB } from "../3.ob"; -export default class StyleLoaderManager extends OB { +export class StyleLoaderManager extends OB { _defaultConfig() { return BI.extend(super._defaultConfig(arguments), {}); } From 455a1618766713b1aef3687a559d6b447540cd89 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Wed, 4 Jan 2023 14:05:28 +0800 Subject: [PATCH 030/300] =?UTF-8?q?=E6=97=A0JIRA=E4=BB=BB=E5=8A=A1=20refac?= =?UTF-8?q?tor:=20func=E4=B8=AD=E7=9A=84=E6=8C=82=E8=BD=BDBI=E6=8C=AA?= =?UTF-8?q?=E8=B5=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/func/index.js | 17 ----------------- src/core/index.js | 3 +++ 2 files changed, 3 insertions(+), 17 deletions(-) diff --git a/src/core/func/index.js b/src/core/func/index.js index 9b24275bf..b04392bdc 100644 --- a/src/core/func/index.js +++ b/src/core/func/index.js @@ -4,20 +4,3 @@ export * from "./date"; export * from "./function"; export * from "./number"; export * from "./string"; - -// need delete -import * as _alias from "./alias"; -import * as _array from "./array"; -import * as _date from "./date"; -import * as _function from "./function"; -import * as _number from "./number"; -import * as _string from "./string"; - -Object.assign(BI, { - ..._alias, - ..._array, - ..._date, - ..._function, - ..._number, - ..._string, -}); diff --git a/src/core/index.js b/src/core/index.js index 397017380..53a8cd755 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -6,6 +6,7 @@ import * as inject from "./5.inject"; import * as action from "./action"; import * as behavior from "./behavior"; import * as controllers from "./controller"; +import * as func from "./func"; import { StyleLoaderManager } from "./loader/loader.style"; import "./h"; import { ShowListener } from "./listener/listener.show"; @@ -18,6 +19,7 @@ export * from "./5.inject"; export * from "./action"; export * from "./behavior"; export * from "./controller"; +export * from "./func"; export { StyleLoaderManager, @@ -34,6 +36,7 @@ Object.assign(BI, { component: inject.shortcut, ...action, ...controllers, + ...func, StyleLoaderManager, ShowListener, }); From e8f2b82e48208687bdaa8d1e3d6c669d1ea1ee4c Mon Sep 17 00:00:00 2001 From: Treecat Date: Wed, 4 Jan 2023 14:57:27 +0800 Subject: [PATCH 031/300] =?UTF-8?q?KERNEL-13962=20refact:=20es6=E6=8C=89?= =?UTF-8?q?=E9=92=AE=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/index.js | 38 ++ src/base/single/bar/bar.loading.js | 52 +- src/base/single/button/button.basic.js | 395 +++++++------- src/base/single/button/button.node.js | 56 +- src/base/single/button/buttons/button.icon.js | 48 +- .../single/button/buttons/button.image.js | 85 +-- src/base/single/button/buttons/button.js | 507 +++++++++--------- src/base/single/button/buttons/button.text.js | 72 +-- .../button/listitem/blankiconicontextitem.js | 79 +-- .../button/listitem/blankicontexticonitem.js | 74 +-- .../button/listitem/blankicontextitem.js | 75 +-- .../button/listitem/icontexticonitem.js | 76 +-- .../single/button/listitem/icontextitem.js | 73 +-- .../single/button/listitem/texticonitem.js | 71 +-- src/base/single/button/listitem/textitem.js | 69 +-- .../single/button/node/icontexticonnode.js | 67 +-- src/base/single/button/node/icontextnode.js | 66 +-- src/base/single/button/node/texticonnode.js | 67 +-- src/base/single/button/node/textnode.js | 65 ++- src/core/index.js | 3 + 20 files changed, 1094 insertions(+), 944 deletions(-) diff --git a/src/base/index.js b/src/base/index.js index b5f9c4faa..a727cb725 100644 --- a/src/base/index.js +++ b/src/base/index.js @@ -15,8 +15,46 @@ import VirtualList from "./list/virtuallist"; import GridView from "./grid/grid"; import Pager from "./pager/pager"; +import { BasicButton } from "./single/button/button.basic"; +import { NodeButton } from "./single/button/button.node"; +import { Button } from "./single/button/buttons/button"; +import { IconButton } from "./single/button/buttons/button.icon"; +import { ImageButton } from "./single/button/buttons/button.image"; +import { TextButton } from "./single/button/buttons/button.text"; +import { BlankIconIconTextItem } from "./single/button/listitem/blankiconicontextitem"; +import { BlankIconTextIconItem } from "./single/button/listitem/blankicontexticonitem"; +import { BlankIconTextItem } from "./single/button/listitem/blankicontextitem"; +import { IconTextIconItem } from "./single/button/listitem/icontexticonitem"; +import { IconTextItem } from "./single/button/listitem/icontextitem"; +import { TextIconItem } from "./single/button/listitem/texticonitem"; +import { TextItem } from "./single/button/listitem/textitem"; +import { IconTextIconNode } from "./single/button/node/icontexticonnode"; +import { IconTextNode } from "./single/button/node/icontextnode"; +import { TextIconNode } from "./single/button/node/texticonnode"; +import { TextNode } from "./single/button/node/textnode"; + + + + BI.extend(BI, { + NodeButton, + BasicButton, + Button, + IconButton, + ImageButton, + TextButton, + BlankIconIconTextItem, + BlankIconTextIconItem, + BlankIconTextItem, + IconTextIconItem, + IconTextItem, + TextIconItem, + TextItem, + IconTextIconNode, + IconTextNode, + TextIconNode, + TextNode, Pane, Single, Text, diff --git a/src/base/single/bar/bar.loading.js b/src/base/single/bar/bar.loading.js index 801331b15..f8bd97970 100644 --- a/src/base/single/bar/bar.loading.js +++ b/src/base/single/bar/bar.loading.js @@ -1,21 +1,26 @@ +import { shortcut, emptyFn } from "../../../core" /** * guy * 加载条 * @type {*|void|Object} */ -BI.LoadingBar = BI.inherit(BI.Single, { - _defaultConfig: function () { - var conf = BI.LoadingBar.superclass._defaultConfig.apply(this, arguments); +@shortcut() +class LoadingBar extends BI.Single { - return BI.extend(conf, { + static xtype = "bi.loading_bar"; + + _defaultConfig() { + const conf = super._defaultConfig.apply(this, arguments); + + return { + ...conf, baseCls: (conf.baseCls || "") + " bi-loading-bar bi-tips", height: 30, - handler: BI.emptyFn, - }); - }, + handler: emptyFn, + } + } - render: function () { - var self = this; + render() { this.loaded = BI.createWidget({ type: "bi.text_button", cls: "loading-text bi-list-item-simple", @@ -23,8 +28,8 @@ BI.LoadingBar = BI.inherit(BI.Single, { width: 120, handler: this.options.handler, }); - this.loaded.on(BI.Controller.EVENT_CHANGE, function (type) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.loaded.on(BI.Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(BI.Controller.EVENT_CHANGE, args); }); this.loading = BI.createWidget({ @@ -33,11 +38,11 @@ BI.LoadingBar = BI.inherit(BI.Single, { height: this.options.height, cls: "loading-background cursor-default", }); - var loaded = BI.createWidget({ + const loaded = BI.createWidget({ type: "bi.center_adapt", items: [this.loaded], }); - var loading = BI.createWidget({ + const loading = BI.createWidget({ type: "bi.center_adapt", items: [this.loading], }); @@ -53,29 +58,28 @@ BI.LoadingBar = BI.inherit(BI.Single, { }], }); this.invisible(); - }, + } - _reset: function () { + _reset() { this.visible(); this.loaded.setText(BI.i18nText("BI-Load_More")); this.loaded.enable(); - }, + } - setLoaded: function () { + setLoaded() { this._reset(); this.cardLayout.showCardByName("loaded"); - }, + } - setEnd: function () { + setEnd() { this.setLoaded(); this.loaded.setText(BI.i18nText("BI-No_More_Data")); this.loaded.disable(); - }, + } - setLoading: function () { + setLoading() { this._reset(); this.cardLayout.showCardByName("loading"); - }, -}); + } +} -BI.shortcut("bi.loading_bar", BI.LoadingBar); diff --git a/src/base/single/button/button.basic.js b/src/base/single/button/button.basic.js index 64865de8b..21f1d9bc8 100644 --- a/src/base/single/button/button.basic.js +++ b/src/base/single/button/button.basic.js @@ -1,15 +1,24 @@ +import Single from "../0.single" +import { emptyFn, shortcut, extend, isFunction, createWidget, Widget, isObject, Controller } from "../../../core" + /** * guy - * @class BI.BasicButton - * @extends BI.Single + * @class BasicButton + * @extends Single * * 一般的button父级 */ -BI.BasicButton = BI.inherit(BI.Single, { - _defaultConfig: function () { - var conf = BI.BasicButton.superclass._defaultConfig.apply(this, arguments); +@shortcut() +export class BasicButton extends Single { + + static xtype = "bi.basic_button"; + + static EVENT_CHANGE = "BasicButton.EVENT_CHANGE"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); - return BI.extend(conf, { + return extend(conf, { _baseCls: (conf._baseCls || "") + " bi-basic-button" + (conf.invalid ? "" : " cursor-pointer") + ((BI.isIE() && BI.getIEVersion() < 10) ? " hack" : ""), // el: {} // 可以通过el来创建button元素 value: "", @@ -24,19 +33,18 @@ BI.BasicButton = BI.inherit(BI.Single, { shadow: false, isShadowShowingOnSelected: false, // 选中状态下是否显示阴影 trigger: null, - handler: BI.emptyFn, + handler: emptyFn, bubble: null, debounce: true }); - }, + } - _init: function () { - var self = this; - var opts = this.options; - opts.selected = BI.isFunction(opts.selected) ? this.__watch(opts.selected, function (context, newValue) { - self.setSelected(newValue); + _init() { + const opts = this.options; + opts.selected = isFunction(opts.selected) ? this.__watch(opts.selected, (context, newValue) => { + this.setSelected(newValue); }) : opts.selected; - BI.BasicButton.superclass._init.apply(this, arguments); + super._init(arguments); if (opts.shadow) { this._createShadow(); @@ -44,9 +52,9 @@ BI.BasicButton = BI.inherit(BI.Single, { if (opts.level) { this.element.addClass("button-" + opts.level); } - }, + } - _initRef: function () { + _initRef() { if (this.options.selected === true) { this.setSelected(true); } @@ -54,29 +62,29 @@ BI.BasicButton = BI.inherit(BI.Single, { BI.nextTick(() => { !this.isDestroyed() && this.bindEvent(); }); - BI.BasicButton.superclass._initRef.apply(this, arguments); - }, + super._initRef.apply(this, arguments); + } // 默认render方法 - render: function () { + render() { return this.options.el; - }, + } - _createShadow: function () { - var self = this, o = this.options; + _createShadow() { + const o = this.options; - function assertMask() { - if (!self.$mask) { - self.$mask = BI.createWidget(BI.isObject(o.shadow) ? o.shadow : {}, { + const assertMask = () => { + if (!this.$mask) { + this.$mask = createWidget(isObject(o.shadow) ? o.shadow : {}, { type: "bi.layout", cls: "bi-button-mask", }); - self.$mask.invisible(); - BI.createWidget({ + this.$mask.invisible(); + createWidget({ type: "bi.absolute", - element: self, + element: this, items: [{ - el: self.$mask, + el: this.$mask, left: 0, right: 0, top: 0, @@ -86,48 +94,129 @@ BI.BasicButton = BI.inherit(BI.Single, { } } - this.element.mouseup(function () { - if (!self._hover && !o.isShadowShowingOnSelected) { + this.element.mouseup(() => { + if (!this._hover && !o.isShadowShowingOnSelected) { assertMask(); - self.$mask.invisible(); + this.$mask.invisible(); } }); - this.element.on("mouseenter." + this.getName(), function (e) { - if (self.element.__isMouseInBounds__(e)) { - if (self.isEnabled() && !self._hover && (o.isShadowShowingOnSelected || !self.isSelected())) { + this.element.on("mouseenter." + this.getName(), (e) => { + if (this.element.__isMouseInBounds__(e)) { + if (this.isEnabled() && !this._hover && (o.isShadowShowingOnSelected || !this.isSelected())) { assertMask(); - self.$mask.visible(); + this.$mask.visible(); } } }); - this.element.on("mousemove." + this.getName(), function (e) { - if (!self.element.__isMouseInBounds__(e)) { - if (self.isEnabled() && !self._hover) { + this.element.on("mousemove." + this.getName(), (e) => { + if (!this.element.__isMouseInBounds__(e)) { + if (this.isEnabled() && !this._hover) { assertMask(); - self.$mask.invisible(); + this.$mask.invisible(); } } }); - this.element.on("mouseleave." + this.getName(), function () { - if (self.isEnabled() && !self._hover) { + this.element.on("mouseleave." + this.getName(), () => { + if (this.isEnabled() && !this._hover) { assertMask(); - self.$mask.invisible(); + this.$mask.invisible(); } }); - }, + } - bindEvent: function () { - var self = this; - var o = this.options, hand = this.handle(); + bindEvent() { + const o = this.options; + let hand = this.handle(); if (!hand) { return; } hand = hand.element; - var triggerArr = (o.trigger || "").split(","); - BI.each(triggerArr, function (idx, trigger) { + + const getBubble = () => { + const bubble = o.bubble; + if (isFunction(bubble)) { + return bubble(); + } + + return bubble; + } + + const clk = (e) => { + ev(e); + if (!this.isEnabled() || !this.isValid()) { + return; + } + if (this.isOnce() && this.isSelected()) { + return; + } + if (BI.isKey(o.bubble) || isFunction(o.bubble)) { + if (BI.isNull(this.combo)) { + let popup; + createWidget({ + type: "bi.absolute", + element: this, + items: [{ + el: { + type: "bi.bubble_combo", + trigger: "", + // bubble的提示不需要一直存在在界面上 + destroyWhenHide: true, + ref: (_ref) => { + this.combo = _ref; + }, + el: { + type: "bi.layout", + height: "100%", + }, + popup: { + type: "bi.text_bubble_bar_popup_view", + text: getBubble(), + ref: (_ref) => { + popup = _ref; + }, + listeners: [{ + eventName: BI.BubblePopupBarView.EVENT_CLICK_TOOLBAR_BUTTON, + action: (...args) => { + const [v] = args; + this.combo.hideView(); + if (v) { + onClick.apply(this, args); + } + }, + }], + }, + listeners: [{ + eventName: BI.BubbleCombo.EVENT_BEFORE_POPUPVIEW, + action: function () { + popup.populate(getBubble()); + }, + }], + }, + left: 0, + right: 0, + bottom: 0, + top: 0, + }], + }); + } + if (this.combo.isViewVisible()) { + this.combo.hideView(); + } else { + this.combo.showView(); + } + + return; + } + onClick.apply(this, arguments); + } + + + + const triggerArr = (o.trigger || "").split(","); + triggerArr.forEach((trigger) => { + let mouseDown = false; switch (trigger) { case "mouseup": - var mouseDown = false; hand.mousedown(function () { mouseDown = true; }); @@ -140,24 +229,24 @@ BI.BasicButton = BI.inherit(BI.Single, { }); break; case "mousedown": - var mouseDown = false; - var selected = false; - hand.mousedown(function (e) { + // let mouseDown = false; + let selected = false; + hand.mousedown((e) => { // if (e.button === 0) { - BI.Widget._renderEngine.createElement(document).bind("mouseup." + self.getName(), function (e) { + Widget._renderEngine.createElement(document).bind("mouseup." + this.getName(), (e) => { // if (e.button === 0) { - if (BI.DOM.isExist(self) && !hand.__isMouseInBounds__(e) && mouseDown === true && !selected) { + if (BI.DOM.isExist(this) && !hand.__isMouseInBounds__(e) && mouseDown === true && !selected) { // self.setSelected(!self.isSelected()); - self._trigger(); + this._trigger(); } mouseDown = false; - BI.Widget._renderEngine.createElement(document).unbind("mouseup." + self.getName()); + Widget._renderEngine.createElement(document).unbind("mouseup." + this.getName()); // } }); if (mouseDown === true) { return; } - if (self.isSelected()) { + if (this.isSelected()) { selected = true; } else { clk(e); @@ -166,14 +255,14 @@ BI.BasicButton = BI.inherit(BI.Single, { ev(e); // } }); - hand.mouseup(function (e) { + hand.mouseup((e) => { // if (e.button === 0) { - if (BI.DOM.isExist(self) && mouseDown === true && selected === true) { + if (BI.DOM.isExist(this) && mouseDown === true && selected === true) { clk(e); } mouseDown = false; selected = false; - BI.Widget._renderEngine.createElement(document).unbind("mouseup." + self.getName()); + Widget._renderEngine.createElement(document).unbind("mouseup." + this.getName()); // } }); break; @@ -181,22 +270,21 @@ BI.BasicButton = BI.inherit(BI.Single, { hand.dblclick(clk); break; case "lclick": - var mouseDown = false; - var interval; - hand.mousedown(function (e) { - BI.Widget._renderEngine.createElement(document).bind("mouseup." + self.getName(), function () { + let interval; + hand.mousedown((e) => { + Widget._renderEngine.createElement(document).bind("mouseup." + this.getName(), () => { interval && clearInterval(interval); interval = null; mouseDown = false; - BI.Widget._renderEngine.createElement(document).unbind("mouseup." + self.getName()); + Widget._renderEngine.createElement(document).unbind("mouseup." + this.getName()); }); if (mouseDown === true) { return; } - if (!self.isEnabled() || !self.isValid()) { + if (!this.isEnabled() || !this.isValid()) { return; } - if (self.isOnce() && self.isSelected()) { + if (this.isOnce() && this.isSelected()) { return; } interval = setInterval(function () { @@ -224,7 +312,7 @@ BI.BasicButton = BI.inherit(BI.Single, { }); // 之后的300ms点击无效 - var onClick = o.debounce ? BI.debounce(this._doClick, BI.EVENT_RESPONSE_TIME, { + let onClick = o.debounce ? BI.debounce(this._doClick, BI.EVENT_RESPONSE_TIME, { "leading": true, "trailing": false, }) : this._doClick; @@ -238,86 +326,13 @@ BI.BasicButton = BI.inherit(BI.Single, { } } - function clk(e) { - ev(e); - if (!self.isEnabled() || !self.isValid()) { - return; - } - if (self.isOnce() && self.isSelected()) { - return; - } - if (BI.isKey(o.bubble) || BI.isFunction(o.bubble)) { - if (BI.isNull(self.combo)) { - var popup; - BI.createWidget({ - type: "bi.absolute", - element: self, - items: [{ - el: { - type: "bi.bubble_combo", - trigger: "", - // bubble的提示不需要一直存在在界面上 - destroyWhenHide: true, - ref: function () { - self.combo = this; - }, - el: { - type: "bi.layout", - height: "100%", - }, - popup: { - type: "bi.text_bubble_bar_popup_view", - text: getBubble(), - ref: function () { - popup = this; - }, - listeners: [{ - eventName: BI.BubblePopupBarView.EVENT_CLICK_TOOLBAR_BUTTON, - action: function (v) { - self.combo.hideView(); - if (v) { - onClick.apply(self, arguments); - } - }, - }], - }, - listeners: [{ - eventName: BI.BubbleCombo.EVENT_BEFORE_POPUPVIEW, - action: function () { - popup.populate(getBubble()); - }, - }], - }, - left: 0, - right: 0, - bottom: 0, - top: 0, - }], - }); - } - if (self.combo.isViewVisible()) { - self.combo.hideView(); - } else { - self.combo.showView(); - } - return; - } - onClick.apply(self, arguments); - } - function getBubble() { - var bubble = self.options.bubble; - if (BI.isFunction(bubble)) { - return bubble(); - } - return bubble; - } - }, + } - _trigger: function (e) { - var o = this.options; + _trigger(e) { + const o = this.options; if (!this.isEnabled()) { return; } @@ -327,22 +342,22 @@ BI.BasicButton = BI.inherit(BI.Single, { this.setSelected(!this.isSelected())); } if (this.isValid()) { - var v = this.getValue(); + const v = this.getValue(); o.handler.call(this, v, this, e); - this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.CLICK, v, this, e); - this.fireEvent(BI.BasicButton.EVENT_CHANGE, v, this); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.CLICK, v, this, e); + this.fireEvent(BasicButton.EVENT_CHANGE, v, this); if (o.action) { BI.Actions.runAction(o.action, "click", o, this); } BI.Actions.runGlobalAction("click", o, this); } - }, + } - _doClick: function (e) { + _doClick(e) { if (!this.isEnabled() || !this.isValid()) { return; } - var isIntercepted = this.beforeClick(e); + const isIntercepted = this.beforeClick(e); // 如果事件已经被消费掉了,就不再触发点击事件 if (isIntercepted) { return; @@ -352,41 +367,41 @@ BI.BasicButton = BI.inherit(BI.Single, { if (this.isEnabled() && this.isValid()) { this.doClick(e); } - }, + } /** * 子类可以得写这个方法,如果返回为 true,则可以阻止 handler 的触发 */ - beforeClick: function () { + beforeClick() { - }, + } - doClick: function () { + doClick() { - }, + } - handle: function () { + handle() { return this; - }, + } - hover: function () { + hover() { this._hover = true; this.handle().element.addClass("hover"); if (this.options.shadow) { this.$mask && this.$mask.setVisible(true); } - }, + } - dishover: function () { + dishover() { this._hover = false; this.handle().element.removeClass("hover"); if (this.options.shadow) { this.$mask && this.$mask.setVisible(false); } - }, + } - setSelected: function (b) { - var o = this.options; + setSelected(b) { + const o = this.options; o.selected = b; if (b) { this.handle().element.addClass("active"); @@ -397,39 +412,39 @@ BI.BasicButton = BI.inherit(BI.Single, { this.$mask && this.$mask.setVisible(false); } this.options.setSelected && this.options.setSelected.call(this, b); - }, + } - isSelected: function () { + isSelected() { return this.options.selected; - }, + } - isOnce: function () { + isOnce() { return this.options.once; - }, + } - isForceSelected: function () { + isForceSelected() { return this.options.forceSelected; - }, + } - isForceNotSelected: function () { + isForceNotSelected() { return this.options.forceNotSelected; - }, + } - isDisableSelected: function () { + isDisableSelected() { return this.options.disableSelected; - }, + } - setText: function (text) { + setText(text) { this.options.text = text; this.options.setText && this.options.setText.call(this, text); - }, + } - getText: function () { + getText() { return this.options.text; - }, + } - _setEnable: function (enable) { - BI.BasicButton.superclass._setEnable.apply(this, arguments); + _setEnable(enable) { + super._setEnable.apply(this, arguments); if (enable === true) { this.element.removeClass("base-disabled disabled"); } else if (enable === false) { @@ -440,12 +455,12 @@ BI.BasicButton = BI.inherit(BI.Single, { this.$mask && this.$mask.setVisible(false); } } - }, - - empty: function () { - BI.Widget._renderEngine.createElement(document).unbind("mouseup." + this.getName()); - BI.BasicButton.superclass.empty.apply(this, arguments); - }, -}); -BI.BasicButton.EVENT_CHANGE = "BasicButton.EVENT_CHANGE"; -BI.shortcut("bi.basic_button", BI.BasicButton); + } + + empty() { + Widget._renderEngine.createElement(document).unbind("mouseup." + this.getName()); + super.empty.apply(this, arguments); + } +} + + diff --git a/src/base/single/button/button.node.js b/src/base/single/button/button.node.js index ae4bd9045..6b2988eb3 100644 --- a/src/base/single/button/button.node.js +++ b/src/base/single/button/button.node.js @@ -1,54 +1,60 @@ +import { BasicButton } from "./button.basic" +import { shortcut, extend, Controller } from "../../../core" + /** * 表示一个可以展开的节点, 不仅有选中状态而且有展开状态 * * Created by GUY on 2015/9/9. - * @class BI.NodeButton - * @extends BI.BasicButton + * @class NodeButton + * @extends BasicButton * @abstract */ -BI.NodeButton = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - var conf = BI.NodeButton.superclass._defaultConfig.apply(this, arguments); +@shortcut() +export class NodeButton extends BasicButton { + + static xtype = "bi.node_button"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); - return BI.extend(conf, { + return extend(conf, { _baseCls: (conf._baseCls || "") + " bi-node", open: false, once: false, }); - }, + } - _initRef: function () { + _initRef() { if (this.isOpened()) { this.setOpened(this.isOpened()); } - BI.NodeButton.superclass._initRef.apply(this, arguments); - }, + super._initRef.apply(this, arguments); + } - doClick: function () { - BI.NodeButton.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); this.setOpened(!this.isOpened()); - }, + } - isOpened: function () { + isOpened() { return !!this.options.open; - }, + } - setOpened: function (b) { + setOpened(b) { this.options.open = !!b; - }, + } - triggerCollapse: function () { + triggerCollapse() { if (this.isOpened()) { this.setOpened(false); - this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, this.getValue(), this); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.COLLAPSE, this.getValue(), this); } - }, + } - triggerExpand: function () { + triggerExpand() { if (!this.isOpened()) { this.setOpened(true); - this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, this.getValue(), this); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, this.getValue(), this); } - }, -}); -BI.shortcut("bi.node_button", BI.NodeButton); + } +} \ No newline at end of file diff --git a/src/base/single/button/buttons/button.icon.js b/src/base/single/button/buttons/button.icon.js index 045126c38..9e8228a55 100644 --- a/src/base/single/button/buttons/button.icon.js +++ b/src/base/single/button/buttons/button.icon.js @@ -1,13 +1,21 @@ +import { BasicButton } from "../button.basic"; +import { shortcut, extend, isNumber, createWidget, isNull } from "../../../../core"; + /** - * @class BI.IconButton - * @extends BI.BasicButton + * @class IconButton + * @extends BasicButton * 图标的button */ -BI.IconButton = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - var conf = BI.IconButton.superclass._defaultConfig.apply(this, arguments); +@shortcut() +export class IconButton extends BasicButton { + + static EVENT_CHANGE = "EVENT_CHANGE"; + static xtype = "bi.icon_button"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); - return BI.extend(conf, { + return extend(conf, { _baseCls: (conf._baseCls || "") + " bi-icon-button horizon-center", hgap: 0, vgap: 0, @@ -18,21 +26,21 @@ BI.IconButton = BI.inherit(BI.BasicButton, { iconWidth: null, iconHeight: null, }); - }, + } - render: function () { - var o = this.options; + render() { + const o = this.options; this.element.css({ textAlign: "center", }); - this.icon = BI.createWidget({ + this.icon = createWidget({ type: "bi.icon", width: o.iconWidth, height: o.iconHeight, }); - if (BI.isNumber(o.height) && o.height > 0 && BI.isNull(o.iconWidth) && BI.isNull(o.iconHeight)) { + if (isNumber(o.height) && o.height > 0 && isNull(o.iconWidth) && isNull(o.iconHeight)) { this.element.css("lineHeight", BI.pixFormat(o.height)); - BI.createWidget({ + createWidget({ type: "bi.default", element: this, hgap: o.hgap, @@ -45,7 +53,7 @@ BI.IconButton = BI.inherit(BI.BasicButton, { }); } else { this.element.css("lineHeight", "1"); - BI.createWidget({ + createWidget({ element: this, type: "bi.center_adapt", hgap: o.hgap, @@ -57,14 +65,12 @@ BI.IconButton = BI.inherit(BI.BasicButton, { items: [this.icon], }); } - }, + } - doClick: function () { - BI.IconButton.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); if (this.isValid()) { - this.fireEvent(BI.IconButton.EVENT_CHANGE, this); + this.fireEvent(IconButton.EVENT_CHANGE, this); } - }, -}); -BI.IconButton.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.icon_button", BI.IconButton); + } +} diff --git a/src/base/single/button/buttons/button.image.js b/src/base/single/button/buttons/button.image.js index 6eeeffbf1..290313fb2 100644 --- a/src/base/single/button/buttons/button.image.js +++ b/src/base/single/button/buttons/button.image.js @@ -1,87 +1,94 @@ +import { BasicButton } from "../button.basic"; +import { shortcut, extend, isNumber, createWidget } from "../../../../core"; + + /** * 图片的button * * Created by GUY on 2016/1/27. - * @class BI.ImageButton - * @extends BI.BasicButton + * @class ImageButton + * @extends BasicButton */ -BI.ImageButton = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - var conf = BI.ImageButton.superclass._defaultConfig.apply(this, arguments); +@shortcut() +export class ImageButton extends BasicButton { + + static EVENT_CHANGE = "EVENT_CHANGE"; + static xtype = "bi.image_button"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); - return BI.extend(conf, { + return extend(conf, { baseCls: (conf.baseCls || "") + " bi-image-button", src: "", iconWidth: "100%", iconHeight: "100%", }); - }, + } - render: function () { - var o = this.options; - this.image = BI.createWidget({ + render() { + const o = this.options; + this.image = createWidget({ type: "bi.img", width: o.iconWidth, height: o.iconHeight, src: o.src, }); - if (BI.isNumber(o.iconWidth) || BI.isNumber(o.iconHeight)) { - BI.createWidget({ + if (isNumber(o.iconWidth) || isNumber(o.iconHeight)) { + createWidget({ type: "bi.center_adapt", element: this, items: [this.image], }); } else { - BI.createWidget({ + createWidget({ type: "bi.adaptive", element: this, items: [this.image], scrollable: false, }); } - }, + } - setWidth: function (w) { - BI.ImageButton.superclass.setWidth.apply(this, arguments); + setWidth(w) { + super.setWidth.apply(this, arguments); this.options.width = w; - }, + } - setHeight: function (h) { - BI.ImageButton.superclass.setHeight.apply(this, arguments); + setHeight(h) { + super.setHeight.apply(this, arguments); this.options.height = h; - }, + } - setImageWidth: function (w) { + setImageWidth(w) { this.image.setWidth(w); - }, + } - setImageHeight: function (h) { + setImageHeight(h) { this.image.setHeight(h); - }, + } - getImageWidth: function () { + getImageWidth() { return this.image.element.width(); - }, + } - getImageHeight: function () { + getImageHeight() { return this.image.element.height(); - }, + } - setSrc: function (src) { + setSrc(src) { this.options.src = src; this.image.setSrc(src); - }, + } - getSrc: function () { + getSrc() { return this.image.getSrc(); - }, + } - doClick: function () { - BI.ImageButton.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); if (this.isValid()) { - this.fireEvent(BI.ImageButton.EVENT_CHANGE, this); + this.fireEvent(ImageButton.EVENT_CHANGE, this); } - }, -}); -BI.ImageButton.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.image_button", BI.ImageButton); + } +} diff --git a/src/base/single/button/buttons/button.js b/src/base/single/button/buttons/button.js index bc1468450..567e115f9 100644 --- a/src/base/single/button/buttons/button.js +++ b/src/base/single/button/buttons/button.js @@ -1,271 +1,276 @@ -(function () { - function isVertical(position) { - return position === "top" || position === "bottom"; +import { BasicButton } from "../button.basic"; +import { isNumber, shortcut, isPlainObject, createWidget } from "../../../../core"; + +function isVertical(position) { + return position === "top" || position === "bottom"; +} + +const loadingCls = "button-loading-font anim-rotate"; + +/** + * 文字类型的按钮 + * @class Button + * @extends BasicButton + * + * @cfg {JSON} options 配置属性 + * @cfg {'common' / 'success' / 'warning' / 'ignore'} [options.level='common'] 按钮类型,用不同颜色强调不同的场景 + */ +@shortcut() +export class Button extends BasicButton { + + _const = { + iconWidth: 18, } - var loadingCls = "button-loading-font anim-rotate"; - - /** - * 文字类型的按钮 - * @class BI.Button - * @extends BI.BasicButton - * - * @cfg {JSON} options 配置属性 - * @cfg {'common'/'success'/'warning'/'ignore'} [options.level='common'] 按钮类型,用不同颜色强调不同的场景 - */ - BI.Button = BI.inherit(BI.BasicButton, { - - _const: { - iconWidth: 18, - }, - - _defaultConfig: function (props) { - var conf = BI.Button.superclass._defaultConfig.apply(this, arguments); - - var adaptiveHeight = 0; - if (isVertical(props.iconPosition)) { - // 图标高度和文字高度默认相等 - adaptiveHeight += (props.textHeight || 16) * 2; - adaptiveHeight += props.iconGap || 0; - var tGap = props.tgap || props.vgap || 2; - var bGap = props.bgap || props.vgap || 2; - adaptiveHeight += (tGap + bGap); + static xtype = "bi.button"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig(props) { + const conf = super._defaultConfig.apply(this, arguments); + + let adaptiveHeight = 0; + if (isVertical(props.iconPosition)) { + // 图标高度和文字高度默认相等 + adaptiveHeight += (props.textHeight || 16) * 2; + adaptiveHeight += props.iconGap || 0; + let tGap = props.tgap || props.vgap || 2; + let bGap = props.bgap || props.vgap || 2; + adaptiveHeight += (tGap + bGap); + } + + let clearMinWidth = props.block === true || props.clear === true || props.plain; + + return { + ...conf, + baseCls: (conf.baseCls || "") + " bi-button" + ((BI.isIE() && BI.isIE9Below()) ? " hack" : ""), + attributes: { + tabIndex: 1, + }, + minWidth: clearMinWidth ? 0 : 80, + height: isVertical(props.iconPosition) ? adaptiveHeight : 24, + shadow: props.clear !== true, + isShadowShowingOnSelected: true, + readonly: true, + iconCls: "", + level: "common", + block: false, // 是否块状显示,即不显示边框,没有最小宽度的限制 + clear: false, // 是否去掉边框和背景 + ghost: false, // 是否幽灵显示, 即正常状态无背景 + loading: false, // 是否处于加载中 + light: false, // 是否使用浅色 + plain: false, // 是否是朴素按钮,和 clear 的区别是 plain 有悬浮效果 + textAlign: "center", + whiteSpace: "nowrap", + textWidth: null, + textHeight: null, + hgap: props.clear ? 0 : (props.plain && !props.text ? 4 : 10), + vgap: 0, + tgap: 0, + bgap: 0, + lgap: 0, + rgap: 0, + icon: "", + iconGap: 0, + iconPosition: "left", + } + } + + render() { + const o = this.options; + + // bi.center_adapt 作用:让 hgap 不影响 iconGap。 + createWidget({ + type: "bi.center_adapt", + horizontalAlign: o.textAlign, + element: this, + ref: (ref) => { + this.containerRef = ref; + }, + hgap: o.hgap, + vgap: o.vgap, + items: this.generateItems(), + }); + + // 如果 options 对应的属性为 true 则给元素添加 class + const classArr = ["block", "clear", "ghost", "plain", "loading", "light"]; + classArr.forEach(clz => { + if (BI.get(o, clz) === true) { + this.element.addClass(clz); } + }) - var clearMinWidth = props.block === true || props.clear === true || props.plain; - - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-button" + ((BI.isIE() && BI.isIE9Below()) ? " hack" : ""), - attributes: { - tabIndex: 1, - }, - minWidth: clearMinWidth ? 0 : 80, - height: isVertical(props.iconPosition) ? adaptiveHeight : 24, - shadow: props.clear !== true, - isShadowShowingOnSelected: true, - readonly: true, - iconCls: "", - level: "common", - block: false, // 是否块状显示,即不显示边框,没有最小宽度的限制 - clear: false, // 是否去掉边框和背景 - ghost: false, // 是否幽灵显示, 即正常状态无背景 - loading: false, // 是否处于加载中 - light: false, // 是否使用浅色 - plain: false, // 是否是朴素按钮,和 clear 的区别是 plain 有悬浮效果 - textAlign: "center", - whiteSpace: "nowrap", - textWidth: null, - textHeight: null, - hgap: props.clear ? 0 : (props.plain && !props.text ? 4 : 10), - vgap: 0, - tgap: 0, - bgap: 0, - lgap: 0, - rgap: 0, - icon: "", - iconGap: 0, - iconPosition: "left", - }); - }, - - render: function () { - var o = this.options, self = this; - - // bi.center_adapt 作用:让 hgap 不影响 iconGap。 - BI.createWidget({ - type: "bi.center_adapt", - horizontalAlign: o.textAlign, - element: this, - ref: (ref) => { - self.containerRef = ref; - }, - hgap: o.hgap, - vgap: o.vgap, - items: self.generateItems(), - }); + if (o.minWidth > 0) { + this.element.css({ "min-width": BI.pixFormat(o.minWidth) }); + } + } - // 如果 options 对应的属性为 true 则给元素添加 class - var classArr = ["block", "clear", "ghost", "plain", "loading", "light"]; - BI.each(classArr, function (_, clz) { - if (BI.get(o, clz) === true) { - self.element.addClass(clz); - } - }); + generateItems(defaultRenderIcon) { + const o = this.options; - if (o.minWidth > 0) { - this.element.css({ "min-width": BI.pixFormat(o.minWidth) }); - } - }, - - generateItems(defaultRenderIcon) { - var o = this.options; - - // 由于button默认情况下有个边框,所以要主动算行高 - var lineHeight, textHeight = o.textHeight; - var hasBorder = false; - if (BI.isNumber(o.height)) { - if (!isVertical(o.iconPosition)) { - if (!(o.clear && o.block && o.light)) { - hasBorder = true; - } - lineHeight = o.height; - } else { - lineHeight = textHeight; + // 由于button默认情况下有个边框,所以要主动算行高 + let lineHeight, textHeight = o.textHeight; + let hasBorder = false; + if (isNumber(o.height)) { + if (!isVertical(o.iconPosition)) { + if (!(o.clear && o.block && o.light)) { + hasBorder = true; } + lineHeight = o.height; + } else { + lineHeight = textHeight; } - if (!textHeight) { - if (o.whiteSpace === "nowrap") { - textHeight = lineHeight; - } + } + if (!textHeight) { + if (o.whiteSpace === "nowrap") { + textHeight = lineHeight; } - - var iconInvisible = !(o.loading || o.iconCls || o.icon || defaultRenderIcon); - - var maxTextWidth = Math.max(o.minWidth, o.width); - maxTextWidth -= (o.hgap * 2 + o.iconGap); - // 减去图标水平占位宽度 - maxTextWidth -= iconInvisible || isVertical(o.iconPosition) ? 0 : this._const.iconWidth; - var textWidth = BI.isNull(o.textWidth) ? maxTextWidth : Math.min(o.textWidth, maxTextWidth); - - this.text = BI.createWidget({ - type: "bi.label", - text: o.text, - whiteSpace: o.whiteSpace, - textAlign: o.textAlign, - textWidth: textWidth, - textHeight: BI.toPix(textHeight, hasBorder ? 2 : 0), + } + + const iconInvisible = !(o.loading || o.iconCls || o.icon || defaultRenderIcon); + + let maxTextWidth = Math.max(o.minWidth, o.width); + maxTextWidth -= (o.hgap * 2 + o.iconGap); + // 减去图标水平占位宽度 + maxTextWidth -= iconInvisible || isVertical(o.iconPosition) ? 0 : this._const.iconWidth; + const textWidth = BI.isNull(o.textWidth) ? maxTextWidth : Math.min(o.textWidth, maxTextWidth); + + this.text = createWidget({ + type: "bi.label", + text: o.text, + whiteSpace: o.whiteSpace, + textAlign: o.textAlign, + textWidth: textWidth, + textHeight: BI.toPix(textHeight, hasBorder ? 2 : 0), + height: BI.toPix(lineHeight, hasBorder ? 2 : 0), + value: o.value, + title: null, + }); + + if (iconInvisible) { + return [this.text]; + } + + this._iconRendered = true; + + if (isPlainObject(o.icon) && !o.loading) { + this.icon = createWidget(o.icon); + } else { + this.icon = createWidget({ + type: "bi.icon_label", + cls: o.loading ? loadingCls : (o.iconCls || o.icon), + width: this._const.iconWidth, height: BI.toPix(lineHeight, hasBorder ? 2 : 0), - value: o.value, - title: null, + lineHeight: BI.toPix(lineHeight, hasBorder ? 2 : 0), + // 不设置,自定义按钮无法居中 + iconWidth: o.iconWidth, + iconHeight: o.iconHeight, + invisible: iconInvisible, }); + } + + const gapContainer = { + lgap: o.iconPosition === "left" && o.text ? o.iconGap : 0, + rgap: o.iconPosition === "right" ? o.iconGap : 0, + tgap: o.iconPosition === "top" ? o.iconGap : 0, + bgap: o.iconPosition === "bottom" ? o.iconGap : 0, + }; + + const items = [this.icon, { el: this.text, ...gapContainer }]; + if (o.iconPosition === "right" || o.iconPosition === "bottom") { + items.reverse(); + } + + return [{ + type: isVertical(o.iconPosition) ? "bi.vertical" : "bi.horizontal", + horizontalAlign: "center", + verticalAlign: "middle", + items, + }]; + } - if (iconInvisible) { - return [this.text]; - } + doClick() { + super.doClick.apply(this, arguments); + if (this.isValid()) { + this.fireEvent(Button.EVENT_CHANGE, this); + } + } - this._iconRendered = true; + _setEnable(enable) { + super._setEnable.apply(this, arguments); + if (enable === true) { + this.element.attr("tabIndex", 1); + } else if (enable === false) { + this.element.removeAttr("tabIndex"); + } + } - if (BI.isPlainObject(o.icon) && !o.loading) { - this.icon = BI.createWidget(o.icon); - } else { - this.icon = BI.createWidget({ - type: "bi.icon_label", - cls: o.loading ? loadingCls : (o.iconCls || o.icon), - width: this._const.iconWidth, - height: BI.toPix(lineHeight, hasBorder ? 2 : 0), - lineHeight: BI.toPix(lineHeight, hasBorder ? 2 : 0), - // 不设置,自定义按钮无法居中 - iconWidth: o.iconWidth, - iconHeight: o.iconHeight, - invisible: iconInvisible, - }); - } + beforeClick() { + return this.isLoading(); + } - var gapContainer = { - lgap: o.iconPosition === "left" && o.text ? o.iconGap : 0, - rgap: o.iconPosition === "right" ? o.iconGap : 0, - tgap: o.iconPosition === "top" ? o.iconGap : 0, - bgap: o.iconPosition === "bottom" ? o.iconGap : 0, - }; + isLoading() { + return this._loading === undefined ? this.options.loading : this._loading; + } - var items = [this.icon, BI.extend({ el: this.text }, gapContainer)]; - if (o.iconPosition === "right" || o.iconPosition === "bottom") { - items.reverse(); - } + loading() { + this._loading = true; + this.element.addClass("loading"); + !this._iconRendered && this.containerRef.populate(this.generateItems(true)); + if (this.icon.loading) { + this.icon.loading(); + } else { + // loadingCls 可以覆盖 iconCls 所以不需要移除 iconCls + this.icon.element.addClass(loadingCls); + this.icon.setVisible(true); + } + } - return [{ - type: isVertical(o.iconPosition) ? "bi.vertical" : "bi.horizontal", - horizontalAlign: "center", - verticalAlign: "middle", - items, - }]; - }, - - doClick: function () { - BI.Button.superclass.doClick.apply(this, arguments); - if (this.isValid()) { - this.fireEvent(BI.Button.EVENT_CHANGE, this); - } - }, - - _setEnable: function (enable) { - BI.Button.superclass._setEnable.apply(this, arguments); - if (enable === true) { - this.element.attr("tabIndex", 1); - } else if (enable === false) { - this.element.removeAttr("tabIndex"); - } - }, - - beforeClick: function () { - return this.isLoading(); - }, - - isLoading: function () { - return this._loading === undefined ? this.options.loading : this._loading; - }, - - loading: function () { - this._loading = true; - this.element.addClass("loading"); - !this._iconRendered && this.containerRef.populate(this.generateItems(true)); - if (this.icon.loading) { - this.icon.loading(); - } else { - // loadingCls 可以覆盖 iconCls 所以不需要移除 iconCls - this.icon.element.addClass(loadingCls); - this.icon.setVisible(true); - } - }, + loaded() { + this._loading = false; + this.element.removeClass("loading"); + if (this.icon.loaded) { + this.icon.loaded(); + } else { + this.icon.element.removeClass(loadingCls); + this.icon.setVisible(!!this.options.iconCls); + } + } - loaded: function () { - this._loading = false; - this.element.removeClass("loading"); - if (this.icon.loaded) { - this.icon.loaded(); - } else { - this.icon.element.removeClass(loadingCls); - this.icon.setVisible(!!this.options.iconCls); - } - }, + setText(text) { + super.setText.apply(this, arguments); + this.text.setText(text); + } - setText: function (text) { - BI.Button.superclass.setText.apply(this, arguments); - this.text.setText(text); - }, + setValue(text) { + super.setValue.apply(this, arguments); + if (!this.isReadOnly()) { + this.text.setValue(text); + } + } + + setIcon(cls) { + const o = this.options; + !this._iconRendered && this.containerRef.populate(this.generateItems(true)); + if (this.icon && o.iconCls !== cls) { + this.icon.element.removeClass(o.iconCls).addClass(cls); + o.iconCls = cls; + } + } + + doRedMark() { + this.text.doRedMark.apply(this.text, arguments); + } + + unRedMark() { + this.text.unRedMark.apply(this.text, arguments); + } + + doHighLight() { + this.text.doHighLight.apply(this.text, arguments); + } + + unHighLight() { + this.text.unHighLight.apply(this.text, arguments); + } +} - setValue: function (text) { - BI.Button.superclass.setValue.apply(this, arguments); - if (!this.isReadOnly()) { - this.text.setValue(text); - } - }, - - setIcon: function (cls) { - var o = this.options; - !this._iconRendered && this.containerRef.populate(this.generateItems(true)); - if (this.icon && o.iconCls !== cls) { - this.icon.element.removeClass(o.iconCls).addClass(cls); - o.iconCls = cls; - } - }, - - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, - - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, - - doHighLight: function () { - this.text.doHighLight.apply(this.text, arguments); - }, - - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - }, - }); - BI.shortcut("bi.button", BI.Button); - BI.Button.EVENT_CHANGE = "EVENT_CHANGE"; -}()); diff --git a/src/base/single/button/buttons/button.text.js b/src/base/single/button/buttons/button.text.js index 38470c291..a7fed2d76 100644 --- a/src/base/single/button/buttons/button.text.js +++ b/src/base/single/button/buttons/button.text.js @@ -1,15 +1,23 @@ +import { BasicButton } from "../button.basic"; +import { shortcut, extend, createWidget } from "../../../../core"; + /** * guy * 可以点击的一行文字 - * @class BI.TextButton - * @extends BI.BasicButton + * @class TextButton + * @extends BasicButton * 文字button */ -BI.TextButton = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - var conf = BI.TextButton.superclass._defaultConfig.apply(this, arguments); +@shortcut() +export class TextButton extends BasicButton { + + static xtype = "bi.text_button"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); - return BI.extend(conf, { + return extend(conf, { baseCls: (conf.baseCls || "") + " bi-text-button", textAlign: "center", whiteSpace: "nowrap", @@ -21,11 +29,11 @@ BI.TextButton = BI.inherit(BI.BasicButton, { vgap: 0, py: "", }); - }, + } - render: function () { - var o = this.options; - this.text = BI.createWidget({ + render() { + const o = this.options; + this.text = createWidget({ type: "bi.label", element: this, textAlign: o.textAlign, @@ -43,48 +51,46 @@ BI.TextButton = BI.inherit(BI.BasicButton, { py: o.py, keyword: o.keyword, }); - }, + } - doClick: function () { - BI.TextButton.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); if (this.isValid()) { this.fireEvent(BI.TextButton.EVENT_CHANGE, this.getValue(), this); } - }, + } - doRedMark: function () { + doRedMark() { this.text.doRedMark.apply(this.text, arguments); - }, + } - unRedMark: function () { + unRedMark() { this.text.unRedMark.apply(this.text, arguments); - }, + } - doHighLight: function () { + doHighLight() { this.text.doHighLight.apply(this.text, arguments); - }, + } - unHighLight: function () { + unHighLight() { this.text.unHighLight.apply(this.text, arguments); - }, + } - setText: function (text) { - BI.TextButton.superclass.setText.apply(this, arguments); + setText(text) { + super.setText.apply(this, arguments); text = BI.isArray(text) ? text.join(",") : text; this.text.setText(text); - }, + } - setStyle: function (style) { + setStyle(style) { this.text.setStyle(style); - }, + } - setValue: function (text) { - BI.TextButton.superclass.setValue.apply(this, arguments); + setValue(text) { + super.setValue.apply(this, arguments); if (!this.isReadOnly()) { text = BI.isArray(text) ? text.join(",") : text; this.text.setValue(text); } - }, -}); -BI.TextButton.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.text_button", BI.TextButton); + } +} diff --git a/src/base/single/button/listitem/blankiconicontextitem.js b/src/base/single/button/listitem/blankiconicontextitem.js index 1f6419008..b826fb558 100644 --- a/src/base/single/button/listitem/blankiconicontextitem.js +++ b/src/base/single/button/listitem/blankiconicontextitem.js @@ -1,14 +1,21 @@ +import { BasicButton } from "../button.basic" +import { emptyFn, shortcut } from "../../../../core" + /** * 带有一个占位 * * Created by GUY on 2015/9/11. - * @class BI.BlankIconIconTextItem - * @extends BI.BasicButton + * @class BlankIconIconTextItem + * @extends BasicButton */ -BI.BlankIconIconTextItem = BI.inherit(BI.BasicButton, { +@shortcut() +export class BlankIconIconTextItem extends BasicButton { + + static EVENT_CHANGE = "EVENT_CHANGE"; + static xtype = "bi.blank_icon_icon_text_item"; - _defaultConfig: function () { - var conf = BI.BlankIconIconTextItem.superclass._defaultConfig.apply(this, arguments); + _defaultConfig() { + var conf = super._defaultConfig(arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-blank-icon-icon-text-item", @@ -22,10 +29,10 @@ BI.BlankIconIconTextItem = BI.inherit(BI.BasicButton, { textLgap: 0, textRgap: 0, }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; return { type: "bi.vertical_adapt", @@ -50,8 +57,8 @@ BI.BlankIconIconTextItem = BI.inherit(BI.BasicButton, { }, { el: { type: "bi.label", - ref: function (_ref) { - self.text = _ref; + ref: (_ref) => { + this.text = _ref; }, textAlign: "left", hgap: o.textHgap, @@ -65,54 +72,52 @@ BI.BlankIconIconTextItem = BI.inherit(BI.BasicButton, { }, }], }; - }, + } - doClick: function () { - BI.BlankIconIconTextItem.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); if (this.isValid()) { - this.fireEvent(BI.BlankIconIconTextItem.EVENT_CHANGE, this.getValue(), this); + this.fireEvent(BlankIconIconTextItem.EVENT_CHANGE, this.getValue(), this); } - }, + } - setSelected: function (b) { - BI.BlankIconIconTextItem.superclass.setSelected.apply(this, arguments); + setSelected(b) { + super.setSelected.apply(this, arguments); this.icon1.setSelected(b); this.icon2.setSelected(b); - }, + } - setValue: function () { + setValue() { if (!this.isReadOnly()) { this.text.setValue.apply(this.text, arguments); } - }, + } - getValue: function () { + getValue() { return this.text.getValue(); - }, + } - setText: function () { + setText() { this.text.setText.apply(this.text, arguments); - }, + } - getText: function () { + getText() { return this.text.getText(); - }, + } - doRedMark: function () { + doRedMark() { this.text.doRedMark.apply(this.text, arguments); - }, + } - unRedMark: function () { + unRedMark() { this.text.unRedMark.apply(this.text, arguments); - }, + } - doHighLight: function () { + doHighLight() { this.text.doHighLight.apply(this.text, arguments); - }, + } - unHighLight: function () { + unHighLight() { this.text.unHighLight.apply(this.text, arguments); - }, -}); -BI.BlankIconIconTextItem.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.blank_icon_icon_text_item", BI.BlankIconIconTextItem); + } +} diff --git a/src/base/single/button/listitem/blankicontexticonitem.js b/src/base/single/button/listitem/blankicontexticonitem.js index 34dc9e7d8..91b7bcbe2 100644 --- a/src/base/single/button/listitem/blankicontexticonitem.js +++ b/src/base/single/button/listitem/blankicontexticonitem.js @@ -1,17 +1,24 @@ +import { BasicButton } from "../button.basic" +import { emptyFn, shortcut, extend } from "../../../../core" + /** * guy * 一个占位符和两个icon和一行数 组成的一行listitem * * Created by GUY on 2015/9/15. - * @class BI.BlankIconTextIconItem - * @extends BI.BasicButton + * @class BlankIconTextIconItem + * @extends BasicButton */ -BI.BlankIconTextIconItem = BI.inherit(BI.BasicButton, { +@shortcut() +export class BlankIconTextIconItem extends BasicButton { + + static xtype = "bi.blank_icon_text_icon_item"; + static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig: function () { - var conf = BI.BlankIconTextIconItem.superclass._defaultConfig.apply(this, arguments); + _defaultConfig() { + const conf = super._defaultConfig(arguments); - return BI.extend(conf, { + return extend(conf, { baseCls: (conf.baseCls || "") + " bi-blank-icon-text-icon-item", iconCls1: "", iconCls2: "", @@ -23,10 +30,10 @@ BI.BlankIconTextIconItem = BI.inherit(BI.BasicButton, { textLgap: 0, textRgap: 0, }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; return { type: "bi.vertical_adapt", @@ -44,8 +51,8 @@ BI.BlankIconTextIconItem = BI.inherit(BI.BasicButton, { }, { el: { type: "bi.label", - ref: function (_ref) { - self.text = _ref; + ref: (_ref) => { + this.text = _ref; }, textAlign: "left", hgap: o.textHgap, @@ -66,48 +73,47 @@ BI.BlankIconTextIconItem = BI.inherit(BI.BasicButton, { iconHeight: o.iconHeight, }], }; - }, + } - doClick: function () { - BI.BlankIconTextIconItem.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); if (this.isValid()) { this.fireEvent(BI.BlankIconTextIconItem.EVENT_CHANGE, this.getValue(), this); } - }, + } - doRedMark: function () { + doRedMark() { this.text.doRedMark.apply(this.text, arguments); - }, + } - unRedMark: function () { + unRedMark() { this.text.unRedMark.apply(this.text, arguments); - }, + } - doHighLight: function () { + doHighLight() { this.text.doHighLight.apply(this.text, arguments); - }, + } - unHighLight: function () { + unHighLight() { this.text.unHighLight.apply(this.text, arguments); - }, + } - setValue: function () { + setValue() { if (!this.isReadOnly()) { this.text.setValue.apply(this.text, arguments); } - }, + } - getValue: function () { + getValue() { return this.text.getValue(); - }, + } - setText: function () { + setText() { this.text.setText.apply(this.text, arguments); - }, + } - getText: function () { + getText() { return this.text.getText(); - }, -}); -BI.BlankIconTextIconItem.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.blank_icon_text_icon_item", BI.BlankIconTextIconItem); + } +} + diff --git a/src/base/single/button/listitem/blankicontextitem.js b/src/base/single/button/listitem/blankicontextitem.js index 08f13d22d..fb63eb8fb 100644 --- a/src/base/single/button/listitem/blankicontextitem.js +++ b/src/base/single/button/listitem/blankicontextitem.js @@ -1,16 +1,23 @@ +import { BasicButton } from "../button.basic" +import { extend, shortcut } from "../../../../core" + /** * 带有一个占位 * * Created by GUY on 2015/9/11. - * @class BI.BlankIconTextItem - * @extends BI.BasicButton + * @class BlankIconTextItem + * @extends BasicButton */ -BI.BlankIconTextItem = BI.inherit(BI.BasicButton, { +@shortcut() +export class BlankIconTextItem extends BasicButton { + + static xtype = "bi.blank_icon_text_item"; + static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig: function () { - var conf = BI.BlankIconTextItem.superclass._defaultConfig.apply(this, arguments); + _defaultConfig() { + const conf = super._defaultConfig(arguments); - return BI.extend(conf, { + return extend(conf, { baseCls: (conf.baseCls || "") + " bi-blank-icon-text-item", blankWidth: 0, iconHeight: null, @@ -21,10 +28,10 @@ BI.BlankIconTextItem = BI.inherit(BI.BasicButton, { textLgap: 0, textRgap: 0, }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; return { type: "bi.vertical_adapt", @@ -42,8 +49,8 @@ BI.BlankIconTextItem = BI.inherit(BI.BasicButton, { }, { el: { type: "bi.label", - ref: function (_ref) { - self.text = _ref; + ref: (_ref) => { + this.text = _ref; }, cls: "list-item-text", textAlign: "left", @@ -58,48 +65,46 @@ BI.BlankIconTextItem = BI.inherit(BI.BasicButton, { }, }], }; - }, + } - doClick: function () { - BI.BlankIconTextItem.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); if (this.isValid()) { - this.fireEvent(BI.BlankIconTextItem.EVENT_CHANGE, this.getValue(), this); + this.fireEvent(BlankIconTextItem.EVENT_CHANGE, this.getValue(), this); } - }, + } - setValue: function () { + setValue() { if (!this.isReadOnly()) { this.text.setValue.apply(this.text, arguments); } - }, + } - getValue: function () { + getValue() { return this.text.getValue(); - }, + } - setText: function () { + setText() { this.text.setText.apply(this.text, arguments); - }, + } - getText: function () { + getText() { return this.text.getText(); - }, + } - doRedMark: function () { + doRedMark() { this.text.doRedMark.apply(this.text, arguments); - }, + } - unRedMark: function () { + unRedMark() { this.text.unRedMark.apply(this.text, arguments); - }, + } - doHighLight: function () { + doHighLight() { this.text.doHighLight.apply(this.text, arguments); - }, + } - unHighLight: function () { + unHighLight() { this.text.unHighLight.apply(this.text, arguments); - }, -}); -BI.BlankIconTextItem.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.blank_icon_text_item", BI.BlankIconTextItem); + } +} diff --git a/src/base/single/button/listitem/icontexticonitem.js b/src/base/single/button/listitem/icontexticonitem.js index 425f47d90..8aadfdd47 100644 --- a/src/base/single/button/listitem/icontexticonitem.js +++ b/src/base/single/button/listitem/icontexticonitem.js @@ -1,17 +1,25 @@ +import { BasicButton } from "../button.basic" +import { extend, shortcut } from "../../../../core" + /** * guy * 两个icon和一行数 组成的一行listitem * * Created by GUY on 2015/9/9. - * @class BI.IconTextIconItem - * @extends BI.BasicButton + * @class IconTextIconItem + * @extends BasicButton */ -BI.IconTextIconItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - var conf = BI.IconTextIconItem.superclass._defaultConfig.apply(this, arguments); +@shortcut() +export class IconTextIconItem extends BasicButton { + + static EVENT_CHANGE = "EVENT_CHANGE"; + static xtype = "bi.icon_text_icon_item"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); - return BI.extend(conf, { + return extend(conf, { baseCls: (conf.baseCls || "") + " bi-icon-text-icon-item", iconCls1: "", iconCls2: "", @@ -22,10 +30,10 @@ BI.IconTextIconItem = BI.inherit(BI.BasicButton, { textLgap: 0, textRgap: 0, }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; return { type: "bi.vertical_adapt", @@ -40,8 +48,8 @@ BI.IconTextIconItem = BI.inherit(BI.BasicButton, { }, { el: { type: "bi.label", - ref: function (_ref) { - self.text = _ref; + ref: (_ref) => { + this.text = _ref; }, textAlign: "left", hgap: o.textHgap, @@ -62,48 +70,46 @@ BI.IconTextIconItem = BI.inherit(BI.BasicButton, { iconHeight: o.iconHeight, }], }; - }, + } - doClick: function () { - BI.IconTextIconItem.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); if (this.isValid()) { - this.fireEvent(BI.IconTextIconItem.EVENT_CHANGE, this.getValue(), this); + this.fireEvent(IconTextIconItem.EVENT_CHANGE, this.getValue(), this); } - }, + } - doRedMark: function () { + doRedMark() { this.text.doRedMark.apply(this.text, arguments); - }, + } - unRedMark: function () { + unRedMark() { this.text.unRedMark.apply(this.text, arguments); - }, + } - doHighLight: function () { + doHighLight() { this.text.doHighLight.apply(this.text, arguments); - }, + } - unHighLight: function () { + unHighLight() { this.text.unHighLight.apply(this.text, arguments); - }, + } - setValue: function () { + setValue() { if (!this.isReadOnly()) { this.text.setValue.apply(this.text, arguments); } - }, + } - getValue: function () { + getValue() { return this.text.getValue(); - }, + } - setText: function () { + setText() { this.text.setText.apply(this.text, arguments); - }, + } - getText: function () { + getText() { return this.text.getText(); - }, -}); -BI.IconTextIconItem.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.icon_text_icon_item", BI.IconTextIconItem); + } +} diff --git a/src/base/single/button/listitem/icontextitem.js b/src/base/single/button/listitem/icontextitem.js index 8fff16335..7aa02bdb3 100644 --- a/src/base/single/button/listitem/icontextitem.js +++ b/src/base/single/button/listitem/icontextitem.js @@ -1,16 +1,23 @@ +import { BasicButton } from "../button.basic" +import { extend, shortcut } from "../../../../core" + /** * guy * * Created by GUY on 2015/9/9. - * @class BI.IconTextItem - * @extends BI.BasicButton + * @class IconTextItem + * @extends BasicButton */ -BI.IconTextItem = BI.inherit(BI.BasicButton, { +@shortcut() +export class IconTextItem extends BasicButton { + + static EVENT_CHANGE = "EVENT_CHANGE"; + static xtype = "bi.icon_text_item"; - _defaultConfig: function () { - var conf = BI.IconTextItem.superclass._defaultConfig.apply(this, arguments); + _defaultConfig() { + const conf = super._defaultConfig(arguments); - return BI.extend(conf, { + return extend(conf, { baseCls: (conf.baseCls || "") + " bi-icon-text-item", direction: BI.Direction.Left, iconWrapperWidth: null, @@ -22,10 +29,10 @@ BI.IconTextItem = BI.inherit(BI.BasicButton, { textLgap: 0, textRgap: 0, }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; return { type: "bi.vertical_adapt", @@ -40,8 +47,8 @@ BI.IconTextItem = BI.inherit(BI.BasicButton, { }, { el: { type: "bi.label", - ref: function (_ref) { - self.text = _ref; + ref: (_ref) => { + this.text = _ref; }, cls: "list-item-text", textAlign: "left", @@ -56,48 +63,46 @@ BI.IconTextItem = BI.inherit(BI.BasicButton, { }, }], }; - }, + } - doClick: function () { - BI.IconTextItem.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); if (this.isValid()) { this.fireEvent(BI.IconTextItem.EVENT_CHANGE, this.getValue(), this); } - }, + } - setValue: function () { + setValue() { if (!this.isReadOnly()) { this.text.setValue.apply(this.text, arguments); } - }, + } - getValue: function () { + getValue() { return this.text.getValue(); - }, + } - setText: function () { + setText() { this.text.setText.apply(this.text, arguments); - }, + } - getText: function () { + getText() { return this.text.getText(); - }, + } - doRedMark: function () { + doRedMark() { this.text.doRedMark.apply(this.text, arguments); - }, + } - unRedMark: function () { + unRedMark() { this.text.unRedMark.apply(this.text, arguments); - }, + } - doHighLight: function () { + doHighLight() { this.text.doHighLight.apply(this.text, arguments); - }, + } - unHighLight: function () { + unHighLight() { this.text.unHighLight.apply(this.text, arguments); - }, -}); -BI.IconTextItem.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.icon_text_item", BI.IconTextItem); + } +} diff --git a/src/base/single/button/listitem/texticonitem.js b/src/base/single/button/listitem/texticonitem.js index a0ece74e6..a8b8077fd 100644 --- a/src/base/single/button/listitem/texticonitem.js +++ b/src/base/single/button/listitem/texticonitem.js @@ -1,17 +1,24 @@ +import { BasicButton } from "../button.basic" +import { extend, shortcut } from "../../../../core" + /** * * 图标的button * * Created by GUY on 2015/9/9. - * @class BI.TextIconItem - * @extends BI.BasicButton + * @class TextIconItem + * @extends BasicButton */ -BI.TextIconItem = BI.inherit(BI.BasicButton, { +@shortcut() +export class TextIconItem extends BasicButton { + + static xtype = "bi.text_icon_item"; + static EVENT_CHANGE = "EVENT_CHANGE" - _defaultConfig: function () { - var conf = BI.TextIconItem.superclass._defaultConfig.apply(this, arguments); + _defaultConfig() { + const conf = super._defaultConfig(arguments); - return BI.extend(conf, { + return extend(conf, { baseCls: (conf.baseCls || "") + " bi-text-icon-item", iconWrapperWidth: null, iconHeight: null, @@ -22,10 +29,10 @@ BI.TextIconItem = BI.inherit(BI.BasicButton, { textLgap: 0, textRgap: 0, }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; return { type: "bi.vertical_adapt", @@ -56,48 +63,46 @@ BI.TextIconItem = BI.inherit(BI.BasicButton, { iconHeight: o.iconHeight, }], }; - }, + } - doClick: function () { - BI.TextIconItem.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); if (this.isValid()) { - this.fireEvent(BI.TextIconItem.EVENT_CHANGE, this.getValue(), this); + this.fireEvent(TextIconItem.EVENT_CHANGE, this.getValue(), this); } - }, + } - setValue: function () { + setValue() { if (!this.isReadOnly()) { this.text.setValue.apply(this.text, arguments); } - }, + } - getValue: function () { + getValue() { return this.text.getValue(); - }, + } - setText: function () { + setText() { this.text.setText.apply(this.text, arguments); - }, + } - getText: function () { + getText() { return this.text.getText(); - }, + } - doRedMark: function () { + doRedMark() { this.text.doRedMark.apply(this.text, arguments); - }, + } - unRedMark: function () { + unRedMark() { this.text.unRedMark.apply(this.text, arguments); - }, + } - doHighLight: function () { + doHighLight() { this.text.doHighLight.apply(this.text, arguments); - }, + } - unHighLight: function () { + unHighLight() { this.text.unHighLight.apply(this.text, arguments); - }, -}); -BI.TextIconItem.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.text_icon_item", BI.TextIconItem); + } +} diff --git a/src/base/single/button/listitem/textitem.js b/src/base/single/button/listitem/textitem.js index c4c810295..82fa1e7ea 100644 --- a/src/base/single/button/listitem/textitem.js +++ b/src/base/single/button/listitem/textitem.js @@ -1,17 +1,24 @@ +import { BasicButton } from "../button.basic" +import { extend, shortcut } from "../../../../core" + /** * guy * 一个button和一行数 组成的一行listitem * * Created by GUY on 2015/9/9. - * @class BI.TextItem - * @extends BI.BasicButton + * @class TextItem + * @extends BasicButton */ -BI.TextItem = BI.inherit(BI.BasicButton, { +@shortcut +export class TextItem extends BasicButton { + + static xtype = "bi.text_item"; + static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig: function () { - var conf = BI.TextItem.superclass._defaultConfig.apply(this, arguments); + _defaultConfig() { + const conf = super._defaultConfig(arguments); - return BI.extend(conf, { + return extend(conf, { baseCls: (conf.baseCls || "") + " bi-text-item", textAlign: "left", whiteSpace: "nowrap", @@ -20,10 +27,10 @@ BI.TextItem = BI.inherit(BI.BasicButton, { textLgap: 0, textRgap: 0, }); - }, + } - render: function () { - var o = this.options; + render() { + const o = this.options; this.text = BI.createWidget({ type: "bi.label", element: this, @@ -40,48 +47,46 @@ BI.TextItem = BI.inherit(BI.BasicButton, { keyword: o.keyword, py: o.py, }); - }, + } - doClick: function () { - BI.TextItem.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); if (this.isValid()) { this.fireEvent(BI.TextItem.EVENT_CHANGE, this.getValue(), this); } - }, + } - doRedMark: function () { + doRedMark() { this.text.doRedMark.apply(this.text, arguments); - }, + } - unRedMark: function () { + unRedMark() { this.text.unRedMark.apply(this.text, arguments); - }, + } - doHighLight: function () { + doHighLight() { this.text.doHighLight.apply(this.text, arguments); - }, + } - unHighLight: function () { + unHighLight() { this.text.unHighLight.apply(this.text, arguments); - }, + } - setValue: function () { + setValue() { if (!this.isReadOnly()) { this.text.setValue.apply(this.text, arguments); } - }, + } - getValue: function () { + getValue() { return this.text.getValue(); - }, + } - setText: function () { + setText() { this.text.setText.apply(this.text, arguments); - }, + } - getText: function () { + getText() { return this.text.getText(); - }, -}); -BI.TextItem.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.text_item", BI.TextItem); + } +} diff --git a/src/base/single/button/node/icontexticonnode.js b/src/base/single/button/node/icontexticonnode.js index 7569490eb..7cbff7f74 100644 --- a/src/base/single/button/node/icontexticonnode.js +++ b/src/base/single/button/node/icontexticonnode.js @@ -1,15 +1,22 @@ +import { NodeButton } from "../button.node" +import { extend, shortcut } from "../../../../core" + /** * guy * Created by GUY on 2015/9/9. - * @class BI.IconTextIconNode - * @extends BI.NodeButton + * @class IconTextIconNode + * @extends NodeButton */ -BI.IconTextIconNode = BI.inherit(BI.NodeButton, { +@shortcut() +export class IconTextIconNode extends NodeButton { + + static xtype = "bi.icon_text_icon_node"; + static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig: function () { - var conf = BI.IconTextIconNode.superclass._defaultConfig.apply(this, arguments); + _defaultConfig() { + const conf = super._defaultConfig(arguments); - return BI.extend(conf, { + return extend(conf, { baseCls: (conf.baseCls || "") + " bi-icon-text-icon-node", iconCls1: "close-ha-font", iconCls2: "close-ha-font", @@ -20,10 +27,10 @@ BI.IconTextIconNode = BI.inherit(BI.NodeButton, { textLgap: 0, textRgap: 0, }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; return { type: "bi.vertical_adapt", @@ -38,8 +45,8 @@ BI.IconTextIconNode = BI.inherit(BI.NodeButton, { }, { el: { type: "bi.label", - ref: function (_ref) { - self.text = _ref; + ref: (_ref) => { + this.text = _ref; }, textAlign: "left", hgap: o.textHgap, @@ -60,40 +67,38 @@ BI.IconTextIconNode = BI.inherit(BI.NodeButton, { iconHeight: o.iconHeight, }], }; - }, + } - doClick: function () { - BI.IconTextIconNode.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); if (this.isValid()) { - this.fireEvent(BI.IconTextIconNode.EVENT_CHANGE, this.getValue(), this); + this.fireEvent(IconTextIconNode.EVENT_CHANGE, this.getValue(), this); } - }, + } - doRedMark: function () { + doRedMark() { this.text.doRedMark.apply(this.text, arguments); - }, + } - unRedMark: function () { + unRedMark() { this.text.unRedMark.apply(this.text, arguments); - }, + } - setValue: function () { + setValue() { if (!this.isReadOnly()) { this.text.setValue.apply(this.text, arguments); } - }, + } - getValue: function () { + getValue() { return this.text.getValue(); - }, + } - setText: function () { + setText() { this.text.setText.apply(this.text, arguments); - }, + } - getText: function () { + getText() { return this.text.getText(); - }, -}); -BI.IconTextIconNode.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.icon_text_icon_node", BI.IconTextIconNode); + } +} diff --git a/src/base/single/button/node/icontextnode.js b/src/base/single/button/node/icontextnode.js index 16383cc7d..6a6260432 100644 --- a/src/base/single/button/node/icontextnode.js +++ b/src/base/single/button/node/icontextnode.js @@ -1,15 +1,22 @@ +import { NodeButton } from "../button.node" +import { extend, shortcut } from "../../../../core" + /** * guy * Created by GUY on 2015/9/9. - * @class BI.IconTextNode - * @extends BI.NodeButton + * @class IconTextNode + * @extends NodeButton */ -BI.IconTextNode = BI.inherit(BI.NodeButton, { +@shortcut() +export class IconTextNode extends NodeButton { + + static EVENT_CHANGE = "EVENT_CHANGE"; + static xtype = "bi.icon_text_node"; - _defaultConfig: function () { - var conf = BI.IconTextNode.superclass._defaultConfig.apply(this, arguments); + _defaultConfig() { + const conf = super._defaultConfig(arguments); - return BI.extend(conf, { + return extend(conf, { baseCls: (conf.baseCls || "") + " bi-icon-text-node", cls: "close-ha-font", iconHeight: null, @@ -19,10 +26,10 @@ BI.IconTextNode = BI.inherit(BI.NodeButton, { textLgap: 0, textRgap: 0, }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; return { type: "bi.vertical_adapt", @@ -37,8 +44,8 @@ BI.IconTextNode = BI.inherit(BI.NodeButton, { }, { el: { type: "bi.label", - ref: function (_ref) { - self.text = _ref; + ref: (_ref) => { + this.text = _ref; }, cls: "list-item-text", textAlign: "left", @@ -53,40 +60,39 @@ BI.IconTextNode = BI.inherit(BI.NodeButton, { }, }], }; - }, + } - doClick: function () { - BI.IconTextNode.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); if (this.isValid()) { this.fireEvent(BI.IconTextNode.EVENT_CHANGE, this.getValue(), this); } - }, + } - setValue: function () { + setValue() { if (!this.isReadOnly()) { this.text.setValue.apply(this.text, arguments); } - }, + } - getValue: function () { + getValue() { return this.text.getValue(); - }, + } - setText: function () { + setText() { this.text.setText.apply(this.text, arguments); - }, + } - getText: function () { + getText() { return this.text.getText(); - }, + } - doRedMark: function () { + doRedMark() { this.text.doRedMark.apply(this.text, arguments); - }, + } - unRedMark: function () { + unRedMark() { this.text.unRedMark.apply(this.text, arguments); - }, -}); -BI.IconTextNode.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.icon_text_node", BI.IconTextNode); + } +} + diff --git a/src/base/single/button/node/texticonnode.js b/src/base/single/button/node/texticonnode.js index 01167b009..02a205047 100644 --- a/src/base/single/button/node/texticonnode.js +++ b/src/base/single/button/node/texticonnode.js @@ -1,14 +1,21 @@ +import { NodeButton } from "../button.node" +import { extend, shortcut } from "../../../../core" + /** * Created by GUY on 2015/9/9. - * @class BI.TextIconNode - * @extends BI.NodeButton + * @class TextIconNode + * @extends NodeButton */ -BI.TextIconNode = BI.inherit(BI.NodeButton, { +@shortcut() +export default class TextIconNode extends NodeButton { + + static EVENT_CHANGE = "EVENT_CHANGE"; + static xtype = "bi.text_icon_node"; - _defaultConfig: function () { - var conf = BI.TextIconNode.superclass._defaultConfig.apply(this, arguments); + _defaultConfig() { + const conf = super._defaultConfig(arguments); - return BI.extend(conf, { + return extend(conf, { baseCls: (conf.baseCls || "") + " bi-text-icon-node", cls: "close-ha-font", iconHeight: null, @@ -18,10 +25,10 @@ BI.TextIconNode = BI.inherit(BI.NodeButton, { textLgap: 0, textRgap: 0, }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; return { type: "bi.vertical_adapt", @@ -29,8 +36,8 @@ BI.TextIconNode = BI.inherit(BI.NodeButton, { items: [{ el: { type: "bi.label", - ref: function (_ref) { - self.text = _ref; + ref: (_ref) => { + this.text = _ref; }, cls: "list-item-text", textAlign: "left", @@ -52,40 +59,38 @@ BI.TextIconNode = BI.inherit(BI.NodeButton, { iconHeight: o.iconHeight, }], }; - }, + } - doClick: function () { - BI.TextIconNode.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); if (this.isValid()) { - this.fireEvent(BI.TextIconNode.EVENT_CHANGE, this.getValue(), this); + this.fireEvent(TextIconNode.EVENT_CHANGE, this.getValue(), this); } - }, + } - setValue: function () { + setValue() { if (!this.isReadOnly()) { this.text.setValue.apply(this.text, arguments); } - }, + } - getValue: function () { + getValue() { return this.text.getValue(); - }, + } - setText: function () { + setText() { this.text.setText.apply(this.text, arguments); - }, + } - getText: function () { + getText() { return this.text.getText(); - }, + } - doRedMark: function () { + doRedMark() { this.text.doRedMark.apply(this.text, arguments); - }, + } - unRedMark: function () { + unRedMark() { this.text.unRedMark.apply(this.text, arguments); - }, -}); -BI.TextIconNode.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.text_icon_node", BI.TextIconNode); + } +} diff --git a/src/base/single/button/node/textnode.js b/src/base/single/button/node/textnode.js index 6ecaa3fbf..80aadb0d3 100644 --- a/src/base/single/button/node/textnode.js +++ b/src/base/single/button/node/textnode.js @@ -1,16 +1,25 @@ +import { NodeButton } from "../button.node" +import { extend, shortcut } from "../../../../core" + /** * guy * * Created by GUY on 2015/9/9. - * @class BI.TextNode - * @extends BI.NodeButton + * @class TextNode + * @extends NodeButton */ -BI.TextNode = BI.inherit(BI.NodeButton, { +@shortcut() +export class TextNode extends NodeButton { + + static xtype = "bi.text_node" + + static EVENT_CHANGE = "EVENT_CHANGE" + - _defaultConfig: function () { - var conf = BI.TextNode.superclass._defaultConfig.apply(this, arguments); + _defaultConfig() { + const conf = super._defaultConfig(arguments); - return BI.extend(conf, { + return extend(conf, { baseCls: (conf.baseCls || "") + " bi-text-node", textAlign: "left", whiteSpace: "nowrap", @@ -19,10 +28,10 @@ BI.TextNode = BI.inherit(BI.NodeButton, { textLgap: 0, textRgap: 0, }); - }, + } - render: function () { - var o = this.options; + render() { + const o = this.options; this.text = BI.createWidget({ type: "bi.label", element: this, @@ -39,40 +48,38 @@ BI.TextNode = BI.inherit(BI.NodeButton, { keyword: o.keyword, py: o.py, }); - }, + } - doClick: function () { - BI.TextNode.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); if (this.isValid()) { - this.fireEvent(BI.TextNode.EVENT_CHANGE, this.getValue(), this); + this.fireEvent(TextNode.EVENT_CHANGE, this.getValue(), this); } - }, + } - doRedMark: function () { + doRedMark() { this.text.doRedMark.apply(this.text, arguments); - }, + } - unRedMark: function () { + unRedMark() { this.text.unRedMark.apply(this.text, arguments); - }, + } - setValue: function () { + setValue() { if (!this.isReadOnly()) { this.text.setValue.apply(this.text, arguments); } - }, + } - getValue: function () { + getValue() { return this.text.getValue(); - }, + } - setText: function () { + setText() { this.text.setText.apply(this.text, arguments); - }, + } - getText: function () { + getText() { return this.text.getText(); - }, -}); -BI.TextNode.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.text_node", BI.TextNode); + } +} diff --git a/src/core/index.js b/src/core/index.js index 18b15a0f2..f4fcbf7c2 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -41,6 +41,9 @@ export * from './2.base'; export * from './4.widget'; export * from './5.inject'; +// 有了后删掉 +export const emptyFn = () => { } + export { shortcut, OB, From bceffd1a0a0cf6383dafbbfadb895849f93be3a8 Mon Sep 17 00:00:00 2001 From: zsmj Date: Wed, 4 Jan 2023 15:03:24 +0800 Subject: [PATCH 032/300] =?UTF-8?q?KERNEL-14012=20feat:=20core/structure?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=A4=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/structure/aes.js | 4036 ++++++++--------- src/core/structure/aspect.js | 103 +- src/core/structure/base64.js | 216 +- src/core/structure/cache.js | 47 +- .../structure/cellSizeAndPositionManager.js | 212 +- src/core/structure/heap.js | 168 +- src/core/structure/index.js | 44 + src/core/structure/linkedHashMap.js | 116 +- src/core/structure/lru.js | 38 +- src/core/structure/prefixIntervalTree.js | 291 +- src/core/structure/queue.js | 143 +- src/core/structure/sectionManager.js | 121 +- src/core/structure/tree.js | 934 ++-- src/core/structure/vector.js | 61 +- 14 files changed, 3277 insertions(+), 3253 deletions(-) create mode 100644 src/core/structure/index.js diff --git a/src/core/structure/aes.js b/src/core/structure/aes.js index ec5d6b86a..b21b49aaa 100644 --- a/src/core/structure/aes.js +++ b/src/core/structure/aes.js @@ -1,2346 +1,2342 @@ -!(function () { - /* - CryptoJS v3.1.2 - code.google.com/p/crypto-js - (c) 2009-2013 by Jeff Mott. All rights reserved. - code.google.com/p/crypto-js/wiki/License - */ +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +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) { /** - * CryptoJS core components. + * CryptoJS namespace. */ - BI.CRYPT_TYPE = BI.CRYPT_TYPE || {}; - BI.CRYPT_TYPE.AES = "aes"; + const C = {}; - var CryptoJS = CryptoJS || (function (Math, undefined) { - /** - * CryptoJS namespace. - */ - var C = {}; - - /** - * Library namespace. - */ - var C_lib = C.lib = {}; - - /** - * Base object for prototypal inheritance. - */ - var Base = C_lib.Base = (function () { - function F () { - } - - return { - /** - * Creates a new object that inherits from this object. - * - * @param {Object} overrides Properties to copy into the new object. - * - * @return {Object} The new object. - * - * @static - * - * @example - * - * var MyType = CryptoJS.lib.Base.extend({ - * field: 'value', - * - * method: function () { - * } - * }); - */ - extend: function (overrides) { - // Spawn - F.prototype = this; - var subtype = new F(); - - // Augment - if (overrides) { - subtype.mixIn(overrides); - } - - // Create default initializer - if (!subtype.hasOwnProperty('init')) { - subtype.init = function () { - subtype.$super.init.apply(this, arguments); - }; - } - - // Initializer's prototype is the subtype object - subtype.init.prototype = subtype; - - // Reference supertype - subtype.$super = this; - - return subtype; - }, - - /** - * Extends this object and runs the init method. - * Arguments to create() will be passed to init(). - * - * @return {Object} The new object. - * - * @static - * - * @example - * - * var instance = MyType.create(); - */ - create: function () { - var instance = this.extend(); - instance.init.apply(instance, arguments); - - return instance; - }, - - /** - * Initializes a newly created object. - * Override this method to add some logic when your objects are created. - * - * @example - * - * var MyType = CryptoJS.lib.Base.extend({ - * init: function () { - * // ... - * } - * }); - */ - init: function () { - }, - - /** - * Copies properties into this object. - * - * @param {Object} properties The properties to mix in. - * - * @example - * - * MyType.mixIn({ - * field: 'value' - * }); - */ - mixIn: function (properties) { - for (var propertyName in properties) { - if (properties.hasOwnProperty(propertyName)) { - this[propertyName] = properties[propertyName]; - } - } + /** + * Library namespace. + */ + const C_lib = C.lib = {}; - // IE won't copy toString using the loop above - if (properties.hasOwnProperty('toString')) { - this.toString = properties.toString; - } - }, - - /** - * Creates a copy of this object. - * - * @return {Object} The clone. - * - * @example - * - * var clone = instance.clone(); - */ - clone: function () { - return this.init.prototype.extend(this); - } - }; - }()); + /** + * Base object for prototypal inheritance. + */ + const Base = C_lib.Base = (function () { + function F() { + } - /** - * An array of 32-bit words. - * - * @property {Array} words The array of 32-bit words. - * @property {number} sigBytes The number of significant bytes in this word array. - */ - var WordArray = C_lib.WordArray = Base.extend({ + return { /** - * Initializes a newly created word array. - * - * @param {Array} words (Optional) An array of 32-bit words. - * @param {number} sigBytes (Optional) The number of significant bytes in the words. - * - * @example + * Creates a new object that inherits from this object. * - * var wordArray = CryptoJS.lib.WordArray.create(); - * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); - * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); - */ - init: function (words, sigBytes) { - words = this.words = words || []; - - if (sigBytes != undefined) { - this.sigBytes = sigBytes; - } else { - this.sigBytes = words.length * 4; - } - }, - - /** - * Converts this word array to a string. + * @param {Object} overrides Properties to copy into the new object. * - * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex + * @return {Object} The new object. * - * @return {string} The stringified word array. + * @static * * @example * - * var string = wordArray + ''; - * var string = wordArray.toString(); - * var string = wordArray.toString(CryptoJS.enc.Utf8); - */ - toString: function (encoder) { - return (encoder || Hex).stringify(this); - }, - - /** - * Concatenates a word array to this word array. - * - * @param {WordArray} wordArray The word array to append. - * - * @return {WordArray} This word array. - * - * @example + * var MyType = CryptoJS.lib.Base.extend({ + * field: 'value', * - * wordArray1.concat(wordArray2); + * method: function () { + * } + * }); */ - concat: function (wordArray) { - // Shortcuts - var thisWords = this.words; - var thatWords = wordArray.words; - var thisSigBytes = this.sigBytes; - var thatSigBytes = wordArray.sigBytes; - - // Clamp excess bits - this.clamp(); - - // Concat - if (thisSigBytes % 4) { - // Copy one byte at a time - for (var i = 0; i < thatSigBytes; i++) { - var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); - } - } else if (thatWords.length > 0xffff) { - // Copy one word at a time - for (var i = 0; i < thatSigBytes; i += 4) { - thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; - } - } else { - // Copy all words at once - thisWords.push.apply(thisWords, thatWords); + extend: function (overrides) { + // Spawn + F.prototype = this; + const subtype = new F(); + + // Augment + if (overrides) { + subtype.mixIn(overrides); } - this.sigBytes += thatSigBytes; - - // Chainable - return this; - }, - /** - * Removes insignificant bits. - * - * @example - * - * wordArray.clamp(); - */ - clamp: function () { - // Shortcuts - var words = this.words; - var sigBytes = this.sigBytes; + // Create default initializer + if (!subtype.hasOwnProperty("init")) { + subtype.init = function () { + subtype.$super.init.apply(this, arguments); + }; + } - // Clamp - words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); - words.length = Math.ceil(sigBytes / 4); - }, + // Initializer's prototype is the subtype object + subtype.init.prototype = subtype; - /** - * Creates a copy of this word array. - * - * @return {WordArray} The clone. - * - * @example - * - * var clone = wordArray.clone(); - */ - clone: function () { - var clone = Base.clone.call(this); - clone.words = this.words.slice(0); + // Reference supertype + subtype.$super = this; - return clone; + return subtype; }, /** - * Creates a word array filled with random bytes. + * Extends this object and runs the init method. + * Arguments to create() will be passed to init(). * - * @param {number} nBytes The number of random bytes to generate. - * - * @return {WordArray} The random word array. + * @return {Object} The new object. * * @static * * @example * - * var wordArray = CryptoJS.lib.WordArray.random(16); + * var instance = MyType.create(); */ - random: function (nBytes) { - var words = []; - for (var i = 0; i < nBytes; i += 4) { - words.push((Math.random() * 0x100000000) | 0); - } - - return new WordArray.init(words, nBytes); - } - }); + create: function () { + const instance = this.extend(); + instance.init.apply(instance, arguments); - /** - * Encoder namespace. - */ - var C_enc = C.enc = {}; + return instance; + }, - /** - * Hex encoding strategy. - */ - var Hex = C_enc.Hex = { /** - * Converts a word array to a hex string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The hex string. - * - * @static + * Initializes a newly created object. + * Override this method to add some logic when your objects are created. * * @example * - * var hexString = CryptoJS.enc.Hex.stringify(wordArray); + * var MyType = CryptoJS.lib.Base.extend({ + * init: function () { + * // ... + * } + * }); */ - stringify: function (wordArray) { - // Shortcuts - var words = wordArray.words; - var sigBytes = wordArray.sigBytes; - - // Convert - var hexChars = []; - for (var i = 0; i < sigBytes; i++) { - var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - hexChars.push((bite >>> 4).toString(16)); - hexChars.push((bite & 0x0f).toString(16)); - } - - return hexChars.join(''); + init: function () { }, /** - * Converts a hex string to a word array. - * - * @param {string} hexStr The hex string. - * - * @return {WordArray} The word array. + * Copies properties into this object. * - * @static + * @param {Object} properties The properties to mix in. * * @example * - * var wordArray = CryptoJS.enc.Hex.parse(hexString); + * MyType.mixIn({ + * field: 'value' + * }); */ - parse: function (hexStr) { - // Shortcut - var hexStrLength = hexStr.length; - - // Convert - var words = []; - for (var i = 0; i < hexStrLength; i += 2) { - words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); + mixIn: function (properties) { + for (const propertyName in properties) { + if (properties.hasOwnProperty(propertyName)) { + this[propertyName] = properties[propertyName]; + } } - return new WordArray.init(words, hexStrLength / 2); - } - }; - - /** - * Latin1 encoding strategy. - */ - var Latin1 = C_enc.Latin1 = { - /** - * Converts a word array to a Latin1 string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The Latin1 string. - * - * @static - * - * @example - * - * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); - */ - stringify: function (wordArray) { - // Shortcuts - var words = wordArray.words; - var sigBytes = wordArray.sigBytes; - - // Convert - var latin1Chars = []; - for (var i = 0; i < sigBytes; i++) { - var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - latin1Chars.push(String.fromCharCode(bite)); + // IE won't copy toString using the loop above + if (properties.hasOwnProperty("toString")) { + this.toString = properties.toString; } - - return latin1Chars.join(''); }, /** - * Converts a Latin1 string to a word array. - * - * @param {string} latin1Str The Latin1 string. - * - * @return {WordArray} The word array. + * Creates a copy of this object. * - * @static + * @return {Object} The clone. * * @example * - * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); + * var clone = instance.clone(); */ - parse: function (latin1Str) { - // Shortcut - var latin1StrLength = latin1Str.length; - - // Convert - var words = []; - for (var i = 0; i < latin1StrLength; i++) { - words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); - } - - return new WordArray.init(words, latin1StrLength); - } + clone: function () { + return this.init.prototype.extend(this); + }, }; + }()); + /** + * An array of 32-bit words. + * + * @property {Array} words The array of 32-bit words. + * @property {number} sigBytes The number of significant bytes in this word array. + */ + var WordArray = C_lib.WordArray = Base.extend({ /** - * UTF-8 encoding strategy. + * Initializes a newly created word array. + * + * @param {Array} words (Optional) An array of 32-bit words. + * @param {number} sigBytes (Optional) The number of significant bytes in the words. + * + * @example + * + * var wordArray = CryptoJS.lib.WordArray.create(); + * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); + * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ - var Utf8 = C_enc.Utf8 = { - /** - * Converts a word array to a UTF-8 string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The UTF-8 string. - * - * @static - * - * @example - * - * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); - */ - stringify: function (wordArray) { - try { - return decodeURIComponent(escape(Latin1.stringify(wordArray))); - } catch (e) { - throw new Error('Malformed UTF-8 data'); - } - }, + init: function (words, sigBytes) { + words = this.words = words || []; - /** - * Converts a UTF-8 string to a word array. - * - * @param {string} utf8Str The UTF-8 string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); - */ - parse: function (utf8Str) { - return Latin1.parse(unescape(encodeURIComponent(utf8Str))); + if (sigBytes != undefined) { + this.sigBytes = sigBytes; + } else { + this.sigBytes = words.length * 4; } - }; + }, /** - * Abstract buffered block algorithm template. + * Converts this word array to a string. + * + * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex + * + * @return {string} The stringified word array. * - * The property blockSize must be implemented in a concrete subtype. + * @example * - * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 + * var string = wordArray + ''; + * var string = wordArray.toString(); + * var string = wordArray.toString(CryptoJS.enc.Utf8); */ - var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ - /** - * Resets this block algorithm's data buffer to its initial state. - * - * @example - * - * bufferedBlockAlgorithm.reset(); - */ - reset: function () { - // Initial values - this._data = new WordArray.init(); - this._nDataBytes = 0; - }, + toString: function (encoder) { + return (encoder || Hex).stringify(this); + }, - /** - * Adds new data to this block algorithm's buffer. - * - * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. - * - * @example - * - * bufferedBlockAlgorithm._append('data'); - * bufferedBlockAlgorithm._append(wordArray); - */ - _append: function (data) { - // Convert string to WordArray, else assume WordArray already - if (typeof data == 'string') { - data = Utf8.parse(data); + /** + * Concatenates a word array to this word array. + * + * @param {WordArray} wordArray The word array to append. + * + * @return {WordArray} This word array. + * + * @example + * + * wordArray1.concat(wordArray2); + */ + concat: function (wordArray) { + // Shortcuts + const thisWords = this.words; + const thatWords = wordArray.words; + const thisSigBytes = this.sigBytes; + const thatSigBytes = wordArray.sigBytes; + + // Clamp excess bits + this.clamp(); + + // Concat + if (thisSigBytes % 4) { + // Copy one byte at a time + for (var i = 0; i < thatSigBytes; i++) { + const thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } - - // Append - this._data.concat(data); - this._nDataBytes += data.sigBytes; - }, - - /** - * Processes available data blocks. - * - * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. - * - * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. - * - * @return {WordArray} The processed data. - * - * @example - * - * var processedData = bufferedBlockAlgorithm._process(); - * var processedData = bufferedBlockAlgorithm._process(!!'flush'); - */ - _process: function (doFlush) { - // Shortcuts - var data = this._data; - var dataWords = data.words; - var dataSigBytes = data.sigBytes; - var blockSize = this.blockSize; - var blockSizeBytes = blockSize * 4; - - // Count blocks ready - var nBlocksReady = dataSigBytes / blockSizeBytes; - if (doFlush) { - // Round up to include partial blocks - nBlocksReady = Math.ceil(nBlocksReady); - } else { - // Round down to include only full blocks, - // less the number of blocks that must remain in the buffer - nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); + } else if (thatWords.length > 0xffff) { + // Copy one word at a time + for (var i = 0; i < thatSigBytes; i += 4) { + thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } + } else { + // Copy all words at once + thisWords.push.apply(thisWords, thatWords); + } + this.sigBytes += thatSigBytes; - // Count words ready - var nWordsReady = nBlocksReady * blockSize; - - // Count bytes ready - var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); + // Chainable + return this; + }, - // Process blocks - if (nWordsReady) { - for (var offset = 0; offset < nWordsReady; offset += blockSize) { - // Perform concrete-algorithm logic - this._doProcessBlock(dataWords, offset); - } + /** + * Removes insignificant bits. + * + * @example + * + * wordArray.clamp(); + */ + clamp: function () { + // Shortcuts + const words = this.words; + const sigBytes = this.sigBytes; + + // Clamp + words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); + words.length = Math.ceil(sigBytes / 4); + }, - // Remove processed words - var processedWords = dataWords.splice(0, nWordsReady); - data.sigBytes -= nBytesReady; - } + /** + * Creates a copy of this word array. + * + * @return {WordArray} The clone. + * + * @example + * + * var clone = wordArray.clone(); + */ + clone: function () { + const clone = Base.clone.call(this); + clone.words = this.words.slice(0); - // Return processed words - return new WordArray.init(processedWords, nBytesReady); - }, + return clone; + }, - /** - * Creates a copy of this object. - * - * @return {Object} The clone. - * - * @example - * - * var clone = bufferedBlockAlgorithm.clone(); - */ - clone: function () { - var clone = Base.clone.call(this); - clone._data = this._data.clone(); + /** + * Creates a word array filled with random bytes. + * + * @param {number} nBytes The number of random bytes to generate. + * + * @return {WordArray} The random word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.lib.WordArray.random(16); + */ + random: function (nBytes) { + const words = []; + for (let i = 0; i < nBytes; i += 4) { + words.push((Math.random() * 0x100000000) | 0); + } - return clone; - }, + return new WordArray.init(words, nBytes); + }, + }); - _minBufferSize: 0 - }); + /** + * Encoder namespace. + */ + const C_enc = C.enc = {}; + /** + * Hex encoding strategy. + */ + var Hex = C_enc.Hex = { /** - * Abstract hasher template. + * Converts a word array to a hex string. * - * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) + * @param {WordArray} wordArray The word array. + * + * @return {string} The hex string. + * + * @static + * + * @example + * + * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ - var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ - /** - * Configuration options. - */ - cfg: Base.extend(), - - /** - * Initializes a newly created hasher. - * - * @param {Object} cfg (Optional) The configuration options to use for this hash computation. - * - * @example - * - * var hasher = CryptoJS.algo.SHA256.create(); - */ - init: function (cfg) { - // Apply config defaults - this.cfg = this.cfg.extend(cfg); - - // Set initial values - this.reset(); - }, + stringify: function (wordArray) { + // Shortcuts + const words = wordArray.words; + const sigBytes = wordArray.sigBytes; + + // Convert + const hexChars = []; + for (let i = 0; i < sigBytes; i++) { + const bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + hexChars.push((bite >>> 4).toString(16)); + hexChars.push((bite & 0x0f).toString(16)); + } - /** - * Resets this hasher to its initial state. - * - * @example - * - * hasher.reset(); - */ - reset: function () { - // Reset data buffer - BufferedBlockAlgorithm.reset.call(this); + return hexChars.join(""); + }, - // Perform concrete-hasher logic - this._doReset(); - }, - - /** - * Updates this hasher with a message. - * - * @param {WordArray|string} messageUpdate The message to append. - * - * @return {Hasher} This hasher. - * - * @example - * - * hasher.update('message'); - * hasher.update(wordArray); - */ - update: function (messageUpdate) { - // Append - this._append(messageUpdate); - - // Update the hash - this._process(); - - // Chainable - return this; - }, + /** + * Converts a hex string to a word array. + * + * @param {string} hexStr The hex string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Hex.parse(hexString); + */ + parse: function (hexStr) { + // Shortcut + const hexStrLength = hexStr.length; + + // Convert + const words = []; + for (let i = 0; i < hexStrLength; i += 2) { + words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); + } - /** - * Finalizes the hash computation. - * Note that the finalize operation is effectively a destructive, read-once operation. - * - * @param {WordArray|string} messageUpdate (Optional) A final message update. - * - * @return {WordArray} The hash. - * - * @example - * - * var hash = hasher.finalize(); - * var hash = hasher.finalize('message'); - * var hash = hasher.finalize(wordArray); - */ - finalize: function (messageUpdate) { - // Final message update - if (messageUpdate) { - this._append(messageUpdate); - } + return new WordArray.init(words, hexStrLength / 2); + }, + }; - // Perform concrete-hasher logic - var hash = this._doFinalize(); + /** + * Latin1 encoding strategy. + */ + const Latin1 = C_enc.Latin1 = { + /** + * Converts a word array to a Latin1 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The Latin1 string. + * + * @static + * + * @example + * + * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + const words = wordArray.words; + const sigBytes = wordArray.sigBytes; + + // Convert + const latin1Chars = []; + for (let i = 0; i < sigBytes; i++) { + const bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + latin1Chars.push(String.fromCharCode(bite)); + } - return hash; - }, + return latin1Chars.join(""); + }, - blockSize: 512 / 32, + /** + * Converts a Latin1 string to a word array. + * + * @param {string} latin1Str The Latin1 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); + */ + parse: function (latin1Str) { + // Shortcut + const latin1StrLength = latin1Str.length; + + // Convert + const words = []; + for (let i = 0; i < latin1StrLength; i++) { + words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); + } - /** - * Creates a shortcut function to a hasher's object interface. - * - * @param {Hasher} hasher The hasher to create a helper for. - * - * @return {Function} The shortcut function. - * - * @static - * - * @example - * - * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); - */ - _createHelper: function (hasher) { - return function (message, cfg) { - return new hasher.init(cfg).finalize(message); - }; - }, + return new WordArray.init(words, latin1StrLength); + }, + }; - /** - * Creates a shortcut function to the HMAC's object interface. - * - * @param {Hasher} hasher The hasher to use in this HMAC helper. - * - * @return {Function} The shortcut function. - * - * @static - * - * @example - * - * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); - */ - _createHmacHelper: function (hasher) { - return function (message, key) { - return new C_algo.HMAC.init(hasher, key).finalize(message); - }; + /** + * UTF-8 encoding strategy. + */ + const Utf8 = C_enc.Utf8 = { + /** + * Converts a word array to a UTF-8 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-8 string. + * + * @static + * + * @example + * + * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); + */ + stringify: function (wordArray) { + try { + return decodeURIComponent(escape(Latin1.stringify(wordArray))); + } catch (e) { + throw new Error("Malformed UTF-8 data"); } - }); + }, /** - * Algorithm namespace. + * Converts a UTF-8 string to a word array. + * + * @param {string} utf8Str The UTF-8 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ - var C_algo = C.algo = {}; - - return C; - }(Math)); - - /* - CryptoJS v3.1.2 - code.google.com/p/crypto-js - (c) 2009-2013 by Jeff Mott. All rights reserved. - code.google.com/p/crypto-js/wiki/License - */ - (function () { - // Shortcuts - var C = CryptoJS; - var C_lib = C.lib; - var WordArray = C_lib.WordArray; - var C_enc = C.enc; + parse: function (utf8Str) { + return Latin1.parse(unescape(encodeURIComponent(utf8Str))); + }, + }; + /** + * Abstract buffered block algorithm template. + * + * The property blockSize must be implemented in a concrete subtype. + * + * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 + */ + const BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** - * Base64 encoding strategy. + * Resets this block algorithm's data buffer to its initial state. + * + * @example + * + * bufferedBlockAlgorithm.reset(); */ - var Base64 = C_enc.Base64 = { - /** - * Converts a word array to a Base64 string. - * - * @param {WordArray} wordArray The word array. - * - * @return {string} The Base64 string. - * - * @static - * - * @example - * - * var base64String = CryptoJS.enc.Base64.stringify(wordArray); - */ - stringify: function (wordArray) { - // Shortcuts - var words = wordArray.words; - var sigBytes = wordArray.sigBytes; - var map = this._map; - - // Clamp excess bits - wordArray.clamp(); - - // Convert - var base64Chars = []; - for (var i = 0; i < sigBytes; i += 3) { - var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; - var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; + reset: function () { + // Initial values + this._data = new WordArray.init(); + this._nDataBytes = 0; + }, - var triplet = (byte1 << 16) | (byte2 << 8) | byte3; + /** + * Adds new data to this block algorithm's buffer. + * + * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. + * + * @example + * + * bufferedBlockAlgorithm._append('data'); + * bufferedBlockAlgorithm._append(wordArray); + */ + _append: function (data) { + // Convert string to WordArray, else assume WordArray already + if (typeof data == "string") { + data = Utf8.parse(data); + } - for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { - base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); - } - } + // Append + this._data.concat(data); + this._nDataBytes += data.sigBytes; + }, - // Add padding - var paddingChar = map.charAt(64); - if (paddingChar) { - while (base64Chars.length % 4) { - base64Chars.push(paddingChar); - } - } + /** + * Processes available data blocks. + * + * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. + * + * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. + * + * @return {WordArray} The processed data. + * + * @example + * + * var processedData = bufferedBlockAlgorithm._process(); + * var processedData = bufferedBlockAlgorithm._process(!!'flush'); + */ + _process: function (doFlush) { + // Shortcuts + const data = this._data; + const dataWords = data.words; + const dataSigBytes = data.sigBytes; + const blockSize = this.blockSize; + const blockSizeBytes = blockSize * 4; + + // Count blocks ready + let nBlocksReady = dataSigBytes / blockSizeBytes; + if (doFlush) { + // Round up to include partial blocks + nBlocksReady = Math.ceil(nBlocksReady); + } else { + // Round down to include only full blocks, + // less the number of blocks that must remain in the buffer + nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); + } - return base64Chars.join(''); - }, + // Count words ready + const nWordsReady = nBlocksReady * blockSize; - /** - * Converts a Base64 string to a word array. - * - * @param {string} base64Str The Base64 string. - * - * @return {WordArray} The word array. - * - * @static - * - * @example - * - * var wordArray = CryptoJS.enc.Base64.parse(base64String); - */ - parse: function (base64Str) { - // Shortcuts - var base64StrLength = base64Str.length; - var map = this._map; - - // Ignore padding - var paddingChar = map.charAt(64); - if (paddingChar) { - var paddingIndex = base64Str.indexOf(paddingChar); - if (paddingIndex != -1) { - base64StrLength = paddingIndex; - } - } + // Count bytes ready + const nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); - // Convert - var words = []; - var nBytes = 0; - for (var i = 0; i < base64StrLength; i++) { - if (i % 4) { - var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); - var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); - words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); - nBytes++; - } + // Process blocks + if (nWordsReady) { + for (let offset = 0; offset < nWordsReady; offset += blockSize) { + // Perform concrete-algorithm logic + this._doProcessBlock(dataWords, offset); } - return WordArray.create(words, nBytes); - }, - - _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' - }; - }()); - - /* - CryptoJS v3.1.2 - code.google.com/p/crypto-js - (c) 2009-2013 by Jeff Mott. All rights reserved. - code.google.com/p/crypto-js/wiki/License - */ - (function (Math) { - // Shortcuts - var C = CryptoJS; - var C_lib = C.lib; - var WordArray = C_lib.WordArray; - var Hasher = C_lib.Hasher; - var C_algo = C.algo; - - // Constants table - var T = []; - - // Compute constants - (function () { - for (var i = 0; i < 64; i++) { - T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; + // Remove processed words + var processedWords = dataWords.splice(0, nWordsReady); + data.sigBytes -= nBytesReady; } - }()); + + // Return processed words + return new WordArray.init(processedWords, nBytesReady); + }, /** - * MD5 hash algorithm. + * Creates a copy of this object. + * + * @return {Object} The clone. + * + * @example + * + * var clone = bufferedBlockAlgorithm.clone(); */ - var MD5 = C_algo.MD5 = Hasher.extend({ - _doReset: function () { - this._hash = new WordArray.init([ - 0x67452301, 0xefcdab89, - 0x98badcfe, 0x10325476 - ]); - }, - - _doProcessBlock: function (M, offset) { - // Swap endian - for (var i = 0; i < 16; i++) { - // Shortcuts - var offset_i = offset + i; - var M_offset_i = M[offset_i]; - - M[offset_i] = ( - (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | - (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) - ); - } + clone: function () { + const clone = Base.clone.call(this); + clone._data = this._data.clone(); - // Shortcuts - var H = this._hash.words; - - var M_offset_0 = M[offset + 0]; - var M_offset_1 = M[offset + 1]; - var M_offset_2 = M[offset + 2]; - var M_offset_3 = M[offset + 3]; - var M_offset_4 = M[offset + 4]; - var M_offset_5 = M[offset + 5]; - var M_offset_6 = M[offset + 6]; - var M_offset_7 = M[offset + 7]; - var M_offset_8 = M[offset + 8]; - var M_offset_9 = M[offset + 9]; - var M_offset_10 = M[offset + 10]; - var M_offset_11 = M[offset + 11]; - var M_offset_12 = M[offset + 12]; - var M_offset_13 = M[offset + 13]; - var M_offset_14 = M[offset + 14]; - var M_offset_15 = M[offset + 15]; - - // Working varialbes - var a = H[0]; - var b = H[1]; - var c = H[2]; - var d = H[3]; - - // Computation - a = FF(a, b, c, d, M_offset_0, 7, T[0]); - d = FF(d, a, b, c, M_offset_1, 12, T[1]); - c = FF(c, d, a, b, M_offset_2, 17, T[2]); - b = FF(b, c, d, a, M_offset_3, 22, T[3]); - a = FF(a, b, c, d, M_offset_4, 7, T[4]); - d = FF(d, a, b, c, M_offset_5, 12, T[5]); - c = FF(c, d, a, b, M_offset_6, 17, T[6]); - b = FF(b, c, d, a, M_offset_7, 22, T[7]); - a = FF(a, b, c, d, M_offset_8, 7, T[8]); - d = FF(d, a, b, c, M_offset_9, 12, T[9]); - c = FF(c, d, a, b, M_offset_10, 17, T[10]); - b = FF(b, c, d, a, M_offset_11, 22, T[11]); - a = FF(a, b, c, d, M_offset_12, 7, T[12]); - d = FF(d, a, b, c, M_offset_13, 12, T[13]); - c = FF(c, d, a, b, M_offset_14, 17, T[14]); - b = FF(b, c, d, a, M_offset_15, 22, T[15]); - - a = GG(a, b, c, d, M_offset_1, 5, T[16]); - d = GG(d, a, b, c, M_offset_6, 9, T[17]); - c = GG(c, d, a, b, M_offset_11, 14, T[18]); - b = GG(b, c, d, a, M_offset_0, 20, T[19]); - a = GG(a, b, c, d, M_offset_5, 5, T[20]); - d = GG(d, a, b, c, M_offset_10, 9, T[21]); - c = GG(c, d, a, b, M_offset_15, 14, T[22]); - b = GG(b, c, d, a, M_offset_4, 20, T[23]); - a = GG(a, b, c, d, M_offset_9, 5, T[24]); - d = GG(d, a, b, c, M_offset_14, 9, T[25]); - c = GG(c, d, a, b, M_offset_3, 14, T[26]); - b = GG(b, c, d, a, M_offset_8, 20, T[27]); - a = GG(a, b, c, d, M_offset_13, 5, T[28]); - d = GG(d, a, b, c, M_offset_2, 9, T[29]); - c = GG(c, d, a, b, M_offset_7, 14, T[30]); - b = GG(b, c, d, a, M_offset_12, 20, T[31]); - - a = HH(a, b, c, d, M_offset_5, 4, T[32]); - d = HH(d, a, b, c, M_offset_8, 11, T[33]); - c = HH(c, d, a, b, M_offset_11, 16, T[34]); - b = HH(b, c, d, a, M_offset_14, 23, T[35]); - a = HH(a, b, c, d, M_offset_1, 4, T[36]); - d = HH(d, a, b, c, M_offset_4, 11, T[37]); - c = HH(c, d, a, b, M_offset_7, 16, T[38]); - b = HH(b, c, d, a, M_offset_10, 23, T[39]); - a = HH(a, b, c, d, M_offset_13, 4, T[40]); - d = HH(d, a, b, c, M_offset_0, 11, T[41]); - c = HH(c, d, a, b, M_offset_3, 16, T[42]); - b = HH(b, c, d, a, M_offset_6, 23, T[43]); - a = HH(a, b, c, d, M_offset_9, 4, T[44]); - d = HH(d, a, b, c, M_offset_12, 11, T[45]); - c = HH(c, d, a, b, M_offset_15, 16, T[46]); - b = HH(b, c, d, a, M_offset_2, 23, T[47]); - - a = II(a, b, c, d, M_offset_0, 6, T[48]); - d = II(d, a, b, c, M_offset_7, 10, T[49]); - c = II(c, d, a, b, M_offset_14, 15, T[50]); - b = II(b, c, d, a, M_offset_5, 21, T[51]); - a = II(a, b, c, d, M_offset_12, 6, T[52]); - d = II(d, a, b, c, M_offset_3, 10, T[53]); - c = II(c, d, a, b, M_offset_10, 15, T[54]); - b = II(b, c, d, a, M_offset_1, 21, T[55]); - a = II(a, b, c, d, M_offset_8, 6, T[56]); - d = II(d, a, b, c, M_offset_15, 10, T[57]); - c = II(c, d, a, b, M_offset_6, 15, T[58]); - b = II(b, c, d, a, M_offset_13, 21, T[59]); - a = II(a, b, c, d, M_offset_4, 6, T[60]); - d = II(d, a, b, c, M_offset_11, 10, T[61]); - c = II(c, d, a, b, M_offset_2, 15, T[62]); - b = II(b, c, d, a, M_offset_9, 21, T[63]); - - // Intermediate hash value - H[0] = (H[0] + a) | 0; - H[1] = (H[1] + b) | 0; - H[2] = (H[2] + c) | 0; - H[3] = (H[3] + d) | 0; - }, - - _doFinalize: function () { - // Shortcuts - var data = this._data; - var dataWords = data.words; - - var nBitsTotal = this._nDataBytes * 8; - var nBitsLeft = data.sigBytes * 8; + return clone; + }, - // Add padding - dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + _minBufferSize: 0, + }); - var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); - var nBitsTotalL = nBitsTotal; - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( - (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | - (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) - ); - dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( - (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | - (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) - ); + /** + * Abstract hasher template. + * + * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) + */ + const Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ + /** + * Configuration options. + */ + cfg: Base.extend(), - data.sigBytes = (dataWords.length + 1) * 4; + /** + * Initializes a newly created hasher. + * + * @param {Object} cfg (Optional) The configuration options to use for this hash computation. + * + * @example + * + * var hasher = CryptoJS.algo.SHA256.create(); + */ + init: function (cfg) { + // Apply config defaults + this.cfg = this.cfg.extend(cfg); - // Hash final blocks - this._process(); + // Set initial values + this.reset(); + }, - // Shortcuts - var hash = this._hash; - var H = hash.words; + /** + * Resets this hasher to its initial state. + * + * @example + * + * hasher.reset(); + */ + reset: function () { + // Reset data buffer + BufferedBlockAlgorithm.reset.call(this); - // Swap endian - for (var i = 0; i < 4; i++) { - // Shortcut - var H_i = H[i]; + // Perform concrete-hasher logic + this._doReset(); + }, - H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | - (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); - } + /** + * Updates this hasher with a message. + * + * @param {WordArray|string} messageUpdate The message to append. + * + * @return {Hasher} This hasher. + * + * @example + * + * hasher.update('message'); + * hasher.update(wordArray); + */ + update: function (messageUpdate) { + // Append + this._append(messageUpdate); - // Return final computed hash - return hash; - }, + // Update the hash + this._process(); - clone: function () { - var clone = Hasher.clone.call(this); - clone._hash = this._hash.clone(); + // Chainable + return this; + }, - return clone; + /** + * Finalizes the hash computation. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} messageUpdate (Optional) A final message update. + * + * @return {WordArray} The hash. + * + * @example + * + * var hash = hasher.finalize(); + * var hash = hasher.finalize('message'); + * var hash = hasher.finalize(wordArray); + */ + finalize: function (messageUpdate) { + // Final message update + if (messageUpdate) { + this._append(messageUpdate); } - }); - - function FF (a, b, c, d, x, s, t) { - var n = a + ((b & c) | (~b & d)) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } - function GG (a, b, c, d, x, s, t) { - var n = a + ((b & d) | (c & ~d)) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } + // Perform concrete-hasher logic + const hash = this._doFinalize(); - function HH (a, b, c, d, x, s, t) { - var n = a + (b ^ c ^ d) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } + return hash; + }, - function II (a, b, c, d, x, s, t) { - var n = a + (c ^ (b | ~d)) + x + t; - return ((n << s) | (n >>> (32 - s))) + b; - } + blockSize: 512 / 32, /** - * Shortcut function to the hasher's object interface. + * Creates a shortcut function to a hasher's object interface. * - * @param {WordArray|string} message The message to hash. + * @param {Hasher} hasher The hasher to create a helper for. * - * @return {WordArray} The hash. + * @return {Function} The shortcut function. * * @static * * @example * - * var hash = CryptoJS.MD5('message'); - * var hash = CryptoJS.MD5(wordArray); + * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ - C.MD5 = Hasher._createHelper(MD5); + _createHelper: function (hasher) { + return function (message, cfg) { + return new hasher.init(cfg).finalize(message); + }; + }, /** - * Shortcut function to the HMAC's object interface. + * Creates a shortcut function to the HMAC's object interface. * - * @param {WordArray|string} message The message to hash. - * @param {WordArray|string} key The secret key. + * @param {Hasher} hasher The hasher to use in this HMAC helper. * - * @return {WordArray} The HMAC. + * @return {Function} The shortcut function. * * @static * * @example * - * var hmac = CryptoJS.HmacMD5(message, key); + * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ - C.HmacMD5 = Hasher._createHmacHelper(MD5); - }(Math)); - - /* - CryptoJS v3.1.2 - code.google.com/p/crypto-js - (c) 2009-2013 by Jeff Mott. All rights reserved. - code.google.com/p/crypto-js/wiki/License - */ - (function () { - // Shortcuts - var C = CryptoJS; - var C_lib = C.lib; - var Base = C_lib.Base; - var WordArray = C_lib.WordArray; - var C_algo = C.algo; - var MD5 = C_algo.MD5; + _createHmacHelper: function (hasher) { + return function (message, key) { + return new C_algo.HMAC.init(hasher, key).finalize(message); + }; + }, + }); + /** + * Algorithm namespace. + */ + var C_algo = C.algo = {}; + + return C; +}(Math)); + +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function () { + // Shortcuts + const C = CryptoJS; + const C_lib = C.lib; + const WordArray = C_lib.WordArray; + const C_enc = C.enc; + + /** + * Base64 encoding strategy. + */ + const Base64 = C_enc.Base64 = { /** - * This key derivation function is meant to conform with EVP_BytesToKey. - * www.openssl.org/docs/crypto/EVP_BytesToKey.html + * Converts a word array to a Base64 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The Base64 string. + * + * @static + * + * @example + * + * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ - var EvpKDF = C_algo.EvpKDF = Base.extend({ - /** - * Configuration options. - * - * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) - * @property {Hasher} hasher The hash algorithm to use. Default: MD5 - * @property {number} iterations The number of iterations to perform. Default: 1 - */ - cfg: Base.extend({ - keySize: 128 / 32, - hasher: MD5, - iterations: 1 - }), - - /** - * Initializes a newly created key derivation function. - * - * @param {Object} cfg (Optional) The configuration options to use for the derivation. - * - * @example - * - * var kdf = CryptoJS.algo.EvpKDF.create(); - * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); - * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); - */ - init: function (cfg) { - this.cfg = this.cfg.extend(cfg); - }, - - /** - * Derives a key from a password. - * - * @param {WordArray|string} password The password. - * @param {WordArray|string} salt A salt. - * - * @return {WordArray} The derived key. - * - * @example - * - * var key = kdf.compute(password, salt); - */ - compute: function (password, salt) { - // Shortcut - var cfg = this.cfg; - - // Init hasher - var hasher = cfg.hasher.create(); - - // Initial values - var derivedKey = WordArray.create(); - - // Shortcuts - var derivedKeyWords = derivedKey.words; - var keySize = cfg.keySize; - var iterations = cfg.iterations; - - // Generate key - while (derivedKeyWords.length < keySize) { - if (block) { - hasher.update(block); - } - var block = hasher.update(password).finalize(salt); - hasher.reset(); - - // Iterations - for (var i = 1; i < iterations; i++) { - block = hasher.finalize(block); - hasher.reset(); - } - - derivedKey.concat(block); + stringify: function (wordArray) { + // Shortcuts + const words = wordArray.words; + const sigBytes = wordArray.sigBytes; + const map = this._map; + + // Clamp excess bits + wordArray.clamp(); + + // Convert + const base64Chars = []; + for (let i = 0; i < sigBytes; i += 3) { + const byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + const byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; + const byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; + + const triplet = (byte1 << 16) | (byte2 << 8) | byte3; + + for (let j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { + base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } - derivedKey.sigBytes = keySize * 4; + } - return derivedKey; + // Add padding + const paddingChar = map.charAt(64); + if (paddingChar) { + while (base64Chars.length % 4) { + base64Chars.push(paddingChar); + } } - }); + + return base64Chars.join(""); + }, /** - * Derives a key from a password. + * Converts a Base64 string to a word array. * - * @param {WordArray|string} password The password. - * @param {WordArray|string} salt A salt. - * @param {Object} cfg (Optional) The configuration options to use for this computation. + * @param {string} base64Str The Base64 string. * - * @return {WordArray} The derived key. + * @return {WordArray} The word array. * * @static * * @example * - * var key = CryptoJS.EvpKDF(password, salt); - * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); - * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); + * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ - C.EvpKDF = function (password, salt, cfg) { - return EvpKDF.create(cfg).compute(password, salt); - }; - }()); + parse: function (base64Str) { + // Shortcuts + let base64StrLength = base64Str.length; + const map = this._map; + + // Ignore padding + const paddingChar = map.charAt(64); + if (paddingChar) { + const paddingIndex = base64Str.indexOf(paddingChar); + if (paddingIndex != -1) { + base64StrLength = paddingIndex; + } + } + // Convert + const words = []; + let nBytes = 0; + for (let i = 0; i < base64StrLength; i++) { + if (i % 4) { + const bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); + const bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); + words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); + nBytes++; + } + } + + return WordArray.create(words, nBytes); + }, + + _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", + }; +}()); + +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function (Math) { + // Shortcuts + const C = CryptoJS; + const C_lib = C.lib; + const WordArray = C_lib.WordArray; + const Hasher = C_lib.Hasher; + const C_algo = C.algo; + + // Constants table + const T = []; + + // Compute constants + (function () { + for (let i = 0; i < 64; i++) { + T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; + } + }()); - /* - CryptoJS v3.1.2 - code.google.com/p/crypto-js - (c) 2009-2013 by Jeff Mott. All rights reserved. - code.google.com/p/crypto-js/wiki/License - */ /** - * Cipher core components. + * MD5 hash algorithm. */ - CryptoJS.lib.Cipher || (function (undefined) { - // Shortcuts - var C = CryptoJS; - var C_lib = C.lib; - var Base = C_lib.Base; - var WordArray = C_lib.WordArray; - var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; - var C_enc = C.enc; - var Utf8 = C_enc.Utf8; - var Base64 = C_enc.Base64; - var C_algo = C.algo; - var EvpKDF = C_algo.EvpKDF; + const MD5 = C_algo.MD5 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0x67452301, 0xefcdab89, + 0x98badcfe, 0x10325476 + ]); + }, - /** - * Abstract base cipher template. - * - * @property {number} keySize This cipher's key size. Default: 4 (128 bits) - * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) - * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. - * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. - */ - var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ - /** - * Configuration options. - * - * @property {WordArray} iv The IV to use for this operation. - */ - cfg: Base.extend(), + _doProcessBlock: function (M, offset) { + // Swap endian + for (let i = 0; i < 16; i++) { + // Shortcuts + const offset_i = offset + i; + const M_offset_i = M[offset_i]; - /** - * Creates this cipher in encryption mode. - * - * @param {WordArray} key The key. - * @param {Object} cfg (Optional) The configuration options to use for this operation. - * - * @return {Cipher} A cipher instance. - * - * @static - * - * @example - * - * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); - */ - createEncryptor: function (key, cfg) { - return this.create(this._ENC_XFORM_MODE, key, cfg); - }, + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ); + } - /** - * Creates this cipher in decryption mode. - * - * @param {WordArray} key The key. - * @param {Object} cfg (Optional) The configuration options to use for this operation. - * - * @return {Cipher} A cipher instance. - * - * @static - * - * @example - * - * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); - */ - createDecryptor: function (key, cfg) { - return this.create(this._DEC_XFORM_MODE, key, cfg); - }, + // Shortcuts + const H = this._hash.words; + + const M_offset_0 = M[offset + 0]; + const M_offset_1 = M[offset + 1]; + const M_offset_2 = M[offset + 2]; + const M_offset_3 = M[offset + 3]; + const M_offset_4 = M[offset + 4]; + const M_offset_5 = M[offset + 5]; + const M_offset_6 = M[offset + 6]; + const M_offset_7 = M[offset + 7]; + const M_offset_8 = M[offset + 8]; + const M_offset_9 = M[offset + 9]; + const M_offset_10 = M[offset + 10]; + const M_offset_11 = M[offset + 11]; + const M_offset_12 = M[offset + 12]; + const M_offset_13 = M[offset + 13]; + const M_offset_14 = M[offset + 14]; + const M_offset_15 = M[offset + 15]; + + // Working varialbes + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + + // Computation + a = FF(a, b, c, d, M_offset_0, 7, T[0]); + d = FF(d, a, b, c, M_offset_1, 12, T[1]); + c = FF(c, d, a, b, M_offset_2, 17, T[2]); + b = FF(b, c, d, a, M_offset_3, 22, T[3]); + a = FF(a, b, c, d, M_offset_4, 7, T[4]); + d = FF(d, a, b, c, M_offset_5, 12, T[5]); + c = FF(c, d, a, b, M_offset_6, 17, T[6]); + b = FF(b, c, d, a, M_offset_7, 22, T[7]); + a = FF(a, b, c, d, M_offset_8, 7, T[8]); + d = FF(d, a, b, c, M_offset_9, 12, T[9]); + c = FF(c, d, a, b, M_offset_10, 17, T[10]); + b = FF(b, c, d, a, M_offset_11, 22, T[11]); + a = FF(a, b, c, d, M_offset_12, 7, T[12]); + d = FF(d, a, b, c, M_offset_13, 12, T[13]); + c = FF(c, d, a, b, M_offset_14, 17, T[14]); + b = FF(b, c, d, a, M_offset_15, 22, T[15]); + + a = GG(a, b, c, d, M_offset_1, 5, T[16]); + d = GG(d, a, b, c, M_offset_6, 9, T[17]); + c = GG(c, d, a, b, M_offset_11, 14, T[18]); + b = GG(b, c, d, a, M_offset_0, 20, T[19]); + a = GG(a, b, c, d, M_offset_5, 5, T[20]); + d = GG(d, a, b, c, M_offset_10, 9, T[21]); + c = GG(c, d, a, b, M_offset_15, 14, T[22]); + b = GG(b, c, d, a, M_offset_4, 20, T[23]); + a = GG(a, b, c, d, M_offset_9, 5, T[24]); + d = GG(d, a, b, c, M_offset_14, 9, T[25]); + c = GG(c, d, a, b, M_offset_3, 14, T[26]); + b = GG(b, c, d, a, M_offset_8, 20, T[27]); + a = GG(a, b, c, d, M_offset_13, 5, T[28]); + d = GG(d, a, b, c, M_offset_2, 9, T[29]); + c = GG(c, d, a, b, M_offset_7, 14, T[30]); + b = GG(b, c, d, a, M_offset_12, 20, T[31]); + + a = HH(a, b, c, d, M_offset_5, 4, T[32]); + d = HH(d, a, b, c, M_offset_8, 11, T[33]); + c = HH(c, d, a, b, M_offset_11, 16, T[34]); + b = HH(b, c, d, a, M_offset_14, 23, T[35]); + a = HH(a, b, c, d, M_offset_1, 4, T[36]); + d = HH(d, a, b, c, M_offset_4, 11, T[37]); + c = HH(c, d, a, b, M_offset_7, 16, T[38]); + b = HH(b, c, d, a, M_offset_10, 23, T[39]); + a = HH(a, b, c, d, M_offset_13, 4, T[40]); + d = HH(d, a, b, c, M_offset_0, 11, T[41]); + c = HH(c, d, a, b, M_offset_3, 16, T[42]); + b = HH(b, c, d, a, M_offset_6, 23, T[43]); + a = HH(a, b, c, d, M_offset_9, 4, T[44]); + d = HH(d, a, b, c, M_offset_12, 11, T[45]); + c = HH(c, d, a, b, M_offset_15, 16, T[46]); + b = HH(b, c, d, a, M_offset_2, 23, T[47]); + + a = II(a, b, c, d, M_offset_0, 6, T[48]); + d = II(d, a, b, c, M_offset_7, 10, T[49]); + c = II(c, d, a, b, M_offset_14, 15, T[50]); + b = II(b, c, d, a, M_offset_5, 21, T[51]); + a = II(a, b, c, d, M_offset_12, 6, T[52]); + d = II(d, a, b, c, M_offset_3, 10, T[53]); + c = II(c, d, a, b, M_offset_10, 15, T[54]); + b = II(b, c, d, a, M_offset_1, 21, T[55]); + a = II(a, b, c, d, M_offset_8, 6, T[56]); + d = II(d, a, b, c, M_offset_15, 10, T[57]); + c = II(c, d, a, b, M_offset_6, 15, T[58]); + b = II(b, c, d, a, M_offset_13, 21, T[59]); + a = II(a, b, c, d, M_offset_4, 6, T[60]); + d = II(d, a, b, c, M_offset_11, 10, T[61]); + c = II(c, d, a, b, M_offset_2, 15, T[62]); + b = II(b, c, d, a, M_offset_9, 21, T[63]); + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + }, - /** - * Initializes a newly created cipher. - * - * @param {number} xformMode Either the encryption or decryption transormation mode constant. - * @param {WordArray} key The key. - * @param {Object} cfg (Optional) The configuration options to use for this operation. - * - * @example - * - * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); - */ - init: function (xformMode, key, cfg) { - // Apply config defaults - this.cfg = this.cfg.extend(cfg); + _doFinalize: function () { + // Shortcuts + const data = this._data; + const dataWords = data.words; - // Store transform mode and key - this._xformMode = xformMode; - this._key = key; + const nBitsTotal = this._nDataBytes * 8; + const nBitsLeft = data.sigBytes * 8; - // Set initial values - this.reset(); - }, + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); - /** - * Resets this cipher to its initial state. - * - * @example - * - * cipher.reset(); - */ - reset: function () { - // Reset data buffer - BufferedBlockAlgorithm.reset.call(this); + const nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); + const nBitsTotalL = nBitsTotal; + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( + (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | + (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) + ); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | + (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) + ); - // Perform concrete-cipher logic - this._doReset(); - }, + data.sigBytes = (dataWords.length + 1) * 4; - /** - * Adds data to be encrypted or decrypted. - * - * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. - * - * @return {WordArray} The data after processing. - * - * @example - * - * var encrypted = cipher.process('data'); - * var encrypted = cipher.process(wordArray); - */ - process: function (dataUpdate) { - // Append - this._append(dataUpdate); + // Hash final blocks + this._process(); - // Process available blocks - return this._process(); - }, + // Shortcuts + const hash = this._hash; + const H = hash.words; - /** - * Finalizes the encryption or decryption process. - * Note that the finalize operation is effectively a destructive, read-once operation. - * - * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. - * - * @return {WordArray} The data after final processing. - * - * @example - * - * var encrypted = cipher.finalize(); - * var encrypted = cipher.finalize('data'); - * var encrypted = cipher.finalize(wordArray); - */ - finalize: function (dataUpdate) { - // Final data update - if (dataUpdate) { - this._append(dataUpdate); - } + // Swap endian + for (let i = 0; i < 4; i++) { + // Shortcut + const H_i = H[i]; - // Perform concrete-cipher logic - var finalProcessedData = this._doFinalize(); + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); + } - return finalProcessedData; - }, + // Return final computed hash + return hash; + }, + + clone: function () { + const clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + }, + }); + + function FF(a, b, c, d, x, s, t) { + const n = a + ((b & c) | (~b & d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function GG(a, b, c, d, x, s, t) { + const n = a + ((b & d) | (c & ~d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function HH(a, b, c, d, x, s, t) { + const n = a + (b ^ c ^ d) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function II(a, b, c, d, x, s, t) { + const n = a + (c ^ (b | ~d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.MD5('message'); + * var hash = CryptoJS.MD5(wordArray); + */ + C.MD5 = Hasher._createHelper(MD5); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacMD5(message, key); + */ + C.HmacMD5 = Hasher._createHmacHelper(MD5); +}(Math)); + +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function () { + // Shortcuts + const C = CryptoJS; + const C_lib = C.lib; + const Base = C_lib.Base; + const WordArray = C_lib.WordArray; + const C_algo = C.algo; + const MD5 = C_algo.MD5; + + /** + * This key derivation function is meant to conform with EVP_BytesToKey. + * www.openssl.org/docs/crypto/EVP_BytesToKey.html + */ + const EvpKDF = C_algo.EvpKDF = Base.extend({ + /** + * Configuration options. + * + * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) + * @property {Hasher} hasher The hash algorithm to use. Default: MD5 + * @property {number} iterations The number of iterations to perform. Default: 1 + */ + cfg: Base.extend({ keySize: 128 / 32, + hasher: MD5, + iterations: 1, + }), + + /** + * Initializes a newly created key derivation function. + * + * @param {Object} cfg (Optional) The configuration options to use for the derivation. + * + * @example + * + * var kdf = CryptoJS.algo.EvpKDF.create(); + * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); + * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); + */ + init: function (cfg) { + this.cfg = this.cfg.extend(cfg); + }, - ivSize: 128 / 32, + /** + * Derives a key from a password. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * + * @return {WordArray} The derived key. + * + * @example + * + * var key = kdf.compute(password, salt); + */ + compute: function (password, salt) { + // Shortcut + const cfg = this.cfg; - _ENC_XFORM_MODE: 1, + // Init hasher + const hasher = cfg.hasher.create(); - _DEC_XFORM_MODE: 2, + // Initial values + const derivedKey = WordArray.create(); - /** - * Creates shortcut functions to a cipher's object interface. - * - * @param {Cipher} cipher The cipher to create a helper for. - * - * @return {Object} An object with encrypt and decrypt shortcut functions. - * - * @static - * - * @example - * - * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); - */ - _createHelper: (function () { - function selectCipherStrategy (key) { - if (typeof key == 'string') { - return PasswordBasedCipher; - } else { - return SerializableCipher; - } + // Shortcuts + const derivedKeyWords = derivedKey.words; + const keySize = cfg.keySize; + const iterations = cfg.iterations; + + // Generate key + while (derivedKeyWords.length < keySize) { + if (block) { + hasher.update(block); + } + var block = hasher.update(password).finalize(salt); + hasher.reset(); + + // Iterations + for (let i = 1; i < iterations; i++) { + block = hasher.finalize(block); + hasher.reset(); } - return function (cipher) { - return { - encrypt: function (message, key, cfg) { - return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); - }, + derivedKey.concat(block); + } + derivedKey.sigBytes = keySize * 4; + + return derivedKey; + }, + }); + + /** + * Derives a key from a password. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * @param {Object} cfg (Optional) The configuration options to use for this computation. + * + * @return {WordArray} The derived key. + * + * @static + * + * @example + * + * var key = CryptoJS.EvpKDF(password, salt); + * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); + * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); + */ + C.EvpKDF = function (password, salt, cfg) { + return EvpKDF.create(cfg).compute(password, salt); + }; +}()); + + +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +/** + * Cipher core components. + */ +CryptoJS.lib.Cipher || (function (undefined) { + // Shortcuts + const C = CryptoJS; + const C_lib = C.lib; + const Base = C_lib.Base; + const WordArray = C_lib.WordArray; + const BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; + const C_enc = C.enc; + const Utf8 = C_enc.Utf8; + const Base64 = C_enc.Base64; + const C_algo = C.algo; + const EvpKDF = C_algo.EvpKDF; + + /** + * Abstract base cipher template. + * + * @property {number} keySize This cipher's key size. Default: 4 (128 bits) + * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) + * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. + * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. + */ + const Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ + /** + * Configuration options. + * + * @property {WordArray} iv The IV to use for this operation. + */ + cfg: Base.extend(), + + /** + * Creates this cipher in encryption mode. + * + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {Cipher} A cipher instance. + * + * @static + * + * @example + * + * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); + */ + createEncryptor: function (key, cfg) { + return this.create(this._ENC_XFORM_MODE, key, cfg); + }, - decrypt: function (ciphertext, key, cfg) { - return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); - } - }; - }; - }()) - }); + /** + * Creates this cipher in decryption mode. + * + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {Cipher} A cipher instance. + * + * @static + * + * @example + * + * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); + */ + createDecryptor: function (key, cfg) { + return this.create(this._DEC_XFORM_MODE, key, cfg); + }, /** - * Abstract base stream cipher template. + * Initializes a newly created cipher. + * + * @param {number} xformMode Either the encryption or decryption transormation mode constant. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @example * - * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) + * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); */ - var StreamCipher = C_lib.StreamCipher = Cipher.extend({ - _doFinalize: function () { - // Process partial blocks - var finalProcessedBlocks = this._process(!!'flush'); + init: function (xformMode, key, cfg) { + // Apply config defaults + this.cfg = this.cfg.extend(cfg); - return finalProcessedBlocks; - }, + // Store transform mode and key + this._xformMode = xformMode; + this._key = key; - blockSize: 1 - }); + // Set initial values + this.reset(); + }, /** - * Mode namespace. + * Resets this cipher to its initial state. + * + * @example + * + * cipher.reset(); */ - var C_mode = C.mode = {}; + reset: function () { + // Reset data buffer + BufferedBlockAlgorithm.reset.call(this); + + // Perform concrete-cipher logic + this._doReset(); + }, /** - * Abstract base block cipher mode template. + * Adds data to be encrypted or decrypted. + * + * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. + * + * @return {WordArray} The data after processing. + * + * @example + * + * var encrypted = cipher.process('data'); + * var encrypted = cipher.process(wordArray); */ - var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ - /** - * Creates this mode for encryption. - * - * @param {Cipher} cipher A block cipher instance. - * @param {Array} iv The IV words. - * - * @static - * - * @example - * - * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); - */ - createEncryptor: function (cipher, iv) { - return this.Encryptor.create(cipher, iv); - }, - - /** - * Creates this mode for decryption. - * - * @param {Cipher} cipher A block cipher instance. - * @param {Array} iv The IV words. - * - * @static - * - * @example - * - * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); - */ - createDecryptor: function (cipher, iv) { - return this.Decryptor.create(cipher, iv); - }, + process: function (dataUpdate) { + // Append + this._append(dataUpdate); - /** - * Initializes a newly created mode. - * - * @param {Cipher} cipher A block cipher instance. - * @param {Array} iv The IV words. - * - * @example - * - * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); - */ - init: function (cipher, iv) { - this._cipher = cipher; - this._iv = iv; - } - }); + // Process available blocks + return this._process(); + }, /** - * Cipher Block Chaining mode. + * Finalizes the encryption or decryption process. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. + * + * @return {WordArray} The data after final processing. + * + * @example + * + * var encrypted = cipher.finalize(); + * var encrypted = cipher.finalize('data'); + * var encrypted = cipher.finalize(wordArray); */ - var CBC = C_mode.CBC = (function () { - /** - * Abstract base CBC mode. - */ - var CBC = BlockCipherMode.extend(); + finalize: function (dataUpdate) { + // Final data update + if (dataUpdate) { + this._append(dataUpdate); + } - /** - * CBC encryptor. - */ - CBC.Encryptor = CBC.extend({ - /** - * Processes the data block at offset. - * - * @param {Array} words The data words to operate on. - * @param {number} offset The offset where the block starts. - * - * @example - * - * mode.processBlock(data.words, offset); - */ - processBlock: function (words, offset) { - // Shortcuts - var cipher = this._cipher; - var blockSize = cipher.blockSize; - - // XOR and encrypt - xorBlock.call(this, words, offset, blockSize); - cipher.encryptBlock(words, offset); - - // Remember this block to use with next block - this._prevBlock = words.slice(offset, offset + blockSize); - } - }); + // Perform concrete-cipher logic + const finalProcessedData = this._doFinalize(); - /** - * CBC decryptor. - */ - CBC.Decryptor = CBC.extend({ - /** - * Processes the data block at offset. - * - * @param {Array} words The data words to operate on. - * @param {number} offset The offset where the block starts. - * - * @example - * - * mode.processBlock(data.words, offset); - */ - processBlock: function (words, offset) { - // Shortcuts - var cipher = this._cipher; - var blockSize = cipher.blockSize; - - // Remember this block to use with next block - var thisBlock = words.slice(offset, offset + blockSize); - - // Decrypt and XOR - cipher.decryptBlock(words, offset); - xorBlock.call(this, words, offset, blockSize); - - // This block becomes the previous block - this._prevBlock = thisBlock; - } - }); + return finalProcessedData; + }, - function xorBlock (words, offset, blockSize) { - // Shortcut - var iv = this._iv; + keySize: 128 / 32, - // Choose mixing block - if (iv) { - var block = iv; + ivSize: 128 / 32, - // Remove IV for subsequent blocks - this._iv = undefined; - } else { - var block = this._prevBlock; - } + _ENC_XFORM_MODE: 1, + + _DEC_XFORM_MODE: 2, - // XOR blocks - for (var i = 0; i < blockSize; i++) { - words[offset + i] ^= block[i]; + /** + * Creates shortcut functions to a cipher's object interface. + * + * @param {Cipher} cipher The cipher to create a helper for. + * + * @return {Object} An object with encrypt and decrypt shortcut functions. + * + * @static + * + * @example + * + * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); + */ + _createHelper: (function () { + function selectCipherStrategy(key) { + if (typeof key == "string") { + return PasswordBasedCipher; + } else { + return SerializableCipher; } } - return CBC; - }()); + return function (cipher) { + return { + encrypt: function (message, key, cfg) { + return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); + }, + + decrypt: function (ciphertext, key, cfg) { + return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); + }, + }; + }; + }()), + }); + + /** + * Abstract base stream cipher template. + * + * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) + */ + const StreamCipher = C_lib.StreamCipher = Cipher.extend({ + _doFinalize: function () { + // Process partial blocks + const finalProcessedBlocks = this._process(!!"flush"); + + return finalProcessedBlocks; + }, + + blockSize: 1, + }); + + /** + * Mode namespace. + */ + const C_mode = C.mode = {}; + /** + * Abstract base block cipher mode template. + */ + const BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ /** - * Padding namespace. + * Creates this mode for encryption. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @static + * + * @example + * + * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); */ - var C_pad = C.pad = {}; + createEncryptor: function (cipher, iv) { + return this.Encryptor.create(cipher, iv); + }, /** - * PKCS #5/7 padding strategy. + * Creates this mode for decryption. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @static + * + * @example + * + * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); */ - var Pkcs7 = C_pad.Pkcs7 = { - /** - * Pads data using the algorithm defined in PKCS #5/7. - * - * @param {WordArray} data The data to pad. - * @param {number} blockSize The multiple that the data should be padded to. - * - * @static - * - * @example - * - * CryptoJS.pad.Pkcs7.pad(wordArray, 4); - */ - pad: function (data, blockSize) { - // Shortcut - var blockSizeBytes = blockSize * 4; - - // Count padding bytes - var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; - - // Create padding word - var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; + createDecryptor: function (cipher, iv) { + return this.Decryptor.create(cipher, iv); + }, - // Create padding - var paddingWords = []; - for (var i = 0; i < nPaddingBytes; i += 4) { - paddingWords.push(paddingWord); - } - var padding = WordArray.create(paddingWords, nPaddingBytes); + /** + * Initializes a newly created mode. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @example + * + * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); + */ + init: function (cipher, iv) { + this._cipher = cipher; + this._iv = iv; + }, + }); - // Add padding - data.concat(padding); - }, + /** + * Cipher Block Chaining mode. + */ + const CBC = C_mode.CBC = (function () { + /** + * Abstract base CBC mode. + */ + const CBC = BlockCipherMode.extend(); + /** + * CBC encryptor. + */ + CBC.Encryptor = CBC.extend({ /** - * Unpads data that had been padded using the algorithm defined in PKCS #5/7. - * - * @param {WordArray} data The data to unpad. + * Processes the data block at offset. * - * @static + * @param {Array} words The data words to operate on. + * @param {number} offset The offset where the block starts. * * @example * - * CryptoJS.pad.Pkcs7.unpad(wordArray); + * mode.processBlock(data.words, offset); */ - unpad: function (data) { - // Get number of padding bytes from last byte - var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + processBlock: function (words, offset) { + // Shortcuts + const cipher = this._cipher; + const blockSize = cipher.blockSize; - // Remove padding - data.sigBytes -= nPaddingBytes; - } - }; + // XOR and encrypt + xorBlock.call(this, words, offset, blockSize); + cipher.encryptBlock(words, offset); + + // Remember this block to use with next block + this._prevBlock = words.slice(offset, offset + blockSize); + }, + }); /** - * Abstract base block cipher template. - * - * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) + * CBC decryptor. */ - var BlockCipher = C_lib.BlockCipher = Cipher.extend({ + CBC.Decryptor = CBC.extend({ /** - * Configuration options. + * Processes the data block at offset. + * + * @param {Array} words The data words to operate on. + * @param {number} offset The offset where the block starts. + * + * @example * - * @property {Mode} mode The block mode to use. Default: CBC - * @property {Padding} padding The padding strategy to use. Default: Pkcs7 + * mode.processBlock(data.words, offset); */ - cfg: Cipher.cfg.extend({ - mode: CBC, - padding: Pkcs7 - }), + processBlock: function (words, offset) { + // Shortcuts + const cipher = this._cipher; + const blockSize = cipher.blockSize; - reset: function () { - // Reset cipher - Cipher.reset.call(this); + // Remember this block to use with next block + const thisBlock = words.slice(offset, offset + blockSize); - // Shortcuts - var cfg = this.cfg; - var iv = cfg.iv; - var mode = cfg.mode; - - // Reset block mode - if (this._xformMode == this._ENC_XFORM_MODE) { - var modeCreator = mode.createEncryptor; - } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { - var modeCreator = mode.createDecryptor; - - // Keep at least one block in the buffer for unpadding - this._minBufferSize = 1; - } - this._mode = modeCreator.call(mode, this, iv && iv.words); - }, + // Decrypt and XOR + cipher.decryptBlock(words, offset); + xorBlock.call(this, words, offset, blockSize); - _doProcessBlock: function (words, offset) { - this._mode.processBlock(words, offset); + // This block becomes the previous block + this._prevBlock = thisBlock; }, + }); - _doFinalize: function () { - // Shortcut - var padding = this.cfg.padding; + function xorBlock(words, offset, blockSize) { + // Shortcut + const iv = this._iv; - // Finalize - if (this._xformMode == this._ENC_XFORM_MODE) { - // Pad data - padding.pad(this._data, this.blockSize); + // Choose mixing block + if (iv) { + var block = iv; - // Process final blocks - var finalProcessedBlocks = this._process(!!'flush'); - } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { - // Process final blocks - var finalProcessedBlocks = this._process(!!'flush'); + // Remove IV for subsequent blocks + this._iv = undefined; + } else { + var block = this._prevBlock; + } - // Unpad data - padding.unpad(finalProcessedBlocks); - } + // XOR blocks + for (let i = 0; i < blockSize; i++) { + words[offset + i] ^= block[i]; + } + } - return finalProcessedBlocks; - }, + return CBC; + }()); - blockSize: 128 / 32 - }); + /** + * Padding namespace. + */ + const C_pad = C.pad = {}; + /** + * PKCS #5/7 padding strategy. + */ + const Pkcs7 = C_pad.Pkcs7 = { /** - * A collection of cipher parameters. - * - * @property {WordArray} ciphertext The raw ciphertext. - * @property {WordArray} key The key to this ciphertext. - * @property {WordArray} iv The IV used in the ciphering operation. - * @property {WordArray} salt The salt used with a key derivation function. - * @property {Cipher} algorithm The cipher algorithm. - * @property {Mode} mode The block mode used in the ciphering operation. - * @property {Padding} padding The padding scheme used in the ciphering operation. - * @property {number} blockSize The block size of the cipher. - * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. + * Pads data using the algorithm defined in PKCS #5/7. + * + * @param {WordArray} data The data to pad. + * @param {number} blockSize The multiple that the data should be padded to. + * + * @static + * + * @example + * + * CryptoJS.pad.Pkcs7.pad(wordArray, 4); */ - var CipherParams = C_lib.CipherParams = Base.extend({ - /** - * Initializes a newly created cipher params object. - * - * @param {Object} cipherParams An object with any of the possible cipher parameters. - * - * @example - * - * var cipherParams = CryptoJS.lib.CipherParams.create({ - * ciphertext: ciphertextWordArray, - * key: keyWordArray, - * iv: ivWordArray, - * salt: saltWordArray, - * algorithm: CryptoJS.algo.AES, - * mode: CryptoJS.mode.CBC, - * padding: CryptoJS.pad.PKCS7, - * blockSize: 4, - * formatter: CryptoJS.format.OpenSSL - * }); - */ - init: function (cipherParams) { - this.mixIn(cipherParams); - }, + pad: function (data, blockSize) { + // Shortcut + const blockSizeBytes = blockSize * 4; - /** - * Converts this cipher params object to a string. - * - * @param {Format} formatter (Optional) The formatting strategy to use. - * - * @return {string} The stringified cipher params. - * - * @throws Error If neither the formatter nor the default formatter is set. - * - * @example - * - * var string = cipherParams + ''; - * var string = cipherParams.toString(); - * var string = cipherParams.toString(CryptoJS.format.OpenSSL); - */ - toString: function (formatter) { - return (formatter || this.formatter).stringify(this); + // Count padding bytes + const nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; + + // Create padding word + const paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; + + // Create padding + const paddingWords = []; + for (let i = 0; i < nPaddingBytes; i += 4) { + paddingWords.push(paddingWord); } - }); + const padding = WordArray.create(paddingWords, nPaddingBytes); + + // Add padding + data.concat(padding); + }, /** - * Format namespace. + * Unpads data that had been padded using the algorithm defined in PKCS #5/7. + * + * @param {WordArray} data The data to unpad. + * + * @static + * + * @example + * + * CryptoJS.pad.Pkcs7.unpad(wordArray); */ - var C_format = C.format = {}; + unpad: function (data) { + // Get number of padding bytes from last byte + const nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + }, + }; + /** + * Abstract base block cipher template. + * + * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) + */ + const BlockCipher = C_lib.BlockCipher = Cipher.extend({ /** - * OpenSSL formatting strategy. + * Configuration options. + * + * @property {Mode} mode The block mode to use. Default: CBC + * @property {Padding} padding The padding strategy to use. Default: Pkcs7 */ - var OpenSSLFormatter = C_format.OpenSSL = { - /** - * Converts a cipher params object to an OpenSSL-compatible string. - * - * @param {CipherParams} cipherParams The cipher params object. - * - * @return {string} The OpenSSL-compatible string. - * - * @static - * - * @example - * - * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); - */ - stringify: function (cipherParams) { - // Shortcuts - var ciphertext = cipherParams.ciphertext; - var salt = cipherParams.salt; + cfg: Cipher.cfg.extend({ + mode: CBC, + padding: Pkcs7, + }), + + reset: function () { + // Reset cipher + Cipher.reset.call(this); + + // Shortcuts + const cfg = this.cfg; + const iv = cfg.iv; + const mode = cfg.mode; + + // Reset block mode + if (this._xformMode == this._ENC_XFORM_MODE) { + var modeCreator = mode.createEncryptor; + } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { + var modeCreator = mode.createDecryptor; + + // Keep at least one block in the buffer for unpadding + this._minBufferSize = 1; + } + this._mode = modeCreator.call(mode, this, iv && iv.words); + }, - // Format - if (salt) { - var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); - } else { - var wordArray = ciphertext; - } + _doProcessBlock: function (words, offset) { + this._mode.processBlock(words, offset); + }, - return wordArray.toString(Base64); - }, + _doFinalize: function () { + // Shortcut + const padding = this.cfg.padding; - /** - * Converts an OpenSSL-compatible string to a cipher params object. - * - * @param {string} openSSLStr The OpenSSL-compatible string. - * - * @return {CipherParams} The cipher params object. - * - * @static - * - * @example - * - * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); - */ - parse: function (openSSLStr) { - // Parse base64 - var ciphertext = Base64.parse(openSSLStr); + // Finalize + if (this._xformMode == this._ENC_XFORM_MODE) { + // Pad data + padding.pad(this._data, this.blockSize); - // Shortcut - var ciphertextWords = ciphertext.words; + // Process final blocks + var finalProcessedBlocks = this._process(!!"flush"); + } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { + // Process final blocks + var finalProcessedBlocks = this._process(!!"flush"); - // Test for salt - if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { - // Extract salt - var salt = WordArray.create(ciphertextWords.slice(2, 4)); + // Unpad data + padding.unpad(finalProcessedBlocks); + } - // Remove salt from ciphertext - ciphertextWords.splice(0, 4); - ciphertext.sigBytes -= 16; - } + return finalProcessedBlocks; + }, - return CipherParams.create({ciphertext: ciphertext, salt: salt}); - } - }; + blockSize: 128 / 32, + }); + + /** + * A collection of cipher parameters. + * + * @property {WordArray} ciphertext The raw ciphertext. + * @property {WordArray} key The key to this ciphertext. + * @property {WordArray} iv The IV used in the ciphering operation. + * @property {WordArray} salt The salt used with a key derivation function. + * @property {Cipher} algorithm The cipher algorithm. + * @property {Mode} mode The block mode used in the ciphering operation. + * @property {Padding} padding The padding scheme used in the ciphering operation. + * @property {number} blockSize The block size of the cipher. + * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. + */ + const CipherParams = C_lib.CipherParams = Base.extend({ + /** + * Initializes a newly created cipher params object. + * + * @param {Object} cipherParams An object with any of the possible cipher parameters. + * + * @example + * + * var cipherParams = CryptoJS.lib.CipherParams.create({ + * ciphertext: ciphertextWordArray, + * key: keyWordArray, + * iv: ivWordArray, + * salt: saltWordArray, + * algorithm: CryptoJS.algo.AES, + * mode: CryptoJS.mode.CBC, + * padding: CryptoJS.pad.PKCS7, + * blockSize: 4, + * formatter: CryptoJS.format.OpenSSL + * }); + */ + init: function (cipherParams) { + this.mixIn(cipherParams); + }, /** - * A cipher wrapper that returns ciphertext as a serializable cipher params object. + * Converts this cipher params object to a string. + * + * @param {Format} formatter (Optional) The formatting strategy to use. + * + * @return {string} The stringified cipher params. + * + * @throws Error If neither the formatter nor the default formatter is set. + * + * @example + * + * var string = cipherParams + ''; + * var string = cipherParams.toString(); + * var string = cipherParams.toString(CryptoJS.format.OpenSSL); */ - var SerializableCipher = C_lib.SerializableCipher = Base.extend({ - /** - * Configuration options. - * - * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL - */ - cfg: Base.extend({ - format: OpenSSLFormatter - }), - - /** - * Encrypts a message. - * - * @param {Cipher} cipher The cipher algorithm to use. - * @param {WordArray|string} message The message to encrypt. - * @param {WordArray} key The key. - * @param {Object} cfg (Optional) The configuration options to use for this operation. - * - * @return {CipherParams} A cipher params object. - * - * @static - * - * @example - * - * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); - * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); - * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); - */ - encrypt: function (cipher, message, key, cfg) { - // Apply config defaults - cfg = this.cfg.extend(cfg); + toString: function (formatter) { + return (formatter || this.formatter).stringify(this); + }, + }); - // Encrypt - var encryptor = cipher.createEncryptor(key, cfg); - var ciphertext = encryptor.finalize(message); + /** + * Format namespace. + */ + const C_format = C.format = {}; - // Shortcut - var cipherCfg = encryptor.cfg; - - // Create and return serializable cipher params - return CipherParams.create({ - ciphertext: ciphertext, - key: key, - iv: cipherCfg.iv, - algorithm: cipher, - mode: cipherCfg.mode, - padding: cipherCfg.padding, - blockSize: cipher.blockSize, - formatter: cfg.format - }); - }, + /** + * OpenSSL formatting strategy. + */ + const OpenSSLFormatter = C_format.OpenSSL = { + /** + * Converts a cipher params object to an OpenSSL-compatible string. + * + * @param {CipherParams} cipherParams The cipher params object. + * + * @return {string} The OpenSSL-compatible string. + * + * @static + * + * @example + * + * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); + */ + stringify: function (cipherParams) { + // Shortcuts + const ciphertext = cipherParams.ciphertext; + const salt = cipherParams.salt; + + // Format + if (salt) { + var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); + } else { + var wordArray = ciphertext; + } - /** - * Decrypts serialized ciphertext. - * - * @param {Cipher} cipher The cipher algorithm to use. - * @param {CipherParams|string} ciphertext The ciphertext to decrypt. - * @param {WordArray} key The key. - * @param {Object} cfg (Optional) The configuration options to use for this operation. - * - * @return {WordArray} The plaintext. - * - * @static - * - * @example - * - * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); - * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); - */ - decrypt: function (cipher, ciphertext, key, cfg) { - // Apply config defaults - cfg = this.cfg.extend(cfg); + return wordArray.toString(Base64); + }, - // Convert string to CipherParams - ciphertext = this._parse(ciphertext, cfg.format); + /** + * Converts an OpenSSL-compatible string to a cipher params object. + * + * @param {string} openSSLStr The OpenSSL-compatible string. + * + * @return {CipherParams} The cipher params object. + * + * @static + * + * @example + * + * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); + */ + parse: function (openSSLStr) { + // Parse base64 + const ciphertext = Base64.parse(openSSLStr); - // Decrypt - var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); + // Shortcut + const ciphertextWords = ciphertext.words; - return plaintext; - }, + // Test for salt + if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { + // Extract salt + var salt = WordArray.create(ciphertextWords.slice(2, 4)); - /** - * Converts serialized ciphertext to CipherParams, - * else assumed CipherParams already and returns ciphertext unchanged. - * - * @param {CipherParams|string} ciphertext The ciphertext. - * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. - * - * @return {CipherParams} The unserialized ciphertext. - * - * @static - * - * @example - * - * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); - */ - _parse: function (ciphertext, format) { - if (typeof ciphertext == 'string') { - return format.parse(ciphertext, this); - } else { - return ciphertext; - } + // Remove salt from ciphertext + ciphertextWords.splice(0, 4); + ciphertext.sigBytes -= 16; } - }); + return CipherParams.create({ ciphertext: ciphertext, salt: salt }); + }, + }; + + /** + * A cipher wrapper that returns ciphertext as a serializable cipher params object. + */ + var SerializableCipher = C_lib.SerializableCipher = Base.extend({ /** - * Key derivation function namespace. + * Configuration options. + * + * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL */ - var C_kdf = C.kdf = {}; + cfg: Base.extend({ + format: OpenSSLFormatter, + }), /** - * OpenSSL key derivation function. + * Encrypts a message. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {WordArray|string} message The message to encrypt. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {CipherParams} A cipher params object. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ - var OpenSSLKdf = C_kdf.OpenSSL = { - /** - * Derives a key and IV from a password. - * - * @param {string} password The password to derive from. - * @param {number} keySize The size in words of the key to generate. - * @param {number} ivSize The size in words of the IV to generate. - * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. - * - * @return {CipherParams} A cipher params object with the key, IV, and salt. - * - * @static - * - * @example - * - * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); - * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); - */ - execute: function (password, keySize, ivSize, salt) { - // Generate random salt - if (!salt) { - salt = WordArray.random(64 / 8); - } + encrypt: function (cipher, message, key, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Encrypt + const encryptor = cipher.createEncryptor(key, cfg); + const ciphertext = encryptor.finalize(message); + + // Shortcut + const cipherCfg = encryptor.cfg; + + // Create and return serializable cipher params + return CipherParams.create({ + ciphertext: ciphertext, + key: key, + iv: cipherCfg.iv, + algorithm: cipher, + mode: cipherCfg.mode, + padding: cipherCfg.padding, + blockSize: cipher.blockSize, + formatter: cfg.format, + }); + }, + + /** + * Decrypts serialized ciphertext. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {CipherParams|string} ciphertext The ciphertext to decrypt. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {WordArray} The plaintext. + * + * @static + * + * @example + * + * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + */ + decrypt: function (cipher, ciphertext, key, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Convert string to CipherParams + ciphertext = this._parse(ciphertext, cfg.format); - // Derive key and IV - var key = EvpKDF.create({keySize: keySize + ivSize}).compute(password, salt); + // Decrypt + const plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); - // Separate key and IV - var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); - key.sigBytes = keySize * 4; + return plaintext; + }, - // Return params - return CipherParams.create({key: key, iv: iv, salt: salt}); + /** + * Converts serialized ciphertext to CipherParams, + * else assumed CipherParams already and returns ciphertext unchanged. + * + * @param {CipherParams|string} ciphertext The ciphertext. + * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. + * + * @return {CipherParams} The unserialized ciphertext. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); + */ + _parse: function (ciphertext, format) { + if (typeof ciphertext == "string") { + return format.parse(ciphertext, this); + } else { + return ciphertext; } - }; + }, + }); + /** + * Key derivation function namespace. + */ + const C_kdf = C.kdf = {}; + + /** + * OpenSSL key derivation function. + */ + const OpenSSLKdf = C_kdf.OpenSSL = { /** - * A serializable cipher wrapper that derives the key from a password, - * and returns ciphertext as a serializable cipher params object. + * Derives a key and IV from a password. + * + * @param {string} password The password to derive from. + * @param {number} keySize The size in words of the key to generate. + * @param {number} ivSize The size in words of the IV to generate. + * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. + * + * @return {CipherParams} A cipher params object with the key, IV, and salt. + * + * @static + * + * @example + * + * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); + * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); */ - var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ - /** - * Configuration options. - * - * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL - */ - cfg: SerializableCipher.cfg.extend({ - kdf: OpenSSLKdf - }), + execute: function (password, keySize, ivSize, salt) { + // Generate random salt + if (!salt) { + salt = WordArray.random(64 / 8); + } - /** - * Encrypts a message using a password. - * - * @param {Cipher} cipher The cipher algorithm to use. - * @param {WordArray|string} message The message to encrypt. - * @param {string} password The password. - * @param {Object} cfg (Optional) The configuration options to use for this operation. - * - * @return {CipherParams} A cipher params object. - * - * @static - * - * @example - * - * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); - * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); - */ - encrypt: function (cipher, message, password, cfg) { - // Apply config defaults - cfg = this.cfg.extend(cfg); + // Derive key and IV + const key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); - // Derive key and other params - var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); + // Separate key and IV + const iv = WordArray.create(key.words.slice(keySize), ivSize * 4); + key.sigBytes = keySize * 4; - // Add IV to config - cfg.iv = derivedParams.iv; + // Return params + return CipherParams.create({ key: key, iv: iv, salt: salt }); + }, + }; - // Encrypt - var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); + /** + * A serializable cipher wrapper that derives the key from a password, + * and returns ciphertext as a serializable cipher params object. + */ + var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ + /** + * Configuration options. + * + * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL + */ + cfg: SerializableCipher.cfg.extend({ + kdf: OpenSSLKdf, + }), - // Mix in derived params - ciphertext.mixIn(derivedParams); + /** + * Encrypts a message using a password. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {WordArray|string} message The message to encrypt. + * @param {string} password The password. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {CipherParams} A cipher params object. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); + * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); + */ + encrypt: function (cipher, message, password, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); - return ciphertext; - }, + // Derive key and other params + const derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); - /** - * Decrypts serialized ciphertext using a password. - * - * @param {Cipher} cipher The cipher algorithm to use. - * @param {CipherParams|string} ciphertext The ciphertext to decrypt. - * @param {string} password The password. - * @param {Object} cfg (Optional) The configuration options to use for this operation. - * - * @return {WordArray} The plaintext. - * - * @static - * - * @example - * - * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); - * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); - */ - decrypt: function (cipher, ciphertext, password, cfg) { - // Apply config defaults - cfg = this.cfg.extend(cfg); + // Add IV to config + cfg.iv = derivedParams.iv; - // Convert string to CipherParams - ciphertext = this._parse(ciphertext, cfg.format); + // Encrypt + const ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); - // Derive key and other params - var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); + // Mix in derived params + ciphertext.mixIn(derivedParams); - // Add IV to config - cfg.iv = derivedParams.iv; + return ciphertext; + }, - // Decrypt - var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); + /** + * Decrypts serialized ciphertext using a password. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {CipherParams|string} ciphertext The ciphertext to decrypt. + * @param {string} password The password. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {WordArray} The plaintext. + * + * @static + * + * @example + * + * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); + * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); + */ + decrypt: function (cipher, ciphertext, password, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); - return plaintext; - } - }); - }()); + // Convert string to CipherParams + ciphertext = this._parse(ciphertext, cfg.format); - /* - CryptoJS v3.1.2 - code.google.com/p/crypto-js - (c) 2009-2013 by Jeff Mott. All rights reserved. - code.google.com/p/crypto-js/wiki/License - */ - /** - * Electronic Codebook block mode. - */ - CryptoJS.mode.ECB = (function () { - var ECB = CryptoJS.lib.BlockCipherMode.extend(); + // Derive key and other params + const derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); - ECB.Encryptor = ECB.extend({ - processBlock: function (words, offset) { - this._cipher.encryptBlock(words, offset); - } - }); + // Add IV to config + cfg.iv = derivedParams.iv; - ECB.Decryptor = ECB.extend({ - processBlock: function (words, offset) { - this._cipher.decryptBlock(words, offset); - } - }); + // Decrypt + const plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); - return ECB; - }()); + return plaintext; + }, + }); +}()); + +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +/** + * Electronic Codebook block mode. + */ +CryptoJS.mode.ECB = (function () { + const ECB = CryptoJS.lib.BlockCipherMode.extend(); + + ECB.Encryptor = ECB.extend({ + processBlock: function (words, offset) { + this._cipher.encryptBlock(words, offset); + }, + }); + ECB.Decryptor = ECB.extend({ + processBlock: function (words, offset) { + this._cipher.decryptBlock(words, offset); + }, + }); - /* - CryptoJS v3.1.2 - code.google.com/p/crypto-js - (c) 2009-2013 by Jeff Mott. All rights reserved. - code.google.com/p/crypto-js/wiki/License - */ + return ECB; +}()); + + +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function () { + // Shortcuts + const C = CryptoJS; + const C_lib = C.lib; + const BlockCipher = C_lib.BlockCipher; + const C_algo = C.algo; + + // Lookup tables + const SBOX = []; + const INV_SBOX = []; + const SUB_MIX_0 = []; + const SUB_MIX_1 = []; + const SUB_MIX_2 = []; + const SUB_MIX_3 = []; + const INV_SUB_MIX_0 = []; + const INV_SUB_MIX_1 = []; + const INV_SUB_MIX_2 = []; + const INV_SUB_MIX_3 = []; + + // Compute lookup tables (function () { - // Shortcuts - var C = CryptoJS; - var C_lib = C.lib; - var BlockCipher = C_lib.BlockCipher; - var C_algo = C.algo; - - // Lookup tables - var SBOX = []; - var INV_SBOX = []; - var SUB_MIX_0 = []; - var SUB_MIX_1 = []; - var SUB_MIX_2 = []; - var SUB_MIX_3 = []; - var INV_SUB_MIX_0 = []; - var INV_SUB_MIX_1 = []; - var INV_SUB_MIX_2 = []; - var INV_SUB_MIX_3 = []; - - // Compute lookup tables - (function () { - // Compute double table - var d = []; - for (var i = 0; i < 256; i++) { - if (i < 128) { - d[i] = i << 1; - } else { - d[i] = (i << 1) ^ 0x11b; - } + // Compute double table + const d = []; + for (var i = 0; i < 256; i++) { + if (i < 128) { + d[i] = i << 1; + } else { + d[i] = (i << 1) ^ 0x11b; } + } - // Walk GF(2^8) - var x = 0; - var xi = 0; - for (var i = 0; i < 256; i++) { - // Compute sbox - var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); - sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; - SBOX[x] = sx; - INV_SBOX[sx] = x; - - // Compute multiplication - var x2 = d[x]; - var x4 = d[x2]; - var x8 = d[x4]; - - // Compute sub bytes, mix columns tables - var t = (d[sx] * 0x101) ^ (sx * 0x1010100); - SUB_MIX_0[x] = (t << 24) | (t >>> 8); - SUB_MIX_1[x] = (t << 16) | (t >>> 16); - SUB_MIX_2[x] = (t << 8) | (t >>> 24); - SUB_MIX_3[x] = t; - - // Compute inv sub bytes, inv mix columns tables - var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); - INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); - INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); - INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); - INV_SUB_MIX_3[sx] = t; - - // Compute next counter - if (!x) { - x = xi = 1; - } else { - x = x2 ^ d[d[d[x8 ^ x2]]]; - xi ^= d[d[xi]]; - } + // Walk GF(2^8) + let x = 0; + let xi = 0; + for (var i = 0; i < 256; i++) { + // Compute sbox + let sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); + sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; + SBOX[x] = sx; + INV_SBOX[sx] = x; + + // Compute multiplication + const x2 = d[x]; + const x4 = d[x2]; + const x8 = d[x4]; + + // Compute sub bytes, mix columns tables + var t = (d[sx] * 0x101) ^ (sx * 0x1010100); + SUB_MIX_0[x] = (t << 24) | (t >>> 8); + SUB_MIX_1[x] = (t << 16) | (t >>> 16); + SUB_MIX_2[x] = (t << 8) | (t >>> 24); + SUB_MIX_3[x] = t; + + // Compute inv sub bytes, inv mix columns tables + var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); + INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); + INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); + INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); + INV_SUB_MIX_3[sx] = t; + + // Compute next counter + if (!x) { + x = xi = 1; + } else { + x = x2 ^ d[d[d[x8 ^ x2]]]; + xi ^= d[d[xi]]; } - }()); + } + }()); - // Precomputed Rcon lookup - var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; + // Precomputed Rcon lookup + const RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; - /** - * AES block cipher algorithm. - */ - var AES = C_algo.AES = BlockCipher.extend({ - _doReset: function () { - // Shortcuts - var key = this._key; - var keyWords = key.words; - var keySize = key.sigBytes / 4; - - // Compute number of rounds - var nRounds = this._nRounds = keySize + 6; - - // Compute number of key schedule rows - var ksRows = (nRounds + 1) * 4; - - // Compute key schedule - var keySchedule = this._keySchedule = []; - for (var ksRow = 0; ksRow < ksRows; ksRow++) { - if (ksRow < keySize) { - keySchedule[ksRow] = keyWords[ksRow]; - } else { - var t = keySchedule[ksRow - 1]; - - if (!(ksRow % keySize)) { - // Rot word - t = (t << 8) | (t >>> 24); - - // Sub word - t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; - - // Mix Rcon - t ^= RCON[(ksRow / keySize) | 0] << 24; - } else if (keySize > 6 && ksRow % keySize == 4) { - // Sub word - t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; - } - - keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; - } - } + /** + * AES block cipher algorithm. + */ + const AES = C_algo.AES = BlockCipher.extend({ + _doReset: function () { + // Shortcuts + const key = this._key; + const keyWords = key.words; + const keySize = key.sigBytes / 4; + + // Compute number of rounds + const nRounds = this._nRounds = keySize + 6; + + // Compute number of key schedule rows + const ksRows = (nRounds + 1) * 4; + + // Compute key schedule + const keySchedule = this._keySchedule = []; + for (var ksRow = 0; ksRow < ksRows; ksRow++) { + if (ksRow < keySize) { + keySchedule[ksRow] = keyWords[ksRow]; + } else { + var t = keySchedule[ksRow - 1]; - // Compute inv key schedule - var invKeySchedule = this._invKeySchedule = []; - for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { - var ksRow = ksRows - invKsRow; + if (!(ksRow % keySize)) { + // Rot word + t = (t << 8) | (t >>> 24); - if (invKsRow % 4) { - var t = keySchedule[ksRow]; - } else { - var t = keySchedule[ksRow - 4]; - } + // Sub word + t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; - if (invKsRow < 4 || ksRow <= 4) { - invKeySchedule[invKsRow] = t; - } else { - invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ - INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; + // Mix Rcon + t ^= RCON[(ksRow / keySize) | 0] << 24; + } else if (keySize > 6 && ksRow % keySize == 4) { + // Sub word + t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; } - } - }, - - encryptBlock: function (M, offset) { - this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); - }, - decryptBlock: function (M, offset) { - // Swap 2nd and 4th rows - var t = M[offset + 1]; - M[offset + 1] = M[offset + 3]; - M[offset + 3] = t; + keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; + } + } - this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); + // Compute inv key schedule + const invKeySchedule = this._invKeySchedule = []; + for (let invKsRow = 0; invKsRow < ksRows; invKsRow++) { + var ksRow = ksRows - invKsRow; - // Inv swap 2nd and 4th rows - var t = M[offset + 1]; - M[offset + 1] = M[offset + 3]; - M[offset + 3] = t; - }, + if (invKsRow % 4) { + var t = keySchedule[ksRow]; + } else { + var t = keySchedule[ksRow - 4]; + } - _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { - // Shortcut - var nRounds = this._nRounds; - - // Get input, add round key - var s0 = M[offset] ^ keySchedule[0]; - var s1 = M[offset + 1] ^ keySchedule[1]; - var s2 = M[offset + 2] ^ keySchedule[2]; - var s3 = M[offset + 3] ^ keySchedule[3]; - - // Key schedule row counter - var ksRow = 4; - - // Rounds - for (var round = 1; round < nRounds; round++) { - // Shift rows, sub bytes, mix columns, add round key - var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; - var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; - var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; - var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; - - // Update state - s0 = t0; - s1 = t1; - s2 = t2; - s3 = t3; + if (invKsRow < 4 || ksRow <= 4) { + invKeySchedule[invKsRow] = t; + } else { + invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ + INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; } + } + }, - // Shift rows, sub bytes, add round key - var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; - var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; - var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; - var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; - - // Set output - M[offset] = t0; - M[offset + 1] = t1; - M[offset + 2] = t2; - M[offset + 3] = t3; - }, + encryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); + }, - keySize: 256 / 32 - }); + decryptBlock: function (M, offset) { + // Swap 2nd and 4th rows + var t = M[offset + 1]; + M[offset + 1] = M[offset + 3]; + M[offset + 3] = t; - /** - * Shortcut functions to the cipher's object interface. - * - * @example - * - * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); - * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); - */ - C.AES = BlockCipher._createHelper(AES); - }()); + this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); + // Inv swap 2nd and 4th rows + var t = M[offset + 1]; + M[offset + 1] = M[offset + 3]; + M[offset + 3] = t; + }, - BI._.extend(BI, { - /** - * aes加密方法 - * aes-128-ecb - * - * @example - * - * var ciphertext = BI.aesEncrypt(text, key); - */ - aesEncrypt: function (text, key) { - key = CryptoJS.enc.Utf8.parse(key); - var cipher = CryptoJS.AES.encrypt(text, key, { - mode: CryptoJS.mode.ECB, - padding: CryptoJS.pad.Pkcs7 - }); + _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { + // Shortcut + const nRounds = this._nRounds; + + // Get input, add round key + let s0 = M[offset] ^ keySchedule[0]; + let s1 = M[offset + 1] ^ keySchedule[1]; + let s2 = M[offset + 2] ^ keySchedule[2]; + let s3 = M[offset + 3] ^ keySchedule[3]; + + // Key schedule row counter + let ksRow = 4; + + // Rounds + for (let round = 1; round < nRounds; round++) { + // Shift rows, sub bytes, mix columns, add round key + var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; + var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; + var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; + var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; + + // Update state + s0 = t0; + s1 = t1; + s2 = t2; + s3 = t3; + } - var base64Cipher = cipher.ciphertext.toString(CryptoJS.enc.Base64); - return base64Cipher; + // Shift rows, sub bytes, add round key + var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; + var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; + var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; + var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; + + // Set output + M[offset] = t0; + M[offset + 1] = t1; + M[offset + 2] = t2; + M[offset + 3] = t3; }, - /** - * aes解密方法 - * @param {String} text - * @param {String} key - */ - aesDecrypt: function (text, key) { - key = CryptoJS.enc.Utf8.parse(key); - var decipher = CryptoJS.AES.decrypt(text, key, { - mode: CryptoJS.mode.ECB, - padding: CryptoJS.pad.Pkcs7 - }); + keySize: 256 / 32, + }); - return CryptoJS.enc.Utf8.stringify(decipher); - } + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); + */ + C.AES = BlockCipher._createHelper(AES); +}()); + + +/** + * aes加密方法 + * aes-128-ecb + * + * @example + * + * var ciphertext = BI.aesEncrypt(text, key); + */ +export function aesEncrypt(text, key) { + key = CryptoJS.enc.Utf8.parse(key); + const cipher = CryptoJS.AES.encrypt(text, key, { + mode: CryptoJS.mode.ECB, + padding: CryptoJS.pad.Pkcs7, }); -}()); \ No newline at end of file + + return cipher.ciphertext.toString(CryptoJS.enc.Base64); +} + +/** + * aes解密方法 + * @param {String} text + * @param {String} key + */ +export function aesDecrypt(text, key) { + key = CryptoJS.enc.Utf8.parse(key); + const decipher = CryptoJS.AES.decrypt(text, key, { + mode: CryptoJS.mode.ECB, + padding: CryptoJS.pad.Pkcs7, + }); + + return CryptoJS.enc.Utf8.stringify(decipher); +} + diff --git a/src/core/structure/aspect.js b/src/core/structure/aspect.js index a104c12ca..ad47d42ae 100644 --- a/src/core/structure/aspect.js +++ b/src/core/structure/aspect.js @@ -1,63 +1,58 @@ -!(function () { - function aspect (type) { - return function (target, methodName, advice) { - var exist = target[methodName], - dispatcher; - - if (!exist || exist.target != target) { - dispatcher = target[methodName] = function () { - // before methods - var beforeArr = dispatcher.before; - var args = arguments, next; - for (var l = beforeArr.length; l--;) { - next = beforeArr[l].advice.apply(this, args); - if (next === false) { - return false; - } - args = next || args; - } - // target method - var rs = dispatcher.method.apply(this, args); - // after methods - var afterArr = dispatcher.after; - for (var i = 0, ii = afterArr.length; i < ii; i++) { - next = afterArr[i].advice.call(this, rs, args); - if (rs === false) { - return false; - } - args = next || args; +function _aspect(type) { + return function (target, methodName, advice) { + let exist = target[methodName], + dispatcher; + + if (!exist || exist.target != target) { + dispatcher = target[methodName] = function () { + // before methods + let beforeArr = dispatcher.before; + let args = arguments, next; + for (let l = beforeArr.length; l--;) { + next = beforeArr[l].advice.apply(this, args); + if (next === false) { + return false; } - return rs; - }; - - dispatcher.before = []; - dispatcher.after = []; - - if (exist) { - dispatcher.method = exist; + args = next || args; } - dispatcher.target = target; - } - - var aspectArr = (dispatcher || exist)[type]; - var obj = { - advice: advice, - _index: aspectArr.length, - remove: function () { - aspectArr.splice(this._index, 1); + // target method + let rs = dispatcher.method.apply(this, args); + // after methods + let afterArr = dispatcher.after; + for (let i = 0, ii = afterArr.length; i < ii; i++) { + next = afterArr[i].advice.call(this, rs, args); + if (rs === false) { + return false; + } + args = next || args; } + return rs; }; - aspectArr.push(obj); - return obj; + dispatcher.before = []; + dispatcher.after = []; + + if (exist) { + dispatcher.method = exist; + } + dispatcher.target = target; + } + + let aspectArr = (dispatcher || exist)[type]; + let obj = { + advice: advice, + _index: aspectArr.length, + remove: function () { + aspectArr.splice(this._index, 1); + }, }; - } + aspectArr.push(obj); - BI.aspect = { - before: aspect("before"), - after: aspect("after") + return obj; }; +} - return BI.aspect; - -})(); \ No newline at end of file +export const aspect = { + before: _aspect("before"), + after: _aspect("after"), +}; diff --git a/src/core/structure/base64.js b/src/core/structure/base64.js index 976fbab9e..9d3f0f217 100644 --- a/src/core/structure/base64.js +++ b/src/core/structure/base64.js @@ -1,130 +1,132 @@ +const _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; -!(function () { - var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; +// private method for UTF-8 encoding +const _utf8_encode = function (string) { + string = string.replace(/\r\n/g, "\n"); + let utftext = ""; + for (let n = 0; n < string.length; n++) { - // private method for UTF-8 encoding - var _utf8_encode = function (string) { - string = string.replace(/\r\n/g, "\n"); - var utftext = ""; - - for (var n = 0; n < string.length; n++) { - - var c = string.charCodeAt(n); - - if (c < 128) { - utftext += String.fromCharCode(c); - } else if ((c > 127) && (c < 2048)) { - utftext += String.fromCharCode((c >> 6) | 192); - utftext += String.fromCharCode((c & 63) | 128); - } else { - utftext += String.fromCharCode((c >> 12) | 224); - utftext += String.fromCharCode(((c >> 6) & 63) | 128); - utftext += String.fromCharCode((c & 63) | 128); - } + const c = string.charCodeAt(n); + if (c < 128) { + utftext += String.fromCharCode(c); + } else if ((c > 127) && (c < 2048)) { + utftext += String.fromCharCode((c >> 6) | 192); + utftext += String.fromCharCode((c & 63) | 128); + } else { + utftext += String.fromCharCode((c >> 12) | 224); + utftext += String.fromCharCode(((c >> 6) & 63) | 128); + utftext += String.fromCharCode((c & 63) | 128); } - return utftext; - }; - - // private method for UTF-8 decoding - var _utf8_decode = function (utftext) { - var string = ""; - var i = 0; - var c = 0, c3 = 0, c2 = 0; - - while (i < utftext.length) { - - c = utftext.charCodeAt(i); - - if (c < 128) { - string += String.fromCharCode(c); - i++; - } else if ((c > 191) && (c < 224)) { - c2 = utftext.charCodeAt(i + 1); - string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); - i += 2; - } else { - c2 = utftext.charCodeAt(i + 1); - c3 = utftext.charCodeAt(i + 2); - string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - i += 3; - } - + } + + return utftext; +}; + +// private method for UTF-8 decoding +const _utf8_decode = function (utftext) { + let string = ""; + let i = 0; + let c = 0, c3 = 0, c2 = 0; + + while (i < utftext.length) { + + c = utftext.charCodeAt(i); + + if (c < 128) { + string += String.fromCharCode(c); + i++; + } else if ((c > 191) && (c < 224)) { + c2 = utftext.charCodeAt(i + 1); + string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); + i += 2; + } else { + c2 = utftext.charCodeAt(i + 1); + c3 = utftext.charCodeAt(i + 2); + string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); + i += 3; } - return string; - }; - - BI._.extend(BI, { - - encode: function (input) { - var output = ""; - var chr1, chr2, chr3, enc1, enc2, enc3, enc4; - var i = 0; - - input = _utf8_encode(input); - while (i < input.length) { - - chr1 = input.charCodeAt(i++); - chr2 = input.charCodeAt(i++); - chr3 = input.charCodeAt(i++); - - enc1 = chr1 >> 2; - enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); - enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); - enc4 = chr3 & 63; - - if (isNaN(chr2)) { - enc3 = enc4 = 64; - } else if (isNaN(chr3)) { - enc4 = 64; - } + } + return string; +}; + +/** + * base64 encode + * @param input + * @returns {string} + */ +export function encode(input) { + let output = ""; + let chr1, chr2, chr3, enc1, enc2, enc3, enc4; + let i = 0; + + input = _utf8_encode(input); + + while (i < input.length) { + + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + enc1 = chr1 >> 2; + enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); + enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); + enc4 = chr3 & 63; + + if (isNaN(chr2)) { + enc3 = enc4 = 64; + } else if (isNaN(chr3)) { + enc4 = 64; + } - output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4); + output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4); - } + } - return output; - }, + return output; +} - // public method for decoding - decode: function (input) { - var output = ""; - var chr1, chr2, chr3; - var enc1, enc2, enc3, enc4; - var i = 0; +/** + * base64 decode + * @param input + * @returns {string} + */ +export function decode(input) { + let output = ""; + let chr1, chr2, chr3; + let enc1, enc2, enc3, enc4; + let i = 0; - input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); - while (i < input.length) { + while (i < input.length) { - enc1 = _keyStr.indexOf(input.charAt(i++)); - enc2 = _keyStr.indexOf(input.charAt(i++)); - enc3 = _keyStr.indexOf(input.charAt(i++)); - enc4 = _keyStr.indexOf(input.charAt(i++)); + enc1 = _keyStr.indexOf(input.charAt(i++)); + enc2 = _keyStr.indexOf(input.charAt(i++)); + enc3 = _keyStr.indexOf(input.charAt(i++)); + enc4 = _keyStr.indexOf(input.charAt(i++)); - chr1 = (enc1 << 2) | (enc2 >> 4); - chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); - chr3 = ((enc3 & 3) << 6) | enc4; + chr1 = (enc1 << 2) | (enc2 >> 4); + chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); + chr3 = ((enc3 & 3) << 6) | enc4; - output = output + String.fromCharCode(chr1); + output = output + String.fromCharCode(chr1); - if (enc3 != 64) { - output = output + String.fromCharCode(chr2); - } - if (enc4 != 64) { - output = output + String.fromCharCode(chr3); - } + if (enc3 != 64) { + output = output + String.fromCharCode(chr2); + } + if (enc4 != 64) { + output = output + String.fromCharCode(chr3); + } - } + } - output = _utf8_decode(output); + output = _utf8_decode(output); - return output; + return output; - } - }); -})(); \ No newline at end of file +} diff --git a/src/core/structure/cache.js b/src/core/structure/cache.js index 5f17bd630..38e238f7a 100644 --- a/src/core/structure/cache.js +++ b/src/core/structure/cache.js @@ -1,43 +1,42 @@ - -BI.Cache = { +export const Cache = { _prefix: "bi", setUsername: function (username) { - localStorage.setItem(BI.Cache._prefix + ".username", (username + "" || "").toUpperCase()); + localStorage.setItem(Cache._prefix + ".username", (username + "" || "").toUpperCase()); }, getUsername: function () { - return localStorage.getItem(BI.Cache._prefix + ".username") || ""; + return localStorage.getItem(Cache._prefix + ".username") || ""; }, _getKeyPrefix: function () { - return BI.Cache.getUsername() + "." + BI.Cache._prefix + "."; + return Cache.getUsername() + "." + Cache._prefix + "."; }, _generateKey: function (key) { - return BI.Cache._getKeyPrefix() + (key || ""); + return Cache._getKeyPrefix() + (key || ""); }, getItem: function (key) { - return localStorage.getItem(BI.Cache._generateKey(key)); + return localStorage.getItem(Cache._generateKey(key)); }, setItem: function (key, value) { - localStorage.setItem(BI.Cache._generateKey(key), value); + localStorage.setItem(Cache._generateKey(key), value); }, removeItem: function (key) { - localStorage.removeItem(BI.Cache._generateKey(key)); + localStorage.removeItem(Cache._generateKey(key)); }, clear: function () { - for (var i = localStorage.length; i >= 0; i--) { - var key = localStorage.key(i); + for (let i = localStorage.length; i >= 0; i--) { + const key = localStorage.key(i); if (key) { - if (key.indexOf(BI.Cache._getKeyPrefix()) === 0) { + if (key.indexOf(Cache._getKeyPrefix()) === 0) { localStorage.removeItem(key); } } } }, keys: function () { - var result = []; - for (var i = localStorage.length; i >= 0; i--) { - var key = localStorage.key(i); + const result = []; + for (let i = localStorage.length; i >= 0; i--) { + const key = localStorage.key(i); if (key) { - var prefix = BI.Cache._getKeyPrefix(); + const prefix = Cache._getKeyPrefix(); if (key.indexOf(prefix) === 0) { result[result.length] = key.substring(prefix.length); } @@ -47,10 +46,10 @@ BI.Cache = { }, addCookie: function (name, value, path, expiresHours) { - var cookieString = name + "=" + encodeURI(value); + let cookieString = name + "=" + encodeURI(value); // 判断是否设置过期时间 if (expiresHours && expiresHours > 0) { - var date = new Date(); + const date = new Date(); // expires是标准GMT格式时间,应该使用时间戳作为起始时间 date.setTime(date.getTime() + expiresHours * 3600 * 1000); cookieString = cookieString + "; expires=" + date.toUTCString(); @@ -61,17 +60,19 @@ BI.Cache = { document.cookie = cookieString; }, getCookie: function (name) { - var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); - if (arr = document.cookie.match(reg)) {return decodeURI(arr[2]);} + let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); + if (arr = document.cookie.match(reg)) { + return decodeURI(arr[2]); + } return null; }, deleteCookie: function (name, path) { - var date = new Date(); + const date = new Date(); date.setTime(date.getTime() - 10000); - var cookieString = name + "=v; expires=" + date.toUTCString(); + let cookieString = name + "=v; expires=" + date.toUTCString(); if (path) { cookieString = cookieString + "; path=" + path; } document.cookie = cookieString; - } + }, }; diff --git a/src/core/structure/cellSizeAndPositionManager.js b/src/core/structure/cellSizeAndPositionManager.js index 9c30fdfdd..0adc4e22c 100644 --- a/src/core/structure/cellSizeAndPositionManager.js +++ b/src/core/structure/cellSizeAndPositionManager.js @@ -1,40 +1,40 @@ -BI.CellSizeAndPositionManager = function (cellCount, cellSizeGetter, estimatedCellSize) { - this._cellSizeGetter = cellSizeGetter; - this._cellCount = cellCount; - this._estimatedCellSize = estimatedCellSize; - this._cellSizeAndPositionData = {}; - this._lastMeasuredIndex = -1; -}; - -BI.CellSizeAndPositionManager.prototype = { - constructor: BI.CellSizeAndPositionManager, - configure: function (cellCount, estimatedCellSize) { +export class CellSizeAndPositionManager { + + constructor(cellCount, cellSizeGetter, estimatedCellSize) { + this._cellSizeGetter = cellSizeGetter; this._cellCount = cellCount; this._estimatedCellSize = estimatedCellSize; - }, + this._cellSizeAndPositionData = {}; + this._lastMeasuredIndex = -1; + } - getCellCount: function () { + configure(cellCount, estimatedCellSize) { + this._cellCount = cellCount; + this._estimatedCellSize = estimatedCellSize; + } + + getCellCount() { return this._cellCount; - }, + } - getEstimatedCellSize: function () { + getEstimatedCellSize() { return this._estimatedCellSize; - }, + } - getLastMeasuredIndex: function () { + getLastMeasuredIndex() { return this._lastMeasuredIndex; - }, + } - getSizeAndPositionOfCell: function (index) { + getSizeAndPositionOfCell(index) { if (index < 0 || index >= this._cellCount) { return; } if (index > this._lastMeasuredIndex) { - var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(); - var offset = lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size; + const lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(); + let offset = lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size; - for (var i = this._lastMeasuredIndex + 1; i <= index; i++) { - var size = this._cellSizeGetter(i); + for (let i = this._lastMeasuredIndex + 1; i <= index; i++) { + const size = this._cellSizeGetter(i); if (size == null || isNaN(size)) { continue; @@ -42,7 +42,7 @@ BI.CellSizeAndPositionManager.prototype = { this._cellSizeAndPositionData[i] = { offset: offset, - size: size + size: size, }; offset += size; @@ -51,28 +51,28 @@ BI.CellSizeAndPositionManager.prototype = { this._lastMeasuredIndex = index; } return this._cellSizeAndPositionData[index]; - }, + } - getSizeAndPositionOfLastMeasuredCell: function () { + getSizeAndPositionOfLastMeasuredCell() { return this._lastMeasuredIndex >= 0 ? this._cellSizeAndPositionData[this._lastMeasuredIndex] : { offset: 0, - size: 0 + size: 0, }; - }, + } - getTotalSize: function () { - var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(); + getTotalSize() { + const lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(); return lastMeasuredCellSizeAndPosition.offset + lastMeasuredCellSizeAndPosition.size + (this._cellCount - this._lastMeasuredIndex - 1) * this._estimatedCellSize; - }, + } - getUpdatedOffsetForIndex: function (align, containerSize, currentOffset, targetIndex) { - var datum = this.getSizeAndPositionOfCell(targetIndex); - var maxOffset = datum.offset; - var minOffset = maxOffset - containerSize + datum.size; + getUpdatedOffsetForIndex(align, containerSize, currentOffset, targetIndex) { + const datum = this.getSizeAndPositionOfCell(targetIndex); + const maxOffset = datum.offset; + const minOffset = maxOffset - containerSize + datum.size; - var idealOffset; + let idealOffset; switch (align) { case "start": @@ -89,25 +89,25 @@ BI.CellSizeAndPositionManager.prototype = { break; } - var totalSize = this.getTotalSize(); + const totalSize = this.getTotalSize(); return Math.max(0, Math.min(totalSize - containerSize, idealOffset)); - }, + } - getVisibleCellRange: function (containerSize, offset) { - var totalSize = this.getTotalSize(); + getVisibleCellRange(containerSize, offset) { + const totalSize = this.getTotalSize(); if (totalSize === 0) { return {}; } - var maxOffset = offset + containerSize; - var start = this._findNearestCell(offset); + const maxOffset = offset + containerSize; + const start = this._findNearestCell(offset); - var datum = this.getSizeAndPositionOfCell(start); + const datum = this.getSizeAndPositionOfCell(start); offset = datum.offset + datum.size; - var stop = start; + let stop = start; while (offset < maxOffset && stop < this._cellCount - 1) { stop++; @@ -116,17 +116,17 @@ BI.CellSizeAndPositionManager.prototype = { return { start: start, - stop: stop + stop: stop, }; - }, + } - resetCell: function (index) { + resetCell(index) { this._lastMeasuredIndex = Math.min(this._lastMeasuredIndex, index - 1); - }, + } - _binarySearch: function (high, low, offset) { - var middle; - var currentOffset; + _binarySearch(high, low, offset) { + let middle; + let currentOffset; while (low <= high) { middle = low + Math.floor((high - low) / 2); @@ -144,10 +144,10 @@ BI.CellSizeAndPositionManager.prototype = { if (low > 0) { return low - 1; } - }, + } - _exponentialSearch: function (index, offset) { - var interval = 1; + _exponentialSearch(index, offset) { + let interval = 1; while (index < this._cellCount && this.getSizeAndPositionOfCell(index).offset < offset) { index += interval; @@ -155,117 +155,115 @@ BI.CellSizeAndPositionManager.prototype = { } return this._binarySearch(Math.min(index, this._cellCount - 1), Math.floor(index / 2), offset); - }, + } - _findNearestCell: function (offset) { + _findNearestCell(offset) { if (isNaN(offset)) { return; } offset = Math.max(0, offset); - var lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(); - var lastMeasuredIndex = Math.max(0, this._lastMeasuredIndex); + const lastMeasuredCellSizeAndPosition = this.getSizeAndPositionOfLastMeasuredCell(); + const lastMeasuredIndex = Math.max(0, this._lastMeasuredIndex); if (lastMeasuredCellSizeAndPosition.offset >= offset) { return this._binarySearch(lastMeasuredIndex, 0, offset); } return this._exponentialSearch(lastMeasuredIndex, offset); - - } -}; -BI.ScalingCellSizeAndPositionManager = function (cellCount, cellSizeGetter, estimatedCellSize, maxScrollSize) { - this._cellSizeAndPositionManager = new BI.CellSizeAndPositionManager(cellCount, cellSizeGetter, estimatedCellSize); - this._maxScrollSize = maxScrollSize || 10000000; -}; + } +} -BI.ScalingCellSizeAndPositionManager.prototype = { - constructor: BI.ScalingCellSizeAndPositionManager, +export class ScalingCellSizeAndPositionManager { + constructor(cellCount, cellSizeGetter, estimatedCellSize, maxScrollSize) { + this._cellSizeAndPositionManager = new CellSizeAndPositionManager(cellCount, cellSizeGetter, estimatedCellSize); + this._maxScrollSize = maxScrollSize || 10000000; + } - configure: function () { + configure() { this._cellSizeAndPositionManager.configure.apply(this._cellSizeAndPositionManager, arguments); - }, + } - getCellCount: function () { + getCellCount() { return this._cellSizeAndPositionManager.getCellCount(); - }, + } - getEstimatedCellSize: function () { + getEstimatedCellSize() { return this._cellSizeAndPositionManager.getEstimatedCellSize(); - }, + } - getLastMeasuredIndex: function () { + getLastMeasuredIndex() { return this._cellSizeAndPositionManager.getLastMeasuredIndex(); - }, + } - getOffsetAdjustment: function (containerSize, offset) { - var totalSize = this._cellSizeAndPositionManager.getTotalSize(); - var safeTotalSize = this.getTotalSize(); - var offsetPercentage = this._getOffsetPercentage(containerSize, offset, safeTotalSize); + getOffsetAdjustment(containerSize, offset) { + const totalSize = this._cellSizeAndPositionManager.getTotalSize(); + const safeTotalSize = this.getTotalSize(); + const offsetPercentage = this._getOffsetPercentage(containerSize, offset, safeTotalSize); return Math.round(offsetPercentage * (safeTotalSize - totalSize)); - }, + } - getSizeAndPositionOfCell: function (index) { + getSizeAndPositionOfCell(index) { return this._cellSizeAndPositionManager.getSizeAndPositionOfCell(index); - }, + } - getSizeAndPositionOfLastMeasuredCell: function () { + getSizeAndPositionOfLastMeasuredCell() { return this._cellSizeAndPositionManager.getSizeAndPositionOfLastMeasuredCell(); - }, + } - getTotalSize: function () { + getTotalSize() { return Math.min(this._maxScrollSize, this._cellSizeAndPositionManager.getTotalSize()); - }, + } - getUpdatedOffsetForIndex: function (align, containerSize, currentOffset, targetIndex) { + getUpdatedOffsetForIndex(align, containerSize, currentOffset, targetIndex) { currentOffset = this._safeOffsetToOffset(containerSize, currentOffset); - var offset = this._cellSizeAndPositionManager.getUpdatedOffsetForIndex(align, containerSize, currentOffset, targetIndex); + const offset = this._cellSizeAndPositionManager.getUpdatedOffsetForIndex(align, containerSize, currentOffset, targetIndex); return this._offsetToSafeOffset(containerSize, offset); - }, + } - getVisibleCellRange: function (containerSize, offset) { + getVisibleCellRange(containerSize, offset) { offset = this._safeOffsetToOffset(containerSize, offset); return this._cellSizeAndPositionManager.getVisibleCellRange(containerSize, offset); - }, + } - resetCell: function (index) { + resetCell(index) { this._cellSizeAndPositionManager.resetCell(index); - }, + } - _getOffsetPercentage: function (containerSize, offset, totalSize) { + _getOffsetPercentage(containerSize, offset, totalSize) { return totalSize <= containerSize ? 0 : offset / (totalSize - containerSize); - }, + } - _offsetToSafeOffset: function (containerSize, offset) { - var totalSize = this._cellSizeAndPositionManager.getTotalSize(); - var safeTotalSize = this.getTotalSize(); + _offsetToSafeOffset(containerSize, offset) { + const totalSize = this._cellSizeAndPositionManager.getTotalSize(); + const safeTotalSize = this.getTotalSize(); if (totalSize === safeTotalSize) { return offset; } - var offsetPercentage = this._getOffsetPercentage(containerSize, offset, totalSize); + const offsetPercentage = this._getOffsetPercentage(containerSize, offset, totalSize); return Math.round(offsetPercentage * (safeTotalSize - containerSize)); - - }, - _safeOffsetToOffset: function (containerSize, offset) { - var totalSize = this._cellSizeAndPositionManager.getTotalSize(); - var safeTotalSize = this.getTotalSize(); + } + + _safeOffsetToOffset(containerSize, offset) { + const totalSize = this._cellSizeAndPositionManager.getTotalSize(); + const safeTotalSize = this.getTotalSize(); if (totalSize === safeTotalSize) { return offset; } - var offsetPercentage = this._getOffsetPercentage(containerSize, offset, safeTotalSize); + const offsetPercentage = this._getOffsetPercentage(containerSize, offset, safeTotalSize); return Math.round(offsetPercentage * (totalSize - containerSize)); - + } -}; \ No newline at end of file +} diff --git a/src/core/structure/heap.js b/src/core/structure/heap.js index b9ac4f890..ae0aed9c1 100644 --- a/src/core/structure/heap.js +++ b/src/core/structure/heap.js @@ -1,115 +1,111 @@ +function defaultComparator(a, b) { + return a < b; +} -(function () { - function defaultComparator (a, b) { - return a < b; - } - - BI.Heap = function (items, comparator) { +export class Heap { + constructor(items, comparator) { this._items = items || []; this._size = this._items.length; this._comparator = comparator || defaultComparator; this._heapify(); - }; - - BI.Heap.prototype = { - constructor: BI.Heap, - empty: function () { - return this._size === 0; - }, + } - pop: function () { - if (this._size === 0) { - return; - } + empty() { + return this._size === 0; + } - var elt = this._items[0]; + pop() { + if (this._size === 0) { + return; + } - var lastElt = this._items.pop(); - this._size--; + const elt = this._items[0]; - if (this._size > 0) { - this._items[0] = lastElt; - this._sinkDown(0); - } + const lastElt = this._items.pop(); + this._size--; - return elt; - }, + if (this._size > 0) { + this._items[0] = lastElt; + this._sinkDown(0); + } - push: function (item) { - this._items[this._size++] = item; - this._bubbleUp(this._size - 1); - }, + return elt; + } - size: function () { - return this._size; - }, + push(item) { + this._items[this._size++] = item; + this._bubbleUp(this._size - 1); + } - peek: function () { - if (this._size === 0) { - return; - } + size() { + return this._size; + } - return this._items[0]; - }, + peek() { + if (this._size === 0) { + return; + } - _heapify: function () { - for (var index = Math.floor((this._size + 1) / 2); index >= 0; index--) { - this._sinkDown(index); - } - }, + return this._items[0]; + } - _bubbleUp: function (index) { - var elt = this._items[index]; - while (index > 0) { - var parentIndex = Math.floor((index + 1) / 2) - 1; - var parentElt = this._items[parentIndex]; + _heapify() { + for (let index = Math.floor((this._size + 1) / 2); index >= 0; index--) { + this._sinkDown(index); + } + } - // if parentElt < elt, stop - if (this._comparator(parentElt, elt)) { - return; - } + _bubbleUp(index) { + const elt = this._items[index]; + while (index > 0) { + const parentIndex = Math.floor((index + 1) / 2) - 1; + const parentElt = this._items[parentIndex]; - // swap - this._items[parentIndex] = elt; - this._items[index] = parentElt; - index = parentIndex; + // if parentElt < elt, stop + if (this._comparator(parentElt, elt)) { + return; } - }, - _sinkDown: function (index) { - var elt = this._items[index]; + // swap + this._items[parentIndex] = elt; + this._items[index] = parentElt; + index = parentIndex; + } + } - while (true) { - var leftChildIndex = 2 * (index + 1) - 1; - var rightChildIndex = 2 * (index + 1); - var swapIndex = -1; + _sinkDown(index) { + const elt = this._items[index]; - if (leftChildIndex < this._size) { - var leftChild = this._items[leftChildIndex]; - if (this._comparator(leftChild, elt)) { - swapIndex = leftChildIndex; - } - } + while (true) { + const leftChildIndex = 2 * (index + 1) - 1; + const rightChildIndex = 2 * (index + 1); + let swapIndex = -1; - if (rightChildIndex < this._size) { - var rightChild = this._items[rightChildIndex]; - if (this._comparator(rightChild, elt)) { - if (swapIndex === -1 || - this._comparator(rightChild, this._items[swapIndex])) { - swapIndex = rightChildIndex; - } - } + if (leftChildIndex < this._size) { + const leftChild = this._items[leftChildIndex]; + if (this._comparator(leftChild, elt)) { + swapIndex = leftChildIndex; } + } - // if we don't have a swap, stop - if (swapIndex === -1) { - return; + if (rightChildIndex < this._size) { + const rightChild = this._items[rightChildIndex]; + if (this._comparator(rightChild, elt)) { + if (swapIndex === -1 || + this._comparator(rightChild, this._items[swapIndex])) { + swapIndex = rightChildIndex; + } } + } - this._items[index] = this._items[swapIndex]; - this._items[swapIndex] = elt; - index = swapIndex; + // if we don't have a swap, stop + if (swapIndex === -1) { + return; } + + this._items[index] = this._items[swapIndex]; + this._items[swapIndex] = elt; + index = swapIndex; } - }; -})(); + } +} diff --git a/src/core/structure/index.js b/src/core/structure/index.js new file mode 100644 index 000000000..4495bf79e --- /dev/null +++ b/src/core/structure/index.js @@ -0,0 +1,44 @@ +import * as a1 from "./aes"; +import * as a2 from "./aspect"; +import * as a3 from "./base64"; +import * as a4 from "./cache"; +import * as a5 from "./cellSizeAndPositionManager"; +import * as a6 from "./heap"; +import * as a7 from "./linkedHashMap"; +import * as a8 from "./lru"; +import * as a9 from "./prefixIntervalTree"; +import * as a10 from "./queue"; +import * as a11 from "./sectionManager"; +import * as a12 from "./tree"; +import * as a13 from "./vector"; + +Object.assign(BI, { + ...a1, + ...a2, + ...a3, + ...a4, + ...a5, + ...a6, + ...a7, + ...a8, + ...a9, + ...a10, + ...a11, + ...a12, + ...a13, +}); + + +export * from "./aes"; +export * from "./aspect"; +export * from "./base64"; +export * from "./cache"; +export * from "./cellSizeAndPositionManager"; +export * from "./heap"; +export * from "./linkedHashMap"; +export * from "./lru"; +export * from "./prefixIntervalTree"; +export * from "./queue"; +export * from "./sectionManager"; +export * from "./tree"; +export * from "./vector"; diff --git a/src/core/structure/linkedHashMap.js b/src/core/structure/linkedHashMap.js index e9328e591..d4a54eafd 100644 --- a/src/core/structure/linkedHashMap.js +++ b/src/core/structure/linkedHashMap.js @@ -1,72 +1,66 @@ - -!(function () { - BI.LinkHashMap = function () { +export class LinkHashMap { + constructor() { this.array = []; this.map = {}; - }; - BI.LinkHashMap.prototype = { - constructor: BI.LinkHashMap, - has: function (key) { - if (key in this.map) { - return true; - } - return false; - }, - - add: function (key, value) { - if (typeof key === "undefined") { - return; - } - if (key in this.map) { - this.map[key] = value; - } else { - this.array.push(key); - this.map[key] = value; - } - }, + } - remove: function (key) { - if (key in this.map) { - delete this.map[key]; - for (var i = 0; i < this.array.length; i++) { - if (this.array[i] == key) { - this.array.splice(i, 1); - break; - } - } - } - }, + has(key) { + return key in this.map; + } - size: function () { - return this.array.length; - }, + add(key, value) { + if (typeof key === "undefined") { + return; + } + if (key in this.map) { + this.map[key] = value; + } else { + this.array.push(key); + this.map[key] = value; + } + } - each: function (fn, scope) { - var scope = scope || window; - var fn = fn || null; - if (fn == null || typeof (fn) !== "function") { - return; - } - for (var i = 0; i < this.array.length; i++) { - var key = this.array[i]; - var value = this.map[key]; - var re = fn.call(scope, key, value, i, this.array, this.map); - if (re == false) { + remove(key) { + if (key in this.map) { + delete this.map[key]; + for (let i = 0; i < this.array.length; i++) { + if (this.array[i] == key) { + this.array.splice(i, 1); break; } } - }, + } + } - get: function (key) { - return this.map[key]; - }, + size() { + return this.array.length; + } - toArray: function () { - var array = []; - this.each(function (key, value) { - array.push(value); - }); - return array; + each(fn, scope) { + scope = scope || window; + fn = fn || null; + if (fn == null || typeof (fn) !== "function") { + return; } - }; -})(); \ No newline at end of file + for (let i = 0; i < this.array.length; i++) { + const key = this.array[i]; + const value = this.map[key]; + const re = fn.call(scope, key, value, i, this.array, this.map); + if (re == false) { + break; + } + } + } + + get(key) { + return this.map[key]; + } + + toArray() { + const array = []; + this.each(function (key, value) { + array.push(value); + }); + return array; + } +} diff --git a/src/core/structure/lru.js b/src/core/structure/lru.js index 5243d75ca..1d1ce30f6 100644 --- a/src/core/structure/lru.js +++ b/src/core/structure/lru.js @@ -1,24 +1,21 @@ - -!(function () { - BI.LRU = function (limit) { +export class LRU { + constructor(limit) { this.size = 0; this.limit = limit; this.head = this.tail = undefined; this._keymap = {}; - }; - - var p = BI.LRU.prototype; + } - p.put = function (key, value) { - var removed; + put(key, value) { + let removed; if (this.size === this.limit) { removed = this.shift(); } - var entry = this.get(key, true); + let entry = this.get(key, true); if (!entry) { entry = { - key: key + key: key, }; this._keymap[key] = entry; if (this.tail) { @@ -33,10 +30,10 @@ entry.value = value; return removed; - }; + } - p.shift = function () { - var entry = this.head; + shift() { + const entry = this.head; if (entry) { this.head = this.head.newer; this.head.older = undefined; @@ -45,11 +42,10 @@ this.size--; } return entry; - }; - + } - p.get = function (key, returnEntry) { - var entry = this._keymap[key]; + get(key, returnEntry) { + const entry = this._keymap[key]; if (entry === undefined) return; if (entry === this.tail) { return returnEntry @@ -78,9 +74,9 @@ return returnEntry ? entry : entry.value; - }; + } - p.has = function (key) { + has(key) { return this._keymap[key] != null; - }; -})(); \ No newline at end of file + } +} diff --git a/src/core/structure/prefixIntervalTree.js b/src/core/structure/prefixIntervalTree.js index 1a180b34d..a1356970f 100644 --- a/src/core/structure/prefixIntervalTree.js +++ b/src/core/structure/prefixIntervalTree.js @@ -1,32 +1,32 @@ // 线段树 -(function () { - var parent = function (node) { - return Math.floor(node / 2); - }; - - var Int32Array = _global.Int32Array || function (size) { - var xs = []; - for (var i = size - 1; i >= 0; --i) { - xs[i] = 0; - } - return xs; - }; - - var ceilLog2 = function (x) { - var y = 1; - while (y < x) { - y *= 2; - } - return y; - }; - - BI.PrefixIntervalTree = function (xs) { +const parent = function (node) { + return Math.floor(node / 2); +}; + +const Int32Array = _global.Int32Array || function (size) { + const xs = []; + for (let i = size - 1; i >= 0; --i) { + xs[i] = 0; + } + return xs; +}; + +const ceilLog2 = function (x) { + let y = 1; + while (y < x) { + y *= 2; + } + return y; +}; + +export class PrefixIntervalTree { + constructor(xs) { this._size = xs.length; this._half = ceilLog2(this._size); // _heap是一个_size两倍以上的堆 this._heap = new Int32Array(2 * this._half); - var i; + let i; // 初始化 >= _size 的堆空间, 即叶子节点 for (i = 0; i < this._size; ++i) { this._heap[this._half + i] = xs[i]; @@ -35,146 +35,143 @@ for (i = this._half - 1; i > 0; --i) { this._heap[i] = this._heap[2 * i] + this._heap[2 * i + 1]; } - }; - - BI.PrefixIntervalTree.prototype = { - constructor: BI.PrefixIntervalTree, - // 往_half之后的空间set值,需要更新其所有祖先节点的值 - set: function (index, value) { - var node = this._half + index; - this._heap[node] = value; - - node = parent(node); - for (; node !== 0; node = parent(node)) { - this._heap[node] = - this._heap[2 * node] + this._heap[2 * node + 1]; - } - }, + } - get: function (index) { - var node = this._half + index; - return this._heap[node]; - }, + static uniform(size, initialValue) { + const xs = []; + for (let i = size - 1; i >= 0; --i) { + xs[i] = initialValue; + } - getSize: function () { - return this._size; - }, - - /** - * get(0) + get(1) + ... + get(end - 1). - */ - sumUntil: function (end) { - if (end === 0) { - return 0; - } + return new PrefixIntervalTree(xs); + } - var node = this._half + end - 1; - var sum = this._heap[node]; - for (; node !== 1; node = parent(node)) { - if (node % 2 === 1) { - sum += this._heap[node - 1]; - } - } + static empty(size) { + return PrefixIntervalTree.uniform(size, 0); + } - return sum; - }, - - /** - * get(0) + get(1) + ... + get(inclusiveEnd). - */ - sumTo: function (inclusiveEnd) { - return this.sumUntil(inclusiveEnd + 1); - }, - - /** - * sum get(begin) + get(begin + 1) + ... + get(end - 1). - */ - sum: function (begin, end) { - return this.sumUntil(end) - this.sumUntil(begin); - }, - - /** - * Returns the smallest i such that 0 <= i <= size and sumUntil(i) <= t, or - * -1 if no such i exists. - */ - greatestLowerBound: function (t) { - if (t < 0) { - return -1; - } + set(index, value) { + let node = this._half + index; + this._heap[node] = value; - var node = 1; - if (this._heap[node] <= t) { - return this._size; - } + node = parent(node); + for (; node !== 0; node = parent(node)) { + this._heap[node] = + this._heap[2 * node] + this._heap[2 * node + 1]; + } + } + + get(index) { + const node = this._half + index; + return this._heap[node]; + } + + getSize() { + return this._size; + } + + /** + * get(0) + get(1) + ... + get(end - 1). + */ + sumUntil(end) { + if (end === 0) { + return 0; + } - while (node < this._half) { - var leftSum = this._heap[2 * node]; - if (t < leftSum) { - node = 2 * node; - } else { - node = 2 * node + 1; - t -= leftSum; - } + let node = this._half + end - 1; + let sum = this._heap[node]; + for (; node !== 1; node = parent(node)) { + if (node % 2 === 1) { + sum += this._heap[node - 1]; } + } - return node - this._half; - }, + return sum; + } + + /** + * get(0) + get(1) + ... + get(inclusiveEnd). + */ + sumTo(inclusiveEnd) { + return this.sumUntil(inclusiveEnd + 1); + } + + /** + * sum get(begin) + get(begin + 1) + ... + get(end - 1). + */ + sum(begin, end) { + return this.sumUntil(end) - this.sumUntil(begin); + } + + /** + * Returns the smallest i such that 0 <= i <= size and sumUntil(i) <= t, or + * -1 if no such i exists. + */ + greatestLowerBound(t) { + if (t < 0) { + return -1; + } - /** - * Returns the smallest i such that 0 <= i <= size and sumUntil(i) < t, or - * -1 if no such i exists. - */ - greatestStrictLowerBound: function (t) { - if (t <= 0) { - return -1; - } + let node = 1; + if (this._heap[node] <= t) { + return this._size; + } - var node = 1; - if (this._heap[node] < t) { - return this._size; + while (node < this._half) { + const leftSum = this._heap[2 * node]; + if (t < leftSum) { + node = 2 * node; + } else { + node = 2 * node + 1; + t -= leftSum; } + } - while (node < this._half) { - var leftSum = this._heap[2 * node]; - if (t <= leftSum) { - node = 2 * node; - } else { - node = 2 * node + 1; - t -= leftSum; - } - } + return node - this._half; + } - return node - this._half; - }, - - /** - * Returns the smallest i such that 0 <= i <= size and t <= sumUntil(i), or - * size + 1 if no such i exists. - */ - leastUpperBound: function (t) { - return this.greatestStrictLowerBound(t) + 1; - }, - - /** - * Returns the smallest i such that 0 <= i <= size and t < sumUntil(i), or - * size + 1 if no such i exists. - */ - leastStrictUpperBound: function (t) { - return this.greatestLowerBound(t) + 1; + /** + * Returns the smallest i such that 0 <= i <= size and sumUntil(i) < t, or + * -1 if no such i exists. + */ + greatestStrictLowerBound(t) { + if (t <= 0) { + return -1; } - }; - BI.PrefixIntervalTree.uniform = function (size, initialValue) { - var xs = []; - for (var i = size - 1; i >= 0; --i) { - xs[i] = initialValue; + let node = 1; + if (this._heap[node] < t) { + return this._size; } - return new BI.PrefixIntervalTree(xs); - }; + while (node < this._half) { + const leftSum = this._heap[2 * node]; + if (t <= leftSum) { + node = 2 * node; + } else { + node = 2 * node + 1; + t -= leftSum; + } + } + + return node - this._half; + } + + /** + * Returns the smallest i such that 0 <= i <= size and t <= sumUntil(i), or + * size + 1 if no such i exists. + */ + leastUpperBound(t) { + return this.greatestStrictLowerBound(t) + 1; + } + + /** + * Returns the smallest i such that 0 <= i <= size and t < sumUntil(i), or + * size + 1 if no such i exists. + */ + leastStrictUpperBound(t) { + return this.greatestLowerBound(t) + 1; + } - BI.PrefixIntervalTree.empty = function (size) { - return BI.PrefixIntervalTree.uniform(size, 0); - }; -})(); +} diff --git a/src/core/structure/queue.js b/src/core/structure/queue.js index 2d8e382e7..9cdf8b596 100644 --- a/src/core/structure/queue.js +++ b/src/core/structure/queue.js @@ -1,89 +1,86 @@ +import {contains, remove} from "../2.base"; -!(function () { - BI.Queue = function (capacity) { +export class Queue { + constructor(capacity) { this.capacity = capacity; this.array = []; - }; - BI.Queue.prototype = { - constructor: BI.Queue, - - contains: function (v) { - return BI.contains(this.array, v); - }, - - indexOf: function (v) { - return BI.contains(this.array, v); - }, - - getElementByIndex: function (index) { - return this.array[index]; - }, - - push: function (v) { - this.array.push(v); - if (this.capacity && this.array.length > this.capacity) { - this.array.shift(); - } - }, + } - pop: function () { - this.array.pop(); - }, + contains(v) { + return contains(this.array, v); + } + + indexOf(v) { + return contains(this.array, v); + } + + getElementByIndex(index) { + return this.array[index]; + } - shift: function () { + push(v) { + this.array.push(v); + if (this.capacity && this.array.length > this.capacity) { this.array.shift(); - }, + } + } - unshift: function (v) { - this.array.unshift(v); - if (this.capacity && this.array.length > this.capacity) { - this.array.pop(); - } - }, + pop() { + this.array.pop(); + } + + shift() { + this.array.shift(); + } + + unshift(v) { + this.array.unshift(v); + if (this.capacity && this.array.length > this.capacity) { + this.array.pop(); + } + } - remove: function (v) { - BI.remove(this.array, v); - }, + remove(v) { + remove(this.array, v); + } - splice: function () { - this.array.splice.apply(this.array, arguments); - }, + splice() { + this.array.splice.apply(this.array, arguments); + } - slice: function () { - this.array.slice.apply(this.array, arguments); - }, + slice() { + this.array.slice.apply(this.array, arguments); + } - size: function () { - return this.array.length; - }, + size() { + return this.array.length; + } - each: function (fn, scope) { - var scope = scope || window; - var fn = fn || null; - if (fn == null || typeof (fn) !== "function") { - return; - } - for (var i = 0; i < this.array.length; i++) { - var re = fn.call(scope, i, this.array[i], this.array); - if (re == false) { - break; - } + each(fn, scope) { + scope = scope || window; + fn = fn || null; + if (fn == null || typeof (fn) !== "function") { + return; + } + for (let i = 0; i < this.array.length; i++) { + const re = fn.call(scope, i, this.array[i], this.array); + if (re === false) { + break; } - }, + } + } - toArray: function () { - return this.array; - }, + toArray() { + return this.array; + } + + fromArray(array) { + array.each(v => this.push(v)); + } + + clear() { + this.array.length = 0; + } +} - fromArray: function (array) { - var self = this; - BI.each(array, function (i, v) { - self.push(v); - }); - }, - clear: function () { - this.array.length = 0; - } - }; -})(); \ No newline at end of file diff --git a/src/core/structure/sectionManager.js b/src/core/structure/sectionManager.js index ee0692072..8eb348253 100644 --- a/src/core/structure/sectionManager.js +++ b/src/core/structure/sectionManager.js @@ -1,5 +1,7 @@ -!(function () { - var Section = function (height, width, x, y) { +import {each, keys, map, size} from "../2.base"; + +class Section { + constructor(height, width, x, y) { this.height = height; this.width = width; this.x = x; @@ -7,82 +9,79 @@ this._indexMap = {}; this._indices = []; - }; - - Section.prototype = { - constructor: Section, - addCellIndex: function (index) { - if (!this._indexMap[index]) { - this._indexMap[index] = true; - this._indices.push(index); - } - }, + } - getCellIndices: function () { - return this._indices; + addCellIndex(index) { + if (!this._indexMap[index]) { + this._indexMap[index] = true; + this._indices.push(index); } - }; + } + + getCellIndices() { + return this._indices; + } +} - var SECTION_SIZE = 100; - BI.SectionManager = function (sectionSize) { - this._sectionSize = sectionSize || SECTION_SIZE; +const SECTION_SIZE = 100; + +export class SectionManager { + constructor(sectionSize = SECTION_SIZE) { + this._sectionSize = sectionSize; this._cellMetadata = []; this._sections = {}; - }; - - BI.SectionManager.prototype = { - constructor: BI.SectionManager, - getCellIndices: function (height, width, x, y) { - var indices = {}; + } - BI.each(this.getSections(height, width, x, y), function (i, section) { - BI.each(section.getCellIndices(), function (j, index) { - indices[index] = index; - }); - }); + getCellIndices(height, width, x, y) { + const indices = {}; - return BI.map(BI.keys(indices), function (i, index) { - return indices[index]; + each(this.getSections(height, width, x, y), function (i, section) { + each(section.getCellIndices(), function (j, index) { + indices[index] = index; }); - }, + }); - getCellMetadata: function (index) { - return this._cellMetadata[index]; - }, + return map(keys(indices), function (i, index) { + return indices[index]; + }); + } - getSections: function (height, width, x, y) { - var sectionXStart = Math.floor(x / this._sectionSize); - var sectionXStop = Math.floor((x + width - 1) / this._sectionSize); - var sectionYStart = Math.floor(y / this._sectionSize); - var sectionYStop = Math.floor((y + height - 1) / this._sectionSize); + getCellMetadata(index) { + return this._cellMetadata[index]; + } - var sections = []; + getSections(height, width, x, y) { + const sectionXStart = Math.floor(x / this._sectionSize); + const sectionXStop = Math.floor((x + width - 1) / this._sectionSize); + const sectionYStart = Math.floor(y / this._sectionSize); + const sectionYStop = Math.floor((y + height - 1) / this._sectionSize); - for (var sectionX = sectionXStart; sectionX <= sectionXStop; sectionX++) { - for (var sectionY = sectionYStart; sectionY <= sectionYStop; sectionY++) { - var key = sectionX + "." + sectionY; + const sections = []; - if (!this._sections[key]) { - this._sections[key] = new Section(this._sectionSize, this._sectionSize, sectionX * this._sectionSize, sectionY * this._sectionSize); - } + for (let sectionX = sectionXStart; sectionX <= sectionXStop; sectionX++) { + for (let sectionY = sectionYStart; sectionY <= sectionYStop; sectionY++) { + const key = sectionX + "." + sectionY; - sections.push(this._sections[key]); + if (!this._sections[key]) { + this._sections[key] = new Section(this._sectionSize, this._sectionSize, sectionX * this._sectionSize, sectionY * this._sectionSize); } + + sections.push(this._sections[key]); } + } - return sections; - }, + return sections; + } - getTotalSectionCount: function () { - return BI.size(this._sections); - }, + getTotalSectionCount() { + return size(this._sections); + } - registerCell: function (cellMetadatum, index) { - this._cellMetadata[index] = cellMetadatum; + registerCell(cellMetadatum, index) { + this._cellMetadata[index] = cellMetadatum; - BI.each(this.getSections(cellMetadatum.height, cellMetadatum.width, cellMetadatum.x, cellMetadatum.y), function (i, section) { - section.addCellIndex(index); - }); - } - }; -})(); \ No newline at end of file + each(this.getSections(cellMetadatum.height, cellMetadatum.width, cellMetadatum.x, cellMetadatum.y), function (i, section) { + section.addCellIndex(index); + }); + } +} diff --git a/src/core/structure/tree.js b/src/core/structure/tree.js index 32e7665b4..a48c17d83 100644 --- a/src/core/structure/tree.js +++ b/src/core/structure/tree.js @@ -1,517 +1,521 @@ -(function () { - BI.Tree = function () { - this.root = new BI.Node(BI.UUID()); - }; - - BI.Tree.prototype = { - constructor: BI.Tree, - addNode: function (node, newNode, index) { - if (BI.isNull(newNode)) { - this.root.addChild(node, index); - } else if (BI.isNull(node)) { - this.root.addChild(newNode, index); - } else { - node.addChild(newNode, index); - } - }, - - isRoot: function (node) { - return node === this.root; - }, - - getRoot: function () { - return this.root; - }, - - clear: function () { - this.root.clear(); - }, - - initTree: function (nodes) { - var self = this; - this.clear(); - var queue = []; - BI.each(nodes, function (i, node) { - var n = new BI.Node(node); - n.set("data", node); - self.addNode(n); - queue.push(n); - }); - while (!BI.isEmpty(queue)) { - var parent = queue.shift(); - var node = parent.get("data"); - BI.each(node.children, function (i, child) { - var n = new BI.Node(child); - n.set("data", child); - queue.push(n); - self.addNode(parent, n); - }); - } - }, +import { + isObject, + UUID, + extend, + isEmpty, + isArray, + first, + last, + findIndex, + isUndefined, + isNull, + each, + deepClone, + isEqual, some, every, clone +} from "../2.base"; + +export class Node { + constructor(id) { + if (isObject(id)) { + extend(this, id); + } else { + this.id = id; + } + this.clear(); + } - _toJSON: function (node) { - var self = this; - var children = []; - BI.each(node.getChildren(), function (i, child) { - children.push(self._toJSON(child)); - }); - return BI.extend({ - id: node.id - }, BI.deepClone(node.get("data")), (children.length > 0 ? { - children: children - } : {})); - }, - - toJSON: function (node) { - var self = this, result = []; - BI.each((node || this.root).getChildren(), function (i, child) { - result.push(self._toJSON(child)); - }); - return result; - }, - - _toJSONWithNode: function (node) { - var self = this; - var children = []; - BI.each(node.getChildren(), function (i, child) { - children.push(self._toJSONWithNode(child)); - }); - return BI.extend({ - id: node.id - }, BI.deepClone(node.get("data")), { - node: node - }, (children.length > 0 ? { - children: children - } : {})); - }, - - toJSONWithNode: function (node) { - var self = this, result = []; - BI.each((node || this.root).getChildren(), function (i, child) { - result.push(self._toJSONWithNode(child)); + set(key, value) { + if (isObject(key)) { + extend(this, key); + return; + } + this[key] = value; + } + + get(key) { + return this[key]; + } + + isLeaf() { + return isEmpty(this.children); + } + + getChildren() { + return this.children; + } + + getChildrenLength() { + return this.children.length; + } + + getFirstChild() { + return first(this.children); + } + + getLastChild() { + return last(this.children); + } + + setLeft(left) { + this.left = left; + } + + getLeft() { + return this.left; + } + + setRight(right) { + this.right = right; + } + + getRight() { + return this.right; + } + + setParent(parent) { + this.parent = parent; + } + + getParent() { + return this.parent; + } + + getChild(index) { + return this.children[index]; + } + + getChildIndex(id) { + return findIndex(this.children, function (i, ch) { + return ch.get("id") === id; + }); + } + + removeChild(id) { + this.removeChildByIndex(this.getChildIndex(id)); + } + + removeChildByIndex(index) { + const before = this.getChild(index - 1); + const behind = this.getChild(index + 1); + if (before != null) { + before.setRight(behind || null); + } + if (behind != null) { + behind.setLeft(before || null); + } + this.children.splice(index, 1); + } + + removeAllChilds() { + this.children = []; + } + + addChild(child, index) { + let cur = null; + if (isUndefined(index)) { + cur = this.children.length - 1; + } else { + cur = index - 1; + } + child.setParent(this); + if (cur >= 0) { + this.getChild(cur) && this.getChild(cur).setRight(child); + child.setLeft(this.getChild(cur)); + } + if (isUndefined(index)) { + this.children.push(child); + } else { + this.children.splice(index, 0, child); + } + } + + equals(obj) { + return this === obj || this.id === obj.id; + } + + clear() { + this.parent = null; + this.left = null; + this.right = null; + this.children = []; + } +} + +export class Tree { + constructor() { + this.root = new Node(UUID()); + } + + addNode(node, newNode, index) { + if (isNull(newNode)) { + this.root.addChild(node, index); + } else if (isNull(node)) { + this.root.addChild(newNode, index); + } else { + node.addChild(newNode, index); + } + } + + isRoot(node) { + return node === this.root; + } + + getRoot() { + return this.root; + } + + clear() { + this.root.clear(); + } + + initTree(nodes) { + this.clear(); + const queue = []; + each(nodes, (i, node) => { + const n = new Node(node); + n.set("data", node); + this.addNode(n); + queue.push(n); + }); + while (!isEmpty(queue)) { + const parent = queue.shift(); + const node = parent.get("data"); + each(node.children, (i, child) => { + const n = new Node(child); + n.set("data", child); + queue.push(n); + this.addNode(parent, n); }); - return result; - }, + } + } + + _toJSON(node) { + const children = []; + each(node.getChildren(), (i, child) => { + children.push(this._toJSON(child)); + }); + return extend({ + id: node.id, + }, deepClone(node.get("data")), (children.length > 0 ? { + children: children, + } : {})); + } + + toJSON(node) { + const result = []; + each((node || this.root).getChildren(), (i, child) => { + result.push(this._toJSON(child)); + }); + return result; + } + + _toJSONWithNode(node) { + const children = []; + each(node.getChildren(), (i, child) => { + children.push(this._toJSONWithNode(child)); + }); + return extend({ + id: node.id, + }, deepClone(node.get("data")), { + node: node, + }, (children.length > 0 ? { + children: children, + } : {})); + } + + toJSONWithNode(node) { + const result = []; + each((node || this.root).getChildren(), (i, child) => { + result.push(this._toJSONWithNode(child)); + }); + return result; + } + + search(root, target, param) { + if (!(root instanceof Node)) { + return this.search(this.root, root, target); + } + let next = null; - search: function (root, target, param) { - if (!(root instanceof BI.Node)) { - return arguments.callee.apply(this, [this.root, root, target]); + if (isNull(target)) { + return null; + } + if (isEqual(root[param || "id"], target)) { + return root; + } + some(root.getChildren(), (i, child) => { + next = this.search(child, target, param); + if (null !== next) { + return true; } - var self = this, next = null; - - if (BI.isNull(target)) { - return null; + }); + return next; + } + + _traverse(node, callback) { + let queue = []; + queue.push(node); + while (!isEmpty(queue)) { + const temp = queue.shift(); + const b = callback && callback(temp); + if (b === false) { + break; } - if (BI.isEqual(root[param || "id"], target)) { - return root; + if (b === true) { + continue; } - BI.any(root.getChildren(), function (i, child) { - next = self.search(child, target, param); - if (null !== next) { - return true; - } - }); - return next; - }, - - _traverse: function (node, callback) { - var queue = []; - queue.push(node); - while (!BI.isEmpty(queue)) { - var temp = queue.shift(); - var b = callback && callback(temp); - if (b === false) { - break; - } - if (b === true) { - continue; - } - if (temp != null) { - queue = queue.concat(temp.getChildren()); - } + if (temp != null) { + queue = queue.concat(temp.getChildren()); } - }, - - traverse: function (callback) { - this._traverse(this.root, callback); - }, - - _recursion: function (node, route, callback) { - var self = this; - return BI.every(node.getChildren(), function (i, child) { - var next = BI.clone(route); - next.push(child.id); - var b = callback && callback(child, next); - if (b === false) { - return false; - } - if (b === true) { - return true; - } - return self._recursion(child, next, callback); - }); - }, - - recursion: function (callback) { - this._recursion(this.root, [], callback); - }, - - inOrderTraverse: function (callback) { - this._inOrderTraverse(this.root, callback); - }, - - // 中序遍历(递归) - _inOrderTraverse: function (node, callback) { - if (node != null) { - this._inOrderTraverse(node.getLeft()); - callback && callback(node); - this._inOrderTraverse(node.getRight()); + } + } + + traverse(callback) { + this._traverse(this.root, callback); + } + + _recursion(node, route, callback) { + return every(node.getChildren(), (i, child) => { + const next = clone(route); + next.push(child.id); + const b = callback && callback(child, next); + if (b === false) { + return false; } - }, - - // 中序遍历(非递归) - nrInOrderTraverse: function (callback) { - - var stack = []; - var node = this.root; - while (node != null || !BI.isEmpty(stack)) { - while (node != null) { - stack.push(node); - node = node.getLeft(); - } - node = stack.pop(); - callback && callback(node); - node = node.getRight(); + if (b === true) { + return true; } - }, + return this._recursion(child, next, callback); + }); + } + + recursion(callback) { + this._recursion(this.root, [], callback); + } + + inOrderTraverse(callback) { + this._inOrderTraverse(this.root, callback); + } + + // 中序遍历(递归) + _inOrderTraverse(node, callback) { + if (node != null) { + this._inOrderTraverse(node.getLeft()); + callback && callback(node); + this._inOrderTraverse(node.getRight()); + } + } - preOrderTraverse: function (callback) { - this._preOrderTraverse(this.root, callback); - }, + // 中序遍历(非递归) + nrInOrderTraverse(callback) { - // 先序遍历(递归) - _preOrderTraverse: function (node, callback) { - if (node != null) { - callback && callback(node); - this._preOrderTraverse(node.getLeft()); - this._preOrderTraverse(node.getRight()); + const stack = []; + let node = this.root; + while (node != null || !isEmpty(stack)) { + while (node != null) { + stack.push(node); + node = node.getLeft(); } - }, - - // 先序遍历(非递归) - nrPreOrderTraverse: function (callback) { - - var stack = []; - var node = this.root; + node = stack.pop(); + callback && callback(node); + node = node.getRight(); + } + } + + preOrderTraverse(callback) { + this._preOrderTraverse(this.root, callback); + } + + // 先序遍历(递归) + _preOrderTraverse(node, callback) { + if (node != null) { + callback && callback(node); + this._preOrderTraverse(node.getLeft()); + this._preOrderTraverse(node.getRight()); + } + } - while (node != null || !BI.isEmpty(stack)) { + // 先序遍历(非递归) + nrPreOrderTraverse(callback) { - while (node != null) { - callback && callback(node); - stack.push(node); - node = node.getLeft(); - } - node = stack.pop(); - node = node.getRight(); - } - }, + const stack = []; + let node = this.root; - postOrderTraverse: function (callback) { - this._postOrderTraverse(this.root, callback); - }, + while (node != null || !isEmpty(stack)) { - // 后序遍历(递归) - _postOrderTraverse: function (node, callback) { - if (node != null) { - this._postOrderTraverse(node.getLeft()); - this._postOrderTraverse(node.getRight()); + while (node != null) { callback && callback(node); + stack.push(node); + node = node.getLeft(); } - }, - - // 后续遍历(非递归) - nrPostOrderTraverse: function (callback) { - - var stack = []; - var node = this.root; - var preNode = null;// 表示最近一次访问的节点 - - while (node != null || !BI.isEmpty(stack)) { - - while (node != null) { - stack.push(node); - node = node.getLeft(); - } - - node = BI.last(stack); - - if (node.getRight() == null || node.getRight() == preNode) { - callback && callback(node); - node = stack.pop(); - preNode = node; - node = null; - } else { - node = node.getRight(); - } - } + node = stack.pop(); + node = node.getRight(); } - }; - - BI.Node = function (id) { - if (BI.isObject(id)) { - BI.extend(this, id); - } else { - this.id = id; + } + + postOrderTraverse(callback) { + this._postOrderTraverse(this.root, callback); + } + + // 后序遍历(递归) + _postOrderTraverse(node, callback) { + if (node != null) { + this._postOrderTraverse(node.getLeft()); + this._postOrderTraverse(node.getRight()); + callback && callback(node); } - this.clear.apply(this, arguments); - }; - - BI.Node.prototype = { - constructor: BI.Node, - - set: function (key, value) { - if (BI.isObject(key)) { - BI.extend(this, key); - return; - } - this[key] = value; - }, - - get: function (key) { - return this[key]; - }, - - isLeaf: function () { - return BI.isEmpty(this.children); - }, - - getChildren: function () { - return this.children; - }, - - getChildrenLength: function () { - return this.children.length; - }, - - getFirstChild: function () { - return BI.first(this.children); - }, - - getLastChild: function () { - return BI.last(this.children); - }, + } - setLeft: function (left) { - this.left = left; - }, + // 后续遍历(非递归) + nrPostOrderTraverse(callback) { - getLeft: function () { - return this.left; - }, + const stack = []; + let node = this.root; + let preNode = null;// 表示最近一次访问的节点 - setRight: function (right) { - this.right = right; - }, + while (node != null || !isEmpty(stack)) { - getRight: function () { - return this.right; - }, - - setParent: function (parent) { - this.parent = parent; - }, - - getParent: function () { - return this.parent; - }, - - getChild: function (index) { - return this.children[index]; - }, - - getChildIndex: function (id) { - return BI.findIndex(this.children, function (i, ch) { - return ch.get("id") === id; - }); - }, - - removeChild: function (id) { - this.removeChildByIndex(this.getChildIndex(id)); - }, - - removeChildByIndex: function (index) { - var before = this.getChild(index - 1); - var behind = this.getChild(index + 1); - if (before != null) { - before.setRight(behind || null); - } - if (behind != null) { - behind.setLeft(before || null); + while (node != null) { + stack.push(node); + node = node.getLeft(); } - this.children.splice(index, 1); - }, - removeAllChilds: function () { - this.children = []; - }, + node = last(stack); - addChild: function (child, index) { - var cur = null; - if (BI.isUndefined(index)) { - cur = this.children.length - 1; + if (node.getRight() == null || node.getRight() === preNode) { + callback && callback(node); + node = stack.pop(); + preNode = node; + node = null; } else { - cur = index - 1; + node = node.getRight(); } - child.setParent(this); - if (cur >= 0) { - this.getChild(cur) && this.getChild(cur).setRight(child); - child.setLeft(this.getChild(cur)); + } + } + + static transformToArrayFormat(nodes, pId, childKey) { + if (!nodes) return []; + let r = []; + childKey = childKey || "children"; + if (isArray(nodes)) { + for (let i = 0, l = nodes.length; i < l; i++) { + const node = clone(nodes[i]); + node.pId = node.pId == null ? pId : node.pId; + delete node.children; + r.push(node); + if (nodes[i][childKey]) { + r = r.concat(Tree.transformToArrayFormat(nodes[i][childKey], node.id)); + } } - if (BI.isUndefined(index)) { - this.children.push(child); - } else { - this.children.splice(index, 0, child); + } else { + const newNodes = clone(nodes); + newNodes.pId = newNodes.pId == null ? pId : newNodes.pId; + delete newNodes.children; + r.push(newNodes); + if (nodes[childKey]) { + r = r.concat(Tree.transformToArrayFormat(nodes[childKey], newNodes.id)); } - }, - - equals: function (obj) { - return this === obj || this.id === obj.id; - }, + } + return r; + } - clear: function () { - this.parent = null; - this.left = null; - this.right = null; - this.children = []; + static arrayFormat(nodes, pId) { + if (!nodes) { + return []; } - }; - - BI.extend(BI.Tree, { - transformToArrayFormat: function (nodes, pId, childKey) { - if (!nodes) return []; - var r = []; - childKey = childKey || "children"; - if (BI.isArray(nodes)) { - for (var i = 0, l = nodes.length; i < l; i++) { - var node = BI.clone(nodes[i]); - node.pId = node.pId == null ? pId : node.pId; - delete node.children; - r.push(node); - if (nodes[i][childKey]) { - r = r.concat(BI.Tree.transformToArrayFormat(nodes[i][childKey], node.id)); - } - } - } else { - var newNodes = BI.clone(nodes); - newNodes.pId = newNodes.pId == null ? pId : newNodes.pId; - delete newNodes.children; - r.push(newNodes); - if (nodes[childKey]) { - r = r.concat(BI.Tree.transformToArrayFormat(nodes[childKey], newNodes.id)); + let r = []; + if (isArray(nodes)) { + for (let i = 0, l = nodes.length; i < l; i++) { + const node = nodes[i]; + node.pId = node.pId == null ? pId : node.pId; + r.push(node); + if (nodes[i]["children"]) { + r = r.concat(Tree.arrayFormat(nodes[i]["children"], node.id)); } } - return r; - }, - - arrayFormat: function (nodes, pId) { - if (!nodes) { - return []; - } - var r = []; - if (BI.isArray(nodes)) { - for (var i = 0, l = nodes.length; i < l; i++) { - var node = nodes[i]; - node.pId = node.pId == null ? pId : node.pId; - r.push(node); - if (nodes[i]["children"]) { - r = r.concat(BI.Tree.arrayFormat(nodes[i]["children"], node.id)); - } - } - } else { - var newNodes = nodes; - newNodes.pId = newNodes.pId == null ? pId : newNodes.pId; - r.push(newNodes); - if (nodes["children"]) { - r = r.concat(BI.Tree.arrayFormat(nodes["children"], newNodes.id)); - } + } else { + const newNodes = nodes; + newNodes.pId = newNodes.pId == null ? pId : newNodes.pId; + r.push(newNodes); + if (nodes["children"]) { + r = r.concat(Tree.arrayFormat(nodes["children"], newNodes.id)); } - return r; - }, + } + return r; + } - transformToTreeFormat: function (sNodes) { - var i, l; - if (!sNodes) { - return []; - } + static transformToTreeFormat(sNodes) { + let i, l; + if (!sNodes) { + return []; + } - if (BI.isArray(sNodes)) { - var r = []; - var tmpMap = {}; - for (i = 0, l = sNodes.length; i < l; i++) { - if (BI.isNull(sNodes[i].id)) { - return sNodes; - } - tmpMap[sNodes[i].id] = BI.clone(sNodes[i]); + if (isArray(sNodes)) { + const r = []; + const tmpMap = {}; + for (i = 0, l = sNodes.length; i < l; i++) { + if (isNull(sNodes[i].id)) { + return sNodes; } - for (i = 0, l = sNodes.length; i < l; i++) { - if (tmpMap[sNodes[i].pId] && sNodes[i].id !== sNodes[i].pId) { - if (!tmpMap[sNodes[i].pId].children) { - tmpMap[sNodes[i].pId].children = []; - } - tmpMap[sNodes[i].pId].children.push(tmpMap[sNodes[i].id]); - } else { - r.push(tmpMap[sNodes[i].id]); + tmpMap[sNodes[i].id] = clone(sNodes[i]); + } + for (i = 0, l = sNodes.length; i < l; i++) { + if (tmpMap[sNodes[i].pId] && sNodes[i].id !== sNodes[i].pId) { + if (!tmpMap[sNodes[i].pId].children) { + tmpMap[sNodes[i].pId].children = []; } - delete tmpMap[sNodes[i].id].pId; + tmpMap[sNodes[i].pId].children.push(tmpMap[sNodes[i].id]); + } else { + r.push(tmpMap[sNodes[i].id]); } - return r; + delete tmpMap[sNodes[i].id].pId; } - return [sNodes]; + return r; + } + return [sNodes]; - }, + } - treeFormat: function (sNodes) { - var i, l; - if (!sNodes) { - return []; - } + static treeFormat(sNodes) { + let i, l; + if (!sNodes) { + return []; + } - if (BI.isArray(sNodes)) { - var r = []; - var tmpMap = {}; - for (i = 0, l = sNodes.length; i < l; i++) { - if (BI.isNull(sNodes[i].id)) { - return sNodes; - } - tmpMap[sNodes[i].id] = sNodes[i]; + if (isArray(sNodes)) { + const r = []; + const tmpMap = {}; + for (i = 0, l = sNodes.length; i < l; i++) { + if (isNull(sNodes[i].id)) { + return sNodes; } - for (i = 0, l = sNodes.length; i < l; i++) { - if (tmpMap[sNodes[i].pId] && sNodes[i].id !== sNodes[i].pId) { - if (!tmpMap[sNodes[i].pId].children) { - tmpMap[sNodes[i].pId].children = []; - } - tmpMap[sNodes[i].pId].children.push(tmpMap[sNodes[i].id]); - } else { - r.push(tmpMap[sNodes[i].id]); + tmpMap[sNodes[i].id] = sNodes[i]; + } + for (i = 0, l = sNodes.length; i < l; i++) { + if (tmpMap[sNodes[i].pId] && sNodes[i].id !== sNodes[i].pId) { + if (!tmpMap[sNodes[i].pId].children) { + tmpMap[sNodes[i].pId].children = []; } + tmpMap[sNodes[i].pId].children.push(tmpMap[sNodes[i].id]); + } else { + r.push(tmpMap[sNodes[i].id]); } - return r; } - return [sNodes]; + return r; + } + return [sNodes]; - }, + } - traversal: function (array, callback, pNode) { - if (BI.isNull(array)) { - return; - } - var self = this; - BI.some(array, function (i, item) { - if (callback(i, item, pNode) === false) { - return true; - } - self.traversal(item.children, callback, item); - }); + static traversal(array, callback, pNode) { + if (isNull(array)) { + return; } - }); -})(); + some(array, (i, item) => { + if (callback(i, item, pNode) === false) { + return true; + } + this.traversal(item.children, callback, item); + }); + } +} diff --git a/src/core/structure/vector.js b/src/core/structure/vector.js index d7ec50e9b..cd52754fd 100644 --- a/src/core/structure/vector.js +++ b/src/core/structure/vector.js @@ -1,27 +1,29 @@ // 向量操作 -BI.Vector = function (x, y) { - this.x = x; - this.y = y; -}; -BI.Vector.prototype = { - constructor: BI.Vector, - cross: function (v) { +export class Vector { + constructor(x, y) { + this.x = x; + this.y = y; + } + + cross(v) { return (this.x * v.y - this.y * v.x); - }, - length: function (v) { + } + + length(v) { return (Math.sqrt(this.x * v.x + this.y * v.y)); } -}; -BI.Region = function (x, y, w, h) { - this.x = x; - this.y = y; - this.w = w; - this.h = h; -}; -BI.Region.prototype = { - constructor: BI.Region, +} + +export class Region { + constructor(x, y, w, h) { + this.x = x; + this.y = y; + this.w = w; + this.h = h; + } + // 判断两个区域是否相交,若相交,则要么顶点互相包含,要么矩形边界(或对角线)相交 - isIntersects: function (obj) { + isIntersects(obj) { if (this.isPointInside(obj.x, obj.y) || this.isPointInside(obj.x + obj.w, obj.y) || this.isPointInside(obj.x, obj.y + obj.h) || @@ -34,17 +36,18 @@ BI.Region.prototype = { return true; } else if (obj.x != null && obj.y != null)// 判断矩形对角线相交 |v1 X v2||v1 X v3| < 0 { - var vector1 = new BI.Vector(this.w, this.h);// 矩形对角线向量 - var vector2 = new BI.Vector(obj.x - this.x, obj.y - this.y); - var vector3 = new BI.Vector(vector2.x + obj.w, vector2.y + obj.h); + const vector1 = new Vector(this.w, this.h);// 矩形对角线向量 + const vector2 = new Vector(obj.x - this.x, obj.y - this.y); + const vector3 = new Vector(vector2.x + obj.w, vector2.y + obj.h); if ((vector1.cross(vector2) * vector1.cross(vector3)) < 0) { return true; } } return false; - }, + } + // 判断一个点是否在这个区域内部 - isPointInside: function (x, y) { + isPointInside(x, y) { if (this.x == null || this.y == null) { return false; } @@ -52,12 +55,14 @@ BI.Region.prototype = { return true; } return false; - }, + } + // 返回区域的重心,因为是矩形所以返回中点 - getPosition: function () { - var pos = []; + getPosition() { + const pos = []; pos.push(this.x + this.w / 2); pos.push(this.y + this.h / 2); return pos; } -}; \ No newline at end of file +} + From 6b58c1b907ff2a60de1bfe42f9295b845ff10c40 Mon Sep 17 00:00:00 2001 From: zsmj Date: Wed, 4 Jan 2023 15:04:47 +0800 Subject: [PATCH 033/300] =?UTF-8?q?KERNEL-14012=20feat:=20core/structure?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=A4=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/index.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/core/index.js b/src/core/index.js index 53a8cd755..2c85e1eda 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -1,4 +1,3 @@ - import * as base from "./2.base"; import * as ob from "./3.ob"; import * as widget from "./4.widget"; @@ -7,10 +6,10 @@ import * as action from "./action"; import * as behavior from "./behavior"; import * as controllers from "./controller"; import * as func from "./func"; -import { StyleLoaderManager } from "./loader/loader.style"; +import {StyleLoaderManager} from "./loader/loader.style"; import "./h"; -import { ShowListener } from "./listener/listener.show"; -import { shortcut } from "./decorator"; +import {ShowListener} from "./listener/listener.show"; +import {shortcut} from "./decorator"; export * from "./2.base"; export * from "./3.ob"; @@ -20,12 +19,13 @@ export * from "./action"; export * from "./behavior"; export * from "./controller"; export * from "./func"; +export * from "./structure"; export { StyleLoaderManager, ShowListener, shortcut, -} +}; Object.assign(BI, { ...base, From b092b80dd4f6f3e4357bd1026c5dfc45e620478c Mon Sep 17 00:00:00 2001 From: impact Date: Wed, 4 Jan 2023 15:34:44 +0800 Subject: [PATCH 034/300] =?UTF-8?q?KERNEL-13901=20refactor:=20label?= =?UTF-8?q?=E3=80=81editor=E3=80=81input=E6=96=87=E4=BB=B6=E5=A4=B9ES6?= =?UTF-8?q?=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/foundation/message.js | 2 +- src/base/index.js | 2 + src/base/single/editor/editor.js | 373 +++--- src/base/single/editor/editor.multifile.js | 112 +- src/base/single/editor/editor.textarea.js | 246 ++-- src/base/single/editor/index.js | 3 + src/base/single/html/html.js | 105 +- src/base/single/icon/icon.js | 23 +- src/base/single/index.js | 8 +- src/base/single/input/file.js | 1286 ++++++++++---------- src/base/single/input/index.js | 2 + src/base/single/input/input.js | 339 +++--- src/base/single/label/abstract.label.js | 601 ++++----- src/base/single/label/html.label.js | 32 +- src/base/single/label/icon.label.js | 62 +- src/base/single/label/index.js | 4 + src/base/single/label/label.js | 36 +- src/base/single/text.pure.js | 75 +- 18 files changed, 1685 insertions(+), 1626 deletions(-) create mode 100644 src/base/single/editor/index.js create mode 100644 src/base/single/input/index.js create mode 100644 src/base/single/label/index.js diff --git a/src/base/foundation/message.js b/src/base/foundation/message.js index add1060ba..40cbb90c5 100644 --- a/src/base/foundation/message.js +++ b/src/base/foundation/message.js @@ -49,7 +49,7 @@ export const Msg = ((() => { }, }], }); - const height = BI.SIZE_CONSANTS.TOAST_TOP; + let height = BI.SIZE_CONSANTS.TOAST_TOP; each(toastStack, function (i, element) { height += element.outerHeight() + 10; }); diff --git a/src/base/index.js b/src/base/index.js index 2c1dc228c..1db6a6206 100644 --- a/src/base/index.js +++ b/src/base/index.js @@ -6,6 +6,7 @@ import GridView from "./grid/grid"; import Pager from "./pager/pager"; import * as combination from "./combination"; import { Msg } from "./foundation/message"; +import * as base from "./0.base"; Object.assign(BI, { Pane, @@ -16,6 +17,7 @@ Object.assign(BI, { Pager, ...combination, Msg, + ...base, }); export * from "./0.base"; diff --git a/src/base/single/editor/editor.js b/src/base/single/editor/editor.js index c0a77c9f6..0cf075a39 100644 --- a/src/base/single/editor/editor.js +++ b/src/base/single/editor/editor.js @@ -3,11 +3,39 @@ * @class BI.Editor * @extends BI.Single */ -BI.Editor = BI.inherit(BI.Single, { - _defaultConfig: function () { - var conf = BI.Editor.superclass._defaultConfig.apply(this, arguments); - - return BI.extend(conf, { +import { shortcut, Controller, extend, createWidget, isKey, isEmptyString, isFunction, isNull, trim, } from "../../../core"; +import { Single } from "../0.single"; +import { Input } from "../input/input"; +import { Bubbles } from "../../0.base"; + +@shortcut() +export class Editor extends Single { + static xtype = "bi.editor"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_CLICK = "EVENT_CLICK"; + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; + static EVENT_SPACE = "EVENT_SPACE"; + static EVENT_BACKSPACE = "EVENT_BACKSPACE"; + + static EVENT_START = "EVENT_START"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; + static EVENT_VALID = "EVENT_VALID"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_ENTER = "EVENT_ENTER"; + static EVENT_RESTRICT = "EVENT_RESTRICT"; + static EVENT_REMOVE = "EVENT_REMOVE"; + static EVENT_EMPTY = "EVENT_EMPTY"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { baseCls: "bi-editor bi-focus-shadow", hgap: 4, vgap: 2, @@ -25,21 +53,21 @@ BI.Editor = BI.inherit(BI.Single, { errorText: "", autoTrim: true, }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const { value, watermark, validationChecker, quitChecker, allowBlank, inputType, hgap, vgap, lgap, rgap, tgap, bgap } = this.options; // 密码输入框设置autocomplete="new-password"的情况下Firefox和chrome不会自动填充密码 - var autocomplete = o.autocomplete ? " autocomplete=" + o.autocomplete : ""; - this.editor = this.addWidget(BI.createWidget({ + const autocomplete = this.options.autocomplete ? " autocomplete=" + this.options.autocomplete : ""; + this.editor = this.addWidget(createWidget({ type: "bi.input", - element: "", + element: "", root: true, - value: o.value, - watermark: o.watermark, - validationChecker: o.validationChecker, - quitChecker: o.quitChecker, - allowBlank: o.allowBlank, + value, + watermark, + validationChecker, + quitChecker, + allowBlank, })); this.editor.element.css({ width: "100%", @@ -50,12 +78,12 @@ BI.Editor = BI.inherit(BI.Single, { margin: "0", }); - var items = [ + const items = [ { el: { type: "bi.absolute", - ref: function (_ref) { - self.contentWrapper = _ref; + ref: (_ref) => { + this.contentWrapper = _ref; }, items: [ { @@ -67,190 +95,189 @@ BI.Editor = BI.inherit(BI.Single, { } ], }, - left: o.hgap + o.lgap, - right: o.hgap + o.rgap, - top: o.vgap + o.tgap, - bottom: o.vgap + o.bgap, + left: hgap + lgap, + right: hgap + rgap, + top: vgap + tgap, + bottom: vgap + bgap, } ]; - BI.createWidget({ + createWidget({ type: "bi.absolute", element: this, - items: items, + items, }); this.setWaterMark(this.options.watermark); - this.editor.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.editor.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.editor.on(BI.Input.EVENT_FOCUS, function () { - self._checkError(); - self.element.addClass("bi-editor-focus"); - self.fireEvent(BI.Editor.EVENT_FOCUS, arguments); + this.editor.on(Input.EVENT_FOCUS, (...args) => { + this._checkError(); + this.element.addClass("bi-editor-focus"); + this.fireEvent(Editor.EVENT_FOCUS, ...args); }); - this.editor.on(BI.Input.EVENT_BLUR, function () { - self._setErrorVisible(false); - self.element.removeClass("bi-editor-focus"); - self.fireEvent(BI.Editor.EVENT_BLUR, arguments); + this.editor.on(Input.EVENT_BLUR, (...args) => { + this._setErrorVisible(false); + this.element.removeClass("bi-editor-focus"); + this.fireEvent(Editor.EVENT_BLUR, ...args); }); - this.editor.on(BI.Input.EVENT_CLICK, function () { - self.fireEvent(BI.Editor.EVENT_CLICK, arguments); + this.editor.on(Input.EVENT_CLICK, (...args) => { + this.fireEvent(Editor.EVENT_CLICK, ...args); }); - this.editor.on(BI.Input.EVENT_CHANGE, function () { - self.fireEvent(BI.Editor.EVENT_CHANGE, arguments); + this.editor.on(Input.EVENT_CHANGE, (...args) => { + this.fireEvent(Editor.EVENT_CHANGE, ...args); }); - this.editor.on(BI.Input.EVENT_KEY_DOWN, function (v) { - self.fireEvent(BI.Editor.EVENT_KEY_DOWN, arguments); + this.editor.on(Input.EVENT_KEY_DOWN, (v, ...args) => { + this.fireEvent(Editor.EVENT_KEY_DOWN, v, ...args); }); - this.editor.on(BI.Input.EVENT_QUICK_DOWN, function (e) { + this.editor.on(Input.EVENT_QUICK_DOWN, (e) => { // tab键就不要隐藏了 - if (e.keyCode !== BI.KeyCode.TAB && self.watermark) { - self.watermark.invisible(); + if (e.keyCode !== BI.KeyCode.TAB && this.watermark) { + this.watermark.invisible(); } }); - this.editor.on(BI.Input.EVENT_VALID, function () { - self._checkWaterMark(); - self._setErrorVisible(false); - self.element.removeClass("error"); - self.fireEvent(BI.Editor.EVENT_VALID, arguments); + this.editor.on(Input.EVENT_VALID, (...args) => { + this._checkWaterMark(); + this._setErrorVisible(false); + this.element.removeClass("error"); + this.fireEvent(Editor.EVENT_VALID, ...args); }); - this.editor.on(BI.Input.EVENT_ERROR, function () { - self._checkWaterMark(); - self.fireEvent(BI.Editor.EVENT_ERROR, arguments); - self._setErrorVisible(self.isEditing()); - self.element.addClass("error"); + this.editor.on(Input.EVENT_ERROR, (...args) => { + this._checkWaterMark(); + this.fireEvent(Editor.EVENT_ERROR, ...args); + this._setErrorVisible(this.isEditing()); + this.element.addClass("error"); }); - this.editor.on(BI.Input.EVENT_RESTRICT, function () { - self._checkWaterMark(); - var tip = self._setErrorVisible(true); - tip && tip.element.fadeOut(100, function () { + this.editor.on(Input.EVENT_RESTRICT, (...args) => { + this._checkWaterMark(); + const tip = this._setErrorVisible(true); + tip && tip.element.fadeOut(100, () => { tip.element.fadeIn(100); }); - self.fireEvent(BI.Editor.EVENT_RESTRICT, arguments); + this.fireEvent(Editor.EVENT_RESTRICT, ...args); }); - this.editor.on(BI.Input.EVENT_EMPTY, function () { - self._checkWaterMark(); - self.fireEvent(BI.Editor.EVENT_EMPTY, arguments); + this.editor.on(Input.EVENT_EMPTY, (...args) => { + this._checkWaterMark(); + this.fireEvent(Editor.EVENT_EMPTY, ...args); }); - this.editor.on(BI.Input.EVENT_ENTER, function () { - self.fireEvent(BI.Editor.EVENT_ENTER, arguments); + this.editor.on(Input.EVENT_ENTER, (...args) => { + this.fireEvent(Editor.EVENT_ENTER, ...args); }); - this.editor.on(BI.Input.EVENT_SPACE, function () { - self.fireEvent(BI.Editor.EVENT_SPACE, arguments); + this.editor.on(Input.EVENT_SPACE, (...args) => { + this.fireEvent(Editor.EVENT_SPACE, ...args); }); - this.editor.on(BI.Input.EVENT_BACKSPACE, function () { - self.fireEvent(BI.Editor.EVENT_BACKSPACE, arguments); + this.editor.on(Input.EVENT_BACKSPACE, (...args) => { + this.fireEvent(Editor.EVENT_BACKSPACE, ...args); }); - this.editor.on(BI.Input.EVENT_REMOVE, function () { - self.fireEvent(BI.Editor.EVENT_REMOVE, arguments); + this.editor.on(Input.EVENT_REMOVE, (...args) => { + this.fireEvent(Editor.EVENT_REMOVE, ...args); }); - this.editor.on(BI.Input.EVENT_START, function () { - self.fireEvent(BI.Editor.EVENT_START, arguments); + this.editor.on(Input.EVENT_START, (...args) => { + this.fireEvent(Editor.EVENT_START, ...args); }); - this.editor.on(BI.Input.EVENT_PAUSE, function () { - self.fireEvent(BI.Editor.EVENT_PAUSE, arguments); + this.editor.on(Input.EVENT_PAUSE, (...args) => { + this.fireEvent(Editor.EVENT_PAUSE, ...args); }); - this.editor.on(BI.Input.EVENT_STOP, function () { - self.fireEvent(BI.Editor.EVENT_STOP, arguments); + this.editor.on(Input.EVENT_STOP, (...args) => { + this.fireEvent(Editor.EVENT_STOP, ...args); }); - this.editor.on(BI.Input.EVENT_CONFIRM, function () { - self.fireEvent(BI.Editor.EVENT_CONFIRM, arguments); + this.editor.on(Input.EVENT_CONFIRM, (...args) => { + this.fireEvent(Editor.EVENT_CONFIRM, ...args); }); - this.editor.on(BI.Input.EVENT_CHANGE_CONFIRM, function () { - self.fireEvent(BI.Editor.EVENT_CHANGE_CONFIRM, arguments); + this.editor.on(Input.EVENT_CHANGE_CONFIRM, (...args) => { + this.fireEvent(Editor.EVENT_CHANGE_CONFIRM, ...args); }); - this.element.click(function (e) { + this.element.click((e) => { e.stopPropagation(); return false; }); - if (BI.isKey(this.options.value) || BI.isEmptyString(this.options.value)) { + if (isKey(this.options.value) || isEmptyString(this.options.value)) { this._checkError(); this._checkWaterMark(); } else { this._checkWaterMark(); } - }, + } - _checkToolTip: function () { - var o = this.options; - var errorText = o.errorText; - if (BI.isFunction(errorText)) { + _checkToolTip() { + const { errorText } = this.options; + if (isFunction(errorText)) { errorText = errorText(this.editor.getValue()); } - if (BI.isKey(errorText)) { - if (!this.isEnabled() || this.isValid() || BI.Bubbles.has(this.getName())) { + if (isKey(errorText)) { + if (!this.isEnabled() || this.isValid() || Bubbles.has(this.getName())) { this.setTitle(""); } else { this.setTitle(errorText); } } - }, + } - _assertWaterMark: function () { - var self = this, o = this.options; - if (BI.isNull(this.watermark)) { - this.watermark = BI.createWidget({ + _assertWaterMark() { + const { height, vgap, tgap } = this.options; + if (isNull(this.watermark)) { + this.watermark = createWidget({ type: "bi.label", cls: "bi-water-mark", text: this.options.watermark, - height: o.height - 2 * o.vgap - o.tgap, + height: height - 2 * vgap - tgap, hgap: 2, whiteSpace: "nowrap", textAlign: "left", }); this.watermark.element.bind({ - mousedown: function (e) { - if (self.isEnabled()) { - self.editor.isEditing() || self.editor.focus(); + mousedown: (e) => { + if (this.isEnabled()) { + this.editor.isEditing() || this.editor.focus(); } else { - self.editor.isEditing() && self.editor.blur(); + this.editor.isEditing() && this.editor.blur(); } e.stopEvent(); }, }); - this.watermark.element.bind("click", function (e) { - if (self.isEnabled()) { - self.editor.isEditing() || self.editor.focus(); + this.watermark.element.bind("click", (e) => { + if (this.isEnabled()) { + this.editor.isEditing() || this.editor.focus(); } else { - self.editor.isEditing() && self.editor.blur(); + this.editor.isEditing() && this.editor.blur(); } e.stopEvent(); }); } - }, + } - _checkError: function () { + _checkError() { this._setErrorVisible(this.isEnabled() && !this.isValid()); this._checkToolTip(); - }, + } - _checkWaterMark: function () { - var o = this.options; - if (!this.disabledWaterMark && this.editor.getValue() === "" && BI.isKey(o.watermark)) { + _checkWaterMark() { + const { watermark } = this.options; + if (!this.disabledWaterMark && this.editor.getValue() === "" && isKey(watermark)) { this.watermark && this.watermark.visible(); } else { this.watermark && this.watermark.invisible(); } - }, + } - setErrorText: function (text) { + setErrorText(text) { this.options.errorText = text; - }, + } - getErrorText: function () { + getErrorText() { return this.options.errorText; - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.options.watermark = v; - if (BI.isNull(this.watermark)) { + if (isNull(this.watermark)) { this._assertWaterMark(); - BI.createWidget({ + createWidget({ type: "bi.absolute", element: this.contentWrapper, items: [ @@ -266,113 +293,91 @@ BI.Editor = BI.inherit(BI.Single, { } this.watermark.setText(v); this._checkWaterMark(); - }, + } - _setErrorVisible: function (b) { - var o = this.options; - var errorText = o.errorText; - if (BI.isFunction(errorText)) { - errorText = errorText(o.autoTrim ? BI.trim(this.editor.getValue()) : this.editor.getValue()); + _setErrorVisible(b) { + const { errorText, autoTrim, simple } = this.options; + if (isFunction(errorText)) { + errorText = errorText(autoTrim ? trim(this.editor.getValue()) : this.editor.getValue()); } - if (!this.disabledError && BI.isKey(errorText)) { - BI.Bubbles[b ? "show" : "hide"](this.getName(), errorText, this, { - adjustYOffset: o.simple ? 1 : 2, + if (!this.disabledError && isKey(errorText)) { + Bubbles[b ? "show" : "hide"](this.getName(), errorText, this, { + adjustYOffset: simple ? 1 : 2, }); this._checkToolTip(); } - }, + } - disableError: function () { + disableError() { this.disabledError = true; this._checkError(); - }, + } - enableError: function () { + enableError() { this.disabledError = false; this._checkError(); - }, + } - disableWaterMark: function () { + disableWaterMark() { this.disabledWaterMark = true; this._checkWaterMark(); - }, + } - enableWaterMark: function () { + enableWaterMark() { this.disabledWaterMark = false; this._checkWaterMark(); - }, + } - focus: function () { + focus() { this.element.addClass("text-editor-focus"); this.editor.focus(); - }, + } - blur: function () { + blur() { this.element.removeClass("text-editor-focus"); this.editor.blur(); - }, + } - selectAll: function () { + selectAll() { this.editor.selectAll(); - }, + } - onKeyDown: function (k) { + onKeyDown(k) { this.editor.onKeyDown(k); - }, + } - setValue: function (v) { - BI.Editor.superclass.setValue.apply(this, arguments); + setValue(v) { + super.setValue(v); this.editor.setValue(v); this._checkError(); this._checkWaterMark(); - }, + } - getLastValidValue: function () { + getLastValidValue() { return this.editor.getLastValidValue(); - }, + } - getLastChangedValue: function () { + getLastChangedValue() { return this.editor.getLastChangedValue(); - }, + } - getValue: function () { + getValue() { if (!this.isValid()) { - return this.options.autoTrim ? BI.trim(this.editor.getLastValidValue()) : this.editor.getLastValidValue(); + return this.options.autoTrim ? trim(this.editor.getLastValidValue()) : this.editor.getLastValidValue(); } - return this.options.autoTrim ? BI.trim(this.editor.getValue()) : this.editor.getValue(); - }, + return this.options.autoTrim ? trim(this.editor.getValue()) : this.editor.getValue(); + } - isEditing: function () { + isEditing() { return this.editor.isEditing(); - }, + } - isValid: function () { + isValid() { return this.editor.isValid(); - }, - - destroyed: function () { - BI.Bubbles.remove(this.getName()); - }, -}); -BI.Editor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.Editor.EVENT_FOCUS = "EVENT_FOCUS"; -BI.Editor.EVENT_BLUR = "EVENT_BLUR"; -BI.Editor.EVENT_CLICK = "EVENT_CLICK"; -BI.Editor.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.Editor.EVENT_SPACE = "EVENT_SPACE"; -BI.Editor.EVENT_BACKSPACE = "EVENT_BACKSPACE"; - -BI.Editor.EVENT_START = "EVENT_START"; -BI.Editor.EVENT_PAUSE = "EVENT_PAUSE"; -BI.Editor.EVENT_STOP = "EVENT_STOP"; -BI.Editor.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.Editor.EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; -BI.Editor.EVENT_VALID = "EVENT_VALID"; -BI.Editor.EVENT_ERROR = "EVENT_ERROR"; -BI.Editor.EVENT_ENTER = "EVENT_ENTER"; -BI.Editor.EVENT_RESTRICT = "EVENT_RESTRICT"; -BI.Editor.EVENT_REMOVE = "EVENT_REMOVE"; -BI.Editor.EVENT_EMPTY = "EVENT_EMPTY"; - -BI.shortcut("bi.editor", BI.Editor); + } + + destroyed() { + Bubbles.remove(this.getName()); + } +} diff --git a/src/base/single/editor/editor.multifile.js b/src/base/single/editor/editor.multifile.js index 21765474d..0954dcbbb 100644 --- a/src/base/single/editor/editor.multifile.js +++ b/src/base/single/editor/editor.multifile.js @@ -6,52 +6,64 @@ * @extends BI.Single * @abstract */ -BI.MultifileEditor = BI.inherit(BI.Widget, { - _defaultConfig: function () { - var conf = BI.MultifileEditor.superclass._defaultConfig.apply(this, arguments); +import { shortcut, Widget, createWidget, extend } from "../../../core"; +import { File } from "../input/file"; - return BI.extend(conf, { +@shortcut() +export class MultifileEditor extends Widget { + static xtype = "bi.multifile_editor"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_UPLOADSTART = "EVENT_UPLOADSTART"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_PROGRESS = "EVENT_PROGRESS"; + static EVENT_UPLOADED = "EVENT_UPLOADED"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { baseCls: (conf.baseCls || "") + " bi-multifile-editor", multiple: false, maxSize: -1, // 1024 * 1024 accept: "", url: "", }); - }, + } - render: function () { - var self = this, o = this.options; - this.file = BI.createWidget({ + render() { + const { name, url, multiple, accept, maxSize, maxLength, title, errorText } = this.options; + this.file = createWidget({ type: "bi.file", cls: "multifile-editor", width: "100%", height: "100%", - name: o.name, - url: o.url, - multiple: o.multiple, - accept: o.accept, - maxSize: o.maxSize, - maxLength: o.maxLength, - title: o.title, - errorText: o.errorText, + name, + url, + multiple, + accept, + maxSize, + maxLength, + title, + errorText, }); - this.file.on(BI.File.EVENT_CHANGE, function () { - self.fireEvent(BI.MultifileEditor.EVENT_CHANGE, arguments); + this.file.on(File.EVENT_CHANGE, (...args) => { + this.fireEvent(MultifileEditor.EVENT_CHANGE, ...args); }); - this.file.on(BI.File.EVENT_UPLOADSTART, function () { - self.fireEvent(BI.MultifileEditor.EVENT_UPLOADSTART, arguments); + this.file.on(File.EVENT_UPLOADSTART, (...args) => { + this.fireEvent(MultifileEditor.EVENT_CHANGE, ...args); }); - this.file.on(BI.File.EVENT_ERROR, function () { - self.fireEvent(BI.MultifileEditor.EVENT_ERROR, arguments); + this.file.on(File.EVENT_ERROR, (...args) => { + this.fireEvent(MultifileEditor.EVENT_CHANGE, ...args); }); - this.file.on(BI.File.EVENT_PROGRESS, function () { - self.fireEvent(BI.MultifileEditor.EVENT_PROGRESS, arguments); + this.file.on(File.EVENT_PROGRESS, (...args) => { + this.fireEvent(MultifileEditor.EVENT_CHANGE, ...args); }); - this.file.on(BI.File.EVENT_UPLOADED, function () { - self.fireEvent(BI.MultifileEditor.EVENT_UPLOADED, arguments); + this.file.on(File.EVENT_UPLOADED, (...args) => { + this.fireEvent(MultifileEditor.EVENT_CHANGE, ...args); }); - BI.createWidget({ + createWidget({ type: "bi.absolute", element: this, items: [{ @@ -66,50 +78,44 @@ BI.MultifileEditor = BI.inherit(BI.Widget, { bottom: 0, }], }); - }, + } - _reset: function () { + _reset() { this.file.reset(); - }, + } - setUrl: function (v) { + setUrl(v) { this.file.setUrl(v); - }, + } - setMaxFileLength: function (v) { + setMaxFileLength(v) { this.file.setMaxFileLength(v); - }, + } - select: function () { + select() { this.file.select(); - }, + } - getQueue: function () { + getQueue() { return this.file.getQueue(); - }, + } - getValue: function () { + getValue() { return this.file.getValue(); - }, + } - upload: function () { + upload() { this._reset(); this.file.upload(); - }, + } - sendFiles: function (files) { + sendFiles(files) { this._reset(); this.file.sendFiles(files); - }, + } - reset: function () { + reset() { this._reset(); - }, -}); -BI.MultifileEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultifileEditor.EVENT_UPLOADSTART = "EVENT_UPLOADSTART"; -BI.MultifileEditor.EVENT_ERROR = "EVENT_ERROR"; -BI.MultifileEditor.EVENT_PROGRESS = "EVENT_PROGRESS"; -BI.MultifileEditor.EVENT_UPLOADED = "EVENT_UPLOADED"; -BI.shortcut("bi.multifile_editor", BI.MultifileEditor); + } +} diff --git a/src/base/single/editor/editor.textarea.js b/src/base/single/editor/editor.textarea.js index d3838d29e..2ef9df43f 100644 --- a/src/base/single/editor/editor.textarea.js +++ b/src/base/single/editor/editor.textarea.js @@ -4,36 +4,50 @@ * @class BI.TextAreaEditor * @extends BI.Single */ -BI.TextAreaEditor = BI.inherit(BI.Single, { - _defaultConfig: function (conf) { - return BI.extend(BI.TextAreaEditor.superclass._defaultConfig.apply(), { +import { shortcut, Widget, Controller, createWidget, extend, isEmptyString, isKey, isNotEmptyString, isNotNull, trim, isFunction } from "../../../core"; +import { Single } from "../0.single"; +import { Bubbles } from "../../0.base"; + +@shortcut() +export class TextAreaEditor extends Single { + static xtype = "bi.textarea_editor"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_EMPTY = "EVENT_EMPTY"; + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; + + _defaultConfig(conf) { + return extend(super._defaultConfig(), { baseCls: "bi-textarea-editor", value: "", errorText: "", adjustYOffset: conf.simple ? 0 : 2, adjustXOffset: 0, offsetStyle: "left", - validationChecker: function () { + validationChecker: () => { return true; }, scrolly: true, }); - }, + } - render: function () { - var o = this.options, self = this; - this.content = BI.createWidget({ + render() { + const { scrolly, value, style } = this.options; + this.content = createWidget({ type: "bi.layout", tagName: "textarea", width: "100%", height: "100%", cls: "bi-textarea textarea-editor-content display-block", - css: o.scrolly ? null : { + css: scrolly ? null : { overflowY: "hidden", }, }); this.content.element.css({ resize: "none" }); - BI.createWidget({ + createWidget({ type: "bi.absolute", element: this, items: [{ @@ -48,90 +62,90 @@ BI.TextAreaEditor = BI.inherit(BI.Single, { }], }); - this.content.element.on("input propertychange", function (e) { - self._checkError(); - self._checkWaterMark(); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.CHANGE, self.getValue(), self); - self.fireEvent(BI.TextAreaEditor.EVENT_CHANGE); - if (BI.isEmptyString(self.getValue())) { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EMPTY, self.getValue(), self); + this.content.element.on("input propertychange", (e) => { + this._checkError(); + this._checkWaterMark(); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.CHANGE, this.getValue(), this); + this.fireEvent(TextAreaEditor.EVENT_CHANGE); + if (isEmptyString(this.getValue())) { + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EMPTY, this.getValue(), this); } }); - this.content.element.focus(function () { - self._checkError(); - self._focus(); - self.fireEvent(BI.TextAreaEditor.EVENT_FOCUS); - BI.Widget._renderEngine.createElement(document).bind("mousedown." + self.getName(), function (e) { - if (BI.DOM.isExist(self) && !self.element.__isMouseInBounds__(e)) { - BI.Widget._renderEngine.createElement(document).unbind("mousedown." + self.getName()); - self.content.element.blur(); + this.content.element.focus(() => { + this._checkError(); + this._focus(); + this.fireEvent(TextAreaEditor.EVENT_FOCUS); + Widget._renderEngine.createElement(document).bind("mousedown." + this.getName(), (e) => { + if (BI.DOM.isExist(this) && !this.element.__isMouseInBounds__(e)) { + Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()); + this.content.element.blur(); } }); }); - this.content.element.blur(function () { - self._setErrorVisible(false); - self._blur(); - if (!self._isError()) { - self.fireEvent(BI.TextAreaEditor.EVENT_CONFIRM); + this.content.element.blur(() => { + this._setErrorVisible(false); + this._blur(); + if (!this._isError()) { + this.fireEvent(TextAreaEditor.EVENT_CONFIRM); } - self.fireEvent(BI.TextAreaEditor.EVENT_BLUR); - BI.Widget._renderEngine.createElement(document).unbind("mousedown." + self.getName()); + this.fireEvent(TextAreaEditor.EVENT_BLUR); + Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()); }); - this.content.element.keydown(function () { + this.content.element.keydown(() => { // 水印快速消失 - self._checkWaterMark(); + this._checkWaterMark(); }); - this.content.element.keyup(function (e) { - self.fireEvent(BI.TextAreaEditor.EVENT_KEY_DOWN, e.keyCode); + this.content.element.keyup((e) => { + this.fireEvent(TextAreaEditor.EVENT_KEY_DOWN, e.keyCode); }); - this.content.element.click(function (e) { + this.content.element.click((e) => { e.stopPropagation(); }); - if (BI.isKey(o.value)) { - this.setValue(o.value); + if (isKey(value)) { + this.setValue(value); } - if (BI.isNotNull(o.style)) { - this.setStyle(o.style); + if (isNotNull(style)) { + this.setStyle(style); } this._checkWaterMark(); - }, + } - _checkWaterMark: function () { - var self = this, o = this.options; - var val = this.getValue(); - if (BI.isNotEmptyString(val)) { + _checkWaterMark() { + const { watermark, scrolly, invalid, disabled, height } = this.options; + const val = this.getValue(); + if (isNotEmptyString(val)) { this.watermark && this.watermark.destroy(); this.watermark = null; } else { - if (BI.isNotEmptyString(o.watermark)) { + if (isNotEmptyString(watermark)) { if (!this.watermark) { - this.watermark = BI.createWidget({ + this.watermark = createWidget({ type: "bi.label", cls: "bi-water-mark textarea-watermark", textAlign: "left", - whiteSpace: o.scrolly ? "normal" : "nowrap", - text: o.watermark, - invalid: o.invalid, - disabled: o.disabled, + whiteSpace: scrolly ? "normal" : "nowrap", + text: watermark, + invalid, + disabled, hgap: 6, - vgap: o.height > 24 ? 4 : 2, - height: o.height > 24 ? "" : o.height, + vgap: height > 24 ? 4 : 2, + height: height > 24 ? "" : height, }); this.watermark.element.bind({ - mousedown: function (e) { - if (self.isEnabled()) { - self.focus(); + mousedown: (e) => { + if (this.isEnabled()) { + this.focus(); } else { - self.blur(); + this.blur(); } e.stopEvent(); }, - click: function (e) { + click: (e) => { e.stopPropagation(); }, }); - BI.createWidget({ + createWidget({ type: "bi.absolute", element: this, items: [{ @@ -142,112 +156,104 @@ BI.TextAreaEditor = BI.inherit(BI.Single, { }], }); } else { - this.watermark.setText(o.watermark); - this.watermark.setValid(!o.invalid); - this.watermark.setEnable(!o.disabled); + this.watermark.setText(watermark); + this.watermark.setValid(!invalid); + this.watermark.setEnable(!disabled); } } } - }, + } - _isError: function () { + _isError() { return this.isEnabled() && !this.options.validationChecker(this.getValue()); - }, + } - _checkError: function () { - var isError = this._isError(); + _checkError() { + const isError = this._isError(); this._setErrorVisible(isError); this.element[isError ? "addClass" : "removeClass"]("error"); - }, + } - _focus: function () { + _focus() { this.content.element.addClass("textarea-editor-focus"); this._checkWaterMark(); - if (BI.isEmptyString(this.getValue())) { - this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EMPTY, this.getValue(), this); + if (isEmptyString(this.getValue())) { + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EMPTY, this.getValue(), this); } - }, + } - _blur: function () { + _blur() { this.content.element.removeClass("textarea-editor-focus"); this._checkWaterMark(); - }, + } - _setErrorVisible: function (b) { - var o = this.options; - var errorText = o.errorText; - if (BI.isFunction(errorText)) { - errorText = errorText(BI.trim(this.getValue())); + _setErrorVisible(b) { + const { errorText, adjustYOffset, adjustXOffset, offsetStyle } = this.options; + if (isFunction(errorText)) { + errorText = errorText(trim(this.getValue())); } - if (!this.disabledError && BI.isKey(errorText)) { - BI.Bubbles[b ? "show" : "hide"](this.getName(), errorText, this, { - adjustYOffset: o.adjustYOffset, - adjustXOffset: o.adjustXOffset, - offsetStyle: o.offsetStyle, + if (!this.disabledError && isKey(errorText)) { + Bubbles[b ? "show" : "hide"](this.getName(), errorText, this, { + adjustYOffset, + adjustXOffset, + offsetStyle, }); } - }, + } - _defaultState: function () { - if (BI.isEmptyString(this.getValue())) { - this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EMPTY, this.getValue(), this); - this.fireEvent(BI.TextAreaEditor.EVENT_EMPTY); + _defaultState() { + if (isEmptyString(this.getValue())) { + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EMPTY, this.getValue(), this); + this.fireEvent(TextAreaEditor.EVENT_EMPTY); } - }, + } - focus: function () { + focus() { this._focus(); this.content.element.focus(); - }, + } - blur: function () { + blur() { this._blur(); this.content.element.blur(); - }, + } - getValue: function () { + getValue() { return this.content.element.val(); - }, + } - setValue: function (value) { + setValue(value) { this.content.element.val(value); this._checkError(); this._checkWaterMark(); this._defaultState(); - }, + } - setStyle: function (style) { + setStyle(style) { this.style = style; this.element.css(style); - this.content.element.css(BI.extend({}, style, { + this.content.element.css(extend({}, style, { color: style.color || BI.DOM.getContrastColor(BI.DOM.isRGBColor(style.backgroundColor) ? BI.DOM.rgb2hex(style.backgroundColor) : style.backgroundColor), })); - }, + } - getStyle: function () { + getStyle() { return this.style; - }, + } - setWatermark: function (v) { + setWatermark(v) { this.options.watermark = v; this._checkWaterMark(); - }, + } - _setValid: function (b) { - BI.TextAreaEditor.superclass._setValid.apply(this, arguments); + _setValid(b) { + super._setValid(arguments); // this.content.setValid(b); // this.watermark && this.watermark.setValid(b); - }, + } - _setEnable: function (b) { - BI.TextAreaEditor.superclass._setEnable.apply(this, [b]); + _setEnable(b) { + super._setEnable(b); this.content && (this.content.element[0].disabled = !b); - }, -}); -BI.TextAreaEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.TextAreaEditor.EVENT_BLUR = "EVENT_BLUR"; -BI.TextAreaEditor.EVENT_FOCUS = "EVENT_FOCUS"; -BI.TextAreaEditor.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.TextAreaEditor.EVENT_EMPTY = "EVENT_EMPTY"; -BI.TextAreaEditor.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.shortcut("bi.textarea_editor", BI.TextAreaEditor); + } +} diff --git a/src/base/single/editor/index.js b/src/base/single/editor/index.js new file mode 100644 index 000000000..0bd7cdf7d --- /dev/null +++ b/src/base/single/editor/index.js @@ -0,0 +1,3 @@ +export { Editor } from "./editor"; +export { MultifileEditor } from "./editor.multifile"; +export { TextAreaEditor } from "./editor.textarea"; \ No newline at end of file diff --git a/src/base/single/html/html.js b/src/base/single/html/html.js index 84c980427..9e78c5364 100644 --- a/src/base/single/html/html.js +++ b/src/base/single/html/html.js @@ -3,9 +3,14 @@ * @class BI.Html * @extends BI.Single */ -BI.Html = BI.inherit(BI.Single, { +import { shortcut, isNumber, createWidget, isWidthOrHeight, isKey } from "../../../core"; +import { Single } from "../0.single"; - props: { +@shortcut() +export class Html extends Single { + static xtype = "bi.html"; + + props = { baseCls: "bi-html", textAlign: "left", whiteSpace: "normal", @@ -19,57 +24,57 @@ BI.Html = BI.inherit(BI.Single, { bgap: 0, text: "", highLight: false, - }, + } - render: function () { - var self = this, o = this.options; - if (o.hgap + o.lgap > 0) { + render() { + const { vgap, hgap, lgap, rgap, tgap, bgap, height, lineHeight, maxWidth, textAlign, whiteSpace, handler, text, value, highLight } = this.options; + if (hgap + lgap > 0) { this.element.css({ - "padding-left": BI.pixFormat(o.hgap + o.lgap), + "padding-left": BI.pixFormat(hgap + lgap), }); } - if (o.hgap + o.rgap > 0) { + if (hgap + rgap > 0) { this.element.css({ - "padding-right": BI.pixFormat(o.hgap + o.rgap), + "padding-right": BI.pixFormat(hgap + rgap), }); } - if (o.vgap + o.tgap > 0) { + if (vgap + tgap > 0) { this.element.css({ - "padding-top": BI.pixFormat(o.vgap + o.tgap), + "padding-top": BI.pixFormat(vgap + tgap), }); } - if (o.vgap + o.bgap > 0) { + if (vgap + bgap > 0) { this.element.css({ - "padding-bottom": BI.pixFormat(o.vgap + o.bgap), + "padding-bottom": BI.pixFormat(vgap + bgap), }); } - if (BI.isNumber(o.height)) { - this.element.css({ lineHeight: BI.pixFormat(o.height) }); + if (isNumber(height)) { + this.element.css({ lineHeight: BI.pixFormat(height) }); } - if (BI.isNumber(o.lineHeight)) { - this.element.css({ lineHeight: BI.pixFormat(o.lineHeight) }); + if (isNumber(lineHeight)) { + this.element.css({ lineHeight: BI.pixFormat(lineHeight) }); } - if (BI.isWidthOrHeight(o.maxWidth)) { - this.element.css({ maxWidth: o.maxWidth }); + if (isWidthOrHeight(maxWidth)) { + this.element.css({ maxWidth }); } - if (BI.isNumber(o.maxWidth)) { - this.element.css({ maxWidth: BI.pixFormat(o.maxWidth) }) + if (isNumber(maxWidth)) { + this.element.css({ maxWidth: BI.pixFormat(maxWidth) }); } this.element.css({ - textAlign: o.textAlign, - whiteSpace: o.whiteSpace, - textOverflow: o.whiteSpace === "nowrap" ? "ellipsis" : "", - overflow: o.whiteSpace === "nowrap" ? "" : "auto", + textAlign, + whiteSpace, + textOverflow: whiteSpace === "nowrap" ? "ellipsis" : "", + overflow: whiteSpace === "nowrap" ? "" : "auto", }); - if (o.handler) { - this.text = BI.createWidget({ + if (handler) { + this.text = createWidget({ type: "bi.layout", tagName: "span", }); - this.text.element.click(function () { - o.handler(self.getValue()); + this.text.element.click(() => { + handler(this.getValue()); }); - BI.createWidget({ + createWidget({ type: "bi.default", element: this, items: [this.text], @@ -78,40 +83,38 @@ BI.Html = BI.inherit(BI.Single, { this.text = this; } - if (BI.isKey(o.text)) { - this.setText(o.text); - } else if (BI.isKey(o.value)) { - this.setText(o.value); + if (isKey(text)) { + this.setText(text); + } else if (isKey(value)) { + this.setText(value); } - if (o.highLight) { + if (highLight) { this.doHighLight(); } - }, + } - doHighLight: function () { + doHighLight() { this.text.element.addClass("bi-high-light"); - }, + } - unHighLight: function () { + unHighLight() { this.text.element.removeClass("bi-high-light"); - }, + } - setValue: function (text) { - BI.Html.superclass.setValue.apply(this, arguments); + setValue(text) { + super.setValue(text); if (!this.isReadOnly()) { this.setText(text); } - }, + } - setStyle: function (css) { + setStyle(css) { this.text.element.css(css); - }, + } - setText: function (text) { - BI.Html.superclass.setText.apply(this, arguments); + setText(text) { + super.setText(text); this.options.text = text; this.text.element.html(text); - }, -}); - -BI.shortcut("bi.html", BI.Html); + } +} diff --git a/src/base/single/icon/icon.js b/src/base/single/icon/icon.js index 916206bbd..8dddd52b9 100644 --- a/src/base/single/icon/icon.js +++ b/src/base/single/icon/icon.js @@ -3,20 +3,25 @@ * @class BI.Icon * @extends BI.Single */ -BI.Icon = BI.inherit(BI.Single, { - _defaultConfig: function () { - var conf = BI.Icon.superclass._defaultConfig.apply(this, arguments); +import { shortcut, extend } from "../../../core"; +import { Single } from "../0.single"; - return BI.extend(conf, { +@shortcut() +export class Icon extends Single { + static xtype = "bi.icon"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { tagName: "i", baseCls: (conf.baseCls || "") + " x-icon b-font horizon-center display-block", }); - }, + } - render: function () { + render() { if (BI.isIE9Below && BI.isIE9Below()) { this.element.addClass("hack"); } - }, -}); -BI.shortcut("bi.icon", BI.Icon); + } +} diff --git a/src/base/single/index.js b/src/base/single/index.js index 748788816..6be792b36 100644 --- a/src/base/single/index.js +++ b/src/base/single/index.js @@ -1,4 +1,10 @@ export { Single } from "./0.single"; export { Text } from "./1.text"; +export { PureText } from "./text.pure"; +export { Icon } from "./icon/icon"; +export { Html } from "./html/html"; export { A } from "./a/a"; -export * from "./tip"; \ No newline at end of file +export * from "./tip"; +export * from "./label"; +export * from "./input"; +export * from "./editor"; \ No newline at end of file diff --git a/src/base/single/input/file.js b/src/base/single/input/file.js index 290970141..8564efda7 100644 --- a/src/base/single/input/file.js +++ b/src/base/single/input/file.js @@ -6,734 +6,738 @@ * @extends BI.Single * @abstract */ -((function (document) { - /** - * @description normalize input.files. create if not present, add item method if not present - * @param Object generated wrap object - * @return Object the wrap object itself - */ - var F = ((function (item) { - return function (input) { - var files = input.files || [input]; - if (!files.item) { - files.item = item; - } +import { shortcut, Widget, some, extend } from "../../../core"; +import { Msg } from "../../foundation/message"; - return files; - }; - })(function (i) { - return this[i]; - })); - - var event = { - - /** - * @description add an event via addEventListener or attachEvent - * @param DOMElement the element to add event - * @param String event name without "on" (e.g. "mouseover") - * @param Function the callback to associate as event - * @return Object noswfupload.event - */ - add: document.addEventListener ? - function (node, name, callback) { - node.addEventListener(name, callback, false); +const document = _global.document || {}; +/** + * @description normalize input.files. create if not present, add item method if not present + * @param Object generated wrap object + * @return Object the wrap object itself + */ +const F = (((item) => { + return (input) => { + const files = input.files || [input]; + if (!files.item) { + files.item = item; + } - return this; - } : - function (node, name, callback) { - node.attachEvent("on" + name, callback); + return files; + }; +})((i) => { + return this[i]; +})); - return this; - }, +const event = { - /** - * @description remove an event via removeEventListener or detachEvent - * @param DOMElement the element to remove event - * @param String event name without "on" (e.g. "mouseover") - * @param Function the callback associated as event - * @return Object noswfupload.event - */ - del: document.removeEventListener ? - function (node, name, callback) { - node.removeEventListener(name, callback, false); - - return this; - } : - function (node, name, callback) { - node.detachEvent("on" + name, callback); + /** + * @description add an event via addEventListener or attachEvent + * @param DOMElement the element to add event + * @param String event name without "on" (e.g. "mouseover") + * @param Function the callback to associate as event + * @return Object noswfupload.event + */ + add: document.addEventListener ? + (node, name, callback) => { + node.addEventListener(name, callback, false); - return this; - }, + return this; + } : + (node, name, callback) => { + node.attachEvent("on" + name, callback); - /** - * @description to block event propagation and prevent event default - * @param void generated event or undefined - * @return Boolean false - */ - stop: function (e) { - if (!e) { - if (self.event) { - event.returnValue = !(event.cancelBubble = true); - } - } else { - e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true; - e.preventDefault ? e.preventDefault() : e.returnValue = false; - } + return this; + }, - return false; + /** + * @description remove an event via removeEventListener or detachEvent + * @param DOMElement the element to remove event + * @param String event name without "on" (e.g. "mouseover") + * @param Function the callback associated as event + * @return Object noswfupload.event + */ + del: document.removeEventListener ? + (node, name, callback) => { + node.removeEventListener(name, callback, false); + + return this; + } : + (node, name, callback) => { + node.detachEvent("on" + name, callback); + + return this; }, - }; - var sendFile = (function (toString) { - var split = "onabort.onerror.onloadstart.onprogress".split("."), - length = split.length, - CRLF = "\r\n", - xhr = new XMLHttpRequest, - sendFile; - function multipart(boundary, name, file) { - return "--".concat( - boundary, CRLF, - "Content-Disposition: form-data; name=\"", name, "\"; filename=\"", _global.encodeURIComponent(file.fileName), "\"", CRLF, - "Content-Type: application/octet-stream", CRLF, - CRLF, - file.getAsBinary(), CRLF, - "--", boundary, "--", CRLF - ); - } - function isFunction (Function) { - return toString.call(Function) === "[object Function]"; + /** + * @description to block event propagation and prevent event default + * @param void generated event or undefined + * @return Boolean false + */ + stop(e) { + if (!e) { + if (self.event) { + event.returnValue = !(event.cancelBubble = true); } + } else { + e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true; + e.preventDefault ? e.preventDefault() : e.returnValue = false; + } + + return false; + }, +}; + +const sendFile = (((toString) => { + const split = "onabort.onerror.onloadstart.onprogress".split("."), + length = split.length, + CRLF = "\r\n"; + let xhr = new XMLHttpRequest, + sendFile; + const multipart = (boundary, name, file) => { + return "--".concat( + boundary, CRLF, + "Content-Disposition: form-data; name=\"", name, "\"; filename=\"", _global.encodeURIComponent(file.fileName), "\"", CRLF, + "Content-Type: application/octet-stream", CRLF, + CRLF, + file.getAsBinary(), CRLF, + "--", boundary, "--", CRLF + ); + } + const isFunction = (Function) => { + return toString.call(Function) === "[object Function]"; + } - // FireFox 3+, Safari 4 beta (Chrome 2 beta file is buggy and will not work) - if (xhr.upload || xhr.sendAsBinary) { - sendFile = function (handler, maxSize, width, height) { - var current = handler.current; - if (-1 < maxSize && maxSize < handler.file.fileSize) { - if (isFunction(handler.onerror)) { - handler.onerror(); - } - - return; - } - for (var xhr = new XMLHttpRequest, - upload = xhr.upload || { - addEventListener: function (event, callback) { - this["on" + event] = callback; - }, - }, - i = 0; - i < length; - i++ - ) { - upload.addEventListener( - split[i].substring(2), - // eslint-disable-next-line no-loop-func - (function (event) { - return function (rpe) { - if (isFunction(handler[event])) { - handler[event](rpe, xhr); - } - }; - }(split[i])), - false - ); + // FireFox 3+, Safari 4 beta (Chrome 2 beta file is buggy and will not work) + if (xhr.upload || xhr.sendAsBinary) { + sendFile = (handler, maxSize, width, height) => { + const current = handler.current; + if (-1 < maxSize && maxSize < handler.file.fileSize) { + if (isFunction(handler.onerror)) { + handler.onerror(); } + + return; + } + const xhr = new XMLHttpRequest, + upload = xhr.upload || { + addEventListener(event, callback) { + this["on" + event] = callback; + }, + }; + for (let i = 0;i < length;i++) { upload.addEventListener( - "load", - function (rpe) { - if (handler.onreadystatechange === false) { - if (isFunction(handler.onload)) { - handler.onload(rpe, xhr); + split[i].substring(2), + // eslint-disable-next-line no-loop-func + (((event) => { + return (rpe) => { + if (isFunction(handler[event])) { + handler[event](rpe, xhr); } - } else { - setTimeout(function () { - if (xhr.readyState === 4) { - if (isFunction(handler.onload)) { - handler.onload(rpe, xhr); - } - } else { - setTimeout(arguments.callee, 15); - } - }, 15); - } - }, + }; + })(split[i])), false ); - xhr.open("post", BI.appendQuery(handler.url, { - filename: _global.encodeURIComponent(handler.file.fileName), - }), true); - if (!xhr.upload) { - var rpe = { loaded: 0, total: handler.file.fileSize || handler.file.size, simulation: true }; - rpe.interval = setInterval(function () { - rpe.loaded += 1024 / 4; - if (rpe.total <= rpe.loaded) { - rpe.loaded = rpe.total; + } + upload.addEventListener( + "load", + (rpe) => { + if (handler.onreadystatechange === false) { + if (isFunction(handler.onload)) { + handler.onload(rpe, xhr); } - upload.onprogress(rpe); - }, 100); - xhr.onabort = function () { - upload.onabort({}); - }; - xhr.onerror = function () { - upload.onerror({}); - }; - xhr.onreadystatechange = function () { - switch (xhr.readyState) { - case 2: - case 3: - if (rpe.total <= rpe.loaded) { - rpe.loaded = rpe.total; - } - upload.onprogress(rpe); - break; - case 4: - clearInterval(rpe.interval); - rpe.interval = 0; - rpe.loaded = rpe.total; - upload.onprogress(rpe); - if (199 < xhr.status && xhr.status < 400) { - upload.onload({}); - var attachO = BI.jsonDecode(xhr.responseText); - attachO.filename = handler.file.fileName; - if (handler.file.type.indexOf("image") !== -1) { - attachO.attach_type = "image"; - } - handler.attach_array[current] = attachO; - } else { - upload.onerror({}); + } else { + const callback = () => { + if (xhr.readyState === 4) { + if (isFunction(handler.onload)) { + handler.onload(rpe, xhr); } - break; - default: - break; + } else { + setTimeout(callback, 15); + } } - }; - upload.onloadstart(rpe); - } else { - xhr.onreadystatechange = function () { - switch (xhr.readyState) { - case 4: - var attachO = BI.jsonDecode(xhr.responseText); + setTimeout(callback, 15); + } + }, + false + ); + xhr.open("post", BI.appendQuery(handler.url, { + filename: _global.encodeURIComponent(handler.file.fileName), + }), true); + if (!xhr.upload) { + const rpe = { loaded: 0, total: handler.file.fileSize || handler.file.size, simulation: true }; + rpe.interval = setInterval(() => { + rpe.loaded += 1024 / 4; + if (rpe.total <= rpe.loaded) { + rpe.loaded = rpe.total; + } + upload.onprogress(rpe); + }, 100); + xhr.onabort = () => { + upload.onabort({}); + }; + xhr.onerror = () => { + upload.onerror({}); + }; + xhr.onreadystatechange = () => { + switch (xhr.readyState) { + case 2: + case 3: + if (rpe.total <= rpe.loaded) { + rpe.loaded = rpe.total; + } + upload.onprogress(rpe); + break; + case 4: + clearInterval(rpe.interval); + rpe.interval = 0; + rpe.loaded = rpe.total; + upload.onprogress(rpe); + if (199 < xhr.status && xhr.status < 400) { + upload.onload({}); + const attachO = BI.jsonDecode(xhr.responseText); + attachO.filename = handler.file.fileName; if (handler.file.type.indexOf("image") !== -1) { attachO.attach_type = "image"; } - attachO.filename = handler.file.fileName; - if (handler.maxLength === 1) { - handler.attach_array[0] = attachO; - // handler.attach_array.push(attachO); - } else { - handler.attach_array[current] = attachO; - } - break; - default: - break; - } - }; - if (isFunction(upload.onloadstart)) { - upload.onloadstart(); - } - } - var boundary = "AjaxUploadBoundary" + (new Date).getTime(); - xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary); - if (handler.file.getAsBinary) { - xhr[xhr.sendAsBinary ? "sendAsBinary" : "send"](multipart(boundary, handler.name, handler.file)); - } else { - xhr.setRequestHeader("Content-Type", "multipart/form-data"); - // xhr.setRequestHeader("X-Name", handler.name); - // xhr.setRequestHeader("X-File-Name", handler.file.fileName); - var form = new FormData(); - form.append("FileData", handler.file); - xhr.send(form); - } - - return handler; - }; - } else { - // Internet Explorer, Opera, others - sendFile = function (handler, maxSize, width, height) { - var current = handler.current, iframe, form; - var url = handler.url.concat(-1 === handler.url.indexOf("?") ? "?" : "&", "AjaxUploadFrame=true"), - rpe = { - loaded: 1, total: 100, simulation: true, interval: setInterval(function () { - if (rpe.loaded < rpe.total) { - ++rpe.loaded; - } - if (isFunction(handler.onprogress)) { - handler.onprogress(rpe, {}); + handler.attach_array[current] = attachO; + } else { + upload.onerror({}); } - }, 100), - }, - target = ["AjaxUpload", (new Date).getTime(), String(Math.random()).substring(2)].join("_"); - function onload() { - iframe.onreadystatechange = iframe.onload = iframe.onerror = null; - form.parentNode.removeChild(form); - form = null; - clearInterval(rpe.interval); - // rpe.loaded = rpe.total; - try { - var responseText = (iframe.contentWindow.document || iframe.contentWindow.contentDocument).body.innerHTML; - var attachO = BI.jsonDecode(responseText); + break; + default: + break; + } + }; + upload.onloadstart(rpe); + } else { + xhr.onreadystatechange = () => { + switch (xhr.readyState) { + case 4: + const attachO = BI.jsonDecode(xhr.responseText); if (handler.file.type.indexOf("image") !== -1) { attachO.attach_type = "image"; } - - // attachO.fileSize = responseText.length; - try { - // decodeURIComponent特殊字符可能有问题, catch一下,保证能正常上传 - attachO.filename = _global.decodeURIComponent(handler.file.fileName); - } catch (e) { - attachO.filename = handler.file.fileName; - } + attachO.filename = handler.file.fileName; if (handler.maxLength === 1) { handler.attach_array[0] = attachO; + // handler.attach_array.push(attachO); } else { handler.attach_array[current] = attachO; } - } catch (e) { - if (isFunction(handler.onerror)) { - handler.onerror(rpe, event || _global.event); - } - } - if (isFunction(handler.onload)) { - handler.onload(rpe, { responseText: responseText }); - } - } - - try { // IE < 8 does not accept enctype attribute ... - var form = document.createElement("
"), - iframe = handler.iframe || (handler.iframe = document.createElement("")); - } catch (e) { - var form = document.createElement("form"), - iframe = handler.iframe || (handler.iframe = document.createElement("iframe")); - form.setAttribute("enctype", "multipart/form-data"); - iframe.setAttribute("name", iframe.id = target); - iframe.setAttribute("src", url); - } - iframe.style.position = "absolute"; - iframe.style.left = iframe.style.top = "-10000px"; - iframe.onload = onload; - iframe.onerror = function (event) { - if (isFunction(handler.onerror)) { - handler.onerror(rpe, event || _global.event); + break; + default: + break; } }; - iframe.onreadystatechange = function () { - if (/loaded|complete/i.test(iframe.readyState)) { - onload(); - - // wei : todo,将附件信息放到handler.attach - } else if (isFunction(handler.onloadprogress)) { + if (isFunction(upload.onloadstart)) { + upload.onloadstart(); + } + } + const boundary = "AjaxUploadBoundary" + (new Date).getTime(); + xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary); + if (handler.file.getAsBinary) { + xhr[xhr.sendAsBinary ? "sendAsBinary" : "send"](multipart(boundary, handler.name, handler.file)); + } else { + xhr.setRequestHeader("Content-Type", "multipart/form-data"); + // xhr.setRequestHeader("X-Name", handler.name); + // xhr.setRequestHeader("X-File-Name", handler.file.fileName); + const form = new FormData(); + form.append("FileData", handler.file); + xhr.send(form); + } + + return handler; + }; + } else { + // Internet Explorer, Opera, others + sendFile = (handler, maxSize, width, height) => { + const current = handler.current; + let iframe, form; + const url = handler.url.concat(-1 === handler.url.indexOf("?") ? "?" : "&", "AjaxUploadFrame=true"), + rpe = { + loaded: 1, total: 100, simulation: true, interval: setInterval(() => { if (rpe.loaded < rpe.total) { ++rpe.loaded; } - handler.onloadprogress(rpe, { - readyState: { - loading: 2, - interactive: 3, - loaded: 4, - complete: 4, - }[iframe.readyState] || 1, - }); + if (isFunction(handler.onprogress)) { + handler.onprogress(rpe, {}); + } + }, 100), + }, + target = ["AjaxUpload", (new Date).getTime(), String(Math.random()).substring(2)].join("_"); + const onload = () => { + iframe.onreadystatechange = iframe.onload = iframe.onerror = null; + form.parentNode.removeChild(form); + form = null; + clearInterval(rpe.interval); + // rpe.loaded = rpe.total; + const responseText = (iframe.contentWindow.document || iframe.contentWindow.contentDocument).body.innerHTML; + try { + const attachO = BI.jsonDecode(responseText); + if (handler.file.type.indexOf("image") !== -1) { + attachO.attach_type = "image"; + } + + // attachO.fileSize = responseText.length; + try { + // decodeURIComponent特殊字符可能有问题, catch一下,保证能正常上传 + attachO.filename = _global.decodeURIComponent(handler.file.fileName); + } catch (e) { + attachO.filename = handler.file.fileName; + } + if (handler.maxLength === 1) { + handler.attach_array[0] = attachO; + } else { + handler.attach_array[current] = attachO; + } + } catch (e) { + if (isFunction(handler.onerror)) { + handler.onerror(rpe, event || _global.event); + } + } + if (isFunction(handler.onload)) { + handler.onload(rpe, { responseText: responseText }); } - }; - form.setAttribute("action", handler.url + "&filename=" + _global.encodeURIComponent(handler.file.fileName)); - form.setAttribute("target", iframe.id); - form.setAttribute("method", "post"); - form.appendChild(handler.file); - form.style.display = "none"; - if (isFunction(handler.onloadstart)) { - handler.onloadstart(rpe, {}); } - var d = document.body || document.documentElement; - d.appendChild(iframe); - d.appendChild(form); - form.submit(); - - return handler; - }; - } - xhr = null; - - return sendFile; - }(Object.prototype.toString)); - - function sendFiles(handler, maxSize, width, height) { - var length = handler.files.length, - onload = handler.onload, - onloadstart = handler.onloadstart; - handler.current = 0; - handler.total = 0; - handler.sent = 0; - while (handler.current < length) { - handler.total += (handler.files[handler.current].fileSize || handler.files[handler.current].size); - handler.current++; - } - handler.current = 0; - if (length && handler.files[0].fileSize !== -1) { - handler.file = handler.files[handler.current]; - - sendFile(handler, maxSize, width, height).onload = function (rpe, xhr) { - handler.onloadstart = null; - handler.sent += (handler.files[handler.current].fileSize || handler.files[handler.current].size); - if (++handler.current < length) { - handler.file = handler.files[handler.current]; - sendFile(handler, maxSize, width, height).onload = arguments.callee; - } else if (onload) { - handler.onloadstart = onloadstart; - handler.onload = onload; - handler.onload(rpe, xhr); + + try { // IE < 8 does not accept enctype attribute ... + const form = document.createElement("
"), + iframe = handler.iframe || (handler.iframe = document.createElement("")); + } catch (e) { + const form = document.createElement("form"), + iframe = handler.iframe || (handler.iframe = document.createElement("iframe")); + form.setAttribute("enctype", "multipart/form-data"); + iframe.setAttribute("name", iframe.id = target); + iframe.setAttribute("src", url); + } + iframe.style.position = "absolute"; + iframe.style.left = iframe.style.top = "-10000px"; + iframe.onload = onload; + iframe.onerror = (event) => { + if (isFunction(handler.onerror)) { + handler.onerror(rpe, event || _global.event); } }; - } else if (length) { - handler.total = length * 100; - handler.file = handler.files[handler.current]; - sendFile(handler, maxSize, width, height).onload = function (rpe, xhr) { - var callee = arguments.callee; - handler.onloadstart = null; - handler.sent += 100; - if (++handler.current < length) { - if (/\b(chrome|safari)\b/i.test(navigator.userAgent)) { - handler.iframe.parentNode.removeChild(handler.iframe); - handler.iframe = null; + iframe.onreadystatechange = () => { + if (/loaded|complete/i.test(iframe.readyState)) { + onload(); + + // wei : todo,将附件信息放到handler.attach + } else if (isFunction(handler.onloadprogress)) { + if (rpe.loaded < rpe.total) { + ++rpe.loaded; } - setTimeout(function () { - handler.file = handler.files[handler.current]; - sendFile(handler, maxSize, width, height).onload = callee; - }, 15); - } else if (onload) { - setTimeout(function () { - handler.iframe.parentNode.removeChild(handler.iframe); - handler.iframe = null; - handler.onloadstart = onloadstart; - handler.onload = onload; - handler.onload(rpe, xhr); - }, 15); + handler.onloadprogress(rpe, { + readyState: { + loading: 2, + interactive: 3, + loaded: 4, + complete: 4, + }[iframe.readyState] || 1, + }); } }; - } + form.setAttribute("action", handler.url + "&filename=" + _global.encodeURIComponent(handler.file.fileName)); + form.setAttribute("target", iframe.id); + form.setAttribute("method", "post"); + form.appendChild(handler.file); + form.style.display = "none"; + if (isFunction(handler.onloadstart)) { + handler.onloadstart(rpe, {}); + } + const d = document.body || document.documentElement; + d.appendChild(iframe); + d.appendChild(form); + form.submit(); - return handler; + return handler; + }; + } + xhr = null; + + return sendFile; +})(Object.prototype.toString)); + +const sendFiles = (handler, maxSize, width, height) => { + const length = handler.files.length, + onload = handler.onload, + onloadstart = handler.onloadstart; + handler.current = 0; + handler.total = 0; + handler.sent = 0; + while (handler.current < length) { + handler.total += (handler.files[handler.current].fileSize || handler.files[handler.current].size); + handler.current++; + } + handler.current = 0; + if (length && handler.files[0].fileSize !== -1) { + handler.file = handler.files[handler.current]; + const callback = (rpe, xhr) => { + handler.onloadstart = null; + handler.sent += (handler.files[handler.current].fileSize || handler.files[handler.current].size); + if (++handler.current < length) { + handler.file = handler.files[handler.current]; + sendFile(handler, maxSize, width, height).onload = callback; + } else if (onload) { + handler.onloadstart = onloadstart; + handler.onload = onload; + handler.onload(rpe, xhr); + } + }; + sendFile(handler, maxSize, width, height).onload = callback; + } else if (length) { + handler.total = length * 100; + handler.file = handler.files[handler.current]; + const callback = (rpe, xhr) => { + handler.onloadstart = null; + handler.sent += 100; + if (++handler.current < length) { + if (/\b(chrome|safari)\b/i.test(navigator.userAgent)) { + handler.iframe.parentNode.removeChild(handler.iframe); + handler.iframe = null; + } + setTimeout(() => { + handler.file = handler.files[handler.current]; + sendFile(handler, maxSize, width, height).onload = callback; + }, 15); + } else if (onload) { + setTimeout(() => { + handler.iframe.parentNode.removeChild(handler.iframe); + handler.iframe = null; + handler.onloadstart = onloadstart; + handler.onload = onload; + handler.onload(rpe, xhr); + }, 15); + } + }; + sendFile(handler, maxSize, width, height).onload = callback; } - var r1 = /\.([^.]+)$/; // .png - var r2 = /\/([^/]+)$/; // image/png + return handler; +} - /** - * 校验文件类型是否合法,同时兼容旧版形式 - * @param fileName - * @param fileType - * @returns {boolean} - */ - function fileTypeValidate(fileName, fileType) { - if (!fileType) { - return true; +const r1 = /\.([^.]+)$/; // .png +const r2 = /\/([^/]+)$/; // image/png + +/** + * 校验文件类型是否合法,同时兼容旧版形式 + * @param fileName + * @param fileType + * @returns {boolean} + */ +const fileTypeValidate = (fileName, fileType) => { + if (!fileType) { + return true; + } + const mimes = fileType.split(","); + if (mimes[0] === fileType) { + mimes = (fileType + "").split(";"); + } + + return some(mimes, (index, mime) => { + let matches; + matches = mime.match(r1); + if (matches) { + return fileName.toLowerCase().indexOf(matches[1]) > -1; } - var mimes = fileType.split(","); - if (mimes[0] === fileType) { - mimes = (fileType + "").split(";"); + matches = mime.match(r2); + if (matches) { + return matches[1] === "*" ? true : fileName.toLowerCase().indexOf(matches[1]) > -1; } - - return BI.some(mimes, function (index, mime) { - var matches; - matches = mime.match(r1); - if (matches) { - return fileName.toLowerCase().indexOf(matches[1]) > -1; - } - matches = mime.match(r2); - if (matches) { - return matches[1] === "*" ? true : fileName.toLowerCase().indexOf(matches[1]) > -1; - } + }); +} + +@shortcut() +export class File extends Widget { + static xtype = "bi.file"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_UPLOADSTART = "EVENT_UPLOADSTART"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_PROGRESS = "EVENT_PROGRESS"; + static EVENT_UPLOADED = "EVENT_UPLOADED"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { + baseCls: (conf.baseCls || "") + " bi-file display-block", + tagName: "input", + attributes: { + type: "file", + }, + name: "", + url: "", + multiple: true, + accept: "", // .png,.pdf,image/jpg,image/* 等 + maxSize: -1, // 1024 * 1024 单位b + maxLength: -1, // 无限制, 与multiple配合使用 + errorText: BI.emptyFn, }); } - BI.File = BI.inherit(BI.Widget, { - _defaultConfig: function () { - var conf = BI.File.superclass._defaultConfig.apply(this, arguments); - - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-file display-block", - tagName: "input", - attributes: { - type: "file", - }, - name: "", - url: "", - multiple: true, - accept: "", // .png,.pdf,image/jpg,image/* 等 - maxSize: -1, // 1024 * 1024 单位b - maxLength: -1, // 无限制, 与multiple配合使用 - errorText: BI.emptyFn, - }); - }, - - render: function () { - var o = this.options; - if (o.multiple === true) { - this.element.attr("multiple", "multiple"); - } - this.element.attr("name", o.name || this.getName()); - this.element.attr("title", o.title || ""); - this.element.attr("accept", o.accept); - }, + render() { + const { multiple, name, title, accept } = this.options; + if (multiple === true) { + this.element.attr("multiple", "multiple"); + } + this.element.attr("name", name || this.getName()); + this.element.attr("title", title || ""); + this.element.attr("accept", accept); + } - created: function () { - var self = this, o = this.options; - // create the noswfupload.wrap Object - // wrap.maxSize 文件大小限制 - // wrap.maxLength 文件个数限制 - var _wrap = this.wrap = this._wrap(this.element[0], o.maxSize); - // fileType could contain whatever text but filter checks *.{extension} - // if present + created() { + const { maxSize, url, accept } = this.options; + // create the noswfupload.wrap Object + // wrap.maxSize 文件大小限制 + // wrap.maxLength 文件个数限制 + const _wrap = this.wrap = this._wrap(this.element[0], maxSize); + // fileType could contain whatever text but filter checks *.{extension} + // if present - // handlers + // handlerszhe - _wrap.onloadstart = function (rpe, xhr) { - self.fireEvent(BI.File.EVENT_UPLOADSTART, arguments); - }; + _wrap.onloadstart = (...args) => { + this.fireEvent(File.EVENT_UPLOADSTART, ...args); + }; - _wrap.onprogress = function (rpe, xhr) { - // percent for each bar + _wrap.onprogress = (rpe, xhr) => { + // percent for each bar - // fileSize is -1 only if browser does not support file info access - // this if splits recent browsers from others - if (this.file.fileSize !== -1) { - // simulation property indicates when the progress event is fake - if (rpe.simulation) { - // empty - } else { - // empty - } + // fileSize is -1 only if browser does not support file info access + // this if splits recent browsers from others + if (_wrap.file.fileSize !== -1) { + // simulation property indicates when the progress event is fake + if (rpe.simulation) { + // empty } else { - // if fileSIze is -1 browser is using an iframe because it does - // not support - // files sent via Ajax (XMLHttpRequest) - // We can still show some information + // empty } - self.fireEvent(BI.File.EVENT_PROGRESS, { - file: this.file, - total: rpe.total, - loaded: rpe.loaded, - simulation: rpe.simulation, - }); - }; + } else { + // if fileSIze is -1 browser is using an iframe because it does + // not support + // files sent via Ajax (XMLHttpRequest) + // We can still show some information + } + this.fireEvent(File.EVENT_PROGRESS, { + file: this.file, + total: rpe.total, + loaded: rpe.loaded, + simulation: rpe.simulation, + }); + }; - // generated if there is something wrong during upload - _wrap.onerror = function () { - // just inform the user something was wrong - self.fireEvent(BI.File.EVENT_ERROR); - }; + // generated if there is something wrong during upload + _wrap.onerror = () => { + // just inform the user something was wrong + this.fireEvent(File.EVENT_ERROR); + }; - // generated when every file has been sent (one or more, it does not - // matter) - _wrap.onload = function (rpe, xhr) { - var self_ = this; - // just show everything is fine ... - // ... and after a second reset the component - setTimeout(function () { - self_.clean(); // remove files from list - self_.hide(); // hide progress bars and enable input file - // enable again the submit button/element - }, 100); - if (200 > xhr.status || xhr.status > 399) { - BI.Msg.toast(BI.i18nText("BI-Upload_File_Error"), { level: "error" }); - self.fireEvent(BI.File.EVENT_ERROR); + // generated when every file has been sent (one or more, it does not + // matter) + _wrap.onload = (rpe, xhr) => { + // just show everything is fine ... + // ... and after a second reset the component + setTimeout(() => { + _wrap.clean(); // remove files from list + _wrap.hide(); // hide progress bars and enable input file + // enable again the submit button/element + }, 100); + if (200 > xhr.status || xhr.status > 399) { + Msg.toast(BI.i18nText("BI-Upload_File_Error"), { level: "error" }); + this.fireEvent(File.EVENT_ERROR); - return; + return; + } + const error = some(_wrap.attach_array, (index, attach) => { + if (attach.errorCode) { + Msg.toast(BI.i18nText(attach.errorMsg), { level: "error" }); + this.fireEvent(File.EVENT_ERROR, attach); + + return true; } - var error = BI.some(_wrap.attach_array, function (index, attach) { - if (attach.errorCode) { - BI.Msg.toast(BI.i18nText(attach.errorMsg), { level: "error" }); - self.fireEvent(BI.File.EVENT_ERROR, attach); + }); + !error && this.fireEvent(File.EVENT_UPLOADED); + }; + _wrap.url = url; + _wrap.fileType = accept; // 文件类型限制 + _wrap.attach_array = []; + _wrap.attach_names = []; + _wrap.attachNum = 0; + } - return true; - } + _events(wrap) { + const { maxLength, errorText } = this.options; + const callback = () => { + event.del(wrap.dom.input, "change", callback); + const input = wrap.dom.input.cloneNode(true); + const files = F(wrap.dom.input); + if (maxLength !== -1 && maxLength < files.length) { + this.fireEvent(File.EVENT_ERROR, { + errorType: 2, }); - !error && self.fireEvent(BI.File.EVENT_UPLOADED); - }; - _wrap.url = o.url; - _wrap.fileType = o.accept; // 文件类型限制 - _wrap.attach_array = []; - _wrap.attach_names = []; - _wrap.attachNum = 0; - }, - - _events: function (wrap) { - var self = this, o = this.options; - event.add(wrap.dom.input, "change", function () { - event.del(wrap.dom.input, "change", arguments.callee); - var input = wrap.dom.input.cloneNode(true); - var files = F(wrap.dom.input); - if (o.maxLength !== -1 && o.maxLength < files.length) { - self.fireEvent(BI.File.EVENT_ERROR, { - errorType: 2, - }); - } else { - for (var i = 0; i < files.length; i++) { - var item = files.item(i); - var tempFile = item.value || item.name; - var value = item.fileName || (item.fileName = tempFile.split("\\").pop()), - size = item.fileSize || item.size; - var validateFileType = fileTypeValidate(value, wrap.fileType); - if (!validateFileType) { - // 文件类型不支持 - BI.Msg.toast(o.errorText({ - errorType: 0, - file: item, - }) || BI.i18nText("BI-Upload_File_Type_Error", wrap.fileType), { level: "error" }); - self.fireEvent(BI.File.EVENT_ERROR, { - errorType: 0, - file: item, - }); - } else if (wrap.maxSize !== -1 && size && wrap.maxSize < size) { - // 文件大小不支持 - BI.Msg.toast(o.errorText({ - errorType: 1, - file: item, - }) || BI.i18nText("BI-Upload_File_Size_Error", Math.ceil(wrap.maxSize / 1024 / 1024)), { level: "error" }); - self.fireEvent(BI.File.EVENT_ERROR, { - errorType: 1, - file: item, - }); - } else { - wrap.files.unshift(item); - } + } else { + for (let i = 0; i < files.length; i++) { + const item = files.item(i); + const tempFile = item.value || item.name; + const value = item.fileName || (item.fileName = tempFile.split("\\").pop()), + size = item.fileSize || item.size; + const validateFileType = fileTypeValidate(value, wrap.fileType); + if (!validateFileType) { + // 文件类型不支持 + Msg.toast(errorText({ + errorType: 0, + file: item, + }) || BI.i18nText("BI-Upload_File_Type_Error", wrap.fileType), { level: "error" }); + this.fireEvent(File.EVENT_ERROR, { + errorType: 0, + file: item, + }); + } else if (wrap.maxSize !== -1 && size && wrap.maxSize < size) { + // 文件大小不支持 + Msg.toast(errorText({ + errorType: 1, + file: item, + }) || BI.i18nText("BI-Upload_File_Size_Error", Math.ceil(wrap.maxSize / 1024 / 1024)), { level: "error" }); + this.fireEvent(File.EVENT_ERROR, { + errorType: 1, + file: item, + }); + } else { + wrap.files.unshift(item); } } - wrap.files.length > 0 && self.fireEvent(BI.File.EVENT_CHANGE, { - files: wrap.files, - }); - input.value = ""; - wrap.dom.input.parentNode.replaceChild(input, wrap.dom.input); - wrap.dom.input = input; - event.add(wrap.dom.input, "change", arguments.callee); + } + wrap.files.length > 0 && this.fireEvent(File.EVENT_CHANGE, { + files: wrap.files, }); + input.value = ""; + wrap.dom.input.parentNode.replaceChild(input, wrap.dom.input); + wrap.dom.input = input; + event.add(wrap.dom.input, "change", callback); + } + event.add(wrap.dom.input, "change", callback); - return wrap; - }, + return wrap; + } - _wrap: function () { - var o = this.options; - // be sure input accept multiple files - var input = this.element[0]; - if (o.multiple === true) { - this.element.attr("multiple", "multiple"); - } - input.value = ""; + _wrap() { + const { multiple, maxSize, maxLength } = this.options; + // be sure input accept multiple files + const input = this.element[0]; + if (multiple === true) { + this.element.attr("multiple", "multiple"); + } + input.value = ""; - // wrap Object - return this._events({ + // wrap Object + return this._events({ - // DOM namespace - dom: { - input: input, // input file - disabled: false, // internal use, checks input file state - }, - name: input.name, // name to send for each file ($_FILES[{name}] in the server) - // maxSize is the maximum amount of bytes for each file - maxSize: o.maxSize ? o.maxSize >> 0 : -1, - maxLength: o.maxLength, - files: [], // file list - - // remove every file from the noswfupload component - clean: function () { - this.files = []; - }, + // DOM namespace + dom: { + input: input, // input file + disabled: false, // internal use, checks input file state + }, + name: input.name, // name to send for each file ($_FILES[{name}] in the server) + // maxSize is the maximum amount of bytes for each file + maxSize: maxSize ? maxSize >> 0 : -1, + maxLength, + files: [], // file list + + // remove every file from the noswfupload component + clean() { + this.files = []; + }, - // upload one file a time (which make progress possible rather than all files in one shot) - // the handler is an object injected into the wrap one, could be the wrap itself or - // something like {onload:function(){alert("OK")},onerror:function(){alert("Error")}, etc ...} - upload: function (handler) { - if (handler) { - for (var key in handler) { - this[key] = handler[key]; - } + // upload one file a time (which make progress possible rather than all files in one shot) + // the handler is an object injected into the wrap one, could be the wrap itself or + // something like {onload:function(){alert("OK")},onerror:function(){alert("Error")}, etc ...} + upload(handler) { + if (handler) { + for (let key in handler) { + this[key] = handler[key]; } - sendFiles(this, this.maxSize); + } + sendFiles(this, this.maxSize); - return this; - }, + return this; + }, - // hide progress bar (total + current) and enable files selection - hide: function () { - if (this.dom.disabled) { - this.dom.disabled = false; - this.dom.input.removeAttribute("disabled"); - } - }, + // hide progress bar (total + current) and enable files selection + hide() { + if (this.dom.disabled) { + this.dom.disabled = false; + this.dom.input.removeAttribute("disabled"); + } + }, - // show progress bar and disable file selection (used during upload) - // total and current are pixels used to style bars - // totalProp and currentProp are properties to change, "height" by default - show: function (total, current, totalProp, currentProp) { - if (!this.dom.disabled) { - this.dom.disabled = true; - this.dom.input.setAttribute("disabled", "disabled"); - } - }, - }); - }, + // show progress bar and disable file selection (used during upload) + // total and current are pixels used to style bars + // totalProp and currentProp are properties to change, "height" by default + show(total, current, totalProp, currentProp) { + if (!this.dom.disabled) { + this.dom.disabled = true; + this.dom.input.setAttribute("disabled", "disabled"); + } + }, + }); + } - setUrl: function(v) { - this.options.url = v; - if (this.wrap) { - this.wrap.url = v; - } - }, + setUrl(v) { + this.options.url = v; + if (this.wrap) { + this.wrap.url = v; + } + } - setMaxFileLength: function (v) { - this.options.maxLength = v; - if (this.wrap) { - this.wrap.maxLength = v; - } - }, + setMaxFileLength(v) { + this.options.maxLength = v; + if (this.wrap) { + this.wrap.maxLength = v; + } + } - select: function () { - this.wrap && BI.Widget._renderEngine.createElement(this.wrap.dom.input).click(); - }, + select() { + this.wrap && Widget._renderEngine.createElement(this.wrap.dom.input).click(); + } - upload: function (handler) { - this.wrap && this.wrap.upload(handler); - }, + upload(handler) { + this.wrap && this.wrap.upload(handler); + } - getValue: function () { - return this.wrap ? this.wrap.attach_array : []; - }, + getValue() { + return this.wrap ? this.wrap.attach_array : []; + } - getQueue: function () { - return this.wrap.files; - }, + getQueue() { + return this.wrap.files; + } - reset: function () { - if (this.wrap) { - this.wrap.attach_array = []; - this.wrap.attach_names = []; - this.wrap.attachNum = 0; - } - }, + reset() { + if (this.wrap) { + this.wrap.attach_array = []; + this.wrap.attach_names = []; + this.wrap.attachNum = 0; + } + } - sendFiles: function (files) { - if (!this.wrap) return; + sendFiles(files) { + if (!this.wrap) return; - this.wrap.dom.input.files = files; + this.wrap.dom.input.files = files; - var event = new CustomEvent("change"); + const event = new CustomEvent("change"); - this.wrap.dom.input.dispatchEvent(event); - }, + this.wrap.dom.input.dispatchEvent(event); + } - _setEnable: function (enable) { - BI.File.superclass._setEnable.apply(this, arguments); - if (enable === true) { - this.element.removeAttr("disabled"); - } else { - this.element.attr("disabled", "disabled"); - } - }, - }); - BI.File.EVENT_CHANGE = "EVENT_CHANGE"; - BI.File.EVENT_UPLOADSTART = "EVENT_UPLOADSTART"; - BI.File.EVENT_ERROR = "EVENT_ERROR"; - BI.File.EVENT_PROGRESS = "EVENT_PROGRESS"; - BI.File.EVENT_UPLOADED = "EVENT_UPLOADED"; - BI.shortcut("bi.file", BI.File); -})(_global.document || {})); + _setEnable(enable) { + super._setEnable(arguments); + if (enable === true) { + this.element.removeAttr("disabled"); + } else { + this.element.attr("disabled", "disabled"); + } + } +} diff --git a/src/base/single/input/index.js b/src/base/single/input/index.js new file mode 100644 index 000000000..4cd03bad2 --- /dev/null +++ b/src/base/single/input/index.js @@ -0,0 +1,2 @@ +export { Input } from "./input"; +export { File } from "./file"; \ No newline at end of file diff --git a/src/base/single/input/input.js b/src/base/single/input/input.js index 8f20bddbb..bd784b350 100644 --- a/src/base/single/input/input.js +++ b/src/base/single/input/input.js @@ -4,237 +4,263 @@ * @extends BI.Single * @type {*|void|Object} */ -BI.Input = BI.inherit(BI.Single, { - _defaultConfig: function () { - var conf = BI.Input.superclass._defaultConfig.apply(this, arguments); +import { shortcut, Controller, extend, debounce, bind, isNull, isEmptyString, isKey, delay, trim, isEqual, nextTick, isEndWithBlank } from "../../../core"; +import { Single } from "../0.single"; - return BI.extend(conf, { +@shortcut() +export class Input extends Single { + static xtype = "bi.input"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_CLICK = "EVENT_CLICK"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; + static EVENT_QUICK_DOWN = "EVENT_QUICK_DOWN"; + static EVENT_SPACE = "EVENT_SPACE"; + static EVENT_BACKSPACE = "EVENT_BACKSPACE"; + + static EVENT_START = "EVENT_START"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_REMOVE = "EVENT_REMOVE"; + static EVENT_EMPTY = "EVENT_EMPTY"; + static EVENT_VALID = "EVENT_VALID"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_ENTER = "EVENT_ENTER"; + static EVENT_RESTRICT = "EVENT_RESTRICT"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { baseCls: (conf.baseCls || "") + " bi-input display-block overflow-dot", tagName: "input", validationChecker: BI.emptyFn, quitChecker: BI.emptyFn, // 按确定键能否退出编辑 allowBlank: false, }); - }, + } - render: function () { - var self = this; - var ctrlKey = false; - var keyCode = null; - var inputEventValid = false; - var _keydown = BI.debounce(function (keyCode) { - self.onKeyDown(keyCode, ctrlKey); - self._keydown_ = false; + render() { + let ctrlKey = false; + let keyCode = null; + let inputEventValid = false; + const _keydown = debounce((keyCode) => { + this.onKeyDown(keyCode, ctrlKey); + this._keydown_ = false; }, BI.EVENT_RESPONSE_TIME); - var _clk = BI.debounce(BI.bind(this._click, this), BI.EVENT_RESPONSE_TIME, { + const _clk = debounce(bind(this._click, this), BI.EVENT_RESPONSE_TIME, { "leading": true, "trailing": false, }); - this._focusDebounce = BI.debounce(BI.bind(this._focus, this), BI.EVENT_RESPONSE_TIME, { + this._focusDebounce = debounce(bind(this._focus, this), BI.EVENT_RESPONSE_TIME, { "leading": true, "trailing": false, }); - this._blurDebounce = BI.debounce(BI.bind(this._blur, this), BI.EVENT_RESPONSE_TIME, { + this._blurDebounce = debounce(bind(this._blur, this), BI.EVENT_RESPONSE_TIME, { "leading": true, "trailing": false, }); this.element - .keydown(function (e) { + .keydown((e) => { inputEventValid = false; ctrlKey = e.ctrlKey || e.metaKey; // mac的cmd支持一下 keyCode = e.keyCode; - self.fireEvent(BI.Input.EVENT_QUICK_DOWN, arguments); + this.fireEvent(Input.EVENT_QUICK_DOWN, e); }) - .keyup(function (e) { + .keyup((e) => { keyCode = null; if (!(inputEventValid && e.keyCode === BI.KeyCode.ENTER)) { - self._keydown_ = true; + this._keydown_ = true; _keydown(e.keyCode); } }) - .on("input propertychange", function (e) { + .on("input propertychange", (e) => { // 输入内容全选并直接删光,如果按键没放开就失去焦点不会触发keyup,被focusout覆盖了 // 其中propertychange在元素属性发生改变的时候就会触发 是为了兼容IE8 // 通过keyCode判断会漏掉输入法点击输入(右键粘贴暂缓) - var originalEvent = e.originalEvent; - if (BI.isNull(originalEvent.propertyName) || originalEvent.propertyName === "value") { + const originalEvent = e.originalEvent; + if (isNull(originalEvent.propertyName) || originalEvent.propertyName === "value") { inputEventValid = true; - self._keydown_ = true; + this._keydown_ = true; _keydown(keyCode); keyCode = null; } }) - .click(function (e) { + .click((e) => { e.stopPropagation(); _clk(); }) - .mousedown(function (e) { - self.element.val(self.element.val()); + .mousedown((e) => { + this.element.val(this.element.val()); }) - .focus(function (e) { // 可以不用冒泡 - self._focusDebounce(); + .focus((e) => { // 可以不用冒泡 + this._focusDebounce(); }) - .blur(function (e) { + .blur((e) => { // DEC-14919 IE11在浏览器重新获得焦点之后会先触发focusout再触发focus,要保持先获得焦点再失去焦点的顺序不变,因此采用blur - self._blurDebounce(); + this._blurDebounce(); }); - if (BI.isKey(this.options.value) || BI.isEmptyString(this.options.value)) { + if (isKey(this.options.value) || isEmptyString(this.options.value)) { this.setValue(this.options.value); } - }, + } - _focus: function () { + _focus() { this.element.addClass("bi-input-focus"); this._checkValidationOnValueChange(); this._isEditing = true; if (this.getValue() === "") { - this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EMPTY, this.getValue(), this); - this.fireEvent(BI.Input.EVENT_EMPTY); - } - this.fireEvent(BI.Input.EVENT_FOCUS); - }, - - _blur: function () { - var self = this; - if (self._keydown_ === true) { - BI.delay(blur, BI.EVENT_RESPONSE_TIME); - } else { - blur(); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EMPTY, this.getValue(), this); + this.fireEvent(Input.EVENT_EMPTY); } + this.fireEvent(Input.EVENT_FOCUS); + } - function blur () { - if (!self.isValid() && self.options.quitChecker.apply(self, [BI.trim(self.getValue())]) !== false) { - self.element.val(self._lastValidValue ? self._lastValidValue : ""); - self._checkValidationOnValueChange(); - self._defaultState(); + _blur() { + const blur = () => { + if (!this.isValid() && this.options.quitChecker.apply(this, [trim(this.getValue())]) !== false) { + this.element.val(this._lastValidValue ? this._lastValidValue : ""); + this._checkValidationOnValueChange(); + this._defaultState(); } - self.element.removeClass("bi-input-focus"); - self._isEditing = false; - self._start = false; - if (self.isValid()) { - var lastValidValue = self._lastValidValue; - self._lastValidValue = self.getValue(); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.CONFIRM, self.getValue(), self); - self.fireEvent(BI.Input.EVENT_CONFIRM); - if (self._lastValidValue !== lastValidValue) { - self.fireEvent(BI.Input.EVENT_CHANGE_CONFIRM); + this.element.removeClass("bi-input-focus"); + this._isEditing = false; + this._start = false; + if (this.isValid()) { + const lastValidValue = this._lastValidValue; + this._lastValidValue = this.getValue(); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.CONFIRM, this.getValue(), this); + this.fireEvent(Input.EVENT_CONFIRM); + if (this._lastValidValue !== lastValidValue) { + this.fireEvent(Input.EVENT_CHANGE_CONFIRM); } } - self.fireEvent(BI.Input.EVENT_BLUR); + this.fireEvent(Input.EVENT_BLUR); } - }, + + if (this._keydown_ === true) { + delay(blur, BI.EVENT_RESPONSE_TIME); + } else { + blur(); + } + } - _click: function () { + _click() { if (this._isEditing !== true) { this.selectAll(); - this.fireEvent(BI.Input.EVENT_CLICK); + this.fireEvent(Input.EVENT_CLICK); } - }, + } - onClick: function () { + onClick() { this._click(); - }, + } - onKeyDown: function (keyCode, ctrlKey) { - if (!this.isValid() || BI.trim(this._lastChangedValue) !== BI.trim(this.getValue())) { + onKeyDown(keyCode, ctrlKey) { + if (!this.isValid() || trim(this._lastChangedValue) !== trim(this.getValue())) { this._checkValidationOnValueChange(); } - if (this.isValid() && BI.trim(this.getValue()) !== "") { - if (BI.trim(this.getValue()) !== this._lastValue && (!this._start || BI.isNull(this._lastValue) || this._lastValue === "") + if (this.isValid() && trim(this.getValue()) !== "") { + if (trim(this.getValue()) !== this._lastValue && (!this._start || isNull(this._lastValue) || this._lastValue === "") || (this._pause === true && !/(\s|\u00A0)$/.test(this.getValue()))) { this._start = true; this._pause = false; - this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.STARTEDIT, this.getValue(), this); - this.fireEvent(BI.Input.EVENT_START); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.STARTEDIT, this.getValue(), this); + this.fireEvent(Input.EVENT_START); } } - if (BI.isEqual(keyCode, BI.KeyCode.ENTER)) { - if (this.isValid() || this.options.quitChecker.apply(this, [BI.trim(this.getValue())]) !== false) { + if (isEqual(keyCode, BI.KeyCode.ENTER)) { + if (this.isValid() || this.options.quitChecker.apply(this, [trim(this.getValue())]) !== false) { this.blur(); - this.fireEvent(BI.Input.EVENT_ENTER); + this.fireEvent(Input.EVENT_ENTER); } else { - this.fireEvent(BI.Input.EVENT_RESTRICT); + this.fireEvent(Input.EVENT_RESTRICT); } } - if (BI.isEqual(keyCode, BI.KeyCode.SPACE)) { - this.fireEvent(BI.Input.EVENT_SPACE); + if (isEqual(keyCode, BI.KeyCode.SPACE)) { + this.fireEvent(Input.EVENT_SPACE); } - if (BI.isEqual(keyCode, BI.KeyCode.BACKSPACE) && this._lastValue === "") { - this.fireEvent(BI.Input.EVENT_REMOVE); + if (isEqual(keyCode, BI.KeyCode.BACKSPACE) && this._lastValue === "") { + this.fireEvent(Input.EVENT_REMOVE); } - if (BI.isEqual(keyCode, BI.KeyCode.BACKSPACE) || BI.isEqual(keyCode, BI.KeyCode.DELETE)) { - this.fireEvent(BI.Input.EVENT_BACKSPACE); + if (isEqual(keyCode, BI.KeyCode.BACKSPACE) || isEqual(keyCode, BI.KeyCode.DELETE)) { + this.fireEvent(Input.EVENT_BACKSPACE); } - this.fireEvent(BI.Input.EVENT_KEY_DOWN, arguments); + this.fireEvent(Input.EVENT_KEY_DOWN, arguments); // _valueChange中会更新_lastValue, 这边缓存用以后续STOP事件服务 - var lastValue = this._lastValue; - if (BI.trim(this.getValue()) !== BI.trim(this._lastValue || "")) { + const lastValue = this._lastValue; + if (trim(this.getValue()) !== trim(this._lastValue || "")) { this._valueChange(); } - if (BI.isEndWithBlank(this.getValue())) { + if (isEndWithBlank(this.getValue())) { this._pause = true; - this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.PAUSE, "", this); - this.fireEvent(BI.Input.EVENT_PAUSE); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.PAUSE, "", this); + this.fireEvent(Input.EVENT_PAUSE); this._defaultState(); } else if ((keyCode === BI.KeyCode.BACKSPACE || keyCode === BI.KeyCode.DELETE) && - BI.trim(this.getValue()) === "" && (lastValue !== null && BI.trim(lastValue) !== "")) { - this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.STOPEDIT, this.getValue(), this); - this.fireEvent(BI.Input.EVENT_STOP); + trim(this.getValue()) === "" && (lastValue !== null && trim(lastValue) !== "")) { + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.STOPEDIT, this.getValue(), this); + this.fireEvent(Input.EVENT_STOP); } - }, + } // 初始状态 - _defaultState: function () { + _defaultState() { if (this.getValue() === "") { - this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EMPTY, this.getValue(), this); - this.fireEvent(BI.Input.EVENT_EMPTY); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EMPTY, this.getValue(), this); + this.fireEvent(Input.EVENT_EMPTY); } this._lastValue = this.getValue(); this._lastSubmitValue = null; - }, + } - _valueChange: function () { - if (this.isValid() && BI.trim(this.getValue()) !== this._lastSubmitValue) { - this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.CHANGE, this.getValue(), this); - this.fireEvent(BI.Input.EVENT_CHANGE); - this._lastSubmitValue = BI.trim(this.getValue()); + _valueChange() { + if (this.isValid() && trim(this.getValue()) !== this._lastSubmitValue) { + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.CHANGE, this.getValue(), this); + this.fireEvent(Input.EVENT_CHANGE); + this._lastSubmitValue = trim(this.getValue()); } if (this.getValue() === "") { - this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EMPTY, this.getValue(), this); - this.fireEvent(BI.Input.EVENT_EMPTY); + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EMPTY, this.getValue(), this); + this.fireEvent(Input.EVENT_EMPTY); } this._lastValue = this.getValue(); - }, + } - _checkValidationOnValueChange: function (callback) { - var self = this, o = this.options; - var v = this.getValue(); - if (o.allowBlank === true && BI.trim(v) === "") { + _checkValidationOnValueChange(callback) { + const { allowBlank, validationChecker } = this.options; + const v = this.getValue(); + if (allowBlank === true && trim(v) === "") { this.setValid(true); callback && callback(); return; } - if (BI.trim(v) === "") { + if (trim(v) === "") { this.setValid(false); callback && callback(); return; } - var checker = o.validationChecker.apply(this, [BI.trim(v)]); + const checker = validationChecker.apply(this, [trim(v)]); if (checker instanceof Promise) { - checker.then(function (validate) { - self.setValid(validate !== false); + checker.then((validate) => { + this.setValid(validate !== false); callback && callback(); }); } else { this.setValid(checker !== false); callback && callback(); } - }, + } - focus: function () { + focus() { if (!this.element.is(":visible")) { throw new Error("input输入框在不可见下不能focus"); } @@ -242,9 +268,9 @@ BI.Input = BI.inherit(BI.Single, { this.element.focus(); this.selectAll(); } - }, + } - blur: function () { + blur() { if (!this.element.is(":visible")) { throw new Error("input输入框在不可见下不能blur"); } @@ -252,84 +278,61 @@ BI.Input = BI.inherit(BI.Single, { this.element.blur(); this._blurDebounce(); } - }, + } - selectAll: function () { + selectAll() { if (!this.element.is(":visible")) { throw new Error("input输入框在不可见下不能select"); } this.element.select(); this._isEditing = true; - }, + } - setValue: function (textValue) { - var self = this; + setValue(textValue) { this.element.val(textValue); - BI.nextTick(function () { - self._checkValidationOnValueChange(function () { - self._defaultState(); - if (self.isValid()) { - self._lastValidValue = self._lastSubmitValue = self.getValue(); + nextTick(() => { + this._checkValidationOnValueChange(() => { + this._defaultState(); + if (this.isValid()) { + this._lastValidValue = this._lastSubmitValue = this.getValue(); } }); }); - }, + } - getValue: function () { + getValue() { return this.element.val() || ""; - }, + } - isEditing: function () { + isEditing() { return this._isEditing; - }, + } - getLastValidValue: function () { + getLastValidValue() { return this._lastValidValue; - }, + } - getLastChangedValue: function () { + getLastChangedValue() { return this._lastChangedValue; - }, + } - _setValid: function () { - BI.Input.superclass._setValid.apply(this, arguments); + _setValid() { + super._setValid(arguments); if (this.isValid()) { this._lastChangedValue = this.getValue(); this.element.removeClass("bi-input-error"); - this.fireEvent(BI.Input.EVENT_VALID, BI.trim(this.getValue()), this); + this.fireEvent(Input.EVENT_VALID, trim(this.getValue()), this); } else { if (this._lastChangedValue === this.getValue()) { this._lastChangedValue = null; } this.element.addClass("bi-input-error"); - this.fireEvent(BI.Input.EVENT_ERROR, BI.trim(this.getValue()), this); + this.fireEvent(Input.EVENT_ERROR, trim(this.getValue()), this); } - }, + } - _setEnable: function (b) { - BI.Input.superclass._setEnable.apply(this, [b]); + _setEnable(b) { + super._setEnable([b]); this.element[0].disabled = !b; - }, -}); -BI.Input.EVENT_CHANGE = "EVENT_CHANGE"; - -BI.Input.EVENT_FOCUS = "EVENT_FOCUS"; -BI.Input.EVENT_CLICK = "EVENT_CLICK"; -BI.Input.EVENT_BLUR = "EVENT_BLUR"; -BI.Input.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.Input.EVENT_QUICK_DOWN = "EVENT_QUICK_DOWN"; -BI.Input.EVENT_SPACE = "EVENT_SPACE"; -BI.Input.EVENT_BACKSPACE = "EVENT_BACKSPACE"; - -BI.Input.EVENT_START = "EVENT_START"; -BI.Input.EVENT_PAUSE = "EVENT_PAUSE"; -BI.Input.EVENT_STOP = "EVENT_STOP"; -BI.Input.EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; -BI.Input.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.Input.EVENT_REMOVE = "EVENT_REMOVE"; -BI.Input.EVENT_EMPTY = "EVENT_EMPTY"; -BI.Input.EVENT_VALID = "EVENT_VALID"; -BI.Input.EVENT_ERROR = "EVENT_ERROR"; -BI.Input.EVENT_ENTER = "EVENT_ENTER"; -BI.Input.EVENT_RESTRICT = "EVENT_RESTRICT"; -BI.shortcut("bi.input", BI.Input); + } +} diff --git a/src/base/single/label/abstract.label.js b/src/base/single/label/abstract.label.js index 19fc0322d..b794e7fc4 100644 --- a/src/base/single/label/abstract.label.js +++ b/src/base/single/label/abstract.label.js @@ -1,399 +1,400 @@ /** * Created by dailer on 2019/6/19. */ -!(function () { - BI.AbstractLabel = BI.inherit(BI.Single, { +import { isNumber, createWidget, extend } from "../../../core"; +import { Single } from "../0.single"; - _defaultConfig: function (props) { - var conf = BI.AbstractLabel.superclass._defaultConfig.apply(this, arguments); +export class AbstractLabel extends Single { - return BI.extend(conf, { - textAlign: "center", - whiteSpace: "nowrap", // normal or nowrap - textWidth: null, - textHeight: null, - hgap: 0, - vgap: 0, - lgap: 0, - rgap: 0, - tgap: 0, - bgap: 0, - highLight: false, - handler: null, - enableHover: props.title !== null, - }); - }, + _defaultConfig(props) { + const conf = super._defaultConfig(arguments); - _createJson: function () { - var o = this.options; + return extend(conf, { + textAlign: "center", + whiteSpace: "nowrap", // normal or nowrap + textWidth: null, + textHeight: null, + hgap: 0, + vgap: 0, + lgap: 0, + rgap: 0, + tgap: 0, + bgap: 0, + highLight: false, + handler: null, + enableHover: props.title !== null, + }); + } - return { - type: "bi.text", - textAlign: o.textAlign, - whiteSpace: o.whiteSpace, - lineHeight: o.textHeight, - maxWidth: "100%", - text: o.text, - value: o.value, - py: o.py, - keyword: o.keyword, - highLight: o.highLight, - handler: o.handler, - }; - }, + _createJson() { + const { textAlign, whiteSpace, textHeight, text, value, py, keyword, highLight, handler } = this.options; - render: function () { - if (this.options.textAlign === "center") { - this._createCenterEl(); - } else { - this._createNotCenterEl(); - } - }, + return { + type: "bi.text", + textAlign, + whiteSpace, + lineHeight: textHeight, + maxWidth: "100%", + text, + value, + py, + keyword, + highLight, + handler, + }; + } - _createCenterEl: function () { - var o = this.options; - var json = this._createJson(); - json.textAlign = "left"; - if (BI.isNumber(o.width) && o.width > 0) { - if (BI.isNumber(o.textWidth) && o.textWidth > 0) { - json.maxWidth = o.textWidth; - if (BI.isNumber(o.height) && o.height > 0) { // 1.1 - BI.createWidget({ - type: "bi.center_adapt", - height: o.height, - columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 - scrollable: o.whiteSpace === "normal", - element: this, - items: [ - { - el: (this.text = BI.createWidget(json)), - } - ], - }); + render() { + if (this.options.textAlign === "center") { + this._createCenterEl(); + } else { + this._createNotCenterEl(); + } + } - return; - } - BI.createWidget({ // 1.2 + _createCenterEl() { + const { width, textWidth, height, whiteSpace, hgap, vgap, lgap, rgap, tgap, bgap, textAlign } = this.options; + const json = this._createJson(); + json.textAlign = "left"; + if (isNumber(width) && width > 0) { + if (isNumber(textWidth) && textWidth > 0) { + json.maxWidth = textWidth; + if (isNumber(height) && height > 0) { // 1.1 + createWidget({ type: "bi.center_adapt", + height, columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 - scrollable: o.whiteSpace === "normal", + scrollable: whiteSpace === "normal", element: this, items: [ { - el: (this.text = BI.createWidget(json)), + el: (this.text = createWidget(json)), } ], }); return; } - if (o.whiteSpace === "normal") { // 1.3 - BI.extend(json, { - hgap: o.hgap, - vgap: o.vgap, - lgap: o.lgap, - rgap: o.rgap, - tgap: o.tgap, - bgap: o.bgap, - }); - this.text = BI.createWidget(json); - BI.createWidget({ - type: "bi.center_adapt", - columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 - scrollable: o.whiteSpace === "normal", - element: this, - items: [this.text], - }); - - return; - } - if (BI.isNumber(o.height) && o.height > 0) { // 1.4 - this.element.css({ - "line-height": BI.pixFormat(o.height), - }); - json.textAlign = o.textAlign; - delete json.maxWidth; - this.text = BI.createWidget(BI.extend(json, { - element: this, - hgap: o.hgap, - vgap: o.vgap, - lgap: o.lgap, - rgap: o.rgap, - tgap: o.tgap, - bgap: o.bgap, - })); - - return; - } - BI.extend(json, { // 1.5 - hgap: o.hgap, - vgap: o.vgap, - lgap: o.lgap, - rgap: o.rgap, - tgap: o.tgap, - bgap: o.bgap, - maxWidth: "100%", - }); - this.text = BI.createWidget(json); - BI.createWidget({ + createWidget({ // 1.2 type: "bi.center_adapt", columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 - scrollable: o.whiteSpace === "normal", - element: this, - items: [this.text], - }); - - return; - } - if (BI.isNumber(o.textWidth) && o.textWidth > 0) { // 1.6 - json.maxWidth = o.textWidth; - BI.createWidget({ - type: "bi.center_adapt", - columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 - scrollable: o.whiteSpace === "normal", + scrollable: whiteSpace === "normal", element: this, items: [ { - el: (this.text = BI.createWidget(json)), + el: (this.text = createWidget(json)), } ], }); return; } - if (o.whiteSpace === "normal") { // 1.7 - BI.extend(json, { - hgap: o.hgap, - vgap: o.vgap, - lgap: o.lgap, - rgap: o.rgap, - tgap: o.tgap, - bgap: o.bgap, + if (whiteSpace === "normal") { // 1.3 + extend(json, { + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, }); - this.text = BI.createWidget(json); - BI.createWidget({ + this.text = createWidget(json); + createWidget({ type: "bi.center_adapt", columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 - scrollable: true, + scrollable: whiteSpace === "normal", element: this, items: [this.text], }); return; } - if (BI.isNumber(o.height) && o.height > 0) { // 1.8 + if (isNumber(height) && height > 0) { // 1.4 this.element.css({ - "line-height": BI.pixFormat(o.height), + "line-height": BI.pixFormat(height), }); - json.textAlign = o.textAlign; + json.textAlign = textAlign; delete json.maxWidth; - this.text = BI.createWidget(BI.extend(json, { + this.text = createWidget(extend(json, { element: this, - hgap: o.hgap, - vgap: o.vgap, - lgap: o.lgap, - rgap: o.rgap, - tgap: o.tgap, - bgap: o.bgap, + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, })); return; } - this.text = BI.createWidget(BI.extend(json, { - hgap: o.hgap, - vgap: o.vgap, - lgap: o.lgap, - rgap: o.rgap, - tgap: o.tgap, - bgap: o.bgap, - })); - BI.createWidget({ + extend(json, { // 1.5 + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, + maxWidth: "100%", + }); + this.text = createWidget(json); + createWidget({ type: "bi.center_adapt", columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 + scrollable: whiteSpace === "normal", element: this, items: [this.text], }); - }, - _createNotCenterEl: function () { - var o = this.options; - var adaptLayout = "bi.vertical_adapt"; - var json = this._createJson(); - if (BI.isNumber(o.width) && o.width > 0) { - if (BI.isNumber(o.textWidth) && o.textWidth > 0) { - json.maxWidth = o.textWidth; - if (BI.isNumber(o.height) && o.height > 0) { // 2.1 - BI.createWidget({ - type: adaptLayout, - horizontalAlign: o.textAlign, - columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 - height: o.height, - scrollable: o.whiteSpace === "normal", - element: this, - items: [ - { - el: (this.text = BI.createWidget(json)), - } - ], - }); - - return; + return; + } + if (isNumber(textWidth) && textWidth > 0) { // 1.6 + json.maxWidth = textWidth; + createWidget({ + type: "bi.center_adapt", + columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 + scrollable: whiteSpace === "normal", + element: this, + items: [ + { + el: (this.text = createWidget(json)), } - BI.createWidget({ // 2.2 + ], + }); + + return; + } + if (whiteSpace === "normal") { // 1.7 + extend(json, { + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, + }); + this.text = createWidget(json); + createWidget({ + type: "bi.center_adapt", + columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 + scrollable: true, + element: this, + items: [this.text], + }); + + return; + } + if (isNumber(height) && height > 0) { // 1.8 + this.element.css({ + "line-height": BI.pixFormat(height), + }); + json.textAlign = textAlign; + delete json.maxWidth; + this.text = createWidget(extend(json, { + element: this, + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, + })); + + return; + } + this.text = createWidget(extend(json, { + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, + })); + createWidget({ + type: "bi.center_adapt", + columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 + element: this, + items: [this.text], + }); + } + + _createNotCenterEl() { + const { width, textWidth, height, whiteSpace, hgap, vgap, lgap, rgap, tgap, bgap, textAlign } = this.options; + const adaptLayout = "bi.vertical_adapt"; + const json = this._createJson(); + if (isNumber(width) && width > 0) { + if (isNumber(textWidth) && textWidth > 0) { + json.maxWidth = textWidth; + if (isNumber(height) && height > 0) { // 2.1 + createWidget({ type: adaptLayout, - horizontalAlign: o.textAlign, + horizontalAlign: textAlign, columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 - scrollable: o.whiteSpace === "normal", - hgap: o.hgap, - vgap: o.vgap, - lgap: o.lgap, - rgap: o.rgap, - tgap: o.tgap, - bgap: o.bgap, + height, + scrollable: whiteSpace === "normal", element: this, items: [ { - el: (this.text = BI.createWidget(json)), + el: (this.text = createWidget(json)), } ], }); return; } - if (BI.isNumber(o.height) && o.height > 0) { // 2.3 - if (o.whiteSpace !== "normal") { - this.element.css({ - "line-height": BI.pixFormat(o.height - (o.vgap * 2)), - }); - } - delete json.maxWidth; - this.text = BI.createWidget(BI.extend(json, { - element: this, - hgap: o.hgap, - vgap: o.vgap, - lgap: o.lgap, - rgap: o.rgap, - tgap: o.tgap, - bgap: o.bgap, - })); - - return; - } - json.maxWidth = o.width - 2 * o.hgap - o.lgap - o.rgap; - BI.createWidget({ // 2.4 + createWidget({ // 2.2 type: adaptLayout, - horizontalAlign: o.textAlign, + horizontalAlign: textAlign, columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 - scrollable: o.whiteSpace === "normal", - hgap: o.hgap, - vgap: o.vgap, - lgap: o.lgap, - rgap: o.rgap, - tgap: o.tgap, - bgap: o.bgap, - element: this, - items: [{ - el: (this.text = BI.createWidget(json)), - }], - }); - - return; - } - if (BI.isNumber(o.textWidth) && o.textWidth > 0) { - json.maxWidth = o.textWidth; - BI.createWidget({ // 2.5 - type: adaptLayout, - horizontalAlign: o.textAlign, - columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 - scrollable: o.whiteSpace === "normal", - hgap: o.hgap, - vgap: o.vgap, - lgap: o.lgap, - rgap: o.rgap, - tgap: o.tgap, - bgap: o.bgap, + scrollable: whiteSpace === "normal", + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, element: this, items: [ { - el: (this.text = BI.createWidget(json)), + el: (this.text = createWidget(json)), } ], }); return; } - if (BI.isNumber(o.height) && o.height > 0) { - if (o.whiteSpace !== "normal") { + if (isNumber(height) && height > 0) { // 2.3 + if (whiteSpace !== "normal") { this.element.css({ - "line-height": BI.pixFormat(o.height - (o.vgap * 2)), + "line-height": BI.pixFormat(height - (vgap * 2)), }); } delete json.maxWidth; - this.text = BI.createWidget(BI.extend(json, { // 2.6 + this.text = createWidget(extend(json, { element: this, - hgap: o.hgap, - vgap: o.vgap, - lgap: o.lgap, - rgap: o.rgap, - tgap: o.tgap, - bgap: o.bgap, + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, })); return; } - this.text = BI.createWidget(BI.extend(json, { - hgap: o.hgap, - vgap: o.vgap, - lgap: o.lgap, - rgap: o.rgap, - tgap: o.tgap, - bgap: o.bgap, - })); - BI.createWidget({ + json.maxWidth = width - 2 * hgap - lgap - rgap; + createWidget({ // 2.4 type: adaptLayout, - horizontalAlign: o.textAlign, + horizontalAlign: textAlign, columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 + scrollable: whiteSpace === "normal", + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, element: this, - scrollable: o.whiteSpace === "normal", - items: [this.text], + items: [{ + el: (this.text = createWidget(json)), + }], }); - }, - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + return; + } + if (isNumber(textWidth) && textWidth > 0) { + json.maxWidth = textWidth; + createWidget({ // 2.5 + type: adaptLayout, + horizontalAlign: textAlign, + columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 + scrollable: whiteSpace === "normal", + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, + element: this, + items: [ + { + el: (this.text = createWidget(json)), + } + ], + }); - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + return; + } + if (isNumber(height) && height > 0) { + if (whiteSpace !== "normal") { + this.element.css({ + "line-height": BI.pixFormat(height - (vgap * 2)), + }); + } + delete json.maxWidth; + this.text = createWidget(extend(json, { // 2.6 + element: this, + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, + })); - doHighLight: function () { - this.text.doHighLight.apply(this.text, arguments); - }, + return; + } + this.text = createWidget(extend(json, { + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, + })); + createWidget({ + type: adaptLayout, + horizontalAlign: textAlign, + columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 + element: this, + scrollable: whiteSpace === "normal", + items: [this.text], + }); + } - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark.apply(this.text, arguments); + } - setText: function (v) { - this.options.text = v; - this.text.setText(v); - }, + unRedMark() { + this.text.unRedMark.apply(this.text, arguments); + } - getText: function () { - return this.options.text; - }, + doHighLight() { + this.text.doHighLight.apply(this.text, arguments); + } - setStyle: function (css) { - this.text.setStyle(css); - }, + unHighLight() { + this.text.unHighLight.apply(this.text, arguments); + } - setValue: function (v) { - BI.AbstractLabel.superclass.setValue.apply(this, arguments); - if (!this.isReadOnly()) { - this.options.text = v; - this.text.setValue(v); - } - }, - }); -}()); + setText(v) { + this.options.text = v; + this.text.setText(v); + } + + getText() { + return this.options.text; + } + + setStyle(css) { + this.text.setStyle(css); + } + + setValue(v) { + super.setValue(v); + if (!this.isReadOnly()) { + this.options.text = v; + this.text.setValue(v); + } + } +} diff --git a/src/base/single/label/html.label.js b/src/base/single/label/html.label.js index e1ac76b66..0fa4f0d14 100644 --- a/src/base/single/label/html.label.js +++ b/src/base/single/label/html.label.js @@ -1,26 +1,28 @@ /** * Created by GUY on 2015/6/26. */ +import { shortcut } from "../../../core"; +import { AbstractLabel } from "./abstract.label" -BI.HtmlLabel = BI.inherit(BI.AbstractLabel, { +@shortcut() +export class HtmlLabel extends AbstractLabel { + static xtype = "bi.html_label"; - props: { + props = { baseCls: "bi-html-label", - }, + } - _createJson: function () { - var o = this.options; + _createJson() { + const { textAlign, whiteSpace, textHeight, text, value, handler } = this.options; return { type: "bi.html", - textAlign: o.textAlign, - whiteSpace: o.whiteSpace, - lineHeight: o.textHeight, - text: o.text, - value: o.value, - handler: o.handler, + textAlign, + whiteSpace, + lineHeight: textHeight, + text, + value, + handler, }; - }, -}); - -BI.shortcut("bi.html_label", BI.HtmlLabel); + } +} diff --git a/src/base/single/label/icon.label.js b/src/base/single/label/icon.label.js index 53a400a05..0f4c1b432 100644 --- a/src/base/single/label/icon.label.js +++ b/src/base/single/label/icon.label.js @@ -1,11 +1,16 @@ /** - * @class BI.IconButton - * @extends BI.BasicButton + * @class BI.IconLabel + * @extends BI.Single * 图标标签 */ -BI.IconLabel = BI.inherit(BI.Single, { +import { shortcut, createWidget, isNumber, isNull } from "../../../core"; +import { Single } from "../0.single"; - props: { +@shortcut() +export class IconLabel extends Single { + static xtype = "bi.icon_label"; + + props = { baseCls: "bi-icon-label horizon-center", hgap: 0, vgap: 0, @@ -16,45 +21,44 @@ BI.IconLabel = BI.inherit(BI.Single, { iconWidth: null, iconHeight: null, lineHeight: null, - }, + } - render: function () { - var o = this.options; + render() { + const { iconWidth, iconHeight, height, lineHeight, hgap, vgap, lgap, rgap, tgap, bgap } = this.options; this.element.css({ textAlign: "center", }); - this.icon = BI.createWidget({ + this.icon = createWidget({ type: "bi.icon", - width: o.iconWidth, - height: o.iconHeight, + width: iconWidth, + height: iconHeight, }); - if (BI.isNumber(o.height) && o.height > 0 && BI.isNull(o.iconWidth) && BI.isNull(o.iconHeight)) { - this.element.css("lineHeight", BI.pixFormat(o.lineHeight || o.height)); - BI.createWidget({ + if (isNumber(height) && height > 0 && isNull(iconWidth) && isNull(iconHeight)) { + this.element.css("lineHeight", BI.pixFormat(lineHeight || height)); + createWidget({ type: "bi.default", element: this, - hgap: o.hgap, - vgap: o.vgap, - lgap: o.lgap, - rgap: o.rgap, - tgap: o.tgap, - bgap: o.bgap, + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, items: [this.icon], }); } else { this.element.css("lineHeight", "1"); - BI.createWidget({ + createWidget({ element: this, type: "bi.center_adapt", - hgap: o.hgap, - vgap: o.vgap, - lgap: o.lgap, - rgap: o.rgap, - tgap: o.tgap, - bgap: o.bgap, + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, items: [this.icon], }); } - }, -}); -BI.shortcut("bi.icon_label", BI.IconLabel); + } +} diff --git a/src/base/single/label/index.js b/src/base/single/label/index.js new file mode 100644 index 000000000..ae3d091db --- /dev/null +++ b/src/base/single/label/index.js @@ -0,0 +1,4 @@ +export { AbstractLabel } from "./abstract.label"; +export { HtmlLabel } from "./html.label"; +export { IconLabel } from "./icon.label"; +export { Label } from "./label"; \ No newline at end of file diff --git a/src/base/single/label/label.js b/src/base/single/label/label.js index 905efd29a..d5924b63b 100644 --- a/src/base/single/label/label.js +++ b/src/base/single/label/label.js @@ -1,39 +1,41 @@ /** * Created by GUY on 2015/6/26. */ +import { shortcut, isFunction, isNotNull } from "../../../core"; +import { AbstractLabel } from "./abstract.label" -BI.Label = BI.inherit(BI.AbstractLabel, { +@shortcut() +export class Label extends AbstractLabel { + static xtype = "bi.label"; - props: { + props = { baseCls: "bi-label", py: "", keyword: "", - }, + } - getTitle: function () { - var title = this.options.title; - var text = this.options.text; - if (BI.isFunction(title)) { + getTitle() { + const title = this.options.title; + const text = this.options.text; + if (isFunction(title)) { return title(); } - if (BI.isNotNull(title)) { + if (isNotNull(title)) { return title; } - if (BI.isFunction(text)) { + if (isFunction(text)) { return text(); } return text; - }, + } - doRedMark: function () { + doRedMark() { this.text.doRedMark.apply(this.text, arguments); - }, + } - unRedMark: function () { + unRedMark() { this.text.unRedMark.apply(this.text, arguments); - }, -}); - -BI.shortcut("bi.label", BI.Label); + } +} diff --git a/src/base/single/text.pure.js b/src/base/single/text.pure.js index 07a201369..b6207c693 100644 --- a/src/base/single/text.pure.js +++ b/src/base/single/text.pure.js @@ -1,46 +1,47 @@ /** * 没有html标签的纯文本 */ -!(function () { - BI.PureText = BI.inherit(BI.Widget, { +import { Widget, shortcut, isFunction, isKey, isNotNull } from "../../core"; +import { Text } from "./1.text"; - props: { - tagName: null, - }, +@shortcut() +export class PureText extends Widget { + static xtype = "bi.pure_text"; + + props = { + tagName: null, + } - render: function () { - var self = this, o = this.options; - var text = BI.isFunction(o.text) ? this.__watch(o.text, function (context, newValue) { - self.setText(newValue); - }) : o.text; - if (BI.isKey(text)) { - this.setText(text); - } else if (BI.isKey(o.value)) { - this.setText(o.value); - } - }, - - _getShowText: function () { - var o = this.options; - var text = BI.isFunction(o.text) ? o.text() : o.text; - text = BI.isKey(text) ? text : o.value; - if (!BI.isKey(text)) { - return ""; - } + render() { + const { text: optionsText, value } = this.options; + const text = isFunction(optionsText) ? this.__watch(optionsText, (context, newValue) => { + this.setText(newValue); + }) : optionsText; + if (isKey(text)) { + this.setText(text); + } else if (isKey(value)) { + this.setText(value); + } + } - return BI.Text.formatText(text + ""); - }, + _getShowText() { + const { text: optionsText, value } = this.options; + const text = isFunction(optionsText) ? optionsText() : optionsText; + text = isKey(text) ? text : value; + if (!isKey(text)) { + return ""; + } - setValue: function (value) { - this.options.value = value; - this.setText(value); - }, + return Text.formatText(text + ""); + } - setText: function (text) { - this.options.text = BI.isNotNull(text) ? text : ""; - this.element.__textKeywordMarked__(this._getShowText()); - }, - }); - BI.shortcut("bi.pure_text", BI.PureText); -}()); + setValue(value) { + this.options.value = value; + this.setText(value); + } + setText(text) { + this.options.text = isNotNull(text) ? text : ""; + this.element.__textKeywordMarked__(this._getShowText()); + } +} From 4efd86dc35c980e3c754611464af6469f7e00f40 Mon Sep 17 00:00:00 2001 From: impact Date: Wed, 4 Jan 2023 16:44:50 +0800 Subject: [PATCH 035/300] =?UTF-8?q?KERNEL-13901=20refactor:=20input?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=A4=B9ES6=E5=8C=96=E8=A1=A5=E5=85=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../single/input/checkbox/checkbox.image.js | 25 +++++---- src/base/single/input/checkbox/checkbox.js | 54 ++++++++++--------- src/base/single/input/index.js | 6 ++- src/base/single/input/radio/radio.image.js | 33 +++++++----- src/base/single/input/radio/radio.js | 53 +++++++++--------- 5 files changed, 96 insertions(+), 75 deletions(-) diff --git a/src/base/single/input/checkbox/checkbox.image.js b/src/base/single/input/checkbox/checkbox.image.js index 0400f6530..04a6c5589 100644 --- a/src/base/single/input/checkbox/checkbox.image.js +++ b/src/base/single/input/checkbox/checkbox.image.js @@ -1,13 +1,21 @@ /** * guy - * @extends BI.Single + * @extends Single * @type {*|void|Object} */ -BI.ImageCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function () { - var conf = BI.ImageCheckbox.superclass._defaultConfig.apply(this, arguments); +import { shortcut, extend } from "../../../../core"; +import { IconButton } from "../../button"; - return BI.extend(conf, { +@shortcut() +export class ImageCheckbox extends IconButton { + static xtype = "bi.image_checkbox"; + + static EVENT_CHANGE = IconButton.EVENT_CHANGE; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { baseCls: (conf.baseCls || "") + " bi-image-checkbox check-box-icon", selected: false, handler: BI.emptyFn, @@ -16,8 +24,5 @@ BI.ImageCheckbox = BI.inherit(BI.IconButton, { iconWidth: 16, iconHeight: 16, }); - }, -}); -BI.ImageCheckbox.EVENT_CHANGE = BI.IconButton.EVENT_CHANGE; - -BI.shortcut("bi.image_checkbox", BI.ImageCheckbox); + } +} diff --git a/src/base/single/input/checkbox/checkbox.js b/src/base/single/input/checkbox/checkbox.js index b25d743e8..ed5ef46f7 100644 --- a/src/base/single/input/checkbox/checkbox.js +++ b/src/base/single/input/checkbox/checkbox.js @@ -1,11 +1,18 @@ /** * guy - * @extends BI.Single + * @extends Single * @type {*|void|Object} */ -BI.Checkbox = BI.inherit(BI.BasicButton, { +import { shortcut } from "../../../../core"; +import { BasicButton } from "../../button"; - props: { +@shortcut() +export class Checkbox extends BasicButton { + static xtype = "bi.checkbox"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + props = { baseCls: "bi-checkbox", selected: false, handler: BI.emptyFn, @@ -13,50 +20,47 @@ BI.Checkbox = BI.inherit(BI.BasicButton, { height: 14, iconWidth: 14, iconHeight: 14, - }, + } - render: function () { - var self = this, o = this.options; + render() { + const { iconWidth, iconHeight } = this.options; return { type: "bi.center_adapt", items: [{ type: "bi.default", - ref: function (_ref) { - self.checkbox = _ref; + ref: (_ref) => { + this.checkbox = _ref; }, cls: "checkbox-content", - width: o.iconWidth, - height: o.iconHeight, + width: iconWidth, + height: iconHeight, }], }; - }, + } - _setEnable: function (enable) { - BI.Checkbox.superclass._setEnable.apply(this, arguments); + _setEnable(enable) { + super._setEnable(enable); if (enable === true) { this.checkbox.element.removeClass("base-disabled disabled"); } else { this.checkbox.element.addClass("base-disabled disabled"); } - }, + } - doClick: function () { - BI.Checkbox.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick(arguments); if (this.isValid()) { - this.fireEvent(BI.Checkbox.EVENT_CHANGE); + this.fireEvent(Checkbox.EVENT_CHANGE); } - }, + } - setSelected: function (b) { - BI.Checkbox.superclass.setSelected.apply(this, arguments); + setSelected(b) { + super.setSelected(b); if (b) { this.checkbox.element.addClass("bi-high-light-background"); } else { this.checkbox.element.removeClass("bi-high-light-background"); } - }, -}); -BI.Checkbox.EVENT_CHANGE = "EVENT_CHANGE"; - -BI.shortcut("bi.checkbox", BI.Checkbox); + } +} diff --git a/src/base/single/input/index.js b/src/base/single/input/index.js index 4cd03bad2..35a8f9b60 100644 --- a/src/base/single/input/index.js +++ b/src/base/single/input/index.js @@ -1,2 +1,6 @@ export { Input } from "./input"; -export { File } from "./file"; \ No newline at end of file +export { File } from "./file"; +export { Checkbox } from "./checkbox/checkbox"; +export { ImageCheckbox } from "./checkbox/checkbox.image"; +export { Radio } from "./radio/radio"; +export { ImageRadio } from "./radio/radio.image"; \ No newline at end of file diff --git a/src/base/single/input/radio/radio.image.js b/src/base/single/input/radio/radio.image.js index f9d870f63..513b1feff 100644 --- a/src/base/single/input/radio/radio.image.js +++ b/src/base/single/input/radio/radio.image.js @@ -1,13 +1,21 @@ /** * guy - * @extends BI.Single + * @extends Single * @type {*|void|Object} */ -BI.ImageRadio = BI.inherit(BI.IconButton, { - _defaultConfig: function () { - var conf = BI.ImageRadio.superclass._defaultConfig.apply(this, arguments); +import { shortcut, extend } from "../../../../core"; +import { IconButton } from "../../button"; - return BI.extend(conf, { +@shortcut() +export class ImageRadio extends IconButton { + static xtype = "bi.image_radio"; + + static EVENT_CHANGE = IconButton.EVENT_CHANGE; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { baseCls: (conf.baseCls || "") + " bi-radio radio-icon", selected: false, handler: BI.emptyFn, @@ -16,15 +24,12 @@ BI.ImageRadio = BI.inherit(BI.IconButton, { iconWidth: 16, iconHeight: 16, }); - }, + } - doClick: function () { - BI.ImageRadio.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick(arguments); if (this.isValid()) { - this.fireEvent(BI.ImageRadio.EVENT_CHANGE); + this.fireEvent(ImageRadio.EVENT_CHANGE); } - }, -}); -BI.ImageRadio.EVENT_CHANGE = BI.IconButton.EVENT_CHANGE; - -BI.shortcut("bi.image_radio", BI.ImageRadio); + } +} diff --git a/src/base/single/input/radio/radio.js b/src/base/single/input/radio/radio.js index f84cf4038..612cd98d8 100644 --- a/src/base/single/input/radio/radio.js +++ b/src/base/single/input/radio/radio.js @@ -1,11 +1,17 @@ /** * guy - * @extends BI.Single + * @extends Single * @type {*|void|Object} */ -BI.Radio = BI.inherit(BI.BasicButton, { +import { shortcut } from "../../../../core"; +import { BasicButton } from "../../button"; - props: { +@shortcut() +export class Radio extends BasicButton { + static xtype = "bi.radio"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + props = { baseCls: "bi-radio", selected: false, handler: BI.emptyFn, @@ -13,50 +19,47 @@ BI.Radio = BI.inherit(BI.BasicButton, { height: 16, iconWidth: 16, iconHeight: 16 - }, + } - render: function () { - var self = this, o = this.options; + render() { + const { iconWidth, iconHeight } = this.options; return { type: "bi.center_adapt", items: [{ type: "bi.layout", cls: "radio-content", - ref: function (_ref) { - self.radio = _ref; + ref: (_ref) => { + this.radio = _ref; }, - width: o.iconWidth, - height: o.iconHeight, + width: iconWidth, + height: iconHeight, }], }; - }, + } - _setEnable: function (enable) { - BI.Radio.superclass._setEnable.apply(this, arguments); + _setEnable(enable) { + super._setEnable(enable); if (enable === true) { this.radio.element.removeClass("base-disabled disabled"); } else { this.radio.element.addClass("base-disabled disabled"); } - }, + } - doClick: function () { - BI.Radio.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick(arguments); if (this.isValid()) { - this.fireEvent(BI.Radio.EVENT_CHANGE); + this.fireEvent(Radio.EVENT_CHANGE); } - }, + } - setSelected: function (b) { - BI.Radio.superclass.setSelected.apply(this, arguments); + setSelected(b) { + super.setSelected(b); if (b) { this.radio.element.addClass("bi-high-light-background"); } else { this.radio.element.removeClass("bi-high-light-background"); } - }, -}); -BI.Radio.EVENT_CHANGE = "EVENT_CHANGE"; - -BI.shortcut("bi.radio", BI.Radio); + } +} From c4184571d3c5b808fb3231add275aa356ffdf513 Mon Sep 17 00:00:00 2001 From: zsmj Date: Wed, 4 Jan 2023 16:46:17 +0800 Subject: [PATCH 036/300] =?UTF-8?q?KERNEL-14012=20feat:=20core/structure?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=A4=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/index.js | 2 ++ src/core/structure/index.js | 31 ------------------------------- 2 files changed, 2 insertions(+), 31 deletions(-) diff --git a/src/core/index.js b/src/core/index.js index 2c85e1eda..fedcc0d26 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -6,6 +6,7 @@ import * as action from "./action"; import * as behavior from "./behavior"; import * as controllers from "./controller"; import * as func from "./func"; +import * as structure from "./structure"; import {StyleLoaderManager} from "./loader/loader.style"; import "./h"; import {ShowListener} from "./listener/listener.show"; @@ -39,4 +40,5 @@ Object.assign(BI, { ...func, StyleLoaderManager, ShowListener, + ...structure, }); diff --git a/src/core/structure/index.js b/src/core/structure/index.js index 4495bf79e..263e41942 100644 --- a/src/core/structure/index.js +++ b/src/core/structure/index.js @@ -1,34 +1,3 @@ -import * as a1 from "./aes"; -import * as a2 from "./aspect"; -import * as a3 from "./base64"; -import * as a4 from "./cache"; -import * as a5 from "./cellSizeAndPositionManager"; -import * as a6 from "./heap"; -import * as a7 from "./linkedHashMap"; -import * as a8 from "./lru"; -import * as a9 from "./prefixIntervalTree"; -import * as a10 from "./queue"; -import * as a11 from "./sectionManager"; -import * as a12 from "./tree"; -import * as a13 from "./vector"; - -Object.assign(BI, { - ...a1, - ...a2, - ...a3, - ...a4, - ...a5, - ...a6, - ...a7, - ...a8, - ...a9, - ...a10, - ...a11, - ...a12, - ...a13, -}); - - export * from "./aes"; export * from "./aspect"; export * from "./base64"; From 4e2a41bfb7a0e0bc7d4395f96cbe1862b6df61b8 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Thu, 5 Jan 2023 00:30:17 +0800 Subject: [PATCH 037/300] =?UTF-8?q?=E6=97=A0JIRA=E4=BB=BB=E5=8A=A1=20chore?= =?UTF-8?q?:=20=E8=A1=A5=E5=85=85eslint=E8=A7=84=E5=88=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .eslintrc | 8 +- src/core/2.base.js | 544 +++++++++++++++++++++++-------------------- src/core/3.ob.js | 11 +- src/core/4.widget.js | 135 ++++++----- src/core/5.inject.js | 201 ++++++++-------- src/core/index.js | 6 +- 6 files changed, 495 insertions(+), 410 deletions(-) diff --git a/.eslintrc b/.eslintrc index eee30f2c7..234d9007a 100644 --- a/.eslintrc +++ b/.eslintrc @@ -27,11 +27,15 @@ "plugins": ["@typescript-eslint/eslint-plugin"], "overrides": [{ "files": ["src/*.js","src/**/*.js", "demo/*.js", "demo/**/*.js", "i18n/**/*.js", "i18n/*.js", "test/**/*.js", "test/*.js", "examples/*.js", "examples/**/*.js"], - "extends": "plugin:@fui/es6", + "extends": "plugin:@fui/esnext", "rules": { "no-param-reassign": "off", "quotes": [2, "double"], - "comma-dangle": ["error", { "arrays": "never", "objects": "always-multiline"}] // 多行对象字面量中要求拖尾逗号 + "comma-dangle": ["error", { "arrays": "never", "objects": "always-multiline"}], // 多行对象字面量中要求拖尾逗号 + "no-var": 2, + "prefer-const": 2, + "indent": ["error", 4], + "no-use-before-define": 0 } }, { "files": ["webpack/*.js", "./*.js", "lib/**/*.js", "lib/*.js", "./bin/*.js", "./bin/**/*.js"], diff --git a/src/core/2.base.js b/src/core/2.base.js index 01814415b..4fe7583de 100644 --- a/src/core/2.base.js +++ b/src/core/2.base.js @@ -3,28 +3,29 @@ * Create By GUY 2014\11\17 * */ -var traverse = function (func, context) { +function traverse (func, context) { return function (value, key, obj) { return func.call(context, key, value, obj); }; -}; -var _apply = function (name) { +} +function _apply(name) { return function () { - return BI._[name].apply(BI._, arguments); + return BI._[name](...arguments); }; -}; -var _applyFunc = function (name) { +} +function _applyFunc(name) { return function () { - var args = Array.prototype.slice.call(arguments, 0); + const args = Array.prototype.slice.call(arguments, 0); args[1] = BI._.isFunction(args[1]) ? traverse(args[1], args[2]) : args[1]; - return BI._[name].apply(BI._, args); + + return BI._[name](...args); }; -}; +} export function assert(v, is) { if (isFunction(is)) { if (!is(v)) { - throw new Error(v + " error"); + throw new Error(`${v} error`); } else { return true; } @@ -33,8 +34,9 @@ export function assert(v, is) { is = [is]; } if (!deepContains(is, v)) { - throw new Error(v + " error"); + throw new Error(`${v} error`); } + return true; } @@ -43,12 +45,13 @@ export function warn(message) { } export function UUID() { - var f = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; - var str = ""; - for (var i = 0; i < 16; i++) { - var r = _global.parseInt(f.length * Math.random(), 10); + const f = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; + let str = ""; + for (let i = 0; i < 16; i++) { + const r = _global.parseInt(f.length * Math.random(), 10); str += f[r]; } + return str; } @@ -66,58 +69,60 @@ export function createWidgets(items, options, context) { } else { options || (options = {}); } - return map(flatten(items), function (i, item) { - return BI.createWidget(item, deepClone(options), context); - }); + + return map(flatten(items), (i, item) => BI.createWidget(item, deepClone(options), context)); } export function createItems(data, innerAttr, outerAttr) { innerAttr = isArray(innerAttr) ? innerAttr : makeArray(flatten(data).length, innerAttr || {}); outerAttr = isArray(outerAttr) ? outerAttr : makeArray(flatten(data).length, outerAttr || {}); - return map(data, function (i, item) { + + return map(data, (i, item) => { if (isArray(item)) { return createItems(item, innerAttr, outerAttr); } if (item instanceof BI.Widget) { return extend({}, innerAttr.shift(), outerAttr.shift(), { type: null, - el: item + el: item, }); } if (innerAttr[0] instanceof BI.Widget) { outerAttr.shift(); + return extend({}, item, { - el: innerAttr.shift() + el: innerAttr.shift(), }); } if (item.el instanceof BI.Widget) { innerAttr.shift(); + return extend({}, outerAttr.shift(), { type: null }, item); } if (item.el) { return extend({}, outerAttr.shift(), item, { - el: extend({}, innerAttr.shift(), item.el) + el: extend({}, innerAttr.shift(), item.el), }); } + return extend({}, outerAttr.shift(), { - el: extend({}, innerAttr.shift(), item) + el: extend({}, innerAttr.shift(), item), }); }); } // 用容器包装items export function packageItems(items, layouts) { - for (var i = layouts.length - 1; i >= 0; i--) { - items = map(items, function (k, it) { - return extend({}, layouts[i], { - items: [ - extend({}, layouts[i].el, { - el: it - }) - ] - }); - }); - } + for (let i = layouts.length - 1; i >= 0; i--) { + items = map(items, (k, it) => extend({}, layouts[i], { + items: [ + extend({}, layouts[i].el, { + el: it, + }) + ], + })); + } + return items; } @@ -125,8 +130,9 @@ export function formatEL(obj) { if (obj && !obj.type && obj.el) { return obj; } + return { - el: obj + el: obj, }; } @@ -140,13 +146,13 @@ export function trans2Element(widgets) { } // 集合相关方法 -BI._.each(["where", "findWhere", "invoke", "pluck", "shuffle", "sample", "toArray", "size"], function (name) { +BI._.each(["where", "findWhere", "invoke", "pluck", "shuffle", "sample", "toArray", "size"], name => { BI[name] = _apply(name); }); BI._.each([ "get", "set", "each", "map", "reduce", "reduceRight", "find", "filter", "reject", "every", "all", "some", "any", "max", "min", "sortBy", "groupBy", "indexBy", "countBy", "partition", "clamp" -], function (name) { +], name => { if (name === "any") { BI[name] = _applyFunc("some"); } else { @@ -185,12 +191,13 @@ export const clamp = BI.clamp; // 数数 export function count(from, to, predicate) { - var t; + let t; if (predicate) { for (t = from; t < to; t++) { predicate(t); } } + return to - from; } @@ -201,45 +208,51 @@ export function inverse(from, to, predicate) { export function firstKey(obj) { let res = undefined; - any(obj, function (key, value) { + any(obj, (key, value) => { res = key; + return true; }); + return res; } export function lastKey(obj) { let res = undefined; - each(obj, function (key, value) { + each(obj, (key, value) => { res = key; + return true; }); + return res; } export function firstObject(obj) { let res = undefined; - any(obj, function (key, value) { + any(obj, (key, value) => { res = value; + return true; }); + return res; } export function lastObject(obj) { let res = undefined; - each(obj, function (key, value) { + each(obj, (key, value) => { res = value; + return true; }); + return res; } export function concat(obj1, obj2) { if (isKey(obj1)) { - return map([].slice.apply(arguments), function (idx, v) { - return v; - }).join(""); + return map([].slice.apply(arguments), (idx, v) => v).join(""); } if (isArray(obj1)) { return BI._.concat.apply([], arguments); @@ -254,6 +267,7 @@ export function backEach(obj, predicate, context) { for (let index = obj.length - 1; index >= 0; index--) { predicate(index, obj[index], obj); } + return false; } @@ -264,6 +278,7 @@ export function backAny(obj, predicate, context) { return true; } } + return false; } @@ -274,12 +289,14 @@ export function backEvery(obj, predicate, context) { return false; } } + return true; } export function backFindKey(obj, predicate, context) { predicate = iteratee(predicate, context); - let objKeys = keys(obj), key; + const objKeys = keys(obj); + let key; for (let i = objKeys.length - 1; i >= 0; i--) { key = objKeys[i]; if (predicate(obj[key], key, obj)) { @@ -311,7 +328,7 @@ export function remove(obj, target, context) { } } } else { - each(obj, function (i, v) { + each(obj, (i, v) => { if ((targetIsFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!targetIsFunction && contains(target, obj[i]))) { delete obj[i]; } @@ -321,7 +338,8 @@ export function remove(obj, target, context) { export function removeAt(obj, index) { index = isArray(index) ? index : [index]; - let objIsArray = isArray(obj), i; + const objIsArray = isArray(obj); + let i; for (i = 0; i < index.length; i++) { if (objIsArray) { obj[index[i]] = "$deleteIndex"; @@ -343,13 +361,15 @@ export function array2String(array) { } export function abc2Int(string) { - let idx = 0, start = "A", str = string.toUpperCase(); + let idx = 0; + const start = "A", str = string.toUpperCase(); for (let i = 0, len = str.length; i < len; ++i) { idx = str.charAt(i).charCodeAt(0) - start.charCodeAt(0) + 26 * idx + 1; if (idx > (2147483646 - str.charAt(i).charCodeAt(0) + start.charCodeAt(0)) / 26) { return 0; } } + return idx; } @@ -367,6 +387,7 @@ export function int2Abc(num) { str = DIGITS[t - 1] + str; idx = (idx - t) / 26; } + return str; } @@ -374,10 +395,10 @@ export function int2Abc(num) { BI._.each([ "first", "initial", "last", "rest", "compact", "flatten", "without", "union", "intersection", "difference", "zip", "unzip", "object", "indexOf", "lastIndexOf", "sortedIndex", "range", "take", "takeRight", "uniqBy" -], function (name) { +], name => { BI[name] = _apply(name); }); -BI._.each(["findIndex", "findLastIndex"], function (name) { +BI._.each(["findIndex", "findLastIndex"], name => { BI[name] = _applyFunc(name); }); export const first = BI.first; @@ -405,7 +426,7 @@ export const findLastIndex = BI.findLastIndex; // 构建一个长度为length的数组 export function makeArray(length, value) { - let res = []; + const res = []; for (let i = 0; i < length; i++) { if (isNull(value)) { res.push(i); @@ -413,11 +434,12 @@ export function makeArray(length, value) { res.push(deepClone(value)); } } + return res; } export function makeObject(array, value) { - let map = {}; + const map = {}; for (let i = 0; i < array.length; i++) { if (isNull(value)) { map[array[i]] = array[i]; @@ -427,11 +449,12 @@ export function makeObject(array, value) { map[array[i]] = deepClone(value); } } + return map; } export function makeArrayByArray(array, value) { - let res = []; + const res = []; if (!array) { return res; } @@ -442,11 +465,12 @@ export function makeArrayByArray(array, value) { res.push(deepClone(value)); } } + return res; } export function uniq(array, isSorted, iteratee, context) { - if (array == null) { + if (array === null) { return []; } if (!isBoolean(isSorted)) { @@ -455,7 +479,8 @@ export function uniq(array, isSorted, iteratee, context) { isSorted = false; } iteratee && (iteratee = traverse(iteratee, context)); - return uniq.call(BI._, array, isSorted, iteratee, context); + + return BI._uniq.call(BI._, array, isSorted, iteratee, context); } // 对象相关方法 @@ -464,7 +489,7 @@ BI._.each([ "defaults", "clone", "property", "propertyOf", "matcher", "isEqual", "isMatch", "isEmpty", "isElement", "isNumber", "isString", "isArray", "isObject", "isPlainObject", "isArguments", "isFunction", "isFinite", "isBoolean", "isDate", "isRegExp", "isError", "isNaN", "isUndefined", "zipObject", "cloneDeep" -], function (name) { +], name => { BI[name] = _apply(name); }); export const keys = BI.keys; @@ -502,7 +527,7 @@ export const isUndefined = BI.isUndefined; export const zipObject = BI.zipObject; export const cloneDeep = BI.cloneDeep; -BI._.each(["mapObject", "findKey", "pick", "omit", "tap"], function (name) { +BI._.each(["mapObject", "findKey", "pick", "omit", "tap"], name => { BI[name] = _applyFunc(name); }); export const mapObject = BI.mapObject; @@ -512,17 +537,18 @@ export const omit = BI.omit; export const tap = BI.tap; export function inherit(sp, overrides) { - let sb = function () { + function sb () { return sp.apply(this, arguments); - }; - let F = function () { - }, spp = sp.prototype; + } + function F () {} + const spp = sp.prototype; F.prototype = spp; sb.prototype = new F(); sb.superclass = spp; extend(sb.prototype, overrides, { - superclass: sp + superclass: sp, }); + return sb; } @@ -542,11 +568,11 @@ export function has(obj, keys) { if (keys.length === 0) { return false; } - return every(keys, function (i, key) { - return BI._.has(obj, key); - }); + + return every(keys, (i, key) => BI._.has(obj, key)); } - return BI._.has.apply(BI._, arguments); + + return BI._.has(...arguments); } export function freeze(value) { @@ -555,6 +581,7 @@ export function freeze(value) { if (Object.freeze && isObject(value)) { return Object.freeze(value); } + return value; } @@ -565,8 +592,9 @@ export function isKey(key) { // 忽略大小写的等于 export function isCapitalEqual(a, b) { - a = isNull(a) ? a : ("" + a).toLowerCase(); - b = isNull(b) ? b : ("" + b).toLowerCase(); + a = isNull(a) ? a : (`${a}`).toLowerCase(); + b = isNull(b) ? b : (`${b}`).toLowerCase(); + return isEqual(a, b); } @@ -603,7 +631,7 @@ export function isNotEmptyObject(obj) { } export function isWindow(obj) { - return obj != null && obj == obj.window; + return obj !== null && obj === obj.window; } export function isPromise(obj) { @@ -614,8 +642,8 @@ export const deepClone = BI._.cloneDeep; export const deepExtend = BI._.deepExtend; export function isDeepMatch(object, attrs) { - let attrsKeys = keys(attrs), length = attrsKeys.length; - if (object == null) { + const attrsKeys = keys(attrs), length = attrsKeys.length; + if (object === null) { return !length; } const obj = Object(object); @@ -625,11 +653,13 @@ export function isDeepMatch(object, attrs) { return false; } } + return true; } export function contains(obj, target, fromIndex) { if (!BI._.isArrayLike(obj)) obj = values(obj); + return indexOf(obj, target, typeof fromIndex === "number" && fromIndex) >= 0; } @@ -637,6 +667,7 @@ export function deepContains(obj, copy) { if (isObject(copy)) { return any(obj, (i, v) => isEqual(v, copy)); } + return contains(obj, copy); } @@ -646,6 +677,7 @@ export function deepIndexOf(obj, target) { return i; } } + return -1; } @@ -667,35 +699,39 @@ export function deepRemove(obj, target) { } }); } + return done; } export function deepWithout(obj, target) { if (isArray(obj)) { - let result = []; + const result = []; for (let i = 0; i < obj.length; i++) { if (!isEqual(target, obj[i])) { result.push(obj[i]); } } + return result; } - let result = {}; + const result = {}; each(obj, (i, v) => { if (!isEqual(target, obj[i])) { result[i] = v; } }); + return result; } export function deepUnique(array) { - let result = []; + const result = []; each(array, (i, item) => { if (!deepContains(result, item)) { result.push(item); } }); + return result; } @@ -703,9 +739,9 @@ export function deepUnique(array) { export function deepDiff(object, other) { object || (object = {}); other || (other = {}); - let result = []; - let used = []; - for (let b in object) { + const result = []; + const used = []; + for (const b in object) { if (has(object, b)) { if (!isEqual(object[b], other[b])) { result.push(b); @@ -713,19 +749,18 @@ export function deepDiff(object, other) { used.push(b); } } - for (let b in other) { + for (const b in other) { if (has(other, b) && !contains(used, b)) { result.push(b); } } + return result; } // 通用方法 -BI._.each(["uniqueId", "result", "chain", "iteratee", "unescape", "before", "after", "chunk"], function (name) { - BI[name] = function () { - return BI._[name].apply(BI._, arguments); - }; +BI._.each(["uniqueId", "result", "chain", "iteratee", "unescape", "before", "after", "chunk"], name => { + BI[name] = (...args) => BI._[name](...args); }); export const uniqueId = BI.uniqueId; export const result = BI.result; @@ -737,10 +772,8 @@ export const after = BI.after; export const chunk = BI.chunk; // 事件相关方法 -BI._.each(["bind", "once", "partial", "debounce", "throttle", "delay", "defer", "wrap"], function (name) { - BI[name] = function () { - return BI._[name].apply(BI._, arguments); - }; +BI._.each(["bind", "once", "partial", "debounce", "throttle", "delay", "defer", "wrap"], name => { + BI[name] = (...args) => BI._[name](...args); }); export const bind = BI.bind; export const once = BI.once; @@ -752,13 +785,13 @@ export const defer = BI.defer; export const wrap = BI.wrap; export const nextTick = (function () { - let callbacks = []; + const callbacks = []; let pending = false; let timerFunc = void 0; function nextTickHandler() { pending = false; - let copies = callbacks.slice(0); + const copies = callbacks.slice(0); callbacks.length = 0; for (let i = 0; i < copies.length; i++) { copies[i](); @@ -766,16 +799,16 @@ export const nextTick = (function () { } if (typeof Promise !== "undefined") { - let p = Promise.resolve(); + const p = Promise.resolve(); timerFunc = function timerFunc() { p.then(nextTickHandler); }; } else if (typeof MutationObserver !== "undefined") { let counter = 1; - let observer = new MutationObserver(nextTickHandler); - let textNode = document.createTextNode(String(counter)); + const observer = new MutationObserver(nextTickHandler); + const textNode = document.createTextNode(String(counter)); observer.observe(textNode, { - characterData: true + characterData: true, }); timerFunc = function timerFunc() { counter = (counter + 1) % 2; @@ -794,16 +827,16 @@ export const nextTick = (function () { return function queueNextTick(cb) { let _resolve = void 0; - let args = [].slice.call(arguments, 1); - callbacks.push(function () { + const args = [].slice.call(arguments, 1); + callbacks.push(() => { if (cb) { try { - cb.apply(null, args); + cb(...args); } catch (e) { console.error(e); } } else if (_resolve) { - _resolve.apply(null, args); + _resolve(...args); } }); if (!pending) { @@ -811,16 +844,16 @@ export const nextTick = (function () { timerFunc(); } // $flow-disable-line - if (!cb && typeof Promise !== 'undefined') { - return new Promise(function (resolve, reject) { + if (!cb && typeof Promise !== "undefined") { + return new Promise(((resolve, reject) => { _resolve = resolve; - }); + })); } }; -})(); +}()); // 数字相关方法 -BI._.each(["random"], function (name) { +BI._.each(["random"], name => { BI[name] = _apply(name); }); export const random = BI.random; @@ -833,13 +866,13 @@ export function parseInt(number) { try { return _global.parseInt(number, radix); } catch (e) { - throw new Error(number + "parse int error"); - return NaN; + throw new Error(`${number}parse int error`); } } export function parseSafeInt(value) { - let MAX_SAFE_INTEGER = 9007199254740991; + const MAX_SAFE_INTEGER = 9007199254740991; + return value ? clamp(parseInt(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) : (value === 0 ? value : 0); @@ -849,8 +882,7 @@ export function parseFloat(number) { try { return _global.parseFloat(number); } catch (e) { - throw new Error(number + "parse float error"); - return NaN; + throw new Error(`${number}parse float error`); } } @@ -863,11 +895,11 @@ export function isPositiveInteger(number) { } export function isNegativeInteger(number) { - return /^\-[1-9][0-9]*$/.test(number); + return /^-[1-9][0-9]*$/.test(number); } export function isInteger(number) { - return /^\-?\d+$/.test(number); + return /^-?\d+$/.test(number); } export function isNumeric(number) { @@ -882,6 +914,7 @@ export function isOdd(number) { if (!isInteger(number)) { return false; } + return (number & 1) === 1; } @@ -889,6 +922,7 @@ export function isEven(number) { if (!isInteger(number)) { return false; } + return (number & 1) === 0; } @@ -901,24 +935,26 @@ export function sum(array, iteratee, context) { sum += Number(item); } }); + return sum; } export function average(array, iteratee, context) { const sumResult = sum(array, iteratee, context); + return sumResult / array.length; } -export function trim() { - return BI._.trim.apply(BI._, arguments); +export function trim(...args) { + return BI._.trim(...args); } export function toUpperCase(string) { - return (string + "").toLocaleUpperCase(); + return (`${string}`).toLocaleUpperCase(); } export function toLowerCase(string) { - return (string + "").toLocaleLowerCase(); + return (`${string}`).toLocaleLowerCase(); } export function isEndWithBlank(string) { @@ -926,12 +962,13 @@ export function isEndWithBlank(string) { } export function isLiteral(exp) { - return /^\s?(true|false|-?[\d\.]+|'[^']*'|"[^"]*")\s?$/.test(exp); + return /^\s?(true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/.test(exp); } export function stripQuotes(str) { const a = str.charCodeAt(0); const b = str.charCodeAt(str.length - 1); + return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str; @@ -964,9 +1001,9 @@ export function isEmptyString(str) { */ export function encrypt(type, text, key) { switch (type) { - case BI.CRYPT_TYPE.AES: - default: - return BI.aesEncrypt(text, key); + case BI.CRYPT_TYPE.AES: + default: + return BI.aesEncrypt(text, key); } } @@ -979,9 +1016,9 @@ export function encrypt(type, text, key) { */ export function decrypt(type, text, key) { switch (type) { - case BI.CRYPT_TYPE.AES: - default: - return BI.aesDecrypt(text, key); + case BI.CRYPT_TYPE.AES: + default: + return BI.aesDecrypt(text, key); } } @@ -1015,6 +1052,7 @@ export function leftPad(val, size, ch) { while (result.length < size) { result = ch + result; } + return result.toString(); } @@ -1030,7 +1068,8 @@ export function leftPad(val, size, ch) { * @return {String} 做了替换后的字符串 */ export function format(format) { - var args = Array.prototype.slice.call(arguments, 1); + const args = Array.prototype.slice.call(arguments, 1); + return format.replace(/\{(\d+)\}/g, (m, i) => args[i]); } @@ -1065,25 +1104,26 @@ export function checkDateVoid(YY, MM, DD, minDate, maxDate) { } else if (YY > maxDate[0]) { back = ["y", 1]; } else if (YY >= minDate[0] && YY <= maxDate[0]) { - if (YY == minDate[0]) { + if (YY === minDate[0]) { if (MM < minDate[1]) { back = ["m"]; - } else if (MM == minDate[1]) { + } else if (MM === minDate[1]) { if (DD < minDate[2]) { back = ["d"]; } } } - if (YY == maxDate[0]) { + if (YY === maxDate[0]) { if (MM > maxDate[1]) { back = ["m", 1]; - } else if (MM == maxDate[1]) { + } else if (MM === maxDate[1]) { if (DD > maxDate[2]) { back = ["d", 1]; } } } } + return back; } @@ -1096,8 +1136,9 @@ export function checkDateLegal(str) { if (ar.length <= 2) { return MM >= 1 && MM <= 12; } - let MD = BI.Date._MD.slice(0); + const MD = BI.Date._MD.slice(0); MD[1] = isLeapYear(YY) ? 29 : 28; + return MM >= 1 && MM <= 12 && DD <= MD[MM - 1]; } @@ -1114,74 +1155,75 @@ export function parseDateTime(str, fmt) { let m; let d; // wei : 对于fmt为‘YYYYMM’或者‘YYYYMMdd’的格式,str的值为类似'201111'的形式,因为年月之间没有分隔符,所以正则表达式分割无效,导致bug7376。 - let a = str.split(/\W+/); - if (fmt.toLowerCase() == "%y%x" || fmt.toLowerCase() == "%y%x%d") { - let yearlength = 4; - let otherlength = 2; + const a = str.split(/\W+/); + if (fmt.toLowerCase() === "%y%x" || fmt.toLowerCase() === "%y%x%d") { + const yearlength = 4; + const otherlength = 2; a[0] = str.substring(0, yearlength); a[1] = str.substring(yearlength, yearlength + otherlength); a[2] = str.substring(yearlength + otherlength, yearlength + otherlength * 2); } - let b = fmt.match(/%./g); + const b = fmt.match(/%./g); let i = 0, j = 0; let hr = 0; let min = 0; let sec = 0; for (i = 0; i < a.length; ++i) { switch (b[i]) { - case "%d": - case "%e": - d = _global.parseInt(a[i], 10); - break; - - case "%X": - m = _global.parseInt(a[i], 10) - 1; - break; - case "%x": - m = _global.parseInt(a[i], 10) - 1; - break; - - case "%Y": - case "%y": - y = _global.parseInt(a[i], 10); - (y < 100) && (y += (y > 29) ? 1900 : 2000); - break; - - case "%b": - case "%B": - for (j = 0; j < 12; ++j) { - if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { - m = j; - break; - } - } - break; - - case "%H": - case "%I": - case "%k": - case "%l": - hr = _global.parseInt(a[i], 10); - break; - - case "%P": - case "%p": - if (/pm/i.test(a[i]) && hr < 12) { - hr += 12; - } else if (/am/i.test(a[i]) && hr >= 12) { - hr -= 12; + case "%d": + case "%e": + d = _global.parseInt(a[i], 10); + break; + + case "%X": + m = _global.parseInt(a[i], 10) - 1; + break; + case "%x": + m = _global.parseInt(a[i], 10) - 1; + break; + + case "%Y": + case "%y": + y = _global.parseInt(a[i], 10); + (y < 100) && (y += (y > 29) ? 1900 : 2000); + break; + + case "%b": + case "%B": + for (j = 0; j < 12; ++j) { + if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() === a[i].toLowerCase()) { + m = j; + break; } - break; - case "%Q": - case "%q": - m = (_global.parseInt(a[i], 10) - 1) * 3; - break; - case "%M": - min = _global.parseInt(a[i], 10); - break; - case "%S": - sec = _global.parseInt(a[i], 10); - break; + } + break; + + case "%H": + case "%I": + case "%k": + case "%l": + hr = _global.parseInt(a[i], 10); + break; + + case "%P": + case "%p": + if (/pm/i.test(a[i]) && hr < 12) { + hr += 12; + } else if (/am/i.test(a[i]) && hr >= 12) { + hr -= 12; + } + break; + case "%Q": + case "%q": + m = (_global.parseInt(a[i], 10) - 1) * 3; + break; + case "%M": + min = _global.parseInt(a[i], 10); + break; + case "%S": + sec = _global.parseInt(a[i], 10); + break; + default: } } // if (!a[i]) { @@ -1205,45 +1247,46 @@ export function parseDateTime(str, fmt) { if (isNaN(sec)) { sec = today.getSeconds(); } - if (y != 0) { + if (y !== 0) { return BI.getDate(y, m, d, hr, min, sec); } y = 0; m = -1; d = 0; for (i = 0; i < a.length; ++i) { - if (a[i].search(/[a-zA-Z]+/) != -1) { + if (a[i].search(/[a-zA-Z]+/) !== -1) { let t = -1; for (j = 0; j < 12; ++j) { - if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { + if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() === a[i].toLowerCase()) { t = j; break; } } - if (t != -1) { - if (m != -1) { + if (t !== -1) { + if (m !== -1) { d = m + 1; } m = t; } - } else if (_global.parseInt(a[i], 10) <= 12 && m == -1) { + } else if (_global.parseInt(a[i], 10) <= 12 && m === -1) { m = a[i] - 1; - } else if (_global.parseInt(a[i], 10) > 31 && y == 0) { + } else if (_global.parseInt(a[i], 10) > 31 && y === 0) { y = _global.parseInt(a[i], 10); (y < 100) && (y += (y > 29) ? 1900 : 2000); - } else if (d == 0) { + } else if (d === 0) { d = a[i]; } } - if (y == 0) { + if (y === 0) { y = today.getFullYear(); } if (m === -1) { m = today.getMonth(); } - if (m != -1 && d != 0) { + if (m !== -1 && d !== 0) { return BI.getDate(y, m, d, hr, min, sec); } + return today; } @@ -1251,49 +1294,51 @@ export function getDate(...args) { const length = args.length; let dt; switch (length) { - // new Date() - case 0: - dt = new Date(); - break; + // new Date() + case 0: + dt = new Date(); + break; // new Date(long) - case 1: - dt = new Date(args[0]); - break; + case 1: + dt = new Date(args[0]); + break; // new Date(year, month) - case 2: - dt = new Date(args[0], args[1]); - break; + case 2: + dt = new Date(args[0], args[1]); + break; // new Date(year, month, day) - case 3: - dt = new Date(args[0], args[1], args[2]); - break; + case 3: + dt = new Date(args[0], args[1], args[2]); + break; // new Date(year, month, day, hour) - case 4: - dt = new Date(args[0], args[1], args[2], args[3]); - break; + case 4: + dt = new Date(args[0], args[1], args[2], args[3]); + break; // new Date(year, month, day, hour, minute) - case 5: - dt = new Date(args[0], args[1], args[2], args[3], args[4]); - break; + case 5: + dt = new Date(args[0], args[1], args[2], args[3], args[4]); + break; // new Date(year, month, day, hour, minute, second) - case 6: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); - break; + case 6: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); + break; // new Date(year, month, day, hour, minute, second, millisecond) - case 7: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - break; - default: - dt = new Date(); - break; + case 7: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + break; + default: + dt = new Date(); + break; } if (isNotNull(BI.timeZone) && (arguments.length === 0 || (arguments.length === 1 && isNumber(arguments[0])))) { const localTime = dt.getTime(); // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 const localOffset = dt.getTimezoneOffset() * 60000; // 获得当地时间偏移的毫秒数 const utc = localTime + localOffset; // utc即GMT时间标准时区 + return new Date(utc + BI.timeZone);// + Pool.timeZone.offset); } + return dt; } @@ -1302,46 +1347,47 @@ export function getTime() { const args = arguments; let dt; switch (length) { - // new Date() - case 0: - dt = new Date(); - break; + // new Date() + case 0: + dt = new Date(); + break; // new Date(long) - case 1: - dt = new Date(args[0]); - break; + case 1: + dt = new Date(args[0]); + break; // new Date(year, month) - case 2: - dt = new Date(args[0], args[1]); - break; + case 2: + dt = new Date(args[0], args[1]); + break; // new Date(year, month, day) - case 3: - dt = new Date(args[0], args[1], args[2]); - break; + case 3: + dt = new Date(args[0], args[1], args[2]); + break; // new Date(year, month, day, hour) - case 4: - dt = new Date(args[0], args[1], args[2], args[3]); - break; + case 4: + dt = new Date(args[0], args[1], args[2], args[3]); + break; // new Date(year, month, day, hour, minute) - case 5: - dt = new Date(args[0], args[1], args[2], args[3], args[4]); - break; + case 5: + dt = new Date(args[0], args[1], args[2], args[3], args[4]); + break; // new Date(year, month, day, hour, minute, second) - case 6: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); - break; + case 6: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); + break; // new Date(year, month, day, hour, minute, second, millisecond) - case 7: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - break; - default: - dt = new Date(); - break; + case 7: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + break; + default: + dt = new Date(); + break; } if (isNotNull(BI.timeZone)) { // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 return dt.getTime() - BI.timeZone - new Date().getTimezoneOffset() * 60000; } + return dt.getTime(); } diff --git a/src/core/3.ob.js b/src/core/3.ob.js index fcd9db92a..8357389fd 100644 --- a/src/core/3.ob.js +++ b/src/core/3.ob.js @@ -1,7 +1,8 @@ import { isFunction, isArray, isObject, isArguments, reduce, bind } from "./2.base"; function obExtend() { - let target = arguments[0] || {}, length = arguments.length, i = 1, name, copy; + const target = arguments[0] || {}, length = arguments.length; + let i = 1, name, copy; for (; i < length; i++) { // Only deal with non-null/undefined values const options = arguments[i]; @@ -53,9 +54,7 @@ export class OB { props = this.props(config); } const defaultProps = obExtend(this._defaultConfig(config), props); - const modifiedDefaultProps = (config && config.type && OB.configFunctions[config.type + ".props"]) ? reduce(OB.configFunctions[config.type + ".props"], function (value, conf, index) { - return obExtend(conf, value.fn(defaultProps, config, value.opt)); - }, {}) : null; + const modifiedDefaultProps = (config && config.type && OB.configFunctions[`${config.type}.props`]) ? reduce(OB.configFunctions[`${config.type}.props`], (value, conf, index) => obExtend(conf, value.fn(defaultProps, config, value.opt)), {}) : null; this.options = obExtend(defaultProps, modifiedDefaultProps, config); } @@ -73,7 +72,7 @@ export class OB { return; } if (isArray(lis)) { - BI._.each(lis, (l) => { + BI._.each(lis, l => { this.on(eventName, l); }); @@ -162,7 +161,7 @@ export class OB { const fns = this._getEvents()[eventName]; if (isArray(fns)) { const newFns = []; - BI._.each(fns, function (ifn) { + BI._.each(fns, ifn => { if (ifn !== fn) { newFns.push(ifn); } diff --git a/src/core/4.widget.js b/src/core/4.widget.js index e67bdb4dc..11faacc6e 100644 --- a/src/core/4.widget.js +++ b/src/core/4.widget.js @@ -30,7 +30,7 @@ function callLifeHook(self, life) { if (hook) { hooks = hooks.concat(isArray(hook) ? hook : [hook]); } - each(hooks, function (i, hook) { + each(hooks, (i, hook) => { hook.call(self); }); } @@ -53,7 +53,7 @@ export class Widget extends OB { baseCls: "", extraCls: "", cls: "", - css: null + css: null, // vdom: false }); @@ -132,6 +132,7 @@ export class Widget extends OB { // 加个保险 if (initCallbackCalled === true) { _global.console && console.error("组件: 请检查beforeInit内部的写法,callback只能执行一次"); + return; } initCallbackCalled = true; @@ -140,18 +141,19 @@ export class Widget extends OB { // 加个保险 if (renderCallbackCalled === true) { _global.console && console.error("组件: 请检查beforeRender内部的写法,callback只能执行一次"); + return; } renderCallbackCalled = true; this._render(); this.__afterRender(); - } + }; if (this.options.beforeRender || this.beforeRender) { this.__async = true; const beforeRenderResult = (this.options.beforeRender || this.beforeRender).call(this, render); if (beforeRenderResult instanceof Promise) { - beforeRenderResult.then(render).catch(function (e) { + beforeRenderResult.then(render).catch(e => { _global.console && console.error(e); render(); }); @@ -160,13 +162,13 @@ export class Widget extends OB { this._render(); this.__afterRender(); } - } + }; if (this.options.beforeInit || this.beforeInit) { this.__asking = true; const beforeInitResult = (this.options.beforeInit || this.beforeInit).call(this, init); if (beforeInitResult instanceof Promise) { - beforeInitResult.then(init).catch(function (e) { + beforeInitResult.then(init).catch(e => { _global.console && console.error(e); init(); }); @@ -206,11 +208,11 @@ export class Widget extends OB { this._initElementWidth(); this._initElementHeight(); if (o._baseCls || o.baseCls || o.extraCls) { - this.element.addClass((o._baseCls || "") + " " + (o.baseCls || "") + " " + (o.extraCls || "")); + this.element.addClass(`${o._baseCls || ""} ${o.baseCls || ""} ${o.extraCls || ""}`); } if (o.cls) { if (isFunction(o.cls)) { - const cls = this.__watch(o.cls, (context, newValue) => { + let cls = this.__watch(o.cls, (context, newValue) => { this.element.removeClass(cls).addClass(cls = newValue); }); this.element.addClass(cls); @@ -229,7 +231,7 @@ export class Widget extends OB { } if (o.css) { if (isFunction(o.css)) { - const css = this.__watch(o.css, (context, newValue) => { + let css = this.__watch(o.css, (context, newValue) => { for (const k in css) { if (isNull(newValue[k])) { newValue[k] = ""; @@ -247,14 +249,13 @@ export class Widget extends OB { __watch(getter, handler, options) { if (_global.Fix) { this._watchers = this._watchers || []; - const watcher = new Fix.Watcher(null, () => { - return getter.call(this, this); - }, (handler && ((v) => { + const watcher = new Fix.Watcher(null, () => getter.call(this, this), (handler && (v => { handler.call(this, this, v); })) || BI.emptyFn, extend({ deep: true }, options)); this._watchers.push(() => { watcher.teardown(); }); + return watcher.value; } else { return getter(); @@ -374,7 +375,7 @@ export class Widget extends OB { each(els, (i, el) => { if (el) { _lazyCreateWidget(el, { - element: this + element: this, }); } }); @@ -422,6 +423,7 @@ export class Widget extends OB { this.__afterMount(lifeHook, predicate); // }, 0); } + return true; } @@ -444,10 +446,12 @@ export class Widget extends OB { _update(nextProps, shouldUpdate) { callLifeHook(this, "beforeUpdate"); + let res; if (shouldUpdate) { - const res = this.update && this.update(nextProps, shouldUpdate); + res = this.update && this.update(nextProps, shouldUpdate); } callLifeHook(this, "updated"); + return res; } @@ -476,7 +480,7 @@ export class Widget extends OB { this.options._disabled = true; } // 递归将所有子组件使能 - each(this._children, function (i, child) { + each(this._children, (i, child) => { !child._manualSetEnable && child._setEnable && child._setEnable(enable); }); } @@ -488,7 +492,7 @@ export class Widget extends OB { this.options._invalid = true; } // 递归将所有子组件使有效 - each(this._children, function (i, child) { + each(this._children, (i, child) => { !child._manualSetValid && child._setValid && child._setValid(valid); }); } @@ -525,36 +529,36 @@ export class Widget extends OB { this.__setElementVisible(true); this._mount(); if (o.animation && !lastVisible) { - this.element.removeClass(o.animation + "-leave").removeClass(o.animation + "-leave-active").addClass(o.animation + "-enter"); + this.element.removeClass(`${o.animation}-leave`).removeClass(`${o.animation}-leave-active`).addClass(`${o.animation}-enter`); if (this._requestAnimationFrame) { cancelAnimationFrame(this._requestAnimationFrame); } this._requestAnimationFrame = () => { - this.element.addClass(o.animation + "-enter-active"); + this.element.addClass(`${o.animation}-enter-active`); }; requestAnimationFrame(this._requestAnimationFrame); if (this._animationDuring) { clearTimeout(this._animationDuring); } this._animationDuring = setTimeout(() => { - this.element.removeClass(o.animation + "-enter").removeClass(o.animation + "-enter-active"); + this.element.removeClass(`${o.animation}-enter`).removeClass(`${o.animation}-enter-active`); }, o.animationDuring); } } else if (visible === false) { if (o.animation && lastVisible) { - this.element.removeClass(o.animation + "-enter").removeClass(o.animation + "-enter-active").addClass(o.animation + "-leave"); + this.element.removeClass(`${o.animation}-enter`).removeClass(`${o.animation}-enter-active`).addClass(`${o.animation}-leave`); if (this._requestAnimationFrame) { cancelAnimationFrame(this._requestAnimationFrame); } this._requestAnimationFrame = () => { - this.element.addClass(o.animation + "-leave-active"); + this.element.addClass(`${o.animation}-leave-active`); }; requestAnimationFrame(this._requestAnimationFrame); if (this._animationDuring) { clearTimeout(this._animationDuring); } this._animationDuring = setTimeout(() => { - this.element.removeClass(o.animation + "-leave").removeClass(o.animation + "-leave-active"); + this.element.removeClass(`${o.animation}-leave`).removeClass(`${o.animation}-leave-active`); this.__setElementVisible(false); }, o.animationDuring); } else { @@ -582,8 +586,8 @@ export class Widget extends OB { doBehavior() { const args = arguments; // 递归将所有子组件使有效 - each(this._children, function (i, child) { - child.doBehavior && child.doBehavior.apply(child, args); + each(this._children, (i, child) => { + child.doBehavior && child.doBehavior(...args); }); } @@ -602,7 +606,7 @@ export class Widget extends OB { name = widget.getName(); } if (isKey(name)) { - name = name + ""; + name = `${name}`; } name = name || widget.getName() || uniqueId("widget"); if (this._children[name]) { @@ -613,6 +617,7 @@ export class Widget extends OB { // TODO: self待删 remove(self._children, this); }); + return (this._children[name] = widget); } @@ -620,20 +625,21 @@ export class Widget extends OB { if (!isKey(name) || name === this.getName()) { return this; } - name = name + ""; - let widget = void 0, other = {}; - any(this._children, function (i, wi) { + name = `${name}`; + let widget = void 0; + const other = {}; + any(this._children, (i, wi) => { if (i === name) { widget = wi; + return true; } other[i] = wi; }); if (!widget) { - any(other, function (i, wi) { - return (widget = wi.getWidgetByName(i)); - }); + any(other, (i, wi) => (widget = wi.getWidgetByName(i))); } + return widget; } @@ -646,7 +652,7 @@ export class Widget extends OB { } hasWidget(name) { - return this._children[name] != null; + return isNotNull(this._children[name]); } getName() { @@ -664,11 +670,13 @@ export class Widget extends OB { attr(key, value) { if (isPlainObject(key)) { each(key, (k, v) => this.attr(k, v)); + return; } if (isNotNull(value)) { - return this.options[key] = value; + this.options[key] = value; } + return this.options[key]; } @@ -729,7 +737,7 @@ export class Widget extends OB { } __d() { - each(this._children, function (i, widget) { + each(this._children, (i, widget) => { widget && widget._unMount && widget._unMount(); }); this._children = {}; @@ -747,7 +755,6 @@ export class Widget extends OB { this.destroyed = null; this._isDestroyed = true; // this._purgeRef(); // 清除ref的时机还是要仔细考虑一下 - } _unMount() { @@ -767,7 +774,7 @@ export class Widget extends OB { _empty () { this._assetMounted(); - each(this._children, function (i, widget) { + each(this._children, (i, widget) => { widget && widget._unMount && widget._unMount(); }); this._children = {}; @@ -801,9 +808,9 @@ export class Widget extends OB { // this.purgeListeners(); // 去掉组件绑定的watcher - each(this._watchers, function (i, unwatches) { + each(this._watchers, (i, unwatches) => { unwatches = isArray(unwatches) ? unwatches : [unwatches]; - each(unwatches, function (j, unwatch) { + each(unwatches, (j, unwatch) => { unwatch(); }); }); @@ -839,7 +846,7 @@ export class Widget extends OB { this._purgeRef(); this.purgeListeners(); } -}; +} let context = null, current = null; const contextStack = [], currentStack = []; @@ -882,35 +889,42 @@ export function useStore(_store) { } if (current) { const currentStore = current._store; - let delegate = {}, origin; + const delegate = {}; + let origin; if (_global.Proxy) { const proxy = new Proxy(delegate, { - get: function (target, key) { + get (target, key) { return Reflect.get(origin, key); }, - set: function (target, key, value) { + set (target, key, value) { return Reflect.set(origin, key, value); - } + }, }); current._store = function () { origin = (_store || currentStore).apply(this, arguments); delegate.$delegate = origin; + return origin; }; - return current.$storeDelegate = proxy; + current.$storeDelegate = proxy; + + return current.$storeDelegate; } current._store = function () { const st = (_store || currentStore).apply(this, arguments); extend(delegate, st); + return st; }; - return current.$storeDelegate = delegate; + current.$storeDelegate = delegate; + + return current.$storeDelegate; } } export function useContext(inject) { // 通过组件找最近的store - const vm = Widget.findStore(Widget.current || Widget.context); + let vm = Widget.findStore(Widget.current || Widget.context); if (vm) { if (inject) { if (vm.$$computed && inject in vm.$$computed) { @@ -928,9 +942,11 @@ export function useContext(inject) { } vm = vm._parent; } + return null; } } + return vm; } @@ -949,18 +965,19 @@ export function watch(vm, watch, handler) { if (isArray(handler)) { for (let i = 0; i < handler.length; i++) { watchers.push(Fix.watch(vm.model, key, innerHandler, { - store: vm + store: vm, })); } } else { watchers.push(Fix.watch(vm.model, key, innerHandler, { - store: vm + store: vm, })); } } // vm中一定有_widget Widget.current._watchers || (Widget.current._watchers = []); Widget.current._watchers = Widget.current._watchers.concat(watchers); + return; } handler = watch; @@ -974,6 +991,7 @@ export function onBeforeMount(beforeMount) { if (current) { if (current.__isMounting) { beforeMount(); + return; } if (!current.beforeMount) { @@ -989,6 +1007,7 @@ export function onMounted(mounted) { if (current) { if (current._isMounted && !this.__async) { mounted(); + return; } if (!current.mounted) { @@ -998,7 +1017,7 @@ export function onMounted(mounted) { } current.mounted.push(mounted); } -}; +} export function onBeforeUnmount(beforeDestroy) { if (current) { @@ -1026,7 +1045,7 @@ Widget.registerRenderEngine = function (engine) { Widget._renderEngine = engine; }; Widget.registerRenderEngine({ - createElement: function (widget) { + createElement (widget) { if (isWidget(widget)) { const o = widget.options; if (o.element) { @@ -1035,13 +1054,15 @@ Widget.registerRenderEngine({ if (o.tagName) { return BI.$(document.createElement(o.tagName)); } + return BI.$(document.createDocumentFragment()); } + return BI.$(widget); }, - createFragment: function () { + createFragment () { return document.createDocumentFragment(); - } + }, }); export function mount(widget, container, predicate, hydrate) { @@ -1049,8 +1070,8 @@ export function mount(widget, container, predicate, hydrate) { // 将widget的element元素都挂载好,并建立相互关系 widget.element.data("__widgets", [widget]); const res = widget._mount(true, false, false, function (w) { - each(w._children, function (i, child) { - const ws = child.element.data("__widgets"); + each(w._children, (i, child) => { + let ws = child.element.data("__widgets"); if (!ws) { ws = []; } @@ -1063,19 +1084,21 @@ export function mount(widget, container, predicate, hydrate) { const c = Widget._renderEngine.createElement; BI.DOM.patchProps(widget.element, c(c(container).children()[0])); - const triggerLifeHook = function (w) { + const triggerLifeHook = w => { w.beforeMount && w.beforeMount(); w.mounted && w.mounted(); - each(w._children, function (i, child) { + each(w._children, (i, child) => { triggerLifeHook(child); }); }; // 最后触发组件树生命周期函数 triggerLifeHook(widget); + return res; } if (container) { Widget._renderEngine.createElement(container).append(widget.element); } + return widget._mount(true, false, false, predicate); } diff --git a/src/core/5.inject.js b/src/core/5.inject.js index 77faa02f3..8a54bbeb7 100644 --- a/src/core/5.inject.js +++ b/src/core/5.inject.js @@ -1,19 +1,19 @@ import { isFunction, isNull, isNotNull, isArray, each, isWidget, extend, init, isEmpty, remove } from "./2.base"; import { OB } from "./3.ob"; -import { Widget } from "./4.widget" +import { Widget } from "./4.widget"; -let moduleInjection = {}, moduleInjectionMap = { +const moduleInjection = {}, moduleInjectionMap = { components: {}, constants: {}, stores: {}, services: {}, models: {}, - providers: {} + providers: {}, }; export function module(xtype, cls) { - if (moduleInjection[xtype] != null) { - _global.console && console.error("module: [" + xtype + "] 已经注册过了"); + if (isNotNull(moduleInjection[xtype])) { + _global.console && console.error(`module: [${xtype}] 已经注册过了`); } else { if (isFunction(cls)) { cls = cls(); @@ -29,7 +29,7 @@ export function module(xtype, cls) { } moduleInjectionMap[k][key].push({ version: cls[k][key], - moduleId: xtype + moduleId: xtype, }); } } @@ -40,10 +40,10 @@ export function module(xtype, cls) { return () => Modules.getModule(xtype); } -let constantInjection = {}; +const constantInjection = {}; export function constant(xtype, cls) { - if (constantInjection[xtype] != null) { - _global.console && console.error("constant: [" + xtype + "]已经注册过了"); + if (isNotNull(constantInjection[xtype])) { + _global.console && console.error(`constant: [${xtype}]已经注册过了`); } else { constantInjection[xtype] = cls; } @@ -51,60 +51,60 @@ export function constant(xtype, cls) { return () => Constants.getConstant(xtype); } -let modelInjection = {}; +const modelInjection = {}; export function model(xtype, cls) { - if (modelInjection[xtype] != null) { - _global.console && console.error("model: [" + xtype + "] 已经注册过了"); + if (isNotNull(modelInjection[xtype])) { + _global.console && console.error(`model: [${xtype}] 已经注册过了`); } else { modelInjection[xtype] = cls; } - return (config) => Models.getModel(xtype, config); + return config => Models.getModel(xtype, config); } -let storeInjection = {}; +const storeInjection = {}; export function store(xtype, cls) { - if (storeInjection[xtype] != null) { - _global.console && console.error("store: [" + xtype + "] 已经注册过了"); + if (isNotNull(storeInjection[xtype])) { + _global.console && console.error(`store: [${xtype}] 已经注册过了`); } else { storeInjection[xtype] = cls; } - return (config) => Stores.getStore(xtype, config); + return config => Stores.getStore(xtype, config); } -let serviceInjection = {}; +const serviceInjection = {}; export function service(xtype, cls) { - if (serviceInjection[xtype] != null) { - _global.console && console.error("service: [" + xtype + "] 已经注册过了"); + if ((serviceInjection[xtype])) { + _global.console && console.error(`service: [${xtype}] 已经注册过了`); } serviceInjection[xtype] = cls; - return (config) => Services.getService(xtype, config); + return config => Services.getService(xtype, config); } -let providerInjection = {}; +const providerInjection = {}; export function provider(xtype, cls) { - if (providerInjection[xtype] != null) { - _global.console && console.error("provider: [" + xtype + "] 已经注册过了"); + if ((providerInjection[xtype])) { + _global.console && console.error(`provider: [${xtype}] 已经注册过了`); } else { providerInjection[xtype] = cls; } - return (config) => Providers.getProvider(xtype, config); + return config => Providers.getProvider(xtype, config); } -let configFunctions = OB.configFunctions = {}; -const runConfigFunction = function (type, configFn) { +const configFunctions = OB.configFunctions = {}; +const runConfigFunction = (type, configFn) => { if (!type || !configFunctions[type]) { return false; } let queue = []; if (configFn) { - queue = configFunctions[type].filter((conf) => conf.fn === configFn); - configFunctions[type] = configFunctions[type].filter((conf) => conf.fn !== configFn); + queue = configFunctions[type].filter(conf => conf.fn === configFn); + configFunctions[type] = configFunctions[type].filter(conf => conf.fn !== configFn); } else { queue = configFunctions[type]; delete configFunctions[type]; @@ -140,7 +140,7 @@ const runConfigFunction = function (type, configFn) { } } if (findVersion === true) { - _global.console && console.error("moduleId: [" + module.moduleId + "] 接口: [" + type + "] 接口版本: [" + version + "] 已过期,版本要求为:", dependencies[module.moduleId], "=>", moduleInjection[module.moduleId]); + _global.console && console.error(`moduleId: [${module.moduleId}] 接口: [${type}] 接口版本: [${version}] 已过期,版本要求为:`, dependencies[module.moduleId], "=>", moduleInjection[module.moduleId]); continue; } } @@ -179,6 +179,7 @@ export function config(type, configFn, opt) { if (providerInstance[type]) { delete providerInstance[type]; } + return configFn(providers[type]); } @@ -187,7 +188,7 @@ export function config(type, configFn, opt) { } configFunctions[type].push({ fn: configFn, - opt: opt + opt, }); if (opt.immediately) { @@ -199,28 +200,30 @@ export function getReference(type, fn) { return BI.Plugin.registerObject(type, fn); } -let actions = {}; -let globalAction = []; +const actions = {}; +const globalAction = []; export function action(type, actionFn) { if (isFunction(type)) { globalAction.push(type); + return () => { - remove(globalAction, (idx) => globalAction.indexOf(actionFn) === idx); + remove(globalAction, idx => globalAction.indexOf(actionFn) === idx); }; } if (!actions[type]) { actions[type] = []; } actions[type].push(actionFn); + return () => { - remove(actions[type], (idx) => actions[type].indexOf(actionFn) === idx); + remove(actions[type], idx => actions[type].indexOf(actionFn) === idx); if (actions[type].length === 0) { delete actions[type]; } }; } -let points = {}; +const points = {}; export function point(type, action, pointFn, after) { if (!points[type]) { points[type] = {}; @@ -235,35 +238,37 @@ export function point(type, action, pointFn, after) { } export const Modules = { - getModule: function (type) { + getModule (type) { if (!moduleInjection[type]) { - _global.console && console.error("module: [" + type + "] 未定义"); + _global.console && console.error(`module: [${type}] 未定义`); } + return moduleInjection[type]; }, - getAllModules: function () { + getAllModules () { return moduleInjection; - } -} + }, +}; export const Constants = { - getConstant: function (type) { + getConstant (type) { if (isNull(constantInjection[type])) { - _global.console && console.error("constant: [" + type + "] 未定义"); + _global.console && console.error(`constant: [${type}] 未定义`); } runConfigFunction(type); + return isFunction(constantInjection[type]) ? constantInjection[type]() : constantInjection[type]; - } -} + }, +}; -const callPoint = function (inst, types) { +function callPoint(inst, types) { types = isArray(types) ? types : [types]; each(types, (idx, type) => { if (points[type]) { for (const action in points[type]) { - let bfns = points[type][action].before; + const bfns = points[type][action].before; if (bfns) { - BI.aspect.before(inst, action, function (bfns) { + BI.aspect.before(inst, action, (function (bfns) { return function () { for (let i = 0, len = bfns.length; i < len; i++) { try { @@ -273,11 +278,11 @@ const callPoint = function (inst, types) { } } }; - }(bfns)); + }(bfns))); } - let afns = points[type][action].after; + const afns = points[type][action].after; if (afns) { - BI.aspect.after(inst, action, function (afns) { + BI.aspect.after(inst, action, (function (afns) { return function () { for (let i = 0, len = afns.length; i < len; i++) { try { @@ -287,66 +292,69 @@ const callPoint = function (inst, types) { } } }; - }(afns)); + }(afns))); } } } }); -}; +} export const Models = { - getModel: function (type, config) { + getModel (type, config) { if (!modelInjection[type]) { - _global.console && console.error("model: [" + type + "] 未定义"); + _global.console && console.error(`model: [${type}] 未定义`); } runConfigFunction(type); - var inst = new modelInjection[type](config); + const inst = new modelInjection[type](config); inst._constructor && inst._constructor(config); inst.mixins && callPoint(inst, inst.mixins); callPoint(inst, type); + return inst; - } -} + }, +}; -let stores = {}; +const stores = {}; export const Stores = { - getStore: function (type, config) { + getStore (type, config) { if (!storeInjection[type]) { - _global.console && console.error("store: [" + type + "] 未定义"); + _global.console && console.error(`store: [${type}] 未定义`); } if (stores[type]) { return stores[type]; } const inst = stores[type] = new storeInjection[type](config); - inst._constructor && inst._constructor(config, function () { + inst._constructor && inst._constructor(config, () => { delete stores[type]; }); callPoint(inst, type); + return inst; - } -} + }, +}; -let services = {}; +const services = {}; export const Services = { getService: (type, config) => { if (!serviceInjection[type]) { - _global.console && console.error("service: [" + type + "] 未定义"); + _global.console && console.error(`service: [${type}] 未定义`); } if (services[type]) { return services[type]; } services[type] = new serviceInjection[type](config); callPoint(services[type], type); + return services[type]; - } -} + }, +}; -let providers = {}, +const providers = {}, providerInstance = {}; export const Providers = { getProvider: (type, config) => { if (!providerInjection[type]) { - _global.console && console.error("provider: [" + type + "] 未定义"); + _global.console && console.error(`provider: [${type}] 未定义`); } runConfigFunction(type); if (!providers[type]) { @@ -355,12 +363,13 @@ export const Providers = { if (!providerInstance[type] && providers[type].$get) { providerInstance[type] = new (providers[type].$get())(config); } + return providerInstance[type]; - } -} + }, +}; export const Actions = { - runAction: function (type, event, config) { + runAction (type, event, config) { each(actions[type], (i, act) => { try { act(event, config); @@ -369,38 +378,38 @@ export const Actions = { } }); }, - runGlobalAction: function () { - var args = [].slice.call(arguments); + runGlobalAction () { + const args = [].slice.call(arguments); each(globalAction, (i, act) => { try { - act.apply(null, args); + act(...args); } catch (e) { _global.console && console.error(e); } }); - } -} + }, +}; -let kv = {}; +const kv = {}; export function shortcut(xtype, cls) { - if (kv[xtype] != null) { - _global.console && console.error("组件: [" + xtype + "] 已经注册过了"); + if (isNotNull(kv[xtype])) { + _global.console && console.error(`组件: [${xtype}] 已经注册过了`); } if (cls) { - cls["xtype"] = xtype; + cls.xtype = xtype; } kv[xtype] = cls; } // 根据配置属性生成widget -const createRealWidget = function (config, context, lazy) { - const cls = isFunction(config.type) ? config.type : kv[config.type]; +const createRealWidget = (config, context, lazy) => { + const Cls = isFunction(config.type) ? config.type : kv[config.type]; - if (!cls) { - throw new Error("组件: [" + config.type + "] 未定义"); + if (!Cls) { + throw new Error(`组件: [${config.type}] 未定义`); } let pushed = false; - const widget = new cls(); + const widget = new Cls(); widget._context = Widget.context || context; if (!Widget.context && context) { pushed = true; @@ -414,6 +423,7 @@ const createRealWidget = function (config, context, lazy) { widget._lazyConstructor(); // } pushed && Widget.popContext(); + return widget; }; @@ -426,15 +436,15 @@ export function createWidget(item, options, context, lazy) { options || (options = {}); } - var el, w; + let el, w; if (item.type || options.type) { el = extend({}, options, item); } else if (item.el && (item.el.type || options.type)) { el = extend({}, options, item.el); } - + let elType; if (el) { - var elType = (el.type && el.type.xtype) || el.type; + elType = (el.type && el.type.xtype) || el.type; runConfigFunction(elType); } @@ -443,7 +453,7 @@ export function createWidget(item, options, context, lazy) { if (isEmpty(item) && isEmpty(options)) { return createWidget({ - type: "bi.layout" + type: "bi.layout", }); } if (isWidget(item)) { @@ -451,7 +461,7 @@ export function createWidget(item, options, context, lazy) { } if (el) { w = BI.Plugin.getWidget(elType, el); - var wType = (w.type && w.type.xtype) || w.type; + const wType = (w.type && w.type.xtype) || w.type; if (wType === elType) { if (BI.Plugin.hasObject(elType)) { if (!w.listeners || isArray(w.listeners)) { @@ -459,7 +469,7 @@ export function createWidget(item, options, context, lazy) { eventName: BI.Events.MOUNT, action: () => { BI.Plugin.getObject(elType, this); - } + }, }]); } else { w.listeners[BI.Events.MOUNT] = [ @@ -469,8 +479,10 @@ export function createWidget(item, options, context, lazy) { ].concat(w.listeners[BI.Events.MOUNT] || []); } } + return createRealWidget(w, context, lazy); } + return createWidget(w, options, context, lazy); } if (isWidget(item.el)) { @@ -485,6 +497,7 @@ export function _lazyCreateWidget (item, options, context) { export function createElement() { const widget = createWidget.apply(this, arguments); + return widget.element; } @@ -504,5 +517,5 @@ export function getResource(type, config) { if (providerInjection[type]) { return Providers.getProvider(type, config); } - throw new Error("未知类型: [" + type + "] 未定义"); + throw new Error(`未知类型: [${type}] 未定义`); } diff --git a/src/core/index.js b/src/core/index.js index 85847f032..d24cd4241 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -22,13 +22,13 @@ export * from "./controller"; export * from "./func"; // 有了后删掉 -export const emptyFn = () => { } +export const emptyFn = () => { }; export { StyleLoaderManager, ShowListener, - shortcut, -} + shortcut +}; Object.assign(BI, { ...base, From 6da3c1967041fc25d61d92d7a5faa33fcaf91714 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Thu, 5 Jan 2023 14:38:08 +0800 Subject: [PATCH 038/300] =?UTF-8?q?=E6=97=A0JIRA=E4=BB=BB=E5=8A=A1=20chore?= =?UTF-8?q?:=20eslint=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .eslintrc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.eslintrc b/.eslintrc index 234d9007a..f5b262e6e 100644 --- a/.eslintrc +++ b/.eslintrc @@ -21,7 +21,8 @@ "ecmaVersion": 6, "sourceType": "module", "ecmaFeatures": { - "modules": true + "modules": true, + "legacyDecorators": true } }, "plugins": ["@typescript-eslint/eslint-plugin"], From 7ae79f12e34d873a2f4c058cf2fe3d880c8eb2a0 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Thu, 5 Jan 2023 15:19:10 +0800 Subject: [PATCH 039/300] =?UTF-8?q?KERNEL-14001=20refactor:=20plguin?= =?UTF-8?q?=E3=80=81system=E7=AD=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/0.foundation.js | 9 +- src/core/6.plugin.js | 204 +++++++++++++++++----------------- src/core/decorator.js | 14 ++- src/core/h.js | 49 +++++---- src/core/index.js | 17 ++- src/core/system.js | 232 ++++++++++++++++++++------------------- src/core/version.js | 2 +- src/core/worker.js | 101 ++++++++--------- 8 files changed, 330 insertions(+), 298 deletions(-) diff --git a/src/core/0.foundation.js b/src/core/0.foundation.js index ea69e97a9..96c6e59ba 100644 --- a/src/core/0.foundation.js +++ b/src/core/0.foundation.js @@ -1,10 +1,11 @@ +/* eslint-disable eqeqeq */ /** * Created by richie on 15/7/8. */ /** * 初始化BI对象 */ -var _global = undefined; +let _global = undefined; if (typeof window !== "undefined") { _global = window; } else if (typeof global !== "undefined") { @@ -20,8 +21,8 @@ if (_global) { } if (_global.BI == null) { - _global.BI = {prepares: []}; + _global.BI = { prepares: [] }; } -if(_global.BI.prepares == null) { +if (_global.BI.prepares == null) { _global.BI.prepares = []; -} \ No newline at end of file +} diff --git a/src/core/6.plugin.js b/src/core/6.plugin.js index bbfd5e5ac..e0561b4fd 100644 --- a/src/core/6.plugin.js +++ b/src/core/6.plugin.js @@ -1,123 +1,127 @@ -BI.Plugin = BI.Plugin || {}; -!(function () { - var _WidgetsPlugin = {}; - var _ObjectPlugin = {}; - var _ConfigPlugin = {}; - var _ConfigRenderPlugin = {}; - var _GlobalWidgetConfigFns = []; - var __GlobalObjectConfigFns = []; - BI.defaults(BI.Plugin, { +const _WidgetsPlugin = {}; +const _ObjectPlugin = {}; +const _ConfigPlugin = {}; +const _ConfigRenderPlugin = {}; +let _GlobalWidgetConfigFns = []; +let __GlobalObjectConfigFns = []; - getWidget: function (type, options) { - if (_GlobalWidgetConfigFns.length > 0) { - var fns = _GlobalWidgetConfigFns.slice(0); - for (var i = fns.length - 1; i >= 0; i--) { - fns[i](type, options); - } +export const Plugin = { + getWidget (type, options) { + if (_GlobalWidgetConfigFns.length > 0) { + const fns = _GlobalWidgetConfigFns.slice(0); + for (let i = fns.length - 1; i >= 0; i--) { + fns[i](type, options); } + } - var res; - if (_ConfigPlugin[type]) { - for (var i = _ConfigPlugin[type].length - 1; i >= 0; i--) { - if (res = _ConfigPlugin[type][i](options)) { - options = res; - } + let res; + if (_ConfigPlugin[type]) { + for (let i = _ConfigPlugin[type].length - 1; i >= 0; i--) { + res = _ConfigPlugin[type][i](options); + if (res) { + options = res; } } - // Deprecated - if (_WidgetsPlugin[type]) { - for (var i = _WidgetsPlugin[type].length - 1; i >= 0; i--) { - if (res = _WidgetsPlugin[type][i](options)) { - return res; - } + } + // Deprecated + if (_WidgetsPlugin[type]) { + for (let i = _WidgetsPlugin[type].length - 1; i >= 0; i--) { + res = _WidgetsPlugin[type][i](options); + if (res) { + return res; } } - return options; - }, + } + + return options; + }, - config: function (widgetConfigFn, objectConfigFn) { - _GlobalWidgetConfigFns = _GlobalWidgetConfigFns.concat(BI._.isArray(widgetConfigFn) ? widgetConfigFn : [widgetConfigFn]); - __GlobalObjectConfigFns = __GlobalObjectConfigFns.concat(BI._.isArray(objectConfigFn) ? objectConfigFn : [objectConfigFn]); - }, + config (widgetConfigFn, objectConfigFn) { + _GlobalWidgetConfigFns = _GlobalWidgetConfigFns.concat(BI._.isArray(widgetConfigFn) ? widgetConfigFn : [widgetConfigFn]); + __GlobalObjectConfigFns = __GlobalObjectConfigFns.concat(BI._.isArray(objectConfigFn) ? objectConfigFn : [objectConfigFn]); + }, - configWidget: function (type, fn, opt) { - // opt.single: true 最后一次注册有效 - if (!_ConfigPlugin[type] || (opt && opt.single)) { - _ConfigPlugin[type] = []; - } - _ConfigPlugin[type].push(fn); - }, + configWidget (type, fn, opt) { + // opt.single: true 最后一次注册有效 + if (!_ConfigPlugin[type] || (opt && opt.single)) { + _ConfigPlugin[type] = []; + } + _ConfigPlugin[type].push(fn); + }, - getRender: function (type, rendered) { - var res; - if (_ConfigRenderPlugin[type]) { - for (var i = _ConfigRenderPlugin[type].length - 1; i >= 0; i--) { - if (res = _ConfigRenderPlugin[type][i](rendered)) { - rendered = res; - } + getRender (type, rendered) { + let res; + if (_ConfigRenderPlugin[type]) { + for (let i = _ConfigRenderPlugin[type].length - 1; i >= 0; i--) { + res = _ConfigRenderPlugin[type][i](rendered); + if (res) { + rendered = res; } } - return rendered; - }, + } + + return rendered; + }, - configRender: function (type, fn) { - if (!_ConfigRenderPlugin[type]) { - _ConfigRenderPlugin[type] = []; - } - _ConfigRenderPlugin[type].push(fn); - }, + configRender (type, fn) { + if (!_ConfigRenderPlugin[type]) { + _ConfigRenderPlugin[type] = []; + } + _ConfigRenderPlugin[type].push(fn); + }, - // Deprecated - registerWidget: function (type, fn) { - if (!_WidgetsPlugin[type]) { - _WidgetsPlugin[type] = []; - } - if (_WidgetsPlugin[type].length > 0) { - console.log("组件已经注册过了!"); - } - _WidgetsPlugin[type].push(fn); - }, + // Deprecated + registerWidget (type, fn) { + if (!_WidgetsPlugin[type]) { + _WidgetsPlugin[type] = []; + } + if (_WidgetsPlugin[type].length > 0) { + console.log("组件已经注册过了!"); + } + _WidgetsPlugin[type].push(fn); + }, - // Deprecated - relieveWidget: function (type) { - delete _WidgetsPlugin[type]; - }, + // Deprecated + relieveWidget (type) { + delete _WidgetsPlugin[type]; + }, - getObject: function (type, object) { - if (__GlobalObjectConfigFns.length > 0) { - var fns = __GlobalObjectConfigFns.slice(0); - for (var i = fns.length - 1; i >= 0; i--) { - fns[i](type, object); - } + getObject (type, object) { + if (__GlobalObjectConfigFns.length > 0) { + const fns = __GlobalObjectConfigFns.slice(0); + for (let i = fns.length - 1; i >= 0; i--) { + fns[i](type, object); } + } - if (_ObjectPlugin[type]) { - var res; - for (var i = 0, len = _ObjectPlugin[type].length; i < len; i++) { - if (res = _ObjectPlugin[type][i](object)) { - object = res; - } + let res; + if (_ObjectPlugin[type]) { + for (let i = 0, len = _ObjectPlugin[type].length; i < len; i++) { + res = _ObjectPlugin[type][i](object); + if (res) { + object = res; } } - return res || object; - }, - - hasObject: function (type) { - return __GlobalObjectConfigFns.length > 0 || !!_ObjectPlugin[type]; - }, + } + + return res || object; + }, - registerObject: function (type, fn) { - if (!_ObjectPlugin[type]) { - _ObjectPlugin[type] = []; - } - if (_ObjectPlugin[type].length > 0) { - console.log("对象已经注册过了!"); - } - _ObjectPlugin[type].push(fn); - }, + hasObject (type) { + return __GlobalObjectConfigFns.length > 0 || !!_ObjectPlugin[type]; + }, - relieveObject: function (type) { - delete _ObjectPlugin[type]; + registerObject (type, fn) { + if (!_ObjectPlugin[type]) { + _ObjectPlugin[type] = []; + } + if (_ObjectPlugin[type].length > 0) { + console.log("对象已经注册过了!"); } - }); -})(); + _ObjectPlugin[type].push(fn); + }, + + relieveObject (type) { + delete _ObjectPlugin[type]; + }, +}; diff --git a/src/core/decorator.js b/src/core/decorator.js index af7a6e005..0e5d5e097 100644 --- a/src/core/decorator.js +++ b/src/core/decorator.js @@ -1,9 +1,21 @@ +// export * from "../../typescript/core/decorator/decorator.ts"; + +import { shortcut as biShortcut, provider as biProvider } from "./5.inject"; + /** * 注册widget */ -import { shortcut as biShortcut } from "./5.inject"; export function shortcut() { return function decorator(Target) { biShortcut(Target.xtype, Target); }; } + +/** + * 注册provider + */ +export function provider() { + return function decorator(Target) { + biProvider(Target.xtype, Target); + }; +} diff --git a/src/core/h.js b/src/core/h.js index b768b1415..c413788c2 100644 --- a/src/core/h.js +++ b/src/core/h.js @@ -1,58 +1,59 @@ -BI.Fragment = function () { -}; +import { isNotNull, isArray, isFunction, isKey, extend } from "./2.base"; -BI.h = function (type, props, children) { - if (children != null) { - if (!BI.isArray(children)) { +export function Fragment () {} + +export function h (type, props, children) { + if (isNotNull(children)) { + if (!isArray(children)) { children = [children]; } } else { children = []; } if (arguments.length > 3) { - for (var i = 3; i < arguments.length; i++) { - if (BI.isArray(arguments[i])) { + for (let i = 3; i < arguments.length; i++) { + if (isArray(arguments[i])) { children = children.concat(arguments[i]); } else { children.push(arguments[i]); } } } - if (type === BI.Fragment) { + if (type === Fragment) { return children; } - if (BI.isFunction(type)) { + if (isFunction(type)) { type = type.xtype || type; } if (type === "el") { - return BI.extend({ - el: children[0] + return extend({ + el: children[0], }, props); } if (type === "left") { - return BI.extend({ - left: children + return extend({ + left: children, }, props); } if (type === "right") { - return BI.extend({ - right: children + return extend({ + right: children, }, props); } if (children.length === 1) { - if (BI.isKey(children[0])) { - return BI.extend({ - type: type + if (isKey(children[0])) { + return extend({ + type, }, { text: children[0] }, props); } - if (BI.isFunction(children[0])) { - return BI.extend({ - type: type + if (isFunction(children[0])) { + return extend({ + type, }, { items: children[0] }, props); } } - return BI.extend({ - type: type + return extend({ + type, }, children.length > 0 ? { items: children } : {}, props); -}; +} diff --git a/src/core/index.js b/src/core/index.js index b7cf86b47..37c581af2 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -2,16 +2,18 @@ import * as base from "./2.base"; import * as ob from "./3.ob"; import * as widget from "./4.widget"; import * as inject from "./5.inject"; +import { Plugin } from "./6.plugin"; +import * as h from "./h"; import * as action from "./action"; import * as behavior from "./behavior"; import * as controllers from "./controller"; import * as func from "./func"; import * as structure from "./structure"; -import {StyleLoaderManager} from "./loader/loader.style"; -import "./h"; -import {ShowListener} from "./listener/listener.show"; -import {shortcut} from "./decorator"; +import { StyleLoaderManager } from "./loader/loader.style"; +import { ShowListener } from "./listener/listener.show"; +import { useInWorker } from "./worker"; +export * from "./decorator"; export * from "./2.base"; export * from "./3.ob"; export * from "./4.widget"; @@ -21,6 +23,7 @@ export * from "./behavior"; export * from "./controller"; export * from "./func"; export * from "./structure"; +export * from "./h"; // 有了后删掉 export const emptyFn = () => { }; @@ -28,7 +31,8 @@ export const emptyFn = () => { }; export { StyleLoaderManager, ShowListener, - shortcut + Plugin, + useInWorker }; Object.assign(BI, { @@ -36,6 +40,7 @@ Object.assign(BI, { ...ob, ...widget, ...inject, + Plugin, ...behavior, component: inject.shortcut, ...action, @@ -44,4 +49,6 @@ Object.assign(BI, { StyleLoaderManager, ShowListener, ...structure, + useInWorker, + ...h, }); diff --git a/src/core/system.js b/src/core/system.js index 545057e49..93be82dc4 100644 --- a/src/core/system.js +++ b/src/core/system.js @@ -3,142 +3,146 @@ * @version 2.0 * Created by windy on 2021/6/30 */ +import { deepExtend, extend, inherit } from "./2.base"; +import { OB } from "./3.ob"; +import { Providers } from "./5.inject"; +import { provider } from "./decorator"; + // 系统参数常量 -!(function () { - var system = { - dependencies: {}, - layoutOptimize: false, - responsiveMode: false, - workerMode: false, - size: { - // 尺寸 - // 通用尺寸 - TOOL_BAR_HEIGHT: 24, - LIST_ITEM_HEIGHT: 24, - TRIGGER_HEIGHT: 24, - TOAST_TOP: 10, - H_GAP_SIZE: "M", - V_GAP_SIZE: "S" - }, - loadingCreator: function(config) { - var loadingSize = (config ? config.loadingSize : "small") || "small"; - - var isIE = BI.isIE(); - - function getSize(v) { - return Math.ceil(v / (loadingSize === "small" ? 2 : 1)); - } - - return { - type: "bi.horizontal", - cls: "bi-loading-widget" + (isIE ? " wave-loading hack" : ""), - height: getSize(60), - width: getSize(60), - hgap: getSize(10), - vgap: 2.5, - items: isIE ? [] : [{ - type: "bi.layout", - cls: "animate-rect rect1", - height: getSize(50), - width: getSize(5) - }, { - type: "bi.layout", - cls: "animate-rect rect2", - height: getSize(50), - width: getSize(5) - }, { - type: "bi.layout", - cls: "animate-rect rect3", - height: getSize(50), - width: getSize(5) - }] - }; +const system = { + dependencies: {}, + layoutOptimize: false, + responsiveMode: false, + workerMode: false, + size: { + // 尺寸 + // 通用尺寸 + TOOL_BAR_HEIGHT: 24, + LIST_ITEM_HEIGHT: 24, + TRIGGER_HEIGHT: 24, + TOAST_TOP: 10, + H_GAP_SIZE: "M", + V_GAP_SIZE: "S", + }, + loadingCreator(config) { + const loadingSize = (config ? config.loadingSize : "small") || "small"; + + const isIE = BI.isIE(); + + function getSize(v) { + return Math.ceil(v / (loadingSize === "small" ? 2 : 1)); } - }; - // 具体尺寸还没定,先写着 - var sizeMap = { - "S": 10, - "M": 20, - "L": 24 - }; + return { + type: "bi.horizontal", + cls: `bi-loading-widget${isIE ? " wave-loading hack" : ""}`, + height: getSize(60), + width: getSize(60), + hgap: getSize(10), + vgap: 2.5, + items: isIE ? [] : [{ + type: "bi.layout", + cls: "animate-rect rect1", + height: getSize(50), + width: getSize(5), + }, { + type: "bi.layout", + cls: "animate-rect rect2", + height: getSize(50), + width: getSize(5), + }, { + type: "bi.layout", + cls: "animate-rect rect3", + height: getSize(50), + width: getSize(5), + }], + }; + }, +}; - function provider () { - this.SYSTEM = system; +// 具体尺寸还没定,先写着 +const sizeMap = { + S: 10, + M: 20, + L: 24, +}; - this.setSize = function (opt) { - BI.deepExtend(system, { size: opt }); - }; +@provider() +export class SystemProvider { + static xtype = "bi.provider.system"; - this.setResponsiveMode = function (mode) { - system.responsiveMode = !!mode; - }; + SYSTEM = system; - this.setWorkerMode = function (mode) { - system.workerMode = !!mode; - }; + setSize(opt) { + deepExtend(system, { size: opt }); + } - this.setLayoutOptimize = function (layoutOptimize) { - system.layoutOptimize = layoutOptimize; - }; + setResponsiveMode(mode) { + system.responsiveMode = !!mode; + } - this.addDependency = function (moduleId, minVersion, maxVersion) { - system.dependencies[moduleId] = { - min: minVersion, - max: maxVersion - }; - }; + setWorkerMode(mode) { + system.workerMode = !!mode; + } - this.addDependencies = function (moduleConfig) { - BI.extend(system.dependencies, moduleConfig); - }; + setLayoutOptimize(layoutOptimize) { + system.layoutOptimize = layoutOptimize; + } - this.setLoadingCreator = function(creator) { - system.loadingCreator = creator; + addDependency(moduleId, minVersion, maxVersion) { + system.dependencies[moduleId] = { + min: minVersion, + max: maxVersion, }; + } + + addDependencies(moduleConfig) { + extend(system.dependencies, moduleConfig); + } - this.$get = function () { - return BI.inherit(BI.OB, { + setLoadingCreator = function(creator) { + system.loadingCreator = creator; + }; - getSize: function () { - var size = system.size; - var H_GAP_SIZE = sizeMap[size.H_GAP_SIZE]; - var V_GAP_SIZE = sizeMap[size.V_GAP_SIZE]; + $get() { + return inherit(OB, { - return BI.extend({}, size, { - H_GAP_SIZE: H_GAP_SIZE, - V_GAP_SIZE: V_GAP_SIZE - }); - }, + getSize () { + const size = system.size; + const H_GAP_SIZE = sizeMap[size.H_GAP_SIZE]; + const V_GAP_SIZE = sizeMap[size.V_GAP_SIZE]; - getResponsiveMode: function () { - return system.responsiveMode; - }, + return extend({}, size, { + H_GAP_SIZE, + V_GAP_SIZE, + }); + }, - getWorkerMode: function () { - return system.workerMode; - }, + getResponsiveMode () { + return system.responsiveMode; + }, - getLayoutOptimize: function () { - return system.layoutOptimize; - }, + getWorkerMode () { + return system.workerMode; + }, - getDependencies: function () { - return system.dependencies; - }, + getLayoutOptimize () { + return system.layoutOptimize; + }, - getLoading: function(config) { - return system.loadingCreator(config); - } - }); - }; - } + getDependencies () { + return system.dependencies; + }, - BI.provider("bi.provider.system", provider); -}()); + getLoading(config) { + return system.loadingCreator(config); + }, + }); + } +} -BI.prepares.push(function () { - BI.SIZE_CONSANTS = BI.Providers.getProvider("bi.provider.system").getSize(); +BI.prepares.push(() => { + BI.SIZE_CONSANTS = Providers.getProvider("bi.provider.system").getSize(); // 不再增加线型的配置了,之后不维护前置版本直接删掉,都用实线连接线 BI.STYLE_CONSTANTS = {}; BI.STYLE_CONSTANTS.LINK_LINE_TYPE = BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT === 24 ? "dashed" : "solid"; diff --git a/src/core/version.js b/src/core/version.js index a850da743..88665e6e3 100644 --- a/src/core/version.js +++ b/src/core/version.js @@ -1 +1 @@ -BI.version = "2.0"; \ No newline at end of file +BI.version = "2.0"; diff --git a/src/core/worker.js b/src/core/worker.js index d3ba08ee4..643e77e1a 100644 --- a/src/core/worker.js +++ b/src/core/worker.js @@ -1,51 +1,54 @@ -!(function () { - BI.useInWorker = function () { - function createWatcher (model, keyOrFn, cb, options) { - if (BI.isPlainObject(cb)) { - options = cb; - cb = cb.handler; - } - options = options || {}; - return Fix.watch(model, keyOrFn, cb, BI.extend(options, { - store: model - })); +import { isPlainObject, extend, each, isArray } from "./2.base"; +import { Models } from "./5.inject"; + +export function useInWorker () { + function createWatcher (model, keyOrFn, cb, options) { + if (isPlainObject(cb)) { + options = cb; + cb = cb.handler; } + options = options || {}; + + return Fix.watch(model, keyOrFn, cb, extend(options, { + store: model, + })); + } - var models = {}, watches = {}; - addEventListener("message", function (e) { - var data = e.data; - switch (data.eventType) { - case "action": - models[data.name][data.action].apply(models[data.name], data.args); - break; - case "destroy": - BI.each(watches[data.name], function (i, unwatches) { - unwatches = BI.isArray(unwatches) ? unwatches : [unwatches]; - BI.each(unwatches, function (j, unwatch) { - unwatch(); - }); - }); - delete models[data.name]; - delete watches[data.name]; - break; - case "create": - var store = models[data.name] = BI.Models.getModel(data.type, data.options); - watches[data.name] = []; - BI.each(data.watches, function (i, key) { - watches[data.name].push(createWatcher(store.model, key, function (newValue, oldValue) { - postMessage(BI.extend({}, data, { - eventType: "watch", - currentWatchType: key - }, {args: [newValue, oldValue]})); - })); - }); - postMessage(BI.extend({}, data, { - eventType: "create" - }, {msg: store.model})); - break; - default: - break; - } - }, false); - }; -}()); + const models = {}, watches = {}; + addEventListener("message", e => { + const data = e.data; + let store; + switch (data.eventType) { + case "action": + models[data.name][data.action](...data.args); + break; + case "destroy": + each(watches[data.name], (i, unwatches) => { + unwatches = isArray(unwatches) ? unwatches : [unwatches]; + each(unwatches, (j, unwatch) => { + unwatch(); + }); + }); + delete models[data.name]; + delete watches[data.name]; + break; + case "create": + store = models[data.name] = Models.getModel(data.type, data.options); + watches[data.name] = []; + each(data.watches, (i, key) => { + watches[data.name].push(createWatcher(store.model, key, (newValue, oldValue) => { + postMessage(extend({}, data, { + eventType: "watch", + currentWatchType: key, + }, { args: [newValue, oldValue] })); + })); + }); + postMessage(extend({}, data, { + eventType: "create", + }, { msg: store.model })); + break; + default: + break; + } + }, false); +} From a18cd23e1c19bfd6452242437472cc8f85e75b3a Mon Sep 17 00:00:00 2001 From: Treecat Date: Fri, 6 Jan 2023 11:12:42 +0800 Subject: [PATCH 040/300] =?UTF-8?q?case/button=E6=96=87=E4=BB=B6=E5=A4=B9?= =?UTF-8?q?=20es6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/single/button/button.basic.js | 211 +++++++++--------- src/base/single/button/button.node.js | 9 +- .../single/button/buttons/button.image.js | 3 +- src/base/single/button/buttons/button.js | 25 +-- src/base/single/button/buttons/button.text.js | 11 +- src/base/single/button/index.js | 2 +- .../button/listitem/blankiconicontextitem.js | 23 +- .../button/listitem/blankicontexticonitem.js | 21 +- .../button/listitem/blankicontextitem.js | 21 +- .../button/listitem/icontexticonitem.js | 21 +- .../single/button/listitem/icontextitem.js | 21 +- .../single/button/listitem/texticonitem.js | 21 +- src/base/single/button/listitem/textitem.js | 19 +- .../single/button/node/icontexticonnode.js | 17 +- src/base/single/button/node/icontextnode.js | 17 +- src/base/single/button/node/texticonnode.js | 17 +- src/base/single/button/node/textnode.js | 15 +- src/case/button/icon/icon.change.js | 68 +++--- src/case/button/icon/icon.trigger.js | 29 ++- .../button/icon/iconhalf/icon.half.image.js | 23 +- src/case/button/icon/iconhalf/icon.half.js | 36 +-- src/case/button/index.js | 29 +++ src/case/button/item.multiselect.js | 64 +++--- src/case/button/item.singleselect.icontext.js | 60 ++--- src/case/button/item.singleselect.js | 65 +++--- src/case/button/item.singleselect.radio.js | 69 +++--- src/case/button/node/node.arrow.js | 71 +++--- src/case/button/node/node.first.plus.js | 82 ++++--- src/case/button/node/node.icon.arrow.js | 99 ++++---- src/case/button/node/node.last.plus.js | 93 ++++---- src/case/button/node/node.mid.plus.js | 85 +++---- .../button/node/node.multilayer.icon.arrow.js | 88 ++++---- src/case/button/node/node.plus.js | 79 ++++--- src/case/button/node/siwtcher.tree.node.js | 45 ++-- src/case/button/node/treenode.js | 79 ++++--- src/case/button/switch.js | 119 +++++----- .../button/treeitem/item.first.treeleaf.js | 108 ++++----- .../button/treeitem/item.icon.treeleaf.js | 86 +++---- .../button/treeitem/item.last.treeleaf.js | 110 ++++----- src/case/button/treeitem/item.mid.treeleaf.js | 110 ++++----- .../treeitem/item.multilayer.icon.treeleaf.js | 94 ++++---- .../button/treeitem/item.root.treeleaf.js | 78 ++++--- src/case/button/treeitem/item.treetextleaf.js | 68 +++--- src/case/button/treeitem/treeitem.js | 64 +++--- src/case/index.js | 7 + 45 files changed, 1330 insertions(+), 1152 deletions(-) create mode 100644 src/case/button/index.js create mode 100644 src/case/index.js diff --git a/src/base/single/button/button.basic.js b/src/base/single/button/button.basic.js index 9375ec638..f2f09216c 100644 --- a/src/base/single/button/button.basic.js +++ b/src/base/single/button/button.basic.js @@ -1,5 +1,5 @@ -import { Single } from "../0.single" -import { emptyFn, shortcut, extend, isFunction, createWidget, Widget, isObject, Controller } from "../../../core" +import { Single } from "../0.single"; +import { emptyFn, shortcut, extend, isFunction, createWidget, Widget, isObject, Controller } from "../../../core"; /** * guy @@ -10,7 +10,6 @@ import { emptyFn, shortcut, extend, isFunction, createWidget, Widget, isObject, */ @shortcut() export class BasicButton extends Single { - static xtype = "bi.basic_button"; static EVENT_CHANGE = "BasicButton.EVENT_CHANGE"; @@ -19,7 +18,7 @@ export class BasicButton extends Single { const conf = super._defaultConfig(arguments); return extend(conf, { - _baseCls: (conf._baseCls || "") + " bi-basic-button" + (conf.invalid ? "" : " cursor-pointer") + ((BI.isIE() && BI.getIEVersion() < 10) ? " hack" : ""), + _baseCls: `${conf._baseCls || ""} bi-basic-button${conf.invalid ? "" : " cursor-pointer"}${(BI.isIE() && BI.getIEVersion() < 10) ? " hack" : ""}`, // el: {} // 可以通过el来创建button元素 value: "", stopEvent: false, @@ -35,7 +34,7 @@ export class BasicButton extends Single { trigger: null, handler: emptyFn, bubble: null, - debounce: true + debounce: true, }); } @@ -50,7 +49,7 @@ export class BasicButton extends Single { this._createShadow(); } if (opts.level) { - this.element.addClass("button-" + opts.level); + this.element.addClass(`button-${opts.level}`); } } @@ -92,7 +91,7 @@ export class BasicButton extends Single { }], }); } - } + }; this.element.mouseup(() => { if (!this._hover && !o.isShadowShowingOnSelected) { @@ -100,7 +99,7 @@ export class BasicButton extends Single { this.$mask.invisible(); } }); - this.element.on("mouseenter." + this.getName(), (e) => { + this.element.on(`mouseenter.${this.getName()}`, e => { if (this.element.__isMouseInBounds__(e)) { if (this.isEnabled() && !this._hover && (o.isShadowShowingOnSelected || !this.isSelected())) { assertMask(); @@ -108,7 +107,7 @@ export class BasicButton extends Single { } } }); - this.element.on("mousemove." + this.getName(), (e) => { + this.element.on(`mousemove.${this.getName()}`, e => { if (!this.element.__isMouseInBounds__(e)) { if (this.isEnabled() && !this._hover) { assertMask(); @@ -116,7 +115,7 @@ export class BasicButton extends Single { } } }); - this.element.on("mouseleave." + this.getName(), () => { + this.element.on(`mouseleave.${this.getName()}`, () => { if (this.isEnabled() && !this._hover) { assertMask(); this.$mask.invisible(); @@ -139,9 +138,9 @@ export class BasicButton extends Single { } return bubble; - } + }; - const clk = (e) => { + const clk = e => { ev(e); if (!this.isEnabled() || !this.isValid()) { return; @@ -161,7 +160,7 @@ export class BasicButton extends Single { trigger: "", // bubble的提示不需要一直存在在界面上 destroyWhenHide: true, - ref: (_ref) => { + ref: _ref => { this.combo = _ref; }, el: { @@ -171,7 +170,7 @@ export class BasicButton extends Single { popup: { type: "bi.text_bubble_bar_popup_view", text: getBubble(), - ref: (_ref) => { + ref: _ref => { popup = _ref; }, listeners: [{ @@ -187,7 +186,7 @@ export class BasicButton extends Single { }, listeners: [{ eventName: BI.BubbleCombo.EVENT_BEFORE_POPUPVIEW, - action: function () { + action () { popup.populate(getBubble()); }, }], @@ -208,113 +207,113 @@ export class BasicButton extends Single { return; } onClick.apply(this, arguments); - } + }; const triggerArr = (o.trigger || "").split(","); - triggerArr.forEach((trigger) => { + triggerArr.forEach(trigger => { let mouseDown = false; + let selected = false; + let interval; switch (trigger) { - case "mouseup": - hand.mousedown(function () { - mouseDown = true; - }); - hand.mouseup(function (e) { - if (mouseDown === true) { - clk(e); - } - mouseDown = false; - ev(e); - }); - break; - case "mousedown": - // let mouseDown = false; - let selected = false; - hand.mousedown((e) => { + case "mouseup": + hand.mousedown(() => { + mouseDown = true; + }); + hand.mouseup(e => { + if (mouseDown === true) { + clk(e); + } + mouseDown = false; + ev(e); + }); + break; + case "mousedown": + // let mouseDown = false; + hand.mousedown(e => { + // if (e.button === 0) { + Widget._renderEngine.createElement(document).bind(`mouseup.${this.getName()}`, e => { // if (e.button === 0) { - Widget._renderEngine.createElement(document).bind("mouseup." + this.getName(), (e) => { - // if (e.button === 0) { - if (BI.DOM.isExist(this) && !hand.__isMouseInBounds__(e) && mouseDown === true && !selected) { - // self.setSelected(!self.isSelected()); - this._trigger(); - } - mouseDown = false; - Widget._renderEngine.createElement(document).unbind("mouseup." + this.getName()); - // } - }); - if (mouseDown === true) { - return; - } - if (this.isSelected()) { - selected = true; - } else { - clk(e); + if (BI.DOM.isExist(this) && !hand.__isMouseInBounds__(e) && mouseDown === true && !selected) { + // self.setSelected(!self.isSelected()); + this._trigger(); } - mouseDown = true; - ev(e); + mouseDown = false; + Widget._renderEngine.createElement(document).unbind(`mouseup.${this.getName()}`); // } }); - hand.mouseup((e) => { - // if (e.button === 0) { - if (BI.DOM.isExist(this) && mouseDown === true && selected === true) { - clk(e); - } + if (mouseDown === true) { + return; + } + if (this.isSelected()) { + selected = true; + } else { + clk(e); + } + mouseDown = true; + ev(e); + // } + }); + hand.mouseup(e => { + // if (e.button === 0) { + if (BI.DOM.isExist(this) && mouseDown === true && selected === true) { + clk(e); + } + mouseDown = false; + selected = false; + Widget._renderEngine.createElement(document).unbind(`mouseup.${this.getName()}`); + // } + }); + break; + case "dblclick": + hand.dblclick(clk); + break; + case "lclick": + hand.mousedown(e => { + Widget._renderEngine.createElement(document).bind(`mouseup.${this.getName()}`, () => { + interval && clearInterval(interval); + interval = null; mouseDown = false; - selected = false; - Widget._renderEngine.createElement(document).unbind("mouseup." + this.getName()); - // } + Widget._renderEngine.createElement(document).unbind(`mouseup.${this.getName()}`); }); - break; - case "dblclick": - hand.dblclick(clk); - break; - case "lclick": - let interval; - hand.mousedown((e) => { - Widget._renderEngine.createElement(document).bind("mouseup." + this.getName(), () => { - interval && clearInterval(interval); - interval = null; - mouseDown = false; - Widget._renderEngine.createElement(document).unbind("mouseup." + this.getName()); - }); - if (mouseDown === true) { - return; - } - if (!this.isEnabled() || !this.isValid()) { - return; - } - if (this.isOnce() && this.isSelected()) { - return; - } - interval = setInterval(function () { - clk(e) - }, 180); - mouseDown = true; + if (mouseDown === true) { + return; + } + if (!this.isEnabled() || !this.isValid()) { + return; + } + if (this.isOnce() && this.isSelected()) { + return; + } + interval = setInterval(() => { + clk(e); + }, 180); + mouseDown = true; + ev(e); + }); + break; + default: + if (o.stopEvent || o.stopPropagation) { + hand.mousedown(e => { ev(e); }); - break; - default: - if (o.stopEvent || o.stopPropagation) { - hand.mousedown(function (e) { - ev(e); - }); + } + hand.click(clk); + // enter键等同于点击 + o.attributes && o.attributes.zIndex >= 0 && hand.keyup(e => { + if (e.keyCode === BI.KeyCode.ENTER) { + clk(e); } - hand.click(clk); - // enter键等同于点击 - o.attributes && o.attributes.zIndex >= 0 && hand.keyup(function (e) { - if (e.keyCode === BI.KeyCode.ENTER) { - clk(e); - } - }); - break; + }); + break; } }); // 之后的300ms点击无效 - let onClick = o.debounce ? BI.debounce(this._doClick, BI.EVENT_RESPONSE_TIME, { - "leading": true, - "trailing": false, + const onClick = o.debounce ? BI.debounce(this._doClick, BI.EVENT_RESPONSE_TIME, { + leading: true, + trailing: false, }) : this._doClick; function ev(e) { @@ -325,10 +324,6 @@ export class BasicButton extends Single { e.stopPropagation(); } } - - - - } _trigger(e) { @@ -458,7 +453,7 @@ export class BasicButton extends Single { } empty() { - Widget._renderEngine.createElement(document).unbind("mouseup." + this.getName()); + Widget._renderEngine.createElement(document).unbind(`mouseup.${this.getName()}`); super.empty.apply(this, arguments); } } diff --git a/src/base/single/button/button.node.js b/src/base/single/button/button.node.js index 6b2988eb3..7b8cc4632 100644 --- a/src/base/single/button/button.node.js +++ b/src/base/single/button/button.node.js @@ -1,5 +1,5 @@ -import { BasicButton } from "./button.basic" -import { shortcut, extend, Controller } from "../../../core" +import { BasicButton } from "./button.basic"; +import { shortcut, extend, Controller } from "../../../core"; /** * 表示一个可以展开的节点, 不仅有选中状态而且有展开状态 @@ -11,14 +11,13 @@ import { shortcut, extend, Controller } from "../../../core" */ @shortcut() export class NodeButton extends BasicButton { - static xtype = "bi.node_button"; _defaultConfig() { const conf = super._defaultConfig(arguments); return extend(conf, { - _baseCls: (conf._baseCls || "") + " bi-node", + _baseCls: `${conf._baseCls || ""} bi-node`, open: false, once: false, }); @@ -57,4 +56,4 @@ export class NodeButton extends BasicButton { this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, this.getValue(), this); } } -} \ No newline at end of file +} diff --git a/src/base/single/button/buttons/button.image.js b/src/base/single/button/buttons/button.image.js index 290313fb2..c6486e359 100644 --- a/src/base/single/button/buttons/button.image.js +++ b/src/base/single/button/buttons/button.image.js @@ -11,7 +11,6 @@ import { shortcut, extend, isNumber, createWidget } from "../../../../core"; */ @shortcut() export class ImageButton extends BasicButton { - static EVENT_CHANGE = "EVENT_CHANGE"; static xtype = "bi.image_button"; @@ -19,7 +18,7 @@ export class ImageButton extends BasicButton { const conf = super._defaultConfig(arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-image-button", + baseCls: `${conf.baseCls || ""} bi-image-button`, src: "", iconWidth: "100%", iconHeight: "100%", diff --git a/src/base/single/button/buttons/button.js b/src/base/single/button/buttons/button.js index 567e115f9..674400853 100644 --- a/src/base/single/button/buttons/button.js +++ b/src/base/single/button/buttons/button.js @@ -17,7 +17,6 @@ const loadingCls = "button-loading-font anim-rotate"; */ @shortcut() export class Button extends BasicButton { - _const = { iconWidth: 18, } @@ -33,16 +32,16 @@ export class Button extends BasicButton { // 图标高度和文字高度默认相等 adaptiveHeight += (props.textHeight || 16) * 2; adaptiveHeight += props.iconGap || 0; - let tGap = props.tgap || props.vgap || 2; - let bGap = props.bgap || props.vgap || 2; + const tGap = props.tgap || props.vgap || 2; + const bGap = props.bgap || props.vgap || 2; adaptiveHeight += (tGap + bGap); } - let clearMinWidth = props.block === true || props.clear === true || props.plain; + const clearMinWidth = props.block === true || props.clear === true || props.plain; return { ...conf, - baseCls: (conf.baseCls || "") + " bi-button" + ((BI.isIE() && BI.isIE9Below()) ? " hack" : ""), + baseCls: `${conf.baseCls || ""} bi-button${(BI.isIE() && BI.isIE9Below()) ? " hack" : ""}`, attributes: { tabIndex: 1, }, @@ -72,7 +71,7 @@ export class Button extends BasicButton { icon: "", iconGap: 0, iconPosition: "left", - } + }; } render() { @@ -83,7 +82,7 @@ export class Button extends BasicButton { type: "bi.center_adapt", horizontalAlign: o.textAlign, element: this, - ref: (ref) => { + ref: ref => { this.containerRef = ref; }, hgap: o.hgap, @@ -97,7 +96,7 @@ export class Button extends BasicButton { if (BI.get(o, clz) === true) { this.element.addClass(clz); } - }) + }); if (o.minWidth > 0) { this.element.css({ "min-width": BI.pixFormat(o.minWidth) }); @@ -139,7 +138,7 @@ export class Button extends BasicButton { text: o.text, whiteSpace: o.whiteSpace, textAlign: o.textAlign, - textWidth: textWidth, + textWidth, textHeight: BI.toPix(textHeight, hasBorder ? 2 : 0), height: BI.toPix(lineHeight, hasBorder ? 2 : 0), value: o.value, @@ -258,19 +257,19 @@ export class Button extends BasicButton { } doRedMark() { - this.text.doRedMark.apply(this.text, arguments); + this.text.doRedMark(...arguments); } unRedMark() { - this.text.unRedMark.apply(this.text, arguments); + this.text.unRedMark(...arguments); } doHighLight() { - this.text.doHighLight.apply(this.text, arguments); + this.text.doHighLight(...arguments); } unHighLight() { - this.text.unHighLight.apply(this.text, arguments); + this.text.unHighLight(...arguments); } } diff --git a/src/base/single/button/buttons/button.text.js b/src/base/single/button/buttons/button.text.js index a7fed2d76..281047b55 100644 --- a/src/base/single/button/buttons/button.text.js +++ b/src/base/single/button/buttons/button.text.js @@ -10,7 +10,6 @@ import { shortcut, extend, createWidget } from "../../../../core"; */ @shortcut() export class TextButton extends BasicButton { - static xtype = "bi.text_button"; static EVENT_CHANGE = "EVENT_CHANGE"; @@ -18,7 +17,7 @@ export class TextButton extends BasicButton { const conf = super._defaultConfig(arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-text-button", + baseCls: `${conf.baseCls || ""} bi-text-button`, textAlign: "center", whiteSpace: "nowrap", textWidth: null, @@ -61,19 +60,19 @@ export class TextButton extends BasicButton { } doRedMark() { - this.text.doRedMark.apply(this.text, arguments); + this.text.doRedMark(...arguments); } unRedMark() { - this.text.unRedMark.apply(this.text, arguments); + this.text.unRedMark(...arguments); } doHighLight() { - this.text.doHighLight.apply(this.text, arguments); + this.text.doHighLight(...arguments); } unHighLight() { - this.text.unHighLight.apply(this.text, arguments); + this.text.unHighLight(...arguments); } setText(text) { diff --git a/src/base/single/button/index.js b/src/base/single/button/index.js index b483234a0..691aa85f7 100644 --- a/src/base/single/button/index.js +++ b/src/base/single/button/index.js @@ -14,4 +14,4 @@ export { TextItem } from "./listitem/textitem"; export { IconTextIconNode } from "./node/icontexticonnode"; export { IconTextNode } from "./node/icontextnode"; export { TextIconNode } from "./node/texticonnode"; -export { TextNode } from "./node/textnode"; \ No newline at end of file +export { TextNode } from "./node/textnode"; diff --git a/src/base/single/button/listitem/blankiconicontextitem.js b/src/base/single/button/listitem/blankiconicontextitem.js index b826fb558..2a471e7b7 100644 --- a/src/base/single/button/listitem/blankiconicontextitem.js +++ b/src/base/single/button/listitem/blankiconicontextitem.js @@ -1,5 +1,5 @@ -import { BasicButton } from "../button.basic" -import { emptyFn, shortcut } from "../../../../core" +import { BasicButton } from "../button.basic"; +import { shortcut } from "../../../../core"; /** * 带有一个占位 @@ -10,15 +10,14 @@ import { emptyFn, shortcut } from "../../../../core" */ @shortcut() export class BlankIconIconTextItem extends BasicButton { - static EVENT_CHANGE = "EVENT_CHANGE"; static xtype = "bi.blank_icon_icon_text_item"; _defaultConfig() { - var conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(arguments); return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-blank-icon-icon-text-item", + baseCls: `${conf.baseCls || ""} bi-blank-icon-icon-text-item`, iconCls1: "", iconCls2: "", blankWidth: 0, @@ -57,7 +56,7 @@ export class BlankIconIconTextItem extends BasicButton { }, { el: { type: "bi.label", - ref: (_ref) => { + ref: _ref => { this.text = _ref; }, textAlign: "left", @@ -89,7 +88,7 @@ export class BlankIconIconTextItem extends BasicButton { setValue() { if (!this.isReadOnly()) { - this.text.setValue.apply(this.text, arguments); + this.text.setValue(...arguments); } } @@ -98,7 +97,7 @@ export class BlankIconIconTextItem extends BasicButton { } setText() { - this.text.setText.apply(this.text, arguments); + this.text.setText(...arguments); } getText() { @@ -106,18 +105,18 @@ export class BlankIconIconTextItem extends BasicButton { } doRedMark() { - this.text.doRedMark.apply(this.text, arguments); + this.text.doRedMark(...arguments); } unRedMark() { - this.text.unRedMark.apply(this.text, arguments); + this.text.unRedMark(...arguments); } doHighLight() { - this.text.doHighLight.apply(this.text, arguments); + this.text.doHighLight(...arguments); } unHighLight() { - this.text.unHighLight.apply(this.text, arguments); + this.text.unHighLight(...arguments); } } diff --git a/src/base/single/button/listitem/blankicontexticonitem.js b/src/base/single/button/listitem/blankicontexticonitem.js index 91b7bcbe2..217906da8 100644 --- a/src/base/single/button/listitem/blankicontexticonitem.js +++ b/src/base/single/button/listitem/blankicontexticonitem.js @@ -1,5 +1,5 @@ -import { BasicButton } from "../button.basic" -import { emptyFn, shortcut, extend } from "../../../../core" +import { BasicButton } from "../button.basic"; +import { shortcut, extend } from "../../../../core"; /** * guy @@ -11,7 +11,6 @@ import { emptyFn, shortcut, extend } from "../../../../core" */ @shortcut() export class BlankIconTextIconItem extends BasicButton { - static xtype = "bi.blank_icon_text_icon_item"; static EVENT_CHANGE = "EVENT_CHANGE"; @@ -19,7 +18,7 @@ export class BlankIconTextIconItem extends BasicButton { const conf = super._defaultConfig(arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-blank-icon-text-icon-item", + baseCls: `${conf.baseCls || ""} bi-blank-icon-text-icon-item`, iconCls1: "", iconCls2: "", blankWidth: 0, @@ -51,7 +50,7 @@ export class BlankIconTextIconItem extends BasicButton { }, { el: { type: "bi.label", - ref: (_ref) => { + ref: _ref => { this.text = _ref; }, textAlign: "left", @@ -83,24 +82,24 @@ export class BlankIconTextIconItem extends BasicButton { } doRedMark() { - this.text.doRedMark.apply(this.text, arguments); + this.text.doRedMark(...arguments); } unRedMark() { - this.text.unRedMark.apply(this.text, arguments); + this.text.unRedMark(...arguments); } doHighLight() { - this.text.doHighLight.apply(this.text, arguments); + this.text.doHighLight(...arguments); } unHighLight() { - this.text.unHighLight.apply(this.text, arguments); + this.text.unHighLight(...arguments); } setValue() { if (!this.isReadOnly()) { - this.text.setValue.apply(this.text, arguments); + this.text.setValue(...arguments); } } @@ -109,7 +108,7 @@ export class BlankIconTextIconItem extends BasicButton { } setText() { - this.text.setText.apply(this.text, arguments); + this.text.setText(...arguments); } getText() { diff --git a/src/base/single/button/listitem/blankicontextitem.js b/src/base/single/button/listitem/blankicontextitem.js index fb63eb8fb..fd2b34d32 100644 --- a/src/base/single/button/listitem/blankicontextitem.js +++ b/src/base/single/button/listitem/blankicontextitem.js @@ -1,5 +1,5 @@ -import { BasicButton } from "../button.basic" -import { extend, shortcut } from "../../../../core" +import { BasicButton } from "../button.basic"; +import { extend, shortcut } from "../../../../core"; /** * 带有一个占位 @@ -10,7 +10,6 @@ import { extend, shortcut } from "../../../../core" */ @shortcut() export class BlankIconTextItem extends BasicButton { - static xtype = "bi.blank_icon_text_item"; static EVENT_CHANGE = "EVENT_CHANGE"; @@ -18,7 +17,7 @@ export class BlankIconTextItem extends BasicButton { const conf = super._defaultConfig(arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-blank-icon-text-item", + baseCls: `${conf.baseCls || ""} bi-blank-icon-text-item`, blankWidth: 0, iconHeight: null, iconWidth: null, @@ -49,7 +48,7 @@ export class BlankIconTextItem extends BasicButton { }, { el: { type: "bi.label", - ref: (_ref) => { + ref: _ref => { this.text = _ref; }, cls: "list-item-text", @@ -76,7 +75,7 @@ export class BlankIconTextItem extends BasicButton { setValue() { if (!this.isReadOnly()) { - this.text.setValue.apply(this.text, arguments); + this.text.setValue(...arguments); } } @@ -85,7 +84,7 @@ export class BlankIconTextItem extends BasicButton { } setText() { - this.text.setText.apply(this.text, arguments); + this.text.setText(...arguments); } getText() { @@ -93,18 +92,18 @@ export class BlankIconTextItem extends BasicButton { } doRedMark() { - this.text.doRedMark.apply(this.text, arguments); + this.text.doRedMark(...arguments); } unRedMark() { - this.text.unRedMark.apply(this.text, arguments); + this.text.unRedMark(...arguments); } doHighLight() { - this.text.doHighLight.apply(this.text, arguments); + this.text.doHighLight(...arguments); } unHighLight() { - this.text.unHighLight.apply(this.text, arguments); + this.text.unHighLight(...arguments); } } diff --git a/src/base/single/button/listitem/icontexticonitem.js b/src/base/single/button/listitem/icontexticonitem.js index 8aadfdd47..1209e8054 100644 --- a/src/base/single/button/listitem/icontexticonitem.js +++ b/src/base/single/button/listitem/icontexticonitem.js @@ -1,5 +1,5 @@ -import { BasicButton } from "../button.basic" -import { extend, shortcut } from "../../../../core" +import { BasicButton } from "../button.basic"; +import { extend, shortcut } from "../../../../core"; /** * guy @@ -12,7 +12,6 @@ import { extend, shortcut } from "../../../../core" @shortcut() export class IconTextIconItem extends BasicButton { - static EVENT_CHANGE = "EVENT_CHANGE"; static xtype = "bi.icon_text_icon_item"; @@ -20,7 +19,7 @@ export class IconTextIconItem extends BasicButton { const conf = super._defaultConfig(arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-icon-text-icon-item", + baseCls: `${conf.baseCls || ""} bi-icon-text-icon-item`, iconCls1: "", iconCls2: "", iconHeight: null, @@ -48,7 +47,7 @@ export class IconTextIconItem extends BasicButton { }, { el: { type: "bi.label", - ref: (_ref) => { + ref: _ref => { this.text = _ref; }, textAlign: "left", @@ -80,24 +79,24 @@ export class IconTextIconItem extends BasicButton { } doRedMark() { - this.text.doRedMark.apply(this.text, arguments); + this.text.doRedMark(...arguments); } unRedMark() { - this.text.unRedMark.apply(this.text, arguments); + this.text.unRedMark(...arguments); } doHighLight() { - this.text.doHighLight.apply(this.text, arguments); + this.text.doHighLight(...arguments); } unHighLight() { - this.text.unHighLight.apply(this.text, arguments); + this.text.unHighLight(...arguments); } setValue() { if (!this.isReadOnly()) { - this.text.setValue.apply(this.text, arguments); + this.text.setValue(...arguments); } } @@ -106,7 +105,7 @@ export class IconTextIconItem extends BasicButton { } setText() { - this.text.setText.apply(this.text, arguments); + this.text.setText(...arguments); } getText() { diff --git a/src/base/single/button/listitem/icontextitem.js b/src/base/single/button/listitem/icontextitem.js index 7aa02bdb3..70ce49654 100644 --- a/src/base/single/button/listitem/icontextitem.js +++ b/src/base/single/button/listitem/icontextitem.js @@ -1,5 +1,5 @@ -import { BasicButton } from "../button.basic" -import { extend, shortcut } from "../../../../core" +import { BasicButton } from "../button.basic"; +import { extend, shortcut } from "../../../../core"; /** * guy @@ -10,7 +10,6 @@ import { extend, shortcut } from "../../../../core" */ @shortcut() export class IconTextItem extends BasicButton { - static EVENT_CHANGE = "EVENT_CHANGE"; static xtype = "bi.icon_text_item"; @@ -18,7 +17,7 @@ export class IconTextItem extends BasicButton { const conf = super._defaultConfig(arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-icon-text-item", + baseCls: `${conf.baseCls || ""} bi-icon-text-item`, direction: BI.Direction.Left, iconWrapperWidth: null, iconHeight: null, @@ -47,7 +46,7 @@ export class IconTextItem extends BasicButton { }, { el: { type: "bi.label", - ref: (_ref) => { + ref: _ref => { this.text = _ref; }, cls: "list-item-text", @@ -74,7 +73,7 @@ export class IconTextItem extends BasicButton { setValue() { if (!this.isReadOnly()) { - this.text.setValue.apply(this.text, arguments); + this.text.setValue(...arguments); } } @@ -83,7 +82,7 @@ export class IconTextItem extends BasicButton { } setText() { - this.text.setText.apply(this.text, arguments); + this.text.setText(...arguments); } getText() { @@ -91,18 +90,18 @@ export class IconTextItem extends BasicButton { } doRedMark() { - this.text.doRedMark.apply(this.text, arguments); + this.text.doRedMark(...arguments); } unRedMark() { - this.text.unRedMark.apply(this.text, arguments); + this.text.unRedMark(...arguments); } doHighLight() { - this.text.doHighLight.apply(this.text, arguments); + this.text.doHighLight(...arguments); } unHighLight() { - this.text.unHighLight.apply(this.text, arguments); + this.text.unHighLight(...arguments); } } diff --git a/src/base/single/button/listitem/texticonitem.js b/src/base/single/button/listitem/texticonitem.js index a8b8077fd..db9b30478 100644 --- a/src/base/single/button/listitem/texticonitem.js +++ b/src/base/single/button/listitem/texticonitem.js @@ -1,5 +1,5 @@ -import { BasicButton } from "../button.basic" -import { extend, shortcut } from "../../../../core" +import { BasicButton } from "../button.basic"; +import { extend, shortcut } from "../../../../core"; /** * @@ -11,7 +11,6 @@ import { extend, shortcut } from "../../../../core" */ @shortcut() export class TextIconItem extends BasicButton { - static xtype = "bi.text_icon_item"; static EVENT_CHANGE = "EVENT_CHANGE" @@ -19,7 +18,7 @@ export class TextIconItem extends BasicButton { const conf = super._defaultConfig(arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-text-icon-item", + baseCls: `${conf.baseCls || ""} bi-text-icon-item`, iconWrapperWidth: null, iconHeight: null, iconWidth: null, @@ -40,7 +39,7 @@ export class TextIconItem extends BasicButton { items: [{ el: { type: "bi.label", - ref: function (_ref) { + ref (_ref) { self.text = _ref; }, cls: "list-item-text", @@ -74,7 +73,7 @@ export class TextIconItem extends BasicButton { setValue() { if (!this.isReadOnly()) { - this.text.setValue.apply(this.text, arguments); + this.text.setValue(...arguments); } } @@ -83,7 +82,7 @@ export class TextIconItem extends BasicButton { } setText() { - this.text.setText.apply(this.text, arguments); + this.text.setText(...arguments); } getText() { @@ -91,18 +90,18 @@ export class TextIconItem extends BasicButton { } doRedMark() { - this.text.doRedMark.apply(this.text, arguments); + this.text.doRedMark(...arguments); } unRedMark() { - this.text.unRedMark.apply(this.text, arguments); + this.text.unRedMark(...arguments); } doHighLight() { - this.text.doHighLight.apply(this.text, arguments); + this.text.doHighLight(...arguments); } unHighLight() { - this.text.unHighLight.apply(this.text, arguments); + this.text.unHighLight(...arguments); } } diff --git a/src/base/single/button/listitem/textitem.js b/src/base/single/button/listitem/textitem.js index 82fa1e7ea..a1bb719b5 100644 --- a/src/base/single/button/listitem/textitem.js +++ b/src/base/single/button/listitem/textitem.js @@ -1,5 +1,5 @@ -import { BasicButton } from "../button.basic" -import { extend, shortcut } from "../../../../core" +import { BasicButton } from "../button.basic"; +import { extend, shortcut } from "../../../../core"; /** * guy @@ -11,7 +11,6 @@ import { extend, shortcut } from "../../../../core" */ @shortcut export class TextItem extends BasicButton { - static xtype = "bi.text_item"; static EVENT_CHANGE = "EVENT_CHANGE"; @@ -19,7 +18,7 @@ export class TextItem extends BasicButton { const conf = super._defaultConfig(arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-text-item", + baseCls: `${conf.baseCls || ""} bi-text-item`, textAlign: "left", whiteSpace: "nowrap", textHgap: 0, @@ -57,24 +56,24 @@ export class TextItem extends BasicButton { } doRedMark() { - this.text.doRedMark.apply(this.text, arguments); + this.text.doRedMark(...arguments); } unRedMark() { - this.text.unRedMark.apply(this.text, arguments); + this.text.unRedMark(...arguments); } doHighLight() { - this.text.doHighLight.apply(this.text, arguments); + this.text.doHighLight(...arguments); } unHighLight() { - this.text.unHighLight.apply(this.text, arguments); + this.text.unHighLight(...arguments); } setValue() { if (!this.isReadOnly()) { - this.text.setValue.apply(this.text, arguments); + this.text.setValue(...arguments); } } @@ -83,7 +82,7 @@ export class TextItem extends BasicButton { } setText() { - this.text.setText.apply(this.text, arguments); + this.text.setText(...arguments); } getText() { diff --git a/src/base/single/button/node/icontexticonnode.js b/src/base/single/button/node/icontexticonnode.js index 7cbff7f74..a08b63c8d 100644 --- a/src/base/single/button/node/icontexticonnode.js +++ b/src/base/single/button/node/icontexticonnode.js @@ -1,5 +1,5 @@ -import { NodeButton } from "../button.node" -import { extend, shortcut } from "../../../../core" +import { NodeButton } from "../button.node"; +import { extend, shortcut } from "../../../../core"; /** * guy @@ -9,7 +9,6 @@ import { extend, shortcut } from "../../../../core" */ @shortcut() export class IconTextIconNode extends NodeButton { - static xtype = "bi.icon_text_icon_node"; static EVENT_CHANGE = "EVENT_CHANGE"; @@ -17,7 +16,7 @@ export class IconTextIconNode extends NodeButton { const conf = super._defaultConfig(arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-icon-text-icon-node", + baseCls: `${conf.baseCls || ""} bi-icon-text-icon-node`, iconCls1: "close-ha-font", iconCls2: "close-ha-font", iconHeight: null, @@ -45,7 +44,7 @@ export class IconTextIconNode extends NodeButton { }, { el: { type: "bi.label", - ref: (_ref) => { + ref: _ref => { this.text = _ref; }, textAlign: "left", @@ -77,16 +76,16 @@ export class IconTextIconNode extends NodeButton { } doRedMark() { - this.text.doRedMark.apply(this.text, arguments); + this.text.doRedMark(...arguments); } unRedMark() { - this.text.unRedMark.apply(this.text, arguments); + this.text.unRedMark(...arguments); } setValue() { if (!this.isReadOnly()) { - this.text.setValue.apply(this.text, arguments); + this.text.setValue(...arguments); } } @@ -95,7 +94,7 @@ export class IconTextIconNode extends NodeButton { } setText() { - this.text.setText.apply(this.text, arguments); + this.text.setText(...arguments); } getText() { diff --git a/src/base/single/button/node/icontextnode.js b/src/base/single/button/node/icontextnode.js index 6a6260432..5135030db 100644 --- a/src/base/single/button/node/icontextnode.js +++ b/src/base/single/button/node/icontextnode.js @@ -1,5 +1,5 @@ -import { NodeButton } from "../button.node" -import { extend, shortcut } from "../../../../core" +import { NodeButton } from "../button.node"; +import { extend, shortcut } from "../../../../core"; /** * guy @@ -9,7 +9,6 @@ import { extend, shortcut } from "../../../../core" */ @shortcut() export class IconTextNode extends NodeButton { - static EVENT_CHANGE = "EVENT_CHANGE"; static xtype = "bi.icon_text_node"; @@ -17,7 +16,7 @@ export class IconTextNode extends NodeButton { const conf = super._defaultConfig(arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-icon-text-node", + baseCls: `${conf.baseCls || ""} bi-icon-text-node`, cls: "close-ha-font", iconHeight: null, iconWidth: null, @@ -44,7 +43,7 @@ export class IconTextNode extends NodeButton { }, { el: { type: "bi.label", - ref: (_ref) => { + ref: _ref => { this.text = _ref; }, cls: "list-item-text", @@ -71,7 +70,7 @@ export class IconTextNode extends NodeButton { setValue() { if (!this.isReadOnly()) { - this.text.setValue.apply(this.text, arguments); + this.text.setValue(...arguments); } } @@ -80,7 +79,7 @@ export class IconTextNode extends NodeButton { } setText() { - this.text.setText.apply(this.text, arguments); + this.text.setText(...arguments); } getText() { @@ -88,11 +87,11 @@ export class IconTextNode extends NodeButton { } doRedMark() { - this.text.doRedMark.apply(this.text, arguments); + this.text.doRedMark(...arguments); } unRedMark() { - this.text.unRedMark.apply(this.text, arguments); + this.text.unRedMark(...arguments); } } diff --git a/src/base/single/button/node/texticonnode.js b/src/base/single/button/node/texticonnode.js index 02a205047..cc3f2dea8 100644 --- a/src/base/single/button/node/texticonnode.js +++ b/src/base/single/button/node/texticonnode.js @@ -1,5 +1,5 @@ -import { NodeButton } from "../button.node" -import { extend, shortcut } from "../../../../core" +import { NodeButton } from "../button.node"; +import { extend, shortcut } from "../../../../core"; /** * Created by GUY on 2015/9/9. @@ -8,7 +8,6 @@ import { extend, shortcut } from "../../../../core" */ @shortcut() export default class TextIconNode extends NodeButton { - static EVENT_CHANGE = "EVENT_CHANGE"; static xtype = "bi.text_icon_node"; @@ -16,7 +15,7 @@ export default class TextIconNode extends NodeButton { const conf = super._defaultConfig(arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-text-icon-node", + baseCls: `${conf.baseCls || ""} bi-text-icon-node`, cls: "close-ha-font", iconHeight: null, iconWidth: null, @@ -36,7 +35,7 @@ export default class TextIconNode extends NodeButton { items: [{ el: { type: "bi.label", - ref: (_ref) => { + ref: _ref => { this.text = _ref; }, cls: "list-item-text", @@ -70,7 +69,7 @@ export default class TextIconNode extends NodeButton { setValue() { if (!this.isReadOnly()) { - this.text.setValue.apply(this.text, arguments); + this.text.setValue(...arguments); } } @@ -79,7 +78,7 @@ export default class TextIconNode extends NodeButton { } setText() { - this.text.setText.apply(this.text, arguments); + this.text.setText(...arguments); } getText() { @@ -87,10 +86,10 @@ export default class TextIconNode extends NodeButton { } doRedMark() { - this.text.doRedMark.apply(this.text, arguments); + this.text.doRedMark(...arguments); } unRedMark() { - this.text.unRedMark.apply(this.text, arguments); + this.text.unRedMark(...arguments); } } diff --git a/src/base/single/button/node/textnode.js b/src/base/single/button/node/textnode.js index 80aadb0d3..e6e990cf7 100644 --- a/src/base/single/button/node/textnode.js +++ b/src/base/single/button/node/textnode.js @@ -1,5 +1,5 @@ -import { NodeButton } from "../button.node" -import { extend, shortcut } from "../../../../core" +import { NodeButton } from "../button.node"; +import { extend, shortcut } from "../../../../core"; /** * guy @@ -10,7 +10,6 @@ import { extend, shortcut } from "../../../../core" */ @shortcut() export class TextNode extends NodeButton { - static xtype = "bi.text_node" static EVENT_CHANGE = "EVENT_CHANGE" @@ -20,7 +19,7 @@ export class TextNode extends NodeButton { const conf = super._defaultConfig(arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-text-node", + baseCls: `${conf.baseCls || ""} bi-text-node`, textAlign: "left", whiteSpace: "nowrap", textHgap: 0, @@ -58,16 +57,16 @@ export class TextNode extends NodeButton { } doRedMark() { - this.text.doRedMark.apply(this.text, arguments); + this.text.doRedMark(...arguments); } unRedMark() { - this.text.unRedMark.apply(this.text, arguments); + this.text.unRedMark(...arguments); } setValue() { if (!this.isReadOnly()) { - this.text.setValue.apply(this.text, arguments); + this.text.setValue(...arguments); } } @@ -76,7 +75,7 @@ export class TextNode extends NodeButton { } setText() { - this.text.setText.apply(this.text, arguments); + this.text.setText(...arguments); } getText() { diff --git a/src/case/button/icon/icon.change.js b/src/case/button/icon/icon.change.js index e65160879..3e5ad6c46 100644 --- a/src/case/button/icon/icon.change.js +++ b/src/case/button/icon/icon.change.js @@ -1,15 +1,25 @@ +import { Single } from "../../../base/single/0.single"; +import { IconButton } from "../../../base/single/button/buttons/button.icon"; +import { shortcut, extend, emptyFn, isFunction, createWidget, Controller } from "../../../core"; + /** * 可以改变图标的button * * Created by GUY on 2016/2/2. * - * @class BI.IconChangeButton - * @extends BI.Single + * @class IconChangeButton + * @extends Single */ -BI.IconChangeButton = BI.inherit(BI.Single, { - _defaultConfig: function () { - var conf = BI.IconChangeButton.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { +@shortcut() +export class IconChangeButton extends Single { + static xtype = "bi.icon_change_button"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { baseCls: "bi-icon-change-button", iconCls: "", iconWidth: null, @@ -24,19 +34,19 @@ BI.IconChangeButton = BI.inherit(BI.Single, { disableSelected: false, // 使能选中 shadow: false, - isShadowShowingOnSelected: false, // 选中状态下是否显示阴影 + isShadowShowingOnSelected: false, // 选中状态下是否显示阴影 trigger: null, - handler: BI.emptyFn + handler: emptyFn, }); - }, + } - _init: function () { - var self = this, o = this.options; - o.iconCls = BI.isFunction(o.iconCls) ? this.__watch(o.iconCls, function (context, newValue) { - self.setIcon(newValue); + _init() { + const o = this.options; + o.iconCls = isFunction(o.iconCls) ? this.__watch(o.iconCls, (context, newValue) => { + this.setIcon(newValue); }) : o.iconCls; - BI.IconChangeButton.superclass._init.apply(this, arguments); - this.button = BI.createWidget({ + super._init.apply(this, arguments); + this.button = createWidget({ type: "bi.icon_button", element: this, cls: o.iconCls, @@ -55,32 +65,30 @@ BI.IconChangeButton = BI.inherit(BI.Single, { shadow: o.shadow, isShadowShowingOnSelected: o.isShadowShowingOnSelected, trigger: o.trigger, - handler: o.handler + handler: o.handler, }); - this.button.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.button.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, args); }); - this.button.on(BI.IconButton.EVENT_CHANGE, function () { - self.fireEvent(BI.IconChangeButton.EVENT_CHANGE, arguments); + this.button.on(IconButton.EVENT_CHANGE, (...args) => { + this.fireEvent(IconChangeButton.EVENT_CHANGE, args); }); - }, + } - isSelected: function () { + isSelected() { return this.button.isSelected(); - }, + } - setSelected: function (b) { + setSelected(b) { this.button.setSelected(b); - }, + } - setIcon: function (cls) { - var o = this.options; + setIcon(cls) { + const o = this.options; if (o.iconCls !== cls) { this.element.removeClass(o.iconCls).addClass(cls); o.iconCls = cls; } } -}); -BI.IconChangeButton.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.icon_change_button", BI.IconChangeButton); +} diff --git a/src/case/button/icon/icon.trigger.js b/src/case/button/icon/icon.trigger.js index daa76b121..1c799edd4 100644 --- a/src/case/button/icon/icon.trigger.js +++ b/src/case/button/icon/icon.trigger.js @@ -1,19 +1,24 @@ +import { IconButton } from "../../../base/single/button/buttons/button.icon"; +import { shortcut, extend } from "../../../core"; + /** * 统一的trigger图标按钮 * * Created by GUY on 2015/9/16. - * @class BI.TriggerIconButton - * @extends BI.IconButton + * @class TriggerIconButton + * @extends IconButton */ -BI.TriggerIconButton = BI.inherit(BI.IconButton, { - - _defaultConfig: function () { - var conf = BI.TriggerIconButton.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-trigger-icon-button overflow-hidden", - extraCls: "pull-down-font" +@shortcut() +export class TriggerIconButton extends IconButton { + static xtype = "bi.trigger_icon_button"; + EVENT_CHANGE = IconButton.EVENT_CHANGE; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-trigger-icon-button overflow-hidden`, + extraCls: "pull-down-font", }); } -}); -BI.TriggerIconButton.EVENT_CHANGE = BI.IconButton.EVENT_CHANGE; -BI.shortcut("bi.trigger_icon_button", BI.TriggerIconButton); +} diff --git a/src/case/button/icon/iconhalf/icon.half.image.js b/src/case/button/icon/iconhalf/icon.half.image.js index a9e9d0014..e165b4d23 100644 --- a/src/case/button/icon/iconhalf/icon.half.image.js +++ b/src/case/button/icon/iconhalf/icon.half.image.js @@ -1,21 +1,28 @@ +import { IconButton } from "../../../../base/single/button/buttons/button.icon"; +import { shortcut, extend } from "../../../../core"; + + /** * guy * @extends BI.Single * @type {*|void|Object} */ -BI.HalfIconButton = BI.inherit(BI.IconButton, { - _defaultConfig: function () { - var conf = BI.HalfIconButton.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { +@shortcut() +export class HalfIconButton extends IconButton { + static xtype = "bi.half_icon_button"; + static EVENT_CHANGE = IconButton.EVENT_CHANGE + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { extraCls: "bi-half-icon-button check-half-select-icon", height: 16, width: 16, iconWidth: 16, iconHeight: 16, - selected: false + selected: false, }); } -}); -BI.HalfIconButton.EVENT_CHANGE = BI.IconButton.EVENT_CHANGE; +} -BI.shortcut("bi.half_icon_button", BI.HalfIconButton); \ No newline at end of file diff --git a/src/case/button/icon/iconhalf/icon.half.js b/src/case/button/icon/iconhalf/icon.half.js index f8c23afc4..1efe6c110 100644 --- a/src/case/button/icon/iconhalf/icon.half.js +++ b/src/case/button/icon/iconhalf/icon.half.js @@ -1,22 +1,31 @@ +import { BasicButton } from "../../../../base/single/button/button.basic"; +import { shortcut, extend } from "../../../../core"; + /** * guy * @extends BI.Single * @type {*|void|Object} */ -BI.HalfButton = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - var conf = BI.HalfIconButton.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { +@shortcut() +export class HalfButton extends BasicButton { + static xtype = "bi.half_button"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { selected: false, width: 14, height: 14, iconWidth: 14, iconHeight: 14, }); - }, + } - render: function () { - var o = this.options; + render() { + const o = this.options; + return { type: "bi.center_adapt", items: [{ @@ -26,15 +35,12 @@ BI.HalfButton = BI.inherit(BI.BasicButton, { height: o.iconHeight, }], }; - }, + } - doClick: function () { - BI.HalfButton.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); if (this.isValid()) { - this.fireEvent(BI.HalfButton.EVENT_CHANGE); + this.fireEvent(HalfButton.EVENT_CHANGE); } } -}); -BI.HalfButton.EVENT_CHANGE = "EVENT_CHANGE"; - -BI.shortcut("bi.half_button", BI.HalfButton); +} diff --git a/src/case/button/index.js b/src/case/button/index.js new file mode 100644 index 000000000..f19d10b13 --- /dev/null +++ b/src/case/button/index.js @@ -0,0 +1,29 @@ +export { MultiSelectItem } from "./item.multiselect"; +export { SingleSelectIconTextItem } from "./item.singleselect.icontext"; +export { SingleSelectItem } from "./item.singleselect"; +export { SingleSelectRadioItem } from "./item.singleselect.radio"; +export { Switch } from "./switch"; + +export { IconChangeButton } from "./icon/icon.change"; +export { TriggerIconButton } from "./icon/icon.trigger"; +export { HalfIconButton } from "./icon/iconhalf/icon.half.image"; +export { HalfButton } from "./icon/iconhalf/icon.half"; + +export { ArrowNode } from "./node/node.arrow"; +export { FirstPlusGroupNode } from "./node/node.first.plus"; +export { IconArrowNode } from "./node/node.icon.arrow"; +export { LastPlusGroupNode } from "./node/node.last.plus"; +export { MidPlusGroupNode } from "./node/node.mid.plus"; +export { MultiLayerIconArrowNode } from "./node/node.multilayer.icon.arrow"; +export { PlusGroupNode } from "./node/node.plus"; +export { TreeNodeSwitcher } from "./node/siwtcher.tree.node"; +export { BasicTreeNode } from "./node/treenode"; + +export { FirstTreeLeafItem } from "./treeitem/item.first.treeleaf"; +export { IconTreeLeafItem } from "./treeitem/item.icon.treeleaf"; +export { LastTreeLeafItem } from "./treeitem/item.last.treeleaf"; +export { MidTreeLeafItem } from "./treeitem/item.mid.treeleaf"; +export { MultiLayerIconTreeLeafItem } from "./treeitem/item.multilayer.icon.treeleaf"; +export { RootTreeLeafItem } from "./treeitem/item.root.treeleaf"; +export { TreeTextLeafItem } from "./treeitem/item.treetextleaf"; +export { BasicTreeItem } from "./treeitem/treeitem"; diff --git a/src/case/button/item.multiselect.js b/src/case/button/item.multiselect.js index b90fafac5..df74642c9 100644 --- a/src/case/button/item.multiselect.js +++ b/src/case/button/item.multiselect.js @@ -1,36 +1,45 @@ +import { BasicButton } from "../../base/single/button/button.basic"; +import { shortcut, extend, createWidget } from "../../core"; + /** * guy * 复选框item * @type {*|void|Object} */ -BI.MultiSelectItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - return BI.extend(BI.MultiSelectItem.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class MultiSelectItem extends BasicButton { + static xtype = "bi.multi_select_item"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { extraCls: "bi-multi-select-item", attributes: { - tabIndex: 1 + tabIndex: 1, }, height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, iconWrapperWidth: 26, }); - }, + } - render: function () { - var self = this, o = this.options; - this.checkbox = BI.createWidget({ - type: "bi.checkbox" + render() { + const o = this.options; + this.checkbox = createWidget({ + type: "bi.checkbox", }); + return { type: "bi.vertical_adapt", columnSize: [o.iconWrapperWidth || o.height, "fill"], items: [{ type: "bi.center_adapt", - items: [this.checkbox] + items: [this.checkbox], }, { el: { type: "bi.label", - ref: function (_ref) { - self.text = _ref; + ref: _ref => { + this.text = _ref; }, cls: "list-item-text", textAlign: "left", @@ -44,11 +53,11 @@ BI.MultiSelectItem = BI.inherit(BI.BasicButton, { text: o.text, keyword: o.keyword, value: o.value, - py: o.py - } - }] + py: o.py, + }, + }], }; - }, + } // _setEnable: function (enable) { // BI.MultiSelectItem.superclass._setEnable.apply(this, arguments); @@ -59,25 +68,24 @@ BI.MultiSelectItem = BI.inherit(BI.BasicButton, { // } // }, - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doClick: function () { + doClick() { BI.MultiSelectItem.superclass.doClick.apply(this, arguments); if (this.isValid()) { this.fireEvent(BI.MultiSelectItem.EVENT_CHANGE, this.getValue(), this); } - }, + } - setSelected: function (v) { + setSelected(v) { BI.MultiSelectItem.superclass.setSelected.apply(this, arguments); this.checkbox.setSelected(v); } -}); -BI.MultiSelectItem.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multi_select_item", BI.MultiSelectItem); +} + diff --git a/src/case/button/item.singleselect.icontext.js b/src/case/button/item.singleselect.icontext.js index 47960e9fa..d92f59050 100644 --- a/src/case/button/item.singleselect.icontext.js +++ b/src/case/button/item.singleselect.icontext.js @@ -1,24 +1,30 @@ +import { Single } from "../../base/single/0.single"; +import { shortcut, extend, createWidget, Controller } from "../../core"; + /** * Created by GUY on 2016/2/2. * * @class BI.SingleSelectIconTextItem * @extends BI.BasicButton */ -BI.SingleSelectIconTextItem = BI.inherit(BI.Single, { - _defaultConfig: function () { - return BI.extend(BI.SingleSelectIconTextItem.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class SingleSelectIconTextItem extends Single { + static xtype = "bi.single_select_icon_text_item"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { extraCls: "bi-single-select-icon-text-item bi-list-item-active", attributes: { - tabIndex: 1 + tabIndex: 1, }, iconCls: "", - height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, }); - }, + } - render: function () { - var self = this, o = this.options; - this.text = BI.createWidget({ + render() { + const o = this.options; + this.text = createWidget({ type: "bi.icon_text_item", element: this, cls: o.iconCls, @@ -35,37 +41,37 @@ BI.SingleSelectIconTextItem = BI.inherit(BI.Single, { text: o.text, keyword: o.keyword, value: o.value, - py: o.py + py: o.py, }); - this.text.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.text.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - }, + } - _setEnable: function (enable) { - BI.SingleSelectIconTextItem.superclass._setEnable.apply(this, arguments); + _setEnable(enable) { + super._setEnable.apply(this, arguments); if (enable === true) { this.element.attr("tabIndex", 1); } else if (enable === false) { this.element.removeAttr("tabIndex"); } - }, + } - isSelected: function () { + isSelected() { return this.text.isSelected(); - }, + } - setSelected: function (b) { + setSelected(b) { this.text.setSelected(b); - }, + } - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); + unRedMark() { + this.text.unRedMark(...arguments); } -}); +} + -BI.shortcut("bi.single_select_icon_text_item", BI.SingleSelectIconTextItem); diff --git a/src/case/button/item.singleselect.js b/src/case/button/item.singleselect.js index 50a1cf6db..9b3e682c7 100644 --- a/src/case/button/item.singleselect.js +++ b/src/case/button/item.singleselect.js @@ -1,19 +1,26 @@ -BI.SingleSelectItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - return BI.extend(BI.SingleSelectItem.superclass._defaultConfig.apply(this, arguments), { +import { BasicButton } from "../../base/single/button/button.basic"; +import { shortcut, extend, createWidget } from "../../core"; + +@shortcut() +export class SingleSelectItem extends BasicButton { + static xtype = "bi.single_select_item"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { extraCls: "bi-single-select-item bi-list-item-active", attributes: { - tabIndex: 1 + tabIndex: 1, }, textHgap: 10, height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - textAlign: "left" + textAlign: "left", }); - }, + } - render: function () { - var self = this, o = this.options; - this.text = BI.createWidget({ + render() { + const o = this.options; + this.text = createWidget({ type: "bi.label", element: this, textAlign: o.textAlign, @@ -27,38 +34,38 @@ BI.SingleSelectItem = BI.inherit(BI.BasicButton, { text: o.text, keyword: o.keyword, value: o.value, - py: o.py + py: o.py, }); - }, + } - _setEnable: function (enable) { - BI.SingleSelectItem.superclass._setEnable.apply(this, arguments); + _setEnable(enable) { + super._setEnable.apply(this, arguments); if (enable === true) { this.element.attr("tabIndex", 1); } else if (enable === false) { this.element.removeAttr("tabIndex"); } - }, + } - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doClick: function () { - BI.SingleSelectItem.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); if (this.isValid()) { - this.fireEvent(BI.SingleSelectItem.EVENT_CHANGE, this.isSelected(), this); + this.fireEvent(SingleSelectItem.EVENT_CHANGE, this.isSelected(), this); } - }, + } - setSelected: function (v) { - BI.SingleSelectItem.superclass.setSelected.apply(this, arguments); + setSelected(v) { + super.setSelected.apply(this, arguments); } -}); +} + + -BI.SingleSelectItem.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.single_select_item", BI.SingleSelectItem); diff --git a/src/case/button/item.singleselect.radio.js b/src/case/button/item.singleselect.radio.js index 74ebe49c9..19a04f120 100644 --- a/src/case/button/item.singleselect.radio.js +++ b/src/case/button/item.singleselect.radio.js @@ -1,23 +1,31 @@ +import { BasicButton } from "../../base/single/button/button.basic"; +import { shortcut, extend } from "../../core"; + /** * guy * 单选框item * @type {*|void|Object} */ -BI.SingleSelectRadioItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - return BI.extend(BI.SingleSelectRadioItem.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class SingleSelectRadioItem extends BasicButton { + static xtype = "bi.single_select_radio_item"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { extraCls: "bi-single-select-radio-item", attributes: { - tabIndex: 1 + tabIndex: 1, }, height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, iconWrapperWidth: 16, textHgap: 10, }); - }, + } + + render() { + const o = this.options; - render: function () { - var self = this, o = this.options; return { type: "bi.vertical_adapt", columnSize: [o.iconWrapperWidth || o.height, "fill"], @@ -25,15 +33,15 @@ BI.SingleSelectRadioItem = BI.inherit(BI.BasicButton, { type: "bi.center_adapt", items: [{ type: "bi.radio", - ref: function (_ref) { - self.radio = _ref; + ref: _ref => { + this.radio = _ref; }, - }] + }], }, { el: { type: "bi.label", - ref: function (_ref) { - self.text = _ref; + ref: _ref => { + this.text = _ref; }, cls: "list-item-text", textAlign: "left", @@ -47,42 +55,39 @@ BI.SingleSelectRadioItem = BI.inherit(BI.BasicButton, { text: o.text, keyword: o.keyword, value: o.value, - py: o.py - } - }] + py: o.py, + }, + }], }; - }, + } - _setEnable: function (enable) { - BI.SingleSelectRadioItem.superclass._setEnable.apply(this, arguments); + _setEnable(enable) { + super._setEnable.apply(this, arguments); if (enable === true) { this.element.attr("tabIndex", 1); } else if (enable === false) { this.element.removeAttr("tabIndex"); } - }, + } - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doClick: function () { + doClick() { BI.SingleSelectRadioItem.superclass.doClick.apply(this, arguments); if (this.isValid()) { this.fireEvent(BI.SingleSelectRadioItem.EVENT_CHANGE, this.isSelected(), this); } - }, + } - setSelected: function (v) { + setSelected(v) { BI.SingleSelectRadioItem.superclass.setSelected.apply(this, arguments); this.radio.setSelected(v); - } -}); +} -BI.SingleSelectRadioItem.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.single_select_radio_item", BI.SingleSelectRadioItem); diff --git a/src/case/button/node/node.arrow.js b/src/case/button/node/node.arrow.js index d0b21ca7c..08cc58605 100644 --- a/src/case/button/node/node.arrow.js +++ b/src/case/button/node/node.arrow.js @@ -1,34 +1,42 @@ +import { NodeButton } from "../../../base/single/button/button.node"; +import { shortcut, extend, createWidget } from "../../../core"; + /** * Created by roy on 15/10/16. */ -BI.ArrowNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.ArrowNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-arrow-group-node bi-list-item", +@shortcut() +export class ArrowNode extends NodeButton { + static xtype = "bi.arrow_group_node"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-arrow-group-node bi-list-item`, id: "", pId: "", open: false, height: 24, - iconWrapperWidth: 16 + iconWrapperWidth: 16, }); - }, + } - render: function () { - var self = this, o = this.options; - this.checkbox = BI.createWidget({ + render() { + const o = this.options; + this.checkbox = createWidget({ type: "bi.arrow_group_node_checkbox", expandIcon: o.expandIcon, collapseIcon: o.collapseIcon, }); + return { type: "bi.vertical_adapt", columnSize: [o.iconWrapperWidth || o.height, "fill"], items: [this.checkbox, { el: { type: "bi.label", - ref: function (_ref) { - self.text = _ref; + ref: _ref => { + this.text = _ref; }, textAlign: "left", whiteSpace: "nowrap", @@ -41,34 +49,33 @@ BI.ArrowNode = BI.inherit(BI.NodeButton, { text: o.text, value: o.value, py: o.py, - keyword: o.keyword - } - }] + keyword: o.keyword, + }, + }], }; - }, + } - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doClick: function () { - BI.ArrowNode.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); this.checkbox.setSelected(this.isOpened()); - }, + } - setText: function (text) { - BI.ArrowNode.superclass.setText.apply(this, arguments); + setText(text) { + super.setText.apply(this, arguments); this.text.setText(text); - }, + } - setOpened: function (v) { - BI.ArrowNode.superclass.setOpened.apply(this, arguments); + setOpened(v) { + super.setOpened.apply(this, arguments); this.checkbox.setSelected(v); } -}); +} -BI.shortcut("bi.arrow_group_node", BI.ArrowNode); diff --git a/src/case/button/node/node.first.plus.js b/src/case/button/node/node.first.plus.js index 989cdec0b..60a266d49 100644 --- a/src/case/button/node/node.first.plus.js +++ b/src/case/button/node/node.first.plus.js @@ -1,33 +1,42 @@ +import { NodeButton } from "../../../base/single/button/button.node"; +import { shortcut, extend, createWidget, Controller } from "../../../core"; + + /** * 加号表示的组节点 * Created by GUY on 2015/9/6. - * @class BI.FirstPlusGroupNode - * @extends BI.NodeButton + * @class FirstPlusGroupNode + * @extends NodeButton */ -BI.FirstPlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.FirstPlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-first-plus-group-node bi-list-item", +@shortcut() +export class FirstPlusGroupNode extends NodeButton { + static xtype = "bi.first_plus_group_node"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-first-plus-group-node bi-list-item`, logic: { - dynamic: false + dynamic: false, }, id: "", pId: "", open: false, - height: 24 + height: 24, }); - }, - _init: function () { - BI.FirstPlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.checkbox = BI.createWidget({ + } + + _init() { + super._init.apply(this, arguments); + const o = this.options; + this.checkbox = createWidget({ type: "bi.first_tree_node_checkbox", stopPropagation: true, iconHeight: o.height, - iconWidth: o.height + iconWidth: o.height, }); - this.text = BI.createWidget({ + this.text = createWidget({ type: "bi.label", textAlign: "left", whiteSpace: "nowrap", @@ -37,9 +46,9 @@ BI.FirstPlusGroupNode = BI.inherit(BI.NodeButton, { text: o.text, value: o.value, py: o.py, - keyword: o.keyword + keyword: o.keyword, }); - this.checkbox.on(BI.Controller.EVENT_CHANGE, function (type) { + this.checkbox.on(Controller.EVENT_CHANGE, function (type) { if (type === BI.Events.CLICK) { if (this.isSelected()) { self.triggerExpand(); @@ -48,37 +57,36 @@ BI.FirstPlusGroupNode = BI.inherit(BI.NodeButton, { } } }); - var type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - var items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { + const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); + const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: this.checkbox + el: this.checkbox, }, this.text); BI.createWidget(BI.extend({ - element: this + element: this, }, BI.LogicFactory.createLogic(type, BI.extend(o.logic, { - items: items + items, })))); - }, + } - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doClick: function () { - BI.FirstPlusGroupNode.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); this.checkbox.setSelected(this.isSelected()); - }, + } - setOpened: function (v) { - BI.FirstPlusGroupNode.superclass.setOpened.apply(this, arguments); + setOpened(v) { + super.setOpened.apply(this, arguments); if (BI.isNotNull(this.checkbox)) { this.checkbox.setSelected(v); } } -}); +} -BI.shortcut("bi.first_plus_group_node", BI.FirstPlusGroupNode); diff --git a/src/case/button/node/node.icon.arrow.js b/src/case/button/node/node.icon.arrow.js index d641e655d..2aa910a9b 100644 --- a/src/case/button/node/node.icon.arrow.js +++ b/src/case/button/node/node.icon.arrow.js @@ -1,18 +1,24 @@ +import { NodeButton } from "../../../base/single/button/button.node"; +import { shortcut, extend, createWidget, Controller } from "../../../core"; + /** * Created by User on 2016/3/31. - */ -/** + * * > + icon + 文本 - * @class BI.IconArrowNode - * @extends BI.NodeButton + * @class IconArrowNode + * @extends NodeButton */ -BI.IconArrowNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.IconArrowNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-icon-arrow-node bi-list-item", +@shortcut() +export class IconArrowNode extends NodeButton { + static xtype = "bi.icon_arrow_node"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-icon-arrow-node bi-list-item`, logic: { - dynamic: false + dynamic: false, }, id: "", pId: "", @@ -21,29 +27,30 @@ BI.IconArrowNode = BI.inherit(BI.NodeButton, { iconHeight: 12, iconWidth: 12, iconCls: "", - iconWrapperWidth: 16 + iconWrapperWidth: 16, }); - }, - _init: function () { - BI.IconArrowNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.checkbox = BI.createWidget({ + } + + _init() { + super._init.apply(this, arguments); + const o = this.options; + this.checkbox = createWidget({ type: "bi.arrow_group_node_checkbox", expandIcon: o.expandIcon, collapseIcon: o.collapseIcon, width: 24, - stopPropagation: true + stopPropagation: true, }); - var icon = BI.createWidget({ + const icon = createWidget({ type: "bi.icon_label", width: 24, cls: o.iconCls, iconWidth: o.iconWidth, - iconHeight: o.iconHeight + iconHeight: o.iconHeight, }); - this.text = BI.createWidget({ + createWidget({ type: "bi.label", textAlign: "left", whiteSpace: "nowrap", @@ -53,52 +60,50 @@ BI.IconArrowNode = BI.inherit(BI.NodeButton, { text: o.text, value: o.value, py: o.py, - keyword: o.keyword + keyword: o.keyword, }); - this.checkbox.on(BI.Controller.EVENT_CHANGE, function (type) { + this.checkbox.on(Controller.EVENT_CHANGE, type => { if (type === BI.Events.CLICK) { - if (this.isSelected()) { - self.triggerExpand(); + if (this.checkbox.isSelected()) { + this.triggerExpand(); } else { - self.triggerCollapse(); + this.triggerCollapse(); } } }); - var type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - var items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { + const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); + const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { width: o.iconWrapperWidth, - el: this.checkbox + el: this.checkbox, }, { width: 16, - el: icon + el: icon, }, this.text); - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic(type, BI.extend(o.logic, { - items: items, - rgap: 5 + createWidget(extend({ + element: this, + }, BI.LogicFactory.createLogic(type, extend(o.logic, { + items, + rgap: 5, })))); - }, + } - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + doRedMark () { + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doClick: function () { + doClick() { BI.IconArrowNode.superclass.doClick.apply(this, arguments); this.checkbox.setSelected(this.isSelected()); - }, + } - setOpened: function (v) { + setOpened(v) { BI.IconArrowNode.superclass.setOpened.apply(this, arguments); if (BI.isNotNull(this.checkbox)) { this.checkbox.setSelected(v); } } -}); - -BI.shortcut("bi.icon_arrow_node", BI.IconArrowNode); +} diff --git a/src/case/button/node/node.last.plus.js b/src/case/button/node/node.last.plus.js index c1a949e3b..0dba75eaf 100644 --- a/src/case/button/node/node.last.plus.js +++ b/src/case/button/node/node.last.plus.js @@ -1,33 +1,40 @@ +import { NodeButton } from "../../../base/single/button/button.node"; +import { shortcut, extend, createWidget, isNotNull } from "../../../core"; + /** * 加号表示的组节点 * Created by GUY on 2015/9/6. - * @class BI.LastPlusGroupNode - * @extends BI.NodeButton + * @class LastPlusGroupNode + * @extends NodeButton */ -BI.LastPlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.LastPlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-last-plus-group-node bi-list-item", +@shortcut() +export class LastPlusGroupNode extends NodeButton { + static xtype = "bi.last_plus_group_node"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-last-plus-group-node bi-list-item`, logic: { - dynamic: false + dynamic: false, }, id: "", pId: "", open: false, - height: 24 + height: 24, }); - }, - _init: function () { + } + _init() { BI.LastPlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.checkbox = BI.createWidget({ + const o = this.options; + this.checkbox = createWidget({ type: "bi.last_tree_node_checkbox", stopPropagation: true, iconHeight: o.height, - iconWidth: o.height + iconWidth: o.height, }); - this.text = BI.createWidget({ + this.text = createWidget({ type: "bi.label", textAlign: "left", whiteSpace: "nowrap", @@ -37,48 +44,46 @@ BI.LastPlusGroupNode = BI.inherit(BI.NodeButton, { text: o.text, value: o.value, py: o.py, - keyword: o.keyword + keyword: o.keyword, }); - this.checkbox.on(BI.Controller.EVENT_CHANGE, function (type) { - if(type === BI.Events.CLICK) { - if (this.isSelected()) { - self.triggerExpand(); + this.checkbox.on(BI.Controller.EVENT_CHANGE, type => { + if (type === BI.Events.CLICK) { + if (this.checkbox.isSelected()) { + this.triggerExpand(); } else { - self.triggerCollapse(); + this.triggerCollapse(); } } }); - var type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - var items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { + const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); + const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: this.checkbox + el: this.checkbox, }, this.text); - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic(type, BI.extend(o.logic, { - items: items + createWidget(extend({ + element: this, + }, BI.LogicFactory.createLogic(type, extend(o.logic, { + items, })))); - }, + } - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doClick: function () { - BI.LastPlusGroupNode.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); this.checkbox.setSelected(this.isSelected()); - }, + } - setOpened: function (v) { - BI.LastPlusGroupNode.superclass.setOpened.apply(this, arguments); - if (BI.isNotNull(this.checkbox)) { + setOpened(v) { + super.setOpened.apply(this, arguments); + if (isNotNull(this.checkbox)) { this.checkbox.setSelected(v); } } -}); - -BI.shortcut("bi.last_plus_group_node", BI.LastPlusGroupNode); \ No newline at end of file +} diff --git a/src/case/button/node/node.mid.plus.js b/src/case/button/node/node.mid.plus.js index 839565114..94ce8b1b9 100644 --- a/src/case/button/node/node.mid.plus.js +++ b/src/case/button/node/node.mid.plus.js @@ -1,33 +1,41 @@ +import { NodeButton } from "../../../base/single/button/button.node"; +import { shortcut, extend, createWidget, Controller } from "../../../core"; + /** * 加号表示的组节点 * Created by GUY on 2015/9/6. * @class BI.MidPlusGroupNode * @extends BI.NodeButton */ -BI.MidPlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.MidPlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-mid-plus-group-node bi-list-item", +@shortcut +export class MidPlusGroupNode extends NodeButton { + static xtype = "bi.mid_plus_group_node"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-mid-plus-group-node bi-list-item`, logic: { - dynamic: false + dynamic: false, }, id: "", pId: "", open: false, - height: 24 + height: 24, }); - }, - _init: function () { - BI.MidPlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.checkbox = BI.createWidget({ + } + + _init() { + super._init.apply(this, arguments); + const o = this.options; + this.checkbox = createWidget({ type: "bi.mid_tree_node_checkbox", stopPropagation: true, iconHeight: o.height, - iconWidth: o.height + iconWidth: o.height, }); - this.text = BI.createWidget({ + this.text = createWidget({ type: "bi.label", textAlign: "left", whiteSpace: "nowrap", @@ -37,48 +45,47 @@ BI.MidPlusGroupNode = BI.inherit(BI.NodeButton, { text: o.text, value: o.value, py: o.py, - keyword: o.keyword + keyword: o.keyword, }); - this.checkbox.on(BI.Controller.EVENT_CHANGE, function (type) { + this.checkbox.on(Controller.EVENT_CHANGE, type => { if (type === BI.Events.CLICK) { - if (this.isSelected()) { - self.triggerExpand(); + if (this.checkbox.isSelected()) { + this.triggerExpand(); } else { - self.triggerCollapse(); + this.triggerCollapse(); } } }); - var type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - var items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { + const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); + const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: this.checkbox + el: this.checkbox, }, this.text); - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic(type, BI.extend(o.logic, { - items: items + createWidget(extend({ + element: this, + }, BI.LogicFactory.createLogic(type, extend(o.logic, { + items, })))); - }, + } - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doClick: function () { - BI.MidPlusGroupNode.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); this.checkbox.setSelected(this.isSelected()); - }, + } - setOpened: function (v) { + setOpened(v) { BI.MidPlusGroupNode.superclass.setOpened.apply(this, arguments); if (BI.isNotNull(this.checkbox)) { this.checkbox.setSelected(v); } } -}); +} -BI.shortcut("bi.mid_plus_group_node", BI.MidPlusGroupNode); \ No newline at end of file diff --git a/src/case/button/node/node.multilayer.icon.arrow.js b/src/case/button/node/node.multilayer.icon.arrow.js index ffa9c50ea..c1a9b35da 100644 --- a/src/case/button/node/node.multilayer.icon.arrow.js +++ b/src/case/button/node/node.multilayer.icon.arrow.js @@ -1,7 +1,14 @@ -BI.MultiLayerIconArrowNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.MultiLayerIconArrowNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { +import { NodeButton } from "../../../base/single/button/button.node"; +import { shortcut, extend, createWidget, Controller, count } from "../../../core"; + +@shortcut() +export class MultiLayerIconArrowNode extends NodeButton { + static xtype = "bi.multilayer_icon_arrow_node"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { extraCls: "bi-multilayer-icon-arrow-node bi-list-item", layer: 0, // 第几层级 id: "", @@ -10,13 +17,14 @@ BI.MultiLayerIconArrowNode = BI.inherit(BI.NodeButton, { height: 24, iconHeight: 16, iconWidth: 16, - iconCls: "" + iconCls: "", }); - }, - _init: function () { - BI.MultiLayerIconArrowNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.node = BI.createWidget({ + } + + _init() { + super._init.apply(this, arguments); + const o = this.options; + this.node = createWidget({ type: "bi.icon_arrow_node", iconCls: o.iconCls, cls: "bi-list-item-none", @@ -30,60 +38,58 @@ BI.MultiLayerIconArrowNode = BI.inherit(BI.NodeButton, { text: o.text, value: o.value, py: o.py, - keyword: o.keyword + keyword: o.keyword, }); - this.node.on(BI.Controller.EVENT_CHANGE, function (type) { - self.setSelected(self.isSelected()); - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.node.on(Controller.EVENT_CHANGE, (...args) => { + this.setSelected(this.isSelected()); + this.fireEvent(Controller.EVENT_CHANGE, args); }); - var items = []; - BI.count(0, o.layer, function () { + const items = []; + count(0, o.layer, () => { items.push({ type: "bi.layout", width: 15, - height: o.height + height: o.height, }); }); items.push(this.node); - BI.createWidget({ + createWidget({ type: "bi.horizontal_adapt", element: this, columnSize: BI.makeArray(o.layer, 15), - items: items + items, }); - }, + } - isOnce: function () { + isOnce() { return true; - }, + } - doRedMark: function () { - this.node.doRedMark.apply(this.node, arguments); - }, + doRedMark() { + this.node.doRedMark(...arguments); + } - unRedMark: function () { - this.node.unRedMark.apply(this.node, arguments); - }, + unRedMark() { + this.node.unRedMark(...arguments); + } - isSelected: function () { + isSelected() { return this.node.isSelected(); - }, + } - setSelected: function (b) { - BI.MultiLayerIconArrowNode.superclass.setSelected.apply(this, arguments); + setSelected(b) { + super.setSelected.apply(this, arguments); this.node.setSelected(b); - }, + } - doClick: function () { - BI.NodeButton.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); this.node.setSelected(this.isSelected()); - }, + } - setOpened: function (v) { - BI.MultiLayerIconArrowNode.superclass.setOpened.apply(this, arguments); + setOpened(v) { + super.setOpened.apply(this, arguments); this.node.setOpened(v); } -}); - -BI.shortcut("bi.multilayer_icon_arrow_node", BI.MultiLayerIconArrowNode); +} diff --git a/src/case/button/node/node.plus.js b/src/case/button/node/node.plus.js index 4b9477ea7..f3f08b0cf 100644 --- a/src/case/button/node/node.plus.js +++ b/src/case/button/node/node.plus.js @@ -1,42 +1,51 @@ +import { NodeButton } from "../../../base/single/button/button.node"; +import { shortcut, extend, createWidget, Controller } from "../../../core"; + /** * 加号表示的组节点 * Created by GUY on 2015/9/6. - * @class BI.PlusGroupNode - * @extends BI.NodeButton + * @class PlusGroupNode + * @extends NodeButton */ -BI.PlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.PlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-plus-group-node bi-list-item", +@shortcut() +export class PlusGroupNode extends NodeButton { + static xtype = "bi.plus_group_node"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-plus-group-node bi-list-item`, id: "", pId: "", open: false, - height: 24 + height: 24, }); - }, + } - render: function () { - var self = this, o = this.options; - this.checkbox = BI.createWidget({ + render() { + const o = this.options; + this.checkbox = createWidget({ type: "bi.tree_node_checkbox", iconHeight: o.height, - iconWidth: o.iconWrapperWidth || o.height + iconWidth: o.iconWrapperWidth || o.height, }); - this.checkbox.on(BI.Controller.EVENT_CHANGE, function (type) { + this.checkbox.on(Controller.EVENT_CHANGE, (...args) => { + const [type] = args; if (type === BI.Events.CLICK) { - self.setSelected(self.isSelected()); + this.setSelected(this.isSelected()); } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.fireEvent(Controller.EVENT_CHANGE, args); }); + return { type: "bi.vertical_adapt", columnSize: [o.iconWrapperWidth || o.height, "fill"], items: [this.checkbox, { el: { type: "bi.label", - ref: function (_ref) { - self.text = _ref; + ref: _ref => { + this.text = _ref; }, textAlign: "left", whiteSpace: "nowrap", @@ -49,31 +58,29 @@ BI.PlusGroupNode = BI.inherit(BI.NodeButton, { text: o.text, value: o.value, keyword: o.keyword, - py: o.py - } - }] + py: o.py, + }, + }], }; - }, + } - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doClick: function () { - BI.PlusGroupNode.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick.apply(this, arguments); this.checkbox.setSelected(this.isSelected()); - }, + } - setOpened: function (v) { - BI.PlusGroupNode.superclass.setOpened.apply(this, arguments); + setOpened(v) { + super.setOpened.apply(this, arguments); if (this.checkbox) { this.checkbox.setSelected(v); } } -}); - -BI.shortcut("bi.plus_group_node", BI.PlusGroupNode); +} diff --git a/src/case/button/node/siwtcher.tree.node.js b/src/case/button/node/siwtcher.tree.node.js index 8669f697b..46519ecb5 100644 --- a/src/case/button/node/siwtcher.tree.node.js +++ b/src/case/button/node/siwtcher.tree.node.js @@ -1,17 +1,23 @@ -BI.TreeNodeSwitcher = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - return BI.extend(BI.TreeNodeSwitcher.superclass._defaultConfig.apply(this, arguments), { +import { NodeButton } from "../../../base/single/button/button.node"; +import { shortcut, extend } from "../../../core"; + +@shortcut() +export class TreeNodeSwitcher extends NodeButton { + static xtype = "bi.tree_node_switcher"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { baseCls: "bi-tree-node-switcher", iconWidth: 24, iconHeight: 24, isFirstNode: false, isLastNode: false, - layer: 0 + layer: 0, }); - }, - - render: function () { + } + render() { const [collapse, expand] = this.getIconCls(); return { @@ -20,10 +26,10 @@ BI.TreeNodeSwitcher = BI.inherit(BI.NodeButton, { iconHeight: this.options.iconHeight, cls: this.options.open ? expand : collapse, }; - }, + } - getIconCls: function () { - var options = this.options; + getIconCls() { + const options = this.options; if (options.layer === 0 && options.isFirstNode && options.isLastNode) { // 只有一层,并且是第一个节点,并且是最后一个节点 return BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? ["tree-solid-collapse-icon-type1", "tree-solid-expand-icon-type1"] : ["tree-collapse-icon-type1", "tree-expand-icon-type1"]; @@ -37,23 +43,20 @@ BI.TreeNodeSwitcher = BI.inherit(BI.NodeButton, { // 其他情况 return BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? ["tree-solid-collapse-icon-type1", "tree-solid-expand-icon-type1"] : ["tree-collapse-icon-type3", "tree-expand-icon-type3"]; } - }, + } - setOpened: function (b) { - BI.TreeNodeSwitcher.superclass.setOpened.apply(this, arguments); + setOpened(b) { + super.setOpened.apply(this, arguments); const [collapse, expand] = this.getIconCls(); if (b) { this.element.addClass(expand).removeClass(collapse); } else { this.element.addClass(collapse).removeClass(expand); } - }, - - doClick: function () { - BI.TreeNodeSwitcher.superclass.doClick.apply(this, arguments); - this.fireEvent(BI.TreeNodeSwitcher.EVENT_CHANGE, this); } -}); -BI.TreeNodeSwitcher.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.tree_node_switcher", BI.TreeNodeSwitcher); + doClick() { + super.doClick.apply(this, arguments); + this.fireEvent(TreeNodeSwitcher.EVENT_CHANGE, this); + } +} diff --git a/src/case/button/node/treenode.js b/src/case/button/node/treenode.js index c557f791c..b2977e50a 100644 --- a/src/case/button/node/treenode.js +++ b/src/case/button/node/treenode.js @@ -1,8 +1,15 @@ -BI.BasicTreeNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function (props) { - var conf = BI.BasicTreeNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-tree-node " + (props.selectable ? "bi-list-item-active" : "bi-list-item"), +import { NodeButton } from "../../../base/single/button/button.node"; +import { shortcut, extend } from "../../../core"; + +@shortcut() +export class BasicTreeNode extends NodeButton { + static xtype = "bi.tree_node"; + + _defaultConfig(props) { + const conf = super._defaultConfig.apply(this, arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-tree-node ${props.selectable ? "bi-list-item-active" : "bi-list-item"}`, id: "", pId: "", open: false, @@ -14,15 +21,15 @@ BI.BasicTreeNode = BI.inherit(BI.NodeButton, { selectable: true, disabled: false, // disabled不会影响展开收起功能 }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; const checkbox = { type: "bi.tree_node_switcher", - __ref: function (_ref) { - self.switcher = _ref; + __ref: _ref => { + this.switcher = _ref; }, iconHeight: o.height, iconWidth: o.iconWrapperWidth || o.height, @@ -32,7 +39,7 @@ BI.BasicTreeNode = BI.inherit(BI.NodeButton, { layer: o.layer, ...o.switcherIcon, stopPropagation: o.selectable, - mounted: function () { + mounted () { this.setEnable(true); }, listeners: [ @@ -42,9 +49,9 @@ BI.BasicTreeNode = BI.inherit(BI.NodeButton, { if (!this.isEnabled() || o.selectable) { this.isOpened() ? this.triggerCollapse() : this.triggerExpand(); } - } + }, } - ] + ], }; return { @@ -53,12 +60,12 @@ BI.BasicTreeNode = BI.inherit(BI.NodeButton, { items: [ { el: checkbox, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, // 偏移公式为每一层的偏移量为节点高度的一半 + lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, // 偏移公式为每一层的偏移量为节点高度的一半 }, { el: { type: "bi.label", - ref: function (_ref) { - self.text = _ref; + ref: _ref => { + this.text = _ref; }, textAlign: "left", whiteSpace: "nowrap", @@ -71,36 +78,36 @@ BI.BasicTreeNode = BI.inherit(BI.NodeButton, { text: o.text, value: o.value, keyword: o.keyword, - py: o.py - } + py: o.py, + }, } - ] + ], }; - }, + } - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doClick: function () { + doClick() { if (this.options.selectable) { return; } - BI.BasicTreeNode.superclass.doClick.apply(this, arguments); - }, + super.doClick.apply(this, arguments); + } - setOpened: function (v) { - BI.BasicTreeNode.superclass.setOpened.apply(this, arguments); + setOpened(v) { + super.setOpened.apply(this, arguments); this.switcher.setOpened(v); - }, + } - setValue: function () { - BI.BasicTreeNode.superclass.setValue.apply(this, arguments); + setValue() { + super.setValue.apply(this, arguments); } -}); +} + -BI.shortcut("bi.tree_node", BI.BasicTreeNode); diff --git a/src/case/button/switch.js b/src/case/button/switch.js index 1ca2bd2b6..c05baa832 100644 --- a/src/case/button/switch.js +++ b/src/case/button/switch.js @@ -1,84 +1,95 @@ /** * Created by Windy on 2018/2/1. */ -BI.Switch = BI.inherit(BI.BasicButton, { - constants: { - CIRCLE_SIZE: 12 - }, +import { BasicButton } from "../../base/single/button/button.basic"; +import { shortcut } from "../../core"; - props: { +@shortcut() +export class Switch extends BasicButton { + static xtype = "bi.switch"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + constants = { + CIRCLE_SIZE: 12, + }; + + props = { extraCls: "bi-switch", attributes: { - tabIndex: 1 + tabIndex: 1, }, height: 20, width: 44, - showTip: false - }, + showTip: false, + }; - render: function () { - var self = this, o = this.options, c = this.constants; - var tgap = (o.height - c.CIRCLE_SIZE) / 2; + render() { + const o = this.options, + c = this.constants; + const tgap = (o.height - c.CIRCLE_SIZE) / 2; + return { type: "bi.absolute", - ref: function () { - self.layout = this; + ref: _ref => { + this.layout = _ref; }, - items: [{ - el: { - type: "bi.text_button", - cls: "circle-button" + items: [ + { + el: { + type: "bi.text_button", + cls: "circle-button", + }, + width: 12, + height: 12, + top: tgap, + left: o.selected ? 28 : 4, }, - width: 12, - height: 12, - top: tgap, - left: o.selected ? 28 : 4 - }, { - type: "bi.label", - text: BI.i18nText("BI-Basic_Simple_Open"), - cls: "content-tip", - left: 8, - top: tgap - 2, - invisible: !(o.showTip && o.selected), - ref: function (ref) { - self.openTip = ref; - } - }, { - type: "bi.label", - text: BI.i18nText("BI-Basic_Simple_Close"), - cls: "content-tip", - right: 8, - top: tgap - 2, - invisible: !(o.showTip && !o.selected), - ref: function (ref) { - self.closeTip = ref; + { + type: "bi.label", + text: BI.i18nText("BI-Basic_Simple_Open"), + cls: "content-tip", + left: 8, + top: tgap - 2, + invisible: !(o.showTip && o.selected), + ref: _ref => { + this.openTip = _ref; + }, + }, + { + type: "bi.label", + text: BI.i18nText("BI-Basic_Simple_Close"), + cls: "content-tip", + right: 8, + top: tgap - 2, + invisible: !(o.showTip && !o.selected), + ref: _ref => { + this.closeTip = _ref; + }, } - }] + ], }; - }, + } - _setEnable: function (enable) { - BI.Switch.superclass._setEnable.apply(this, arguments); + _setEnable(enable) { + super._setEnable.apply(this, arguments); if (enable === true) { this.element.attr("tabIndex", 1); } else if (enable === false) { this.element.removeAttr("tabIndex"); } - }, + } - setSelected: function (v) { - BI.Switch.superclass.setSelected.apply(this, arguments); + setSelected(v) { + super.setSelected.apply(this, arguments); this.layout.attr("items")[0].left = v ? 28 : 4; this.layout.resize(); this.options.showTip && this.openTip.setVisible(v); this.options.showTip && this.closeTip.setVisible(!v); - }, + } - doClick: function () { - BI.Switch.superclass.doClick.apply(this, arguments); - this.fireEvent(BI.Switch.EVENT_CHANGE, this.isSelected()); + doClick() { + super.doClick.apply(this, arguments); + this.fireEvent(Switch.EVENT_CHANGE, this.isSelected()); } -}); -BI.Switch.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.switch", BI.Switch); +} diff --git a/src/case/button/treeitem/item.first.treeleaf.js b/src/case/button/treeitem/item.first.treeleaf.js index 52663de39..d09376bc0 100644 --- a/src/case/button/treeitem/item.first.treeleaf.js +++ b/src/case/button/treeitem/item.first.treeleaf.js @@ -1,20 +1,27 @@ -BI.FirstTreeLeafItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - return BI.extend(BI.FirstTreeLeafItem.superclass._defaultConfig.apply(this, arguments), { +import { BasicButton } from "../../../base/single/button/button.basic"; +import { shortcut, extend, createWidget } from "../../../core"; + +@shortcut() +export class FirstTreeLeafItem extends BasicButton { + static xtype = "bi.first_tree_leaf_item"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { extraCls: "bi-first-tree-leaf-item bi-list-item-active", logic: { - dynamic: false + dynamic: false, }, id: "", pId: "", layer: 0, - height: 24 + height: 24, }); - }, - _init: function () { - BI.FirstTreeLeafItem.superclass._init.apply(this, arguments); - var o = this.options; - this.text = BI.createWidget({ + } + + _init() { + super._init.apply(this, arguments); + const o = this.options; + this.text = createWidget({ type: "bi.label", textAlign: "left", whiteSpace: "nowrap", @@ -24,76 +31,75 @@ BI.FirstTreeLeafItem = BI.inherit(BI.BasicButton, { text: o.text, value: o.value, py: o.py, - keyword: o.keyword + keyword: o.keyword, }); - var type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - var items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, ((o.layer === 0) ? "" : { + const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); + const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, ((o.layer === 0) ? "" : { width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, el: { type: "bi.layout", cls: (o.pNode && o.pNode.isLastNode) ? "" : this._getBaseLineCls(), width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, - height: o.height - } + height: o.height, + }, }), { width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, el: { type: "bi.layout", cls: this._getFirstLineCls(), width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - height: o.height - } + height: o.height, + }, }, { - el: this.text + el: this.text, }); - BI.createWidget(BI.extend({ - element: this + createWidget(extend({ + element: this, }, BI.LogicFactory.createLogic(type, BI.extend(o.logic, { - items: items + items, })))); - }, + } - _getBaseLineCls: function () { + _getBaseLineCls() { switch (BI.STYLE_CONSTANTS.LINK_LINE_TYPE) { - case "solid": - return "base-solid-line-conn-background"; - default: - return "base-line-conn-background"; + case "solid": + return "base-solid-line-conn-background"; + default: + return "base-line-conn-background"; } - }, + } - _getFirstLineCls: function () { + _getFirstLineCls() { switch (BI.STYLE_CONSTANTS.LINK_LINE_TYPE) { - case "solid": - return "first-solid-line-conn-background"; - default: - return "first-line-conn-background"; + case "solid": + return "first-solid-line-conn-background"; + default: + return "first-line-conn-background"; } - }, + } - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doHighLight: function () { - this.text.doHighLight.apply(this.text, arguments); - }, + doHighLight() { + this.text.doHighLight(...arguments); + } - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - }, + unHighLight() { + this.text.unHighLight(...arguments); + } - getId: function () { + getId() { return this.options.id; - }, + } - getPId: function () { + getPId() { return this.options.pId; } -}); +} -BI.shortcut("bi.first_tree_leaf_item", BI.FirstTreeLeafItem); \ No newline at end of file diff --git a/src/case/button/treeitem/item.icon.treeleaf.js b/src/case/button/treeitem/item.icon.treeleaf.js index 92fd5e348..280270774 100644 --- a/src/case/button/treeitem/item.icon.treeleaf.js +++ b/src/case/button/treeitem/item.icon.treeleaf.js @@ -1,33 +1,39 @@ -BI.IconTreeLeafItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - return BI.extend(BI.IconTreeLeafItem.superclass._defaultConfig.apply(this, arguments), { +import { BasicButton } from "../../../base/single/button/button.basic"; +import { shortcut, extend, createWidget } from "../../../core"; + +@shortcut() +export class IconTreeLeafItem extends BasicButton { + static xtype = "bi.icon_tree_leaf_item"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { extraCls: "bi-icon-tree-leaf-item bi-list-item-active", logic: { - dynamic: false + dynamic: false, }, height: 24, iconWidth: 16, iconHeight: 16, - iconCls: "" + iconCls: "", }); - }, + } - _init: function () { - BI.IconTreeLeafItem.superclass._init.apply(this, arguments); - var self = this, o = this.options; + _init() { + super._init.apply(this, arguments); + const o = this.options; - var icon = BI.createWidget({ + const icon = createWidget({ type: "bi.center_adapt", width: 24, cls: o.iconCls, items: [{ type: "bi.icon", width: o.iconWidth, - height: o.iconHeight - }] + height: o.iconHeight, + }], }); - this.text = BI.createWidget({ + this.text = createWidget({ type: "bi.label", textAlign: "left", whiteSpace: "nowrap", @@ -37,46 +43,44 @@ BI.IconTreeLeafItem = BI.inherit(BI.BasicButton, { text: o.text, value: o.value, py: o.py, - keyword: o.keyword + keyword: o.keyword, }); - var type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - var items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { + const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); + const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { width: 16, - el: icon + el: icon, }, { - el: this.text + el: this.text, }); - BI.createWidget(BI.extend({ - element: this + createWidget(BI.extend({ + element: this, }, BI.LogicFactory.createLogic(type, BI.extend(o.logic, { - items: items, - hgap: 5 + items, + hgap: 5, })))); - }, + } - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doHighLight: function () { - this.text.doHighLight.apply(this.text, arguments); - }, + doHighLight() { + this.text.doHighLight(...arguments); + } - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - }, + unHighLight() { + this.text.unHighLight(...arguments); + } - getId: function () { + getId() { return this.options.id; - }, + } - getPId: function () { + getPId() { return this.options.pId; } -}); - -BI.shortcut("bi.icon_tree_leaf_item", BI.IconTreeLeafItem); \ No newline at end of file +} diff --git a/src/case/button/treeitem/item.last.treeleaf.js b/src/case/button/treeitem/item.last.treeleaf.js index 76449063e..887b95a2f 100644 --- a/src/case/button/treeitem/item.last.treeleaf.js +++ b/src/case/button/treeitem/item.last.treeleaf.js @@ -1,20 +1,27 @@ -BI.LastTreeLeafItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - return BI.extend(BI.LastTreeLeafItem.superclass._defaultConfig.apply(this, arguments), { +import { BasicButton } from "../../../base/single/button/button.basic"; +import { shortcut, extend, createWidget } from "../../../core"; + +@shortcut() +export class LastTreeLeafItem extends BasicButton { + static xtype = "bi.last_tree_leaf_item"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { extraCls: "bi-last-tree-leaf-item bi-list-item-active", logic: { - dynamic: false + dynamic: false, }, id: "", pId: "", layer: 0, - height: 24 + height: 24, }); - }, - _init: function () { - BI.LastTreeLeafItem.superclass._init.apply(this, arguments); - var o = this.options; - this.text = BI.createWidget({ + } + + _init() { + super._init.apply(this, arguments); + const o = this.options; + this.text = createWidget({ type: "bi.label", textAlign: "left", whiteSpace: "nowrap", @@ -24,76 +31,75 @@ BI.LastTreeLeafItem = BI.inherit(BI.BasicButton, { text: o.text, value: o.value, py: o.py, - keyword: o.keyword + keyword: o.keyword, }); - var type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - var items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, ((o.layer === 0) ? "" : { + const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); + const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, ((o.layer === 0) ? "" : { width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, el: { type: "bi.layout", cls: (o.pNode && o.pNode.isLastNode) ? "" : this._getBaseLineCls(), width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, - height: o.height - } + height: o.height, + }, }), { width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, el: { type: "bi.layout", cls: this._getLastLineCls(), width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - height: o.height - } + height: o.height, + }, }, { - el: this.text + el: this.text, }); - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic(type, BI.extend(o.logic, { - items: items + createWidget(BI.extend({ + element: this, + }, BI.LogicFactory.createLogic(type, extend(o.logic, { + items, })))); - }, + } - _getBaseLineCls: function () { + _getBaseLineCls() { switch (BI.STYLE_CONSTANTS.LINK_LINE_TYPE) { - case "solid": - return "base-solid-line-conn-background"; - default: - return "base-line-conn-background"; + case "solid": + return "base-solid-line-conn-background"; + default: + return "base-line-conn-background"; } - }, + } - _getLastLineCls: function () { + _getLastLineCls() { switch (BI.STYLE_CONSTANTS.LINK_LINE_TYPE) { - case "solid": - return "last-solid-line-conn-background"; - default: - return "last-line-conn-background"; + case "solid": + return "last-solid-line-conn-background"; + default: + return "last-line-conn-background"; } - }, + } - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doHighLight: function () { - this.text.doHighLight.apply(this.text, arguments); - }, + doHighLight() { + this.text.doHighLight(...arguments); + } - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - }, + unHighLight() { + this.text.unHighLight(...arguments); + } - getId: function () { + getId() { return this.options.id; - }, + } - getPId: function () { + getPId() { return this.options.pId; } -}); +} -BI.shortcut("bi.last_tree_leaf_item", BI.LastTreeLeafItem); \ No newline at end of file diff --git a/src/case/button/treeitem/item.mid.treeleaf.js b/src/case/button/treeitem/item.mid.treeleaf.js index 58af36e4e..69e7bee6b 100644 --- a/src/case/button/treeitem/item.mid.treeleaf.js +++ b/src/case/button/treeitem/item.mid.treeleaf.js @@ -1,20 +1,27 @@ -BI.MidTreeLeafItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - return BI.extend(BI.MidTreeLeafItem.superclass._defaultConfig.apply(this, arguments), { +import { BasicButton } from "../../../base/single/button/button.basic"; +import { shortcut, extend, createWidget } from "../../../core"; + +@shortcut() +export class MidTreeLeafItem extends BasicButton { + static xtype = "bi.mid_tree_leaf_item"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { extraCls: "bi-mid-tree-leaf-item bi-list-item-active", logic: { - dynamic: false + dynamic: false, }, id: "", pId: "", layer: 0, - height: 24 + height: 24, }); - }, - _init: function () { - BI.MidTreeLeafItem.superclass._init.apply(this, arguments); - var o = this.options; - this.text = BI.createWidget({ + } + + _init() { + super._init.apply(this, arguments); + const o = this.options; + this.text = createWidget({ type: "bi.label", textAlign: "left", whiteSpace: "nowrap", @@ -24,76 +31,75 @@ BI.MidTreeLeafItem = BI.inherit(BI.BasicButton, { text: o.text, value: o.value, py: o.py, - keyword: o.keyword + keyword: o.keyword, }); - var type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - var items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, ((o.layer === 0) ? "" : { + const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); + const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, ((o.layer === 0) ? "" : { width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, el: { type: "bi.layout", cls: (o.pNode && o.pNode.isLastNode) ? "" : this._getBaseLineCls(), width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, - height: o.height - } + height: o.height, + }, }), { width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, el: { type: "bi.layout", cls: this._getMidLineCls(), width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - height: o.height - } + height: o.height, + }, }, { - el: this.text + el: this.text, }); - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic(type, BI.extend(o.logic, { - items: items + createWidget(extend({ + element: this, + }, BI.LogicFactory.createLogic(type, extend(o.logic, { + items, })))); - }, + } - _getBaseLineCls: function () { + _getBaseLineCls() { switch (BI.STYLE_CONSTANTS.LINK_LINE_TYPE) { - case "solid": - return "base-solid-line-conn-background"; - default: - return "base-line-conn-background"; + case "solid": + return "base-solid-line-conn-background"; + default: + return "base-line-conn-background"; } - }, + } - _getMidLineCls: function () { + _getMidLineCls() { switch (BI.STYLE_CONSTANTS.LINK_LINE_TYPE) { - case "solid": - return "mid-solid-line-conn-background"; - default: - return "mid-line-conn-background"; + case "solid": + return "mid-solid-line-conn-background"; + default: + return "mid-line-conn-background"; } - }, + } - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark () { + this.text.unRedMark(...arguments); + } - doHighLight: function () { - this.text.doHighLight.apply(this.text, arguments); - }, + doHighLight() { + this.text.doHighLight(...arguments); + } - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - }, + unHighLight() { + this.text.unHighLight(...arguments); + } - getId: function () { + getId() { return this.options.id; - }, + } - getPId: function () { + getPId() { return this.options.pId; } -}); +} -BI.shortcut("bi.mid_tree_leaf_item", BI.MidTreeLeafItem); \ No newline at end of file diff --git a/src/case/button/treeitem/item.multilayer.icon.treeleaf.js b/src/case/button/treeitem/item.multilayer.icon.treeleaf.js index 363a348c0..2d5e043fb 100644 --- a/src/case/button/treeitem/item.multilayer.icon.treeleaf.js +++ b/src/case/button/treeitem/item.multilayer.icon.treeleaf.js @@ -1,22 +1,29 @@ +import { BasicButton } from "../../../base/single/button/button.basic"; +import { shortcut, extend, createWidget, Controller, makeArray } from "../../../core"; + /** * @class BI.MultiLayerIconTreeLeafItem * @extends BI.BasicButton */ -BI.MultiLayerIconTreeLeafItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - return BI.extend(BI.MultiLayerIconTreeLeafItem.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class MultiLayerIconTreeLeafItem extends BasicButton { + static xtype = "bi.multilayer_icon_tree_leaf_item"; + + _defaultConfig() { + return extend(super._defaultConfig(arguments), { extraCls: "bi-multilayer-icon-tree-leaf-item bi-list-item-active", layer: 0, height: 24, iconCls: "", iconHeight: 16, - iconWidth: 16 + iconWidth: 16, }); - }, - _init: function () { - BI.MultiLayerIconTreeLeafItem.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.item = BI.createWidget({ + } + + _init() { + super._init.apply(this, arguments); + const o = this.options; + this.item = createWidget({ type: "bi.icon_tree_leaf_item", cls: "bi-list-item-none", iconCls: o.iconCls, @@ -30,69 +37,70 @@ BI.MultiLayerIconTreeLeafItem = BI.inherit(BI.BasicButton, { py: o.py, keyword: o.keyword, iconWidth: o.iconWidth, - iconHeight: o.iconHeight + iconHeight: o.iconHeight, }); - this.item.on(BI.Controller.EVENT_CHANGE, function (type) { + this.item.on(Controller.EVENT_CHANGE, (...args) => { + const [type] = args; if (type === BI.Events.CLICK) {// 本身实现click功能 return; } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.fireEvent(Controller.EVENT_CHANGE, args); }); - var items = []; - BI.count(0, o.layer, function () { + const items = []; + BI.count(0, o.layer, () => { items.push({ type: "bi.layout", width: 15, - height: o.height + height: o.height, }); }); items.push(this.item); - BI.createWidget({ + createWidget({ type: "bi.horizontal_adapt", element: this, - columnSize: BI.makeArray(o.layer, 15), - items: items + columnSize: makeArray(o.layer, 15), + items, }); - }, - - doRedMark: function () { - this.item.doRedMark.apply(this.item, arguments); - }, + } - unRedMark: function () { - this.item.unRedMark.apply(this.item, arguments); - }, + doRedMark () { + this.item.doRedMark(...arguments); + } - doHighLight: function () { - this.item.doHighLight.apply(this.item, arguments); - }, + unRedMark () { + this.item.unRedMark(...arguments); + } + + doHighLight() { + this.item.doHighLight(...arguments); + } - unHighLight: function () { - this.item.unHighLight.apply(this.item, arguments); - }, + unHighLight () { + this.item.unHighLight(...arguments); + } - getId: function () { + getId () { return this.options.id; - }, + } - getPId: function () { + getPId () { return this.options.pId; - }, + } - doClick: function () { + doClick () { BI.MultiLayerIconTreeLeafItem.superclass.doClick.apply(this, arguments); this.item.setSelected(this.isSelected()); - }, + } - setSelected: function (v) { + setSelected(v) { BI.MultiLayerIconTreeLeafItem.superclass.setSelected.apply(this, arguments); this.item.setSelected(v); - }, + } - getValue: function () { + getValue() { return this.options.value; } -}); +} + -BI.shortcut("bi.multilayer_icon_tree_leaf_item", BI.MultiLayerIconTreeLeafItem); diff --git a/src/case/button/treeitem/item.root.treeleaf.js b/src/case/button/treeitem/item.root.treeleaf.js index f4637afdc..f6fdd9c81 100644 --- a/src/case/button/treeitem/item.root.treeleaf.js +++ b/src/case/button/treeitem/item.root.treeleaf.js @@ -1,22 +1,27 @@ -BI.RootTreeLeafItem = BI.inherit(BI.BasicButton, { - props: { +import { BasicButton } from "../../../base/single/button/button.basic"; +import { shortcut, extend } from "../../../core"; + +@shortcut() +export class RootTreeLeafItem extends BasicButton { + static xtype = "bi.root_tree_leaf_item"; + + props = { baseCls: "bi-root-tree-leaf-item bi-list-item-active", logic: { - dynamic: false + dynamic: false, }, id: "", pId: "", layer: 0, - height: 24 - }, + height: 24, + } - render: function () { - var self = this; - var o = this.options; - var text = { + render() { + const o = this.options; + const text = { type: "bi.label", - ref: function (_ref) { - self.text = _ref; + ref: _ref => { + this.text = _ref; }, textAlign: "left", whiteSpace: "nowrap", @@ -26,49 +31,48 @@ BI.RootTreeLeafItem = BI.inherit(BI.BasicButton, { text: o.text, value: o.value, py: o.py, - keyword: o.keyword + keyword: o.keyword, }; - var type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - var items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { + const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); + const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, el: { type: "bi.layout", width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - height: o.height - } + height: o.height, + }, }, { - el: text + el: text, }); - return BI.LogicFactory.createLogic(type, BI.extend(o.logic, { - items: items + return BI.LogicFactory.createLogic(type, extend(o.logic, { + items, })); - }, + } - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doHighLight: function () { - this.text.doHighLight.apply(this.text, arguments); - }, + doHighLight() { + this.text.doHighLight(...arguments); + } - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - }, + unHighLight() { + this.text.unHighLight(...arguments); + } - getId: function () { + getId() { return this.options.id; - }, + } - getPId: function () { + getPId() { return this.options.pId; } -}); +} -BI.shortcut("bi.root_tree_leaf_item", BI.RootTreeLeafItem); diff --git a/src/case/button/treeitem/item.treetextleaf.js b/src/case/button/treeitem/item.treetextleaf.js index 872663fd0..2dca402e8 100644 --- a/src/case/button/treeitem/item.treetextleaf.js +++ b/src/case/button/treeitem/item.treetextleaf.js @@ -1,25 +1,32 @@ +import { BasicButton } from "../../../base/single/button/button.basic"; +import { shortcut, extend, createWidget } from "../../../core"; + /** * 树叶子节点 * Created by GUY on 2015/9/6. * @class BI.TreeTextLeafItem * @extends BI.BasicButton */ -BI.TreeTextLeafItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - return BI.extend(BI.TreeTextLeafItem.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class TreeTextLeafItem extends BasicButton { + static xtype = "bi.tree_text_leaf_item"; + + _defaultConfig() { + return extend(super._defaultConfig.apply(this, arguments), { extraCls: "bi-tree-text-leaf-item bi-list-item-active", id: "", pId: "", height: 24, hgap: 0, lgap: 0, - rgap: 0 + rgap: 0, }); - }, - _init: function () { - BI.TreeTextLeafItem.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.text = BI.createWidget({ + } + + _init() { + super._init.apply(this, arguments); + const o = this.options; + this.text = createWidget({ type: "bi.label", textAlign: "left", whiteSpace: "nowrap", @@ -31,40 +38,39 @@ BI.TreeTextLeafItem = BI.inherit(BI.BasicButton, { text: o.text, value: o.value, py: o.py, - keyword: o.keyword + keyword: o.keyword, }); - BI.createWidget({ + createWidget({ type: "bi.htape", element: this, items: [{ - el: this.text - }] + el: this.text, + }], }); - }, + } - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doHighLight: function () { - this.text.doHighLight.apply(this.text, arguments); - }, + doHighLight() { + this.text.doHighLight(...arguments); + } - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - }, + unHighLight() { + this.text.unHighLight(...arguments); + } - getId: function () { + getId() { return this.options.id; - }, + } - getPId: function () { + getPId() { return this.options.pId; } -}); +} -BI.shortcut("bi.tree_text_leaf_item", BI.TreeTextLeafItem); diff --git a/src/case/button/treeitem/treeitem.js b/src/case/button/treeitem/treeitem.js index 4ab512a29..c6235facd 100644 --- a/src/case/button/treeitem/treeitem.js +++ b/src/case/button/treeitem/treeitem.js @@ -1,8 +1,15 @@ -BI.BasicTreeItem = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.BasicTreeItem.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-tree-item bi-list-item-active", +import { NodeButton } from "../../../base/single/button/button.node"; +import { shortcut, extend } from "../../../core"; + +@shortcut() +export class BasicTreeItem extends NodeButton { + static xtype = "bi.tree_item"; + + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-tree-item bi-list-item-active`, id: "", pId: "", height: 24, @@ -10,10 +17,10 @@ BI.BasicTreeItem = BI.inherit(BI.NodeButton, { isFirstNode: false, isLastNode: false, }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; return { type: "bi.vertical_adapt", @@ -26,13 +33,13 @@ BI.BasicTreeItem = BI.inherit(BI.NodeButton, { width: o.height, cls: this.getLineCls(), }, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, // 偏移公式为每一层的偏移量为节点高度的一半 + lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, // 偏移公式为每一层的偏移量为节点高度的一半 }, { el: { type: "bi.label", - ref: function (_ref) { - self.text = _ref; + ref: _ref => { + this.text = _ref; }, textAlign: "left", whiteSpace: "nowrap", @@ -45,15 +52,15 @@ BI.BasicTreeItem = BI.inherit(BI.NodeButton, { text: o.text, value: o.value, keyword: o.keyword, - py: o.py + py: o.py, }, } - ] + ], }; - }, + } - getLineCls: function () { - var options = this.options; + getLineCls() { + const options = this.options; if (options.layer === 0 && options.isFirstNode && options.isLastNode) { return ""; } else if (options.layer === 0 && options.isFirstNode) { @@ -63,24 +70,21 @@ BI.BasicTreeItem = BI.inherit(BI.NodeButton, { } else { return BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? "tree-mid-solid-line-conn-background" : "mid-line-conn-background"; } - }, + } - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - getId: function () { + getId() { return this.options.id; - }, + } - getPId: function () { + getPId() { return this.options.pId; } - -}); - -BI.shortcut("bi.tree_item", BI.BasicTreeItem); +} diff --git a/src/case/index.js b/src/case/index.js new file mode 100644 index 000000000..5e8b11baf --- /dev/null +++ b/src/case/index.js @@ -0,0 +1,7 @@ +import * as button from "./button"; + +Object.assign(BI, { + ...button, +}); + +export * from "./button"; From 4addb6aefd86ad8dc1a9cce735b26e7074951e3c Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Fri, 6 Jan 2023 11:16:09 +0800 Subject: [PATCH 041/300] =?UTF-8?q?KERNEL-14035=20refactor:=20constant?= =?UTF-8?q?=E3=80=81element=E3=80=81logic=E6=96=87=E4=BB=B6=E5=A4=B9?= =?UTF-8?q?=E5=8F=8A=E6=95=B4=E4=BD=93eslint=E4=B8=80=E4=B8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/1.pane.js | 12 +- src/core/2.base.js | 3 +- src/core/action/action.js | 15 +- src/core/action/action.show.js | 17 +- src/core/action/index.js | 2 +- src/core/behavior/0.behavior.js | 24 +- src/core/behavior/behavior.highlight.js | 26 +- src/core/behavior/behavior.redmark.js | 21 +- src/core/behavior/index.js | 27 +- src/core/constant/events.js | 879 ++++++++++---------- src/core/constant/index.js | 2 + src/core/constant/var.js | 327 ++++---- src/core/controller/0.controller.js | 4 +- src/core/controller/controller.broadcast.js | 11 +- src/core/controller/controller.bubbles.js | 38 +- src/core/controller/controller.drawer.js | 38 +- src/core/controller/controller.layer.js | 55 +- src/core/controller/controller.masker.js | 2 +- src/core/controller/controller.popover.js | 46 +- src/core/controller/controller.resizer.js | 21 +- src/core/controller/controller.tooltips.js | 40 +- src/core/controller/index.js | 2 +- src/core/element/element.js | 124 +-- src/core/element/index.js | 21 +- src/core/element/plugins/attr.js | 45 +- src/core/element/plugins/class.js | 38 +- src/core/element/plugins/css.js | 40 +- src/core/element/plugins/data.js | 25 +- src/core/element/plugins/empty.js | 17 +- src/core/element/plugins/event.js | 63 +- src/core/element/plugins/html.js | 32 +- src/core/element/plugins/index.js | 58 +- src/core/element/plugins/keywordMark.js | 11 +- src/core/element/plugins/renderToHtml.js | 124 +-- src/core/element/plugins/renderToString.js | 96 ++- src/core/element/plugins/text.js | 20 +- src/core/element/plugins/val.js | 18 +- src/core/index.js | 9 +- src/core/listener/listener.show.js | 20 +- src/core/loader/loader.style.js | 9 +- src/core/logic/index.js | 83 ++ src/core/logic/logic.js | 82 +- src/core/logic/logic.layout.js | 109 ++- 43 files changed, 1377 insertions(+), 1279 deletions(-) create mode 100644 src/core/constant/index.js create mode 100644 src/core/logic/index.js diff --git a/src/base/1.pane.js b/src/base/1.pane.js index ebbaac636..1e6bf38b5 100644 --- a/src/base/1.pane.js +++ b/src/base/1.pane.js @@ -33,7 +33,7 @@ export class Pane extends Widget { element: this, items: [{ type: "bi.label", - ref: (_ref) => { + ref: _ref => { this._tipText = _ref; }, cls: "bi-tips", @@ -54,15 +54,15 @@ export class Pane extends Widget { // loading的异步情况下由loaded后对面板的populate的时机决定 this.setTipVisible(false); if (o.overlap === true) { - if (!Layers.has(this.getName() + "-loading")) { + if (!Layers.has(`${this.getName()}-loading`)) { createWidget({ type: "bi.center_adapt", cls: "loading-container", items: this._getLoadingTipItems(loadingAnimation), - element: Layers.make(this.getName() + "-loading", this), + element: Layers.make(`${this.getName()}-loading`, this), }); } - Layers.show(this.getName() + "-loading"); + Layers.show(`${this.getName()}-loading`); } else if (isNull(this._loading)) { loadingAnimation.element.css("zIndex", 1); createWidget({ @@ -94,7 +94,7 @@ export class Pane extends Widget { return [{ type: "bi.vertical", - ref: (_ref) => { + ref: _ref => { this._loading = _ref; }, items: loadingTipItems, @@ -102,7 +102,7 @@ export class Pane extends Widget { } loaded() { - Layers.remove(this.getName() + "-loading"); + Layers.remove(`${this.getName()}-loading`); this._loading && this._loading.destroy(); this.options.onLoaded(); this.fireEvent(Pane.EVENT_LOADED); diff --git a/src/core/2.base.js b/src/core/2.base.js index 4fe7583de..003839ec4 100644 --- a/src/core/2.base.js +++ b/src/core/2.base.js @@ -488,7 +488,7 @@ BI._.each([ "keys", "allKeys", "values", "pairs", "invert", "create", "functions", "extend", "extendOwn", "defaults", "clone", "property", "propertyOf", "matcher", "isEqual", "isMatch", "isEmpty", "isElement", "isNumber", "isString", "isArray", "isObject", "isPlainObject", "isArguments", "isFunction", "isFinite", - "isBoolean", "isDate", "isRegExp", "isError", "isNaN", "isUndefined", "zipObject", "cloneDeep" + "isBoolean", "isDate", "isRegExp", "isError", "isNaN", "isUndefined", "zipObject", "cloneDeep", "pickBy" ], name => { BI[name] = _apply(name); }); @@ -526,6 +526,7 @@ export const isNaN = BI.isNaN; export const isUndefined = BI.isUndefined; export const zipObject = BI.zipObject; export const cloneDeep = BI.cloneDeep; +export const pickBy = BI.pickBy; BI._.each(["mapObject", "findKey", "pick", "omit", "tap"], name => { BI[name] = _applyFunc(name); diff --git a/src/core/action/action.js b/src/core/action/action.js index b87ea1e21..bfe20fd80 100644 --- a/src/core/action/action.js +++ b/src/core/action/action.js @@ -6,10 +6,11 @@ * @abstract */ import { OB } from "../3.ob"; + export class Action extends OB { props = { src: null, - tar: null + tar: null, }; actionPerformed(src, tar, callback) { @@ -20,15 +21,3 @@ export class Action extends OB { } } - -BI.ActionFactory = { - createAction: function (key, options) { - var action; - switch (key) { - case "show": - action = BI.ShowAction; - break; - } - return new action(options); - } -}; diff --git a/src/core/action/action.show.js b/src/core/action/action.show.js index 1084ec542..8ed0162f1 100644 --- a/src/core/action/action.show.js +++ b/src/core/action/action.show.js @@ -1,10 +1,9 @@ /** * guy * 由一个元素切换到另一个元素的行为 - * @class BI.ShowAction - * @extends BI.Action */ import { Action } from "./action"; + export class ShowAction extends Action { actionPerformed(src, tar, callback) { tar = tar || this.options.tar; @@ -18,3 +17,17 @@ export class ShowAction extends Action { callback && callback(); } } + +export const ActionFactory = { + createAction (key, options) { + let Action; + switch (key) { + case "show": + Action = ShowAction; + break; + default: + } + + return new Action(options); + }, +}; diff --git a/src/core/action/index.js b/src/core/action/index.js index f82304e43..c73457134 100644 --- a/src/core/action/index.js +++ b/src/core/action/index.js @@ -1,2 +1,2 @@ export { Action } from "./action"; -export { ShowAction } from "./action.show"; \ No newline at end of file +export { ShowAction, ActionFactory } from "./action.show"; diff --git a/src/core/behavior/0.behavior.js b/src/core/behavior/0.behavior.js index 5adc59d3d..22496e242 100644 --- a/src/core/behavior/0.behavior.js +++ b/src/core/behavior/0.behavior.js @@ -1,30 +1,14 @@ -BI.BehaviorFactory = { - createBehavior: function (key, options) { - var behavior; - switch (key) { - case "highlight": - behavior = BI.HighlightBehavior; - break; - case "redmark": - behavior = BI.RedMarkBehavior; - break; - } - return new behavior(options); - } -}; - /** * guy * 行为控件 - * @class BI.Behavior - * @extends BI.OB */ - import { OB } from "../3.ob"; +import { extend } from "../2.base"; + export class Behavior extends OB { _defaultConfig() { - return BI.extend(super._defaultConfig(arguments), { - rule: () => true + return extend(super._defaultConfig(arguments), { + rule: () => true, }); } diff --git a/src/core/behavior/behavior.highlight.js b/src/core/behavior/behavior.highlight.js index 1c0676b90..f66355c65 100644 --- a/src/core/behavior/behavior.highlight.js +++ b/src/core/behavior/behavior.highlight.js @@ -1,33 +1,33 @@ /** * guy - * - * @class BI.HighlightBehavior - * @extends BI.Behavior */ import { Behavior } from "./0.behavior"; +import { isFunction, each } from "../2.base"; +import { Single } from "../../base"; + export class HighlightBehavior extends Behavior { doBehavior(items) { const args = Array.prototype.slice.call(arguments, 1), - o = this.options; - BI.each(items, function (i, item) { - if (item instanceof BI.Single) { - const rule = o.rule(item.getValue(), item); + { rule } = this.options; + each(items, (i, item) => { + if (item instanceof Single) { + const rules = rule(item.getValue(), item); function doBe (run) { if (run === true) { - item.doHighLight && item.doHighLight.apply(item, args); + item.doHighLight && item.doHighLight(...args); } else { - item.unHighLight && item.unHighLight.apply(item, args); + item.unHighLight && item.unHighLight(...args); } } - if (BI.isFunction(rule)) { - rule(doBe); + if (isFunction(rules)) { + rules(doBe); } else { - doBe(rule); + doBe(rules); } } else { - item.doBehavior && item.doBehavior.apply(item, args); + item.doBehavior && item.doBehavior(...args); } }); } diff --git a/src/core/behavior/behavior.redmark.js b/src/core/behavior/behavior.redmark.js index 5beb0797f..7ca2b9df2 100644 --- a/src/core/behavior/behavior.redmark.js +++ b/src/core/behavior/behavior.redmark.js @@ -1,23 +1,24 @@ /** * guy * 标红行为 - * @class BI.RedMarkBehavior - * @extends BI.Behavior */ import { Behavior } from "./0.behavior"; +import { each } from "../2.base"; +import { Single } from "../../base"; + export class RedMarkBehavior extends Behavior { doBehavior(items) { - const args = Array.prototype.slice.call(arguments, 1), - o = this.options; - BI.each(items, function (i, item) { - if(item instanceof BI.Single) { - if (o.rule(item.getValue(), item)) { - item.doRedMark && item.doRedMark.apply(item, args); + const args = Array.prototype.slice.call(arguments, 1), + { rule } = this.options; + each(items, (i, item) => { + if (item instanceof Single) { + if (rule(item.getValue(), item)) { + item.doRedMark && item.doRedMark(...args); } else { - item.doRedMark && item.unRedMark.apply(item, args); + item.doRedMark && item.unRedMark(...args); } } else { - item.doBehavior && item.doBehavior.apply(item, args); + item.doBehavior && item.doBehavior(...args); } }); } diff --git a/src/core/behavior/index.js b/src/core/behavior/index.js index ee2ae69ed..52d5f6499 100644 --- a/src/core/behavior/index.js +++ b/src/core/behavior/index.js @@ -1,3 +1,26 @@ + +import { HighlightBehavior } from "./behavior.highlight"; +import { RedMarkBehavior } from "./behavior.redmark"; + +export const BehaviorFactory = { + createBehavior (key, options) { + let Behavior; + switch (key) { + case "highlight": + Behavior = HighlightBehavior; + break; + case "redmark": + Behavior = RedMarkBehavior; + break; + default: + } + + return new Behavior(options); + }, +}; + export { Behavior } from "./0.behavior"; -export { HighlightBehavior } from "./behavior.highlight"; -export { RedMarkBehavior } from "./behavior.redmark"; \ No newline at end of file +export { + HighlightBehavior, + RedMarkBehavior +}; diff --git a/src/core/constant/events.js b/src/core/constant/events.js index 76eb97021..656f2e9ca 100644 --- a/src/core/constant/events.js +++ b/src/core/constant/events.js @@ -1,444 +1,441 @@ /** * 事件集合 - * @class BI.Events */ -BI._.extend(BI, { - Events: { - - /** - * @static - * @property keydown事件 - */ - KEYDOWN: "_KEYDOWN", - - /** - * @static - * @property 回撤事件 - */ - BACKSPACE: "_BACKSPACE", - - /** - * @static - * @property 空格事件 - */ - SPACE: "_SPACE", - - /** - * @static - * @property 回车事件 - */ - ENTER: "_ENTER", - - /** - * @static - * @property 确定事件 - */ - CONFIRM: "_CONFIRM", - - /** - * @static - * @property 错误事件 - */ - ERROR: "_ERROR", - - /** - * @static - * @property 暂停事件 - */ - PAUSE: "_PAUSE", - - /** - * @static - * @property destroy事件 - */ - DESTROY: "_DESTROY", - - /** - * @static - * @property 挂载事件 - */ - MOUNT: "_MOUNT", - - /** - * @static - * @property 取消挂载事件 - */ - UNMOUNT: "_UNMOUNT", - - /** - * @static - * @property 清除选择 - */ - CLEAR: "_CLEAR", - - /** - * @static - * @property 添加数据 - */ - ADD: "_ADD", - - /** - * @static - * @property 正在编辑状态事件 - */ - EDITING: "_EDITING", - - /** - * @static - * @property 空状态事件 - */ - EMPTY: "_EMPTY", - - /** - * @static - * @property 显示隐藏事件 - */ - VIEW: "_VIEW", - - /** - * @static - * @property 窗体改变大小 - */ - RESIZE: "_RESIZE", - - /** - * @static - * @property 编辑前事件 - */ - BEFOREEDIT: "_BEFOREEDIT", - - /** - * @static - * @property 编辑后事件 - */ - AFTEREDIT: "_AFTEREDIT", - - /** - * @static - * @property 开始编辑事件 - */ - STARTEDIT: "_STARTEDIT", - - /** - * @static - * @property 停止编辑事件 - */ - STOPEDIT: "_STOPEDIT", - - /** - * @static - * @property 值改变事件 - */ - CHANGE: "_CHANGE", - - /** - * @static - * @property 下拉弹出菜单事件 - */ - EXPAND: "_EXPAND", - - /** - * @static - * @property 关闭下拉菜单事件 - */ - COLLAPSE: "_COLLAPSE", - - /** - * @static - * @property 下拉菜单切换展开收起事件 - */ - TOGGLE: "_TOGGLE", - - /** - * @static - * @property 回调事件 - */ - CALLBACK: "_CALLBACK", - - /** - * @static - * @property 点击事件 - */ - CLICK: "_CLICK", - - /** - * @static - * @property 状态改变事件,一般是用在复选按钮和单选按钮 - */ - STATECHANGE: "_STATECHANGE", - - /** - * @static - * @property 状态改变前事件 - */ - BEFORESTATECHANGE: "_BEFORESTATECHANGE", - - - /** - * @static - * @property 初始化事件 - */ - INIT: "_INIT", - - /** - * @static - * @property 初始化后事件 - */ - AFTERINIT: "_AFTERINIT", - - /** - * @static - * @property 滚动条滚动事件 - */ - SCROLL: "_SCROLL", - - - /** - * @static - * @property 开始加载事件 - */ - STARTLOAD: "_STARTLOAD", - - /** - * @static - * @property 加载后事件 - */ - AFTERLOAD: "_AFTERLOAD", - - - /** - * @static - * @property 提交前事件 - */ - BS: "beforesubmit", - - /** - * @static - * @property 提交后事件 - */ - AS: "aftersubmit", - - /** - * @static - * @property 提交完成事件 - */ - SC: "submitcomplete", - - /** - * @static - * @property 提交失败事件 - */ - SF: "submitfailure", - - /** - * @static - * @property 提交成功事件 - */ - SS: "submitsuccess", - - /** - * @static - * @property 校验提交前事件 - */ - BVW: "beforeverifywrite", - - /** - * @static - * @property 校验提交后事件 - */ - AVW: "afterverifywrite", - - /** - * @static - * @property 校验后事件 - */ - AV: "afterverify", - - /** - * @static - * @property 填报前事件 - */ - BW: "beforewrite", - - /** - * @static - * @property 填报后事件 - */ - AW: "afterwrite", - - /** - * @static - * @property 填报成功事件 - */ - WS: "writesuccess", - - /** - * @static - * @property 填报失败事件 - */ - WF: "writefailure", - - /** - * @static - * @property 添加行前事件 - */ - BA: "beforeappend", - - /** - * @static - * @property 添加行后事件 - */ - AA: "afterappend", - - /** - * @static - * @property 删除行前事件 - */ - BD: "beforedelete", - - /** - * @static - * @property 删除行后事件 - */ - AD: "beforedelete", - - /** - * @static - * @property 未提交离开事件 - */ - UC: "unloadcheck", - - - /** - * @static - * @property PDF导出前事件 - */ - BTOPDF: "beforetopdf", - - /** - * @static - * @property PDF导出后事件 - */ - ATOPDF: "aftertopdf", - - /** - * @static - * @property Excel导出前事件 - */ - BTOEXCEL: "beforetoexcel", - - /** - * @static - * @property Excel导出后事件 - */ - ATOEXCEL: "aftertoexcel", - - /** - * @static - * @property Word导出前事件 - */ - BTOWORD: "beforetoword", - - /** - * @static - * @property Word导出后事件 - */ - ATOWORD: "aftertoword", - - /** - * @static - * @property 图片导出前事件 - */ - BTOIMAGE: "beforetoimage", - - /** - * @static - * @property 图片导出后事件 - */ - ATOIMAGE: "aftertoimage", - - /** - * @static - * @property HTML导出前事件 - */ - BTOHTML: "beforetohtml", - - /** - * @static - * @property HTML导出后事件 - */ - ATOHTML: "aftertohtml", - - /** - * @static - * @property Excel导入前事件 - */ - BIMEXCEL: "beforeimportexcel", - - /** - * @static - * @property Excel导出后事件 - */ - AIMEXCEL: "afterimportexcel", - - /** - * @static - * @property PDF打印前事件 - */ - BPDFPRINT: "beforepdfprint", - - /** - * @static - * @property PDF打印后事件 - */ - APDFPRINT: "afterpdfprint", - - /** - * @static - * @property Flash打印前事件 - */ - BFLASHPRINT: "beforeflashprint", - - /** - * @static - * @property Flash打印后事件 - */ - AFLASHPRINT: "afterflashprint", - - /** - * @static - * @property Applet打印前事件 - */ - BAPPLETPRINT: "beforeappletprint", - - /** - * @static - * @property Applet打印后事件 - */ - AAPPLETPRINT: "afterappletprint", - - /** - * @static - * @property 服务器打印前事件 - */ - BSEVERPRINT: "beforeserverprint", - - /** - * @static - * @property 服务器打印后事件 - */ - ASERVERPRINT: "afterserverprint", - - /** - * @static - * @property 邮件发送前事件 - */ - BEMAIL: "beforeemail", - - /** - * @static - * @property 邮件发送后事件 - */ - AEMAIL: "afteremail" - } -}); +export const Events = { + + /** + * @static + * @property keydown事件 + */ + KEYDOWN: "_KEYDOWN", + + /** + * @static + * @property 回撤事件 + */ + BACKSPACE: "_BACKSPACE", + + /** + * @static + * @property 空格事件 + */ + SPACE: "_SPACE", + + /** + * @static + * @property 回车事件 + */ + ENTER: "_ENTER", + + /** + * @static + * @property 确定事件 + */ + CONFIRM: "_CONFIRM", + + /** + * @static + * @property 错误事件 + */ + ERROR: "_ERROR", + + /** + * @static + * @property 暂停事件 + */ + PAUSE: "_PAUSE", + + /** + * @static + * @property destroy事件 + */ + DESTROY: "_DESTROY", + + /** + * @static + * @property 挂载事件 + */ + MOUNT: "_MOUNT", + + /** + * @static + * @property 取消挂载事件 + */ + UNMOUNT: "_UNMOUNT", + + /** + * @static + * @property 清除选择 + */ + CLEAR: "_CLEAR", + + /** + * @static + * @property 添加数据 + */ + ADD: "_ADD", + + /** + * @static + * @property 正在编辑状态事件 + */ + EDITING: "_EDITING", + + /** + * @static + * @property 空状态事件 + */ + EMPTY: "_EMPTY", + + /** + * @static + * @property 显示隐藏事件 + */ + VIEW: "_VIEW", + + /** + * @static + * @property 窗体改变大小 + */ + RESIZE: "_RESIZE", + + /** + * @static + * @property 编辑前事件 + */ + BEFOREEDIT: "_BEFOREEDIT", + + /** + * @static + * @property 编辑后事件 + */ + AFTEREDIT: "_AFTEREDIT", + + /** + * @static + * @property 开始编辑事件 + */ + STARTEDIT: "_STARTEDIT", + + /** + * @static + * @property 停止编辑事件 + */ + STOPEDIT: "_STOPEDIT", + + /** + * @static + * @property 值改变事件 + */ + CHANGE: "_CHANGE", + + /** + * @static + * @property 下拉弹出菜单事件 + */ + EXPAND: "_EXPAND", + + /** + * @static + * @property 关闭下拉菜单事件 + */ + COLLAPSE: "_COLLAPSE", + + /** + * @static + * @property 下拉菜单切换展开收起事件 + */ + TOGGLE: "_TOGGLE", + + /** + * @static + * @property 回调事件 + */ + CALLBACK: "_CALLBACK", + + /** + * @static + * @property 点击事件 + */ + CLICK: "_CLICK", + + /** + * @static + * @property 状态改变事件,一般是用在复选按钮和单选按钮 + */ + STATECHANGE: "_STATECHANGE", + + /** + * @static + * @property 状态改变前事件 + */ + BEFORESTATECHANGE: "_BEFORESTATECHANGE", + + + /** + * @static + * @property 初始化事件 + */ + INIT: "_INIT", + + /** + * @static + * @property 初始化后事件 + */ + AFTERINIT: "_AFTERINIT", + + /** + * @static + * @property 滚动条滚动事件 + */ + SCROLL: "_SCROLL", + + + /** + * @static + * @property 开始加载事件 + */ + STARTLOAD: "_STARTLOAD", + + /** + * @static + * @property 加载后事件 + */ + AFTERLOAD: "_AFTERLOAD", + + + /** + * @static + * @property 提交前事件 + */ + BS: "beforesubmit", + + /** + * @static + * @property 提交后事件 + */ + AS: "aftersubmit", + + /** + * @static + * @property 提交完成事件 + */ + SC: "submitcomplete", + + /** + * @static + * @property 提交失败事件 + */ + SF: "submitfailure", + + /** + * @static + * @property 提交成功事件 + */ + SS: "submitsuccess", + + /** + * @static + * @property 校验提交前事件 + */ + BVW: "beforeverifywrite", + + /** + * @static + * @property 校验提交后事件 + */ + AVW: "afterverifywrite", + + /** + * @static + * @property 校验后事件 + */ + AV: "afterverify", + + /** + * @static + * @property 填报前事件 + */ + BW: "beforewrite", + + /** + * @static + * @property 填报后事件 + */ + AW: "afterwrite", + + /** + * @static + * @property 填报成功事件 + */ + WS: "writesuccess", + + /** + * @static + * @property 填报失败事件 + */ + WF: "writefailure", + + /** + * @static + * @property 添加行前事件 + */ + BA: "beforeappend", + + /** + * @static + * @property 添加行后事件 + */ + AA: "afterappend", + + /** + * @static + * @property 删除行前事件 + */ + BD: "beforedelete", + + /** + * @static + * @property 删除行后事件 + */ + AD: "beforedelete", + + /** + * @static + * @property 未提交离开事件 + */ + UC: "unloadcheck", + + + /** + * @static + * @property PDF导出前事件 + */ + BTOPDF: "beforetopdf", + + /** + * @static + * @property PDF导出后事件 + */ + ATOPDF: "aftertopdf", + + /** + * @static + * @property Excel导出前事件 + */ + BTOEXCEL: "beforetoexcel", + + /** + * @static + * @property Excel导出后事件 + */ + ATOEXCEL: "aftertoexcel", + + /** + * @static + * @property Word导出前事件 + */ + BTOWORD: "beforetoword", + + /** + * @static + * @property Word导出后事件 + */ + ATOWORD: "aftertoword", + + /** + * @static + * @property 图片导出前事件 + */ + BTOIMAGE: "beforetoimage", + + /** + * @static + * @property 图片导出后事件 + */ + ATOIMAGE: "aftertoimage", + + /** + * @static + * @property HTML导出前事件 + */ + BTOHTML: "beforetohtml", + + /** + * @static + * @property HTML导出后事件 + */ + ATOHTML: "aftertohtml", + + /** + * @static + * @property Excel导入前事件 + */ + BIMEXCEL: "beforeimportexcel", + + /** + * @static + * @property Excel导出后事件 + */ + AIMEXCEL: "afterimportexcel", + + /** + * @static + * @property PDF打印前事件 + */ + BPDFPRINT: "beforepdfprint", + + /** + * @static + * @property PDF打印后事件 + */ + APDFPRINT: "afterpdfprint", + + /** + * @static + * @property Flash打印前事件 + */ + BFLASHPRINT: "beforeflashprint", + + /** + * @static + * @property Flash打印后事件 + */ + AFLASHPRINT: "afterflashprint", + + /** + * @static + * @property Applet打印前事件 + */ + BAPPLETPRINT: "beforeappletprint", + + /** + * @static + * @property Applet打印后事件 + */ + AAPPLETPRINT: "afterappletprint", + + /** + * @static + * @property 服务器打印前事件 + */ + BSEVERPRINT: "beforeserverprint", + + /** + * @static + * @property 服务器打印后事件 + */ + ASERVERPRINT: "afterserverprint", + + /** + * @static + * @property 邮件发送前事件 + */ + BEMAIL: "beforeemail", + + /** + * @static + * @property 邮件发送后事件 + */ + AEMAIL: "afteremail", +}; diff --git a/src/core/constant/index.js b/src/core/constant/index.js new file mode 100644 index 000000000..205529687 --- /dev/null +++ b/src/core/constant/index.js @@ -0,0 +1,2 @@ +export { Events } from "./events"; +export * from "./var"; diff --git a/src/core/constant/var.js b/src/core/constant/var.js index f9acb8b30..a109324c0 100644 --- a/src/core/constant/var.js +++ b/src/core/constant/var.js @@ -1,167 +1,170 @@ /** * 常量 */ +import { isNumber } from "../2.base"; -BI._.extend(BI, { - MAX: 0xfffffffffffffff, - MIN: -0xfffffffffffffff, - EVENT_RESPONSE_TIME: 200, - EVENT_BLUR: true, - zIndex_layer: 1e5, - zIndex_popover: 1e6, - zIndex_popup: 1e7, - zIndex_masker: 1e8, - zIndex_tip: 1e9, - emptyStr: "", - pixUnit: "px", - pixRatio: 1, - // 一定返回最终的单位 - pixFormat: function (pix, border) { - if (!BI.isNumber(pix)) { - return pix; - } - if (BI.pixUnit === "px") { - return (pix / BI.pixRatio - (border || 0)) + BI.pixUnit; - } - var length = pix / BI.pixRatio + BI.pixUnit; - if (border > 0) { - return `calc(${length} - ${border + "px"})`; - } - return length; - }, - toPix: function (pix, border) { - if (!BI.isNumber(pix)) { - return pix; - } - if (BI.pixUnit === "px") { - return pix - (border || 0) * BI.pixRatio; - } - if (border > 0) { - return `calc(${pix / BI.pixRatio + BI.pixUnit} - ${border + "px"})`; - } +export const MAX = 0xfffffffffffffff; +export const MIN = -0xfffffffffffffff; +export const EVENT_RESPONSE_TIME = 200; +export const EVENT_BLUR = true; +export const zIndex_layer = 1e5; +export const zIndex_popover = 1e6; +export const zIndex_popup = 1e7; +export const zIndex_masker = 1e8; +export const zIndex_tip = 1e9; +export const emptyStr = ""; +export const pixUnit = "px"; +export const pixRatio = 1; +export const empty = null; +export const Key = { + 48: "0", + 49: "1", + 50: "2", + 51: "3", + 52: "4", + 53: "5", + 54: "6", + 55: "7", + 56: "8", + 57: "9", + 65: "a", + 66: "b", + 67: "c", + 68: "d", + 69: "e", + 70: "f", + 71: "g", + 72: "h", + 73: "i", + 74: "j", + 75: "k", + 76: "l", + 77: "m", + 78: "n", + 79: "o", + 80: "p", + 81: "q", + 82: "r", + 83: "s", + 84: "t", + 85: "u", + 86: "v", + 87: "w", + 88: "x", + 89: "y", + 90: "z", + 96: "0", + 97: "1", + 98: "2", + 99: "3", + 100: "4", + 101: "5", + 102: "6", + 103: "7", + 104: "8", + 105: "9", + 106: "*", + 107: "+", + 109: "-", + 110: ".", + 111: "/", +}; +export const KeyCode = { + BACKSPACE: 8, + COMMA: 188, + DELETE: 46, + DOWN: 40, + END: 35, + ENTER: 13, + ESCAPE: 27, + HOME: 36, + LEFT: 37, + NUMPAD_ADD: 107, + NUMPAD_DECIMAL: 110, + NUMPAD_DIVIDE: 111, + NUMPAD_ENTER: 108, + NUMPAD_MULTIPLY: 106, + NUMPAD_SUBTRACT: 109, + PAGE_DOWN: 34, + PAGE_UP: 33, + PERIOD: 190, + RIGHT: 39, + SPACE: 32, + TAB: 9, + UP: 38, +}; +export const Status = { + SUCCESS: 1, + WRONG: 2, + START: 3, + END: 4, + WAITING: 5, + READY: 6, + RUNNING: 7, + OUTOFBOUNDS: 8, + NULL: -1, +}; +export const Direction = { + Top: "top", + Bottom: "bottom", + Left: "left", + Right: "right", + Custom: "custom", +}; +export const Axis = { + Vertical: "vertical", + Horizontal: "horizontal", +}; +export const Selection = { + Default: -2, + None: -1, + Single: 0, + Multi: 1, + All: 2, +}; +export const HorizontalAlign = { + Left: "left", + Right: "right", + Center: "center", + Stretch: "stretch", +}; +export const VerticalAlign = { + Middle: "middle", + Top: "top", + Bottom: "bottom", + Stretch: "stretch", +}; +export const StartOfWeek = 1; +export const BlankSplitChar = "\u200b \u200b"; + +// 一定返回最终的单位 +export function pixFormat(pix, border) { + if (!isNumber(pix)) { + return pix; + } + if (pixUnit === "px") { + return (pix / pixRatio - (border || 0)) + pixUnit; + } + const length = pix / pixRatio + pixUnit; + if (border > 0) { + return `calc(${length} - ${`${border}px`})`; + } + + return length; +} + +export function toPix(pix, border) { + if (!isNumber(pix)) { return pix; - }, - emptyFn: function () { - }, - empty: null, - Key: { - 48: "0", - 49: "1", - 50: "2", - 51: "3", - 52: "4", - 53: "5", - 54: "6", - 55: "7", - 56: "8", - 57: "9", - 65: "a", - 66: "b", - 67: "c", - 68: "d", - 69: "e", - 70: "f", - 71: "g", - 72: "h", - 73: "i", - 74: "j", - 75: "k", - 76: "l", - 77: "m", - 78: "n", - 79: "o", - 80: "p", - 81: "q", - 82: "r", - 83: "s", - 84: "t", - 85: "u", - 86: "v", - 87: "w", - 88: "x", - 89: "y", - 90: "z", - 96: "0", - 97: "1", - 98: "2", - 99: "3", - 100: "4", - 101: "5", - 102: "6", - 103: "7", - 104: "8", - 105: "9", - 106: "*", - 107: "+", - 109: "-", - 110: ".", - 111: "/" - }, - KeyCode: { - BACKSPACE: 8, - COMMA: 188, - DELETE: 46, - DOWN: 40, - END: 35, - ENTER: 13, - ESCAPE: 27, - HOME: 36, - LEFT: 37, - NUMPAD_ADD: 107, - NUMPAD_DECIMAL: 110, - NUMPAD_DIVIDE: 111, - NUMPAD_ENTER: 108, - NUMPAD_MULTIPLY: 106, - NUMPAD_SUBTRACT: 109, - PAGE_DOWN: 34, - PAGE_UP: 33, - PERIOD: 190, - RIGHT: 39, - SPACE: 32, - TAB: 9, - UP: 38 - }, - Status: { - SUCCESS: 1, - WRONG: 2, - START: 3, - END: 4, - WAITING: 5, - READY: 6, - RUNNING: 7, - OUTOFBOUNDS: 8, - NULL: -1 - }, - Direction: { - Top: "top", - Bottom: "bottom", - Left: "left", - Right: "right", - Custom: "custom" - }, - Axis: { - Vertical: "vertical", - Horizontal: "horizontal" - }, - Selection: { - Default: -2, - None: -1, - Single: 0, - Multi: 1, - All: 2 - }, - HorizontalAlign: { - Left: "left", - Right: "right", - Center: "center", - Stretch: "stretch" - }, - VerticalAlign: { - Middle: "middle", - Top: "top", - Bottom: "bottom", - Stretch: "stretch" - }, - StartOfWeek: 1, - BlankSplitChar: "\u200b \u200b", -}); + } + if (pixUnit === "px") { + return pix - (border || 0) * pixRatio; + } + if (border > 0) { + return `calc(${pix / pixRatio + pixUnit} - ${`${border}px`})`; + } + + return pix; +} + +export function emptyFn() {} diff --git a/src/core/controller/0.controller.js b/src/core/controller/0.controller.js index 0841a9358..7cda6a2a5 100644 --- a/src/core/controller/0.controller.js +++ b/src/core/controller/0.controller.js @@ -2,11 +2,9 @@ * guy * 控制器 * Controller层超类 - * @class BI.Controller - * @extends BI.OB - * @abstract */ import { OB } from "../3.ob"; + export class Controller extends OB { static EVENT_CHANGE = "__EVENT_CHANGE__"; } diff --git a/src/core/controller/controller.broadcast.js b/src/core/controller/controller.broadcast.js index f0cc90c8d..3f1eb3035 100644 --- a/src/core/controller/controller.broadcast.js +++ b/src/core/controller/controller.broadcast.js @@ -2,9 +2,10 @@ * 广播 * * Created by GUY on 2015/12/23. - * @class */ import { Controller } from "./0.controller"; +import { each, remove } from "../2.base"; + export class BroadcastController extends Controller { init() { this._broadcasts = {}; @@ -15,23 +16,25 @@ export class BroadcastController extends Controller { this._broadcasts[name] = []; } this._broadcasts[name].push(fn); + return () => this.remove(name, fn); } send(name) { const args = [].slice.call(arguments, 1); - BI.each(this._broadcasts[name], (i, fn) => fn.apply(null, args)); + each(this._broadcasts[name], (i, fn) => fn(...args)); } remove(name, fn) { if (fn) { - BI.remove(this._broadcasts[name], (index, cb) => fn === cb); + remove(this._broadcasts[name], (index, cb) => fn === cb); if (this._broadcasts[name].length === 0) { delete this._broadcasts[name]; } } else { delete this._broadcasts[name]; } + return this; } -} \ No newline at end of file +} diff --git a/src/core/controller/controller.bubbles.js b/src/core/controller/controller.bubbles.js index e596eac60..64147fdcc 100644 --- a/src/core/controller/controller.bubbles.js +++ b/src/core/controller/controller.bubbles.js @@ -3,9 +3,11 @@ * 控制气泡图的显示方向 * * Created by GUY on 2015/8/21. - * @class */ import { Controller } from "./0.controller"; +import { isNotNull, each } from "../2.base"; +import { createWidget } from "../5.inject"; + export class BubblesController extends Controller { init() { this.storeBubbles = {}; @@ -30,12 +32,12 @@ export class BubblesController extends Controller { // const fixed = opt.fixed !== false; if (!this.storeBubbles[name]) { - this.storeBubbles[name] = BI.createWidget({ + this.storeBubbles[name] = createWidget({ type: "bi.text", - cls: "bi-bubble" + " bubble-" + level, - text: text, + cls: `bi-bubble bubble-${level}`, + text, hgap: 5, - height: 18 + height: 18, }); } const bubble = this.storeBubbles[name]; @@ -43,14 +45,14 @@ export class BubblesController extends Controller { bubble.setText(text); } - BI.createWidget({ + createWidget({ type: "bi.default", element: container, items: [ { - el: bubble + el: bubble, } - ] + ], }); if (this.storePoppers[name]) { this.storePoppers[name].destroy(); @@ -59,32 +61,34 @@ export class BubblesController extends Controller { placement: ({ left: "top-start", center: "top", - right: "top-end" + right: "top-end", })[offsetStyle], strategy: "fixed", modifiers: [ { name: "offset", options: { - offset: [adjustXOffset, adjustYOffset] - } + offset: [adjustXOffset, adjustYOffset], + }, }, { name: "preventOverflow", - enabled: false + enabled: false, } - ] + ], }); + return this; } hide(name) { this.remove(name); + return this; } has(name) { - return this.storeBubbles[name] != null; + return isNotNull(this.storeBubbles[name]); } remove(name) { @@ -94,14 +98,16 @@ export class BubblesController extends Controller { this.storeBubbles[name].destroy(); this.storePoppers[name] && this.storePoppers[name].destroy(); delete this.storeBubbles[name]; + return this; } removeAll() { - BI.each(this.storeBubbles, (name, bubble) => bubble.destroy()); - BI.each(this.storePoppers, (name, popper) => popper.destroy()); + each(this.storeBubbles, (name, bubble) => bubble.destroy()); + each(this.storePoppers, (name, popper) => popper.destroy()); this.storeBubbles = {}; this.storePoppers = {}; + return this; } } diff --git a/src/core/controller/controller.drawer.js b/src/core/controller/controller.drawer.js index 51a80b734..806d8c67b 100644 --- a/src/core/controller/controller.drawer.js +++ b/src/core/controller/controller.drawer.js @@ -1,10 +1,11 @@ /** * guy * popover弹出层控制器, z-index在100w层级 - * @class BI.popoverController - * @extends BI.Controller */ import { Controller } from "./0.controller"; +import { each, isNotNull } from "../2.base"; +import { createWidget } from "../5.inject"; + export class DrawerController extends Controller { constructor() { super(); @@ -13,7 +14,7 @@ export class DrawerController extends Controller { } props = { modal: true, // 模态窗口 - render: "body" + render: "body", } init() { @@ -28,15 +29,15 @@ export class DrawerController extends Controller { if (this.has(name)) { return this; } - const popover = BI.createWidget(options || {}, { - type: "bi.drawer" + const popover = createWidget(options || {}, { + type: "bi.drawer", }, context); this.add(name, popover, options, context); + return this; } open(name) { - const o = this.options; if (!this.has(name)) { return this; } @@ -59,6 +60,7 @@ export class DrawerController extends Controller { const popover = this.get(name); popover.show && popover.show(); } + return this; } @@ -71,6 +73,7 @@ export class DrawerController extends Controller { this.floatContainer[name].invisible(); this.modal && this.floatContainer[name].element.__releaseZIndexMask__(this.zindexMap[name]); } + return this; } @@ -91,23 +94,23 @@ export class DrawerController extends Controller { if (this.has(name)) { return this; } - this.floatContainer[name] = BI.createWidget({ + this.floatContainer[name] = createWidget({ type: "bi.absolute", cls: "bi-popup-view", items: [{ - el: (this.floatLayer[name] = BI.createWidget({ + el: (this.floatLayer[name] = createWidget({ type: "bi.absolute", - items: [popover] + items: [popover], }, context)), left: 0, right: 0, top: 0, - bottom: 0 - }] + bottom: 0, + }], }); this.floatManager[name] = popover; popover.on(BI.Drawer.EVENT_CLOSE, () => this.close(name)); - BI.createWidget({ + createWidget({ type: "bi.absolute", element: options.container || this.options.render, items: [{ @@ -115,9 +118,10 @@ export class DrawerController extends Controller { left: 0, right: 0, top: 0, - bottom: 0 - }] + bottom: 0, + }], }); + return this; } @@ -126,7 +130,7 @@ export class DrawerController extends Controller { } has(name) { - return BI.isNotNull(this.floatManager[name]); + return isNotNull(this.floatManager[name]); } remove(name) { @@ -140,11 +144,12 @@ export class DrawerController extends Controller { delete this.zindexMap[name]; delete this.floatContainer[name]; delete this.floatOpened[name]; + return this; } removeAll() { - BI.each(this.floatContainer, (name, container) => { + each(this.floatContainer, (name, container) => { container.destroy(); this.modal && this.floatContainer[name].element.__releaseZIndexMask__(this.zindexMap[name]); }); @@ -153,6 +158,7 @@ export class DrawerController extends Controller { this.floatContainer = {}; this.floatOpened = {}; this.zindexMap = {}; + return this; } } diff --git a/src/core/controller/controller.layer.js b/src/core/controller/controller.layer.js index 6356588ab..eb47237e1 100644 --- a/src/core/controller/controller.layer.js +++ b/src/core/controller/controller.layer.js @@ -2,9 +2,12 @@ * 弹出层面板控制器, z-index在10w层级 * * Created by GUY on 2015/6/24. - * @class */ import { Controller } from "./0.controller"; +import { isNull, isNotNull, each, keys, isWidget, isNotEmptyString, extend } from "../2.base"; +import { Widget } from "../4.widget"; +import { createWidget } from "../5.inject"; + export class LayerController extends Controller { constructor() { super(); @@ -12,7 +15,7 @@ export class LayerController extends Controller { } props = { - render: "body" + render: "body", } init() { @@ -22,11 +25,11 @@ export class LayerController extends Controller { } _initResizer() { - this.resizer = BI.Resizers.add("layerController" + BI.uniqueId(), BI.bind(this._resize, this)); + this.resizer = BI.Resizers.add(`layerController${BI.uniqueId()}`, BI.bind(this._resize, this)); } _resize() { - BI.each(this.layouts, function (i, layer) { + each(this.layouts, (i, layer) => { if (layer.element.is(":visible")) { layer.element.trigger("__resize__"); } @@ -34,37 +37,38 @@ export class LayerController extends Controller { } make(name, container, op, context) { - if (BI.isWidget(container)) { + if (isWidget(container)) { op = op || {}; op.container = container; } else { context = op; op = container; } + return this.create(name, null, op, context); } create(name, from, op, context) { - BI.isNull(this.resizer) && this._initResizer(); + isNull(this.resizer) && this._initResizer(); if (this.has(name)) { return this.get(name); } op || (op = {}); const offset = op.offset || {}; let w = from; - if (BI.isWidget(from)) { + if (isWidget(from)) { w = from.element; } - if (BI.isNotEmptyString(w)) { - w = BI.Widget._renderEngine.createElement(w); + if (isNotEmptyString(w)) { + w = Widget._renderEngine.createElement(w); } if (this.has(name)) { return this.get(name); } - const widget = BI.createWidget((op.render || {}), BI.extend({ - type: "bi.layout" + const widget = createWidget((op.render || {}), extend({ + type: "bi.layout", }, op), context); - const layout = BI.createWidget({ + const layout = createWidget({ type: "bi.absolute", invisible: true, items: [ @@ -73,11 +77,11 @@ export class LayerController extends Controller { left: 0, right: 0, top: 0, - bottom: 0 + bottom: 0, } - ] + ], }, context); - BI.createWidget({ + createWidget({ type: "bi.absolute", element: op.container || this.options.render, items: [ @@ -86,20 +90,19 @@ export class LayerController extends Controller { left: offset.left || 0, right: offset.right || 0, top: offset.top || 0, - bottom: offset.bottom || 0 + bottom: offset.bottom || 0, } - ] + ], }); if (w) { layout.element.addClass("bi-popup-view"); function getComputedPosition() { - - var css = { + const css = { left: w.offset().left + (offset.left || 0), top: w.offset().top + (offset.top || 0), width: offset.width || (w.outerWidth() - (offset.left || 0) - (offset.right || 0)) || "", - height: offset.height || (w.outerHeight() - (offset.top || 0) - (offset.bottom || 0)) || "" + height: offset.height || (w.outerHeight() - (offset.top || 0) - (offset.bottom || 0)) || "", }; const { top, left, scaleY, scaleX } = BI.DOM.getPositionRelativeContainingBlockRect(layout.element[0]); @@ -112,12 +115,13 @@ export class LayerController extends Controller { layout.element.css(getComputedPosition()); - layout.element.on("__resize__", function () { + layout.element.on("__resize__", () => { w.is(":visible") && layout.element.css(getComputedPosition()); }); } this.add(name, widget, layout); + return widget; } @@ -127,6 +131,7 @@ export class LayerController extends Controller { } this._getLayout(name).visible(); this._getLayout(name).element.css("z-index", this.zindex++).show(0, callback).trigger("__resize__"); + return this; } @@ -136,6 +141,7 @@ export class LayerController extends Controller { } this._getLayout(name).invisible(); this._getLayout(name).element.hide(0, callback); + return this; } @@ -151,6 +157,7 @@ export class LayerController extends Controller { this.layerManager[name] = layer; this.layouts[name] = layout; layout.element.css("z-index", this.zindex++); + return this; } @@ -163,7 +170,7 @@ export class LayerController extends Controller { } has(name) { - return this.layerManager[name] != null; + return isNotNull(this.layerManager[name]); } remove(name) { @@ -174,16 +181,18 @@ export class LayerController extends Controller { this.layouts[name].destroy(); delete this.layerManager[name]; delete this.layouts[name]; + return this; } removeAll() { - BI.each(BI.keys(this.layerManager), (index, name) => { + each(keys(this.layerManager), (index, name) => { this.layerManager[name].destroy(); this.layouts[name].destroy(); }); this.layerManager = {}; this.layouts = {}; + return this; } } diff --git a/src/core/controller/controller.masker.js b/src/core/controller/controller.masker.js index 7ff0532bc..6a2fa10d6 100644 --- a/src/core/controller/controller.masker.js +++ b/src/core/controller/controller.masker.js @@ -2,9 +2,9 @@ * 遮罩面板, z-index在1亿层级 * * Created by GUY on 2015/6/24. - * @class */ import { LayerController } from "./controller.layer"; + export class MaskersController extends LayerController { init() { super.init(arguments); diff --git a/src/core/controller/controller.popover.js b/src/core/controller/controller.popover.js index dc8e6a14d..9d6bc9700 100644 --- a/src/core/controller/controller.popover.js +++ b/src/core/controller/controller.popover.js @@ -1,10 +1,12 @@ /** * guy * popover弹出层控制器, z-index在100w层级 - * @class BI.popoverController - * @extends BI.Controller */ import { Controller } from "./0.controller"; +import { isNotNull, each } from "../2.base"; +import { Widget } from "../4.widget"; +import { createWidget } from "../5.inject"; + export class PopoverController extends Controller { constructor() { super(); @@ -14,7 +16,7 @@ export class PopoverController extends Controller { props = { modal: true, // 模态窗口 - render: "body" + render: "body", } init() { @@ -30,10 +32,11 @@ export class PopoverController extends Controller { if (this.has(name)) { return this; } - const popover = BI.createWidget(options || {}, { - type: "bi.popover" + const popover = createWidget(options || {}, { + type: "bi.popover", }, context); this.add(name, popover, options, context); + return this; } @@ -52,8 +55,8 @@ export class PopoverController extends Controller { this.floatContainer[name].visible(); const popover = this.get(name); popover.show && popover.show(); - const W = BI.Widget._renderEngine.createElement(this.options.render).width(), - H = BI.Widget._renderEngine.createElement(this.options.render).height(); + const W = Widget._renderEngine.createElement(this.options.render).width(), + H = Widget._renderEngine.createElement(this.options.render).height(); const w = popover.element.width(), h = popover.element.height(); let left = (W - w) / 2, top = (H - h) / 2; if (left < 0) { @@ -64,10 +67,11 @@ export class PopoverController extends Controller { } popover.element.css({ // 这里直接用px就可以 - left: left + "px", - top: top + "px" + left: `${left}px`, + top: `${top}px`, }); } + return this; } @@ -80,6 +84,7 @@ export class PopoverController extends Controller { this.floatContainer[name].invisible(); this.modal && this.floatContainer[name].element.__releaseZIndexMask__(this.zindexMap[name]); } + return this; } @@ -100,23 +105,23 @@ export class PopoverController extends Controller { if (this.has(name)) { return this; } - this.floatContainer[name] = BI.createWidget({ + this.floatContainer[name] = createWidget({ type: "bi.absolute", cls: "bi-popup-view", items: [{ - el: (this.floatLayer[name] = BI.createWidget({ + el: (this.floatLayer[name] = createWidget({ type: "bi.absolute", - items: [popover] + items: [popover], }, context)), left: 0, right: 0, top: 0, - bottom: 0 - }] + bottom: 0, + }], }); this.floatManager[name] = popover; popover.on(BI.Popover.EVENT_CLOSE, () => this.close(name)); - BI.createWidget({ + createWidget({ type: "bi.absolute", element: options.container || this.options.render, items: [{ @@ -124,9 +129,10 @@ export class PopoverController extends Controller { left: 0, right: 0, top: 0, - bottom: 0 - }] + bottom: 0, + }], }); + return this; } @@ -135,7 +141,7 @@ export class PopoverController extends Controller { } has(name) { - return BI.isNotNull(this.floatManager[name]); + return isNotNull(this.floatManager[name]); } remove(name) { @@ -149,11 +155,12 @@ export class PopoverController extends Controller { delete this.zindexMap[name]; delete this.floatContainer[name]; delete this.floatOpened[name]; + return this; } removeAll() { - BI.each(this.floatContainer, (name, container) => { + each(this.floatContainer, (name, container) => { container.destroy(); this.modal && this.floatContainer[name].element.__releaseZIndexMask__(this.zindexMap[name]); }); @@ -162,6 +169,7 @@ export class PopoverController extends Controller { this.floatContainer = {}; this.floatOpened = {}; this.zindexMap = {}; + return this; } diff --git a/src/core/controller/controller.resizer.js b/src/core/controller/controller.resizer.js index 5b8c400b8..e14ee1ad0 100644 --- a/src/core/controller/controller.resizer.js +++ b/src/core/controller/controller.resizer.js @@ -2,49 +2,53 @@ * window.resize 控制器 * * Created by GUY on 2015/6/24. - * @class */ import { Controller } from "./0.controller"; -export class ResizeController extends Controller { +import { isNull, each, debounce, isNotNull, isFunction } from "../2.base"; +import { Widget } from "../4.widget"; +export class ResizeController extends Controller { init() { this.resizerManger = {}; } _initResizeListener() { - this.resizeHandler = BI.debounce((ev) => this._resize(ev), 30); + this.resizeHandler = debounce(ev => this._resize(ev), 30); if ("onorientationchange" in _global) { _global.onorientationchange = this.resizeHandler; } else { - BI.Widget._renderEngine.createElement(_global).resize(this.resizeHandler); + Widget._renderEngine.createElement(_global).resize(this.resizeHandler); } } _resize(ev) { - BI.each(this.resizerManger, function (key, resizer) { + each(this.resizerManger, (key, resizer) => { if (resizer instanceof BI.$) { if (resizer.is(":visible")) { resizer.trigger("__resize__"); } + return; } if (resizer instanceof BI.Layout) { resizer.resize(); + return; } - if (BI.isFunction(resizer)) { + if (isFunction(resizer)) { resizer(ev); } }); } add(name, resizer) { - BI.isNull(this.resizeHandler) && this._initResizeListener(); + isNull(this.resizeHandler) && this._initResizeListener(); if (this.has(name)) { return this; } this.resizerManger[name] = resizer; + return () => this.remove(name); } @@ -53,7 +57,7 @@ export class ResizeController extends Controller { } has(name) { - return this.resizerManger[name] != null; + return isNotNull(this.resizerManger[name]); } remove(name) { @@ -61,6 +65,7 @@ export class ResizeController extends Controller { return this; } delete this.resizerManger[name]; + return this; } } diff --git a/src/core/controller/controller.tooltips.js b/src/core/controller/controller.tooltips.js index e084caba9..da571a504 100644 --- a/src/core/controller/controller.tooltips.js +++ b/src/core/controller/controller.tooltips.js @@ -3,10 +3,12 @@ * 控制tooltip的显示, 且页面中只有一个tooltip显示 * * Created by GUY on 2015/9/8. - * @class BI.TooltipsController - * @extends BI.Controller */ import { Controller } from "./0.controller"; +import { each, isNotNull } from "../2.base"; +import { Widget } from "../4.widget"; +import { createWidget } from "../5.inject"; + export class TooltipsController extends Controller { init() { this.tooltipsManager = {}; @@ -23,17 +25,17 @@ export class TooltipsController extends Controller { * @private */ _createTooltip(opt) { - return BI.createWidget({ + return createWidget({ type: "bi.tooltip", ...opt, - stopEvent: true + stopEvent: true, }); } // opt: {container: '', belowMouse: false} show(e, name, tooltipOpt, context, opt) { opt || (opt = {}); - BI.each(this.showingTips, (i, tip) => this.hide(i)); + each(this.showingTips, (i, tip) => this.hide(i)); this.showingTips = {}; if (!this.has(name)) { this.create(name, tooltipOpt, document.fullscreenElement ? context : (opt.container || "body")); @@ -51,7 +53,7 @@ export class TooltipsController extends Controller { const tooltip = this.get(name); tooltip.element.css({ left: "0px", - top: "0px" + top: "0px", }); tooltip.visible(); tooltip.element.height(tooltip.element[0].scrollHeight); @@ -60,10 +62,10 @@ export class TooltipsController extends Controller { // const scale = context.element.offset().left / context.element.get(0).getBoundingClientRect().left; // const x = (e.pageX || e.clientX) * scale + 15, y = (e.pageY || e.clientY) * scale + 15; let x = (e.pageX || e.clientX) + 15, y = (e.pageY || e.clientY) + 15; - if (x + tooltip.element.outerWidth() > BI.Widget._renderEngine.createElement("body").outerWidth()) { + if (x + tooltip.element.outerWidth() > Widget._renderEngine.createElement("body").outerWidth()) { x -= tooltip.element.outerWidth() + 15; } - const bodyHeight = BI.Widget._renderEngine.createElement("body").outerHeight(); + const bodyHeight = Widget._renderEngine.createElement("body").outerHeight(); if (y + tooltip.element.outerHeight() > bodyHeight || top + tooltip.element.outerHeight() > bodyHeight) { y -= tooltip.element.outerHeight() + 15; !opt.belowMouse && (y = Math.min(y, offset.top - tooltip.element.outerHeight() - 5)); @@ -72,13 +74,14 @@ export class TooltipsController extends Controller { } tooltip.element.css({ // 这里直接用px就可以 - left: x < 0 ? 0 : x + "px", - top: y < 0 ? 0 : y + "px" + left: x < 0 ? 0 : `${x}px`, + top: y < 0 ? 0 : `${y}px`, }); tooltip.element.hover(() => { this.remove(name); - context.element.trigger("mouseleave.title" + context.getName()); + context.element.trigger(`mouseleave.title${context.getName()}`); }); + return this; } @@ -89,6 +92,7 @@ export class TooltipsController extends Controller { delete this.showingTips[name]; this.get(name).element.hide(0, callback); this.get(name).invisible(); + return this; } @@ -96,15 +100,16 @@ export class TooltipsController extends Controller { if (!this.has(name)) { const tooltip = this._createTooltip(tooltipOpt); this.add(name, tooltip); - BI.createWidget({ + createWidget({ type: "bi.absolute", element: context || "body", items: [{ - el: tooltip - }] + el: tooltip, + }], }); tooltip.invisible(); } + return this.get(name); } @@ -113,6 +118,7 @@ export class TooltipsController extends Controller { return this; } this.set(name, bubble); + return this; } @@ -125,7 +131,7 @@ export class TooltipsController extends Controller { } has(name) { - return this.tooltipsManager[name] != null; + return isNotNull(this.tooltipsManager[name]); } remove(name) { @@ -134,15 +140,17 @@ export class TooltipsController extends Controller { } this.tooltipsManager[name].destroy(); delete this.tooltipsManager[name]; + return this; } removeAll() { - BI.each(this.tooltipsManager, function (name, tooltip) { + each(this.tooltipsManager, (name, tooltip) => { tooltip.destroy(); }); this.tooltipsManager = {}; this.showingTips = {}; + return this; } } diff --git a/src/core/controller/index.js b/src/core/controller/index.js index 91701e15f..c025e0daa 100644 --- a/src/core/controller/index.js +++ b/src/core/controller/index.js @@ -6,4 +6,4 @@ export { LayerController } from "./controller.layer"; export { MaskersController } from "./controller.masker"; export { PopoverController } from "./controller.popover"; export { ResizeController } from "./controller.resizer"; -export { TooltipsController } from "./controller.tooltips"; \ No newline at end of file +export { TooltipsController } from "./controller.tooltips"; diff --git a/src/core/element/element.js b/src/core/element/element.js index 7bf1c9d4a..9b08c0762 100644 --- a/src/core/element/element.js +++ b/src/core/element/element.js @@ -1,74 +1,76 @@ -import { registFunction } from './plugins'; +import { registFunction } from "./plugins"; +import { isWidget, isString } from "../2.base"; export function Element(widget, attribs) { - this.l = this.r = this.t = this.b = 0; // 边框 - this.marginLeft = this.marginRight = this.marginTop = this.marginBottom = 0; //间距 - this.position = {}; - this.classMap = {}; - this.classList = []; - this.children = []; - this.attribs = attribs || {}; - this.styles = {}; - // 兼容处理 - this['0'] = this; - this.style = {}; - if (!widget) { - this.nodeName = 'body'; - this.position.x = 0; - this.position.y = 0; - this.attribs.id = 'body'; - } else if (BI.isWidget(widget)) { - this.widget = widget; - this.nodeName = widget.options.tagName; - this.textBaseLine = widget.options.textBaseLine; - } else if (BI.isString(widget)) { - this.nodeName = widget; - } + this.l = this.r = this.t = this.b = 0; // 边框 + this.marginLeft = this.marginRight = this.marginTop = this.marginBottom = 0; // 间距 + this.position = {}; + this.classMap = {}; + this.classList = []; + this.children = []; + this.attribs = attribs || {}; + this.styles = {}; + // 兼容处理 + this["0"] = this; + this.style = {}; + if (!widget) { + this.nodeName = "body"; + this.position.x = 0; + this.position.y = 0; + this.attribs.id = "body"; + } else if (isWidget(widget)) { + this.widget = widget; + this.nodeName = widget.options.tagName; + this.textBaseLine = widget.options.textBaseLine; + } else if (isString(widget)) { + this.nodeName = widget; + } } initElement(Element); registFunction(Element); function initElement(element) { - element.prototype = { - appendChild(child) { - child.parent = this; - if (this.children.push(child) !== 1) { - var sibling = this.children[this.children.length - 2]; - sibling.next = child; - child.prev = sibling; - child.next = null; - } - }, - append(child) { - child.parent = this; - if (this.children.push(child) !== 1) { - var sibling = this.children[this.children.length - 2]; - sibling.next = child; - child.prev = sibling; - child.next = null; - } - }, - getParent() { - return this.parent; - }, - getSiblings() { - var parent = this.getParent(); - return parent ? parent.getChildren() : [this]; - }, - getChildren() { - return this.children; - }, + element.prototype = { + appendChild(child) { + child.parent = this; + if (this.children.push(child) !== 1) { + const sibling = this.children[this.children.length - 2]; + sibling.next = child; + child.prev = sibling; + child.next = null; + } + }, + append(child) { + child.parent = this; + if (this.children.push(child) !== 1) { + const sibling = this.children[this.children.length - 2]; + sibling.next = child; + child.prev = sibling; + child.next = null; + } + }, + getParent() { + return this.parent; + }, + getSiblings() { + const parent = this.getParent(); + + return parent ? parent.getChildren() : [this]; + }, + getChildren() { + return this.children; + }, - getBounds() { - return {}; - }, + getBounds() { + return {}; + }, - width() { + width() { - }, - height() { + }, + height() { - } - }; + }, + }; } diff --git a/src/core/element/index.js b/src/core/element/index.js index bbc4eb926..070afb0f3 100644 --- a/src/core/element/index.js +++ b/src/core/element/index.js @@ -1,16 +1,17 @@ -import { Element } from './element'; +import { Element } from "./element"; +import { isString, isWidget } from "../2.base"; BI.Element = Element; BI.Element.renderEngine = { - createElement: (widget) => { - // eslint-disable-next-line no-undef - if (BI.isWidget(widget)) { - var o = widget.options; + createElement: widget => { + if (isWidget(widget)) { + const o = widget.options; if (o.element instanceof Element) { return o.element; } - if (typeof o.element === 'string' && o.element !== 'body') { + if (typeof o.element === "string" && o.element !== "body") { o.root = false; + return new Element(widget); } @@ -18,14 +19,14 @@ BI.Element.renderEngine = { return new Element(); } } - // eslint-disable-next-line no-undef - if (BI.isString(widget)) { + if (isString(widget)) { return new Element(widget); } + return new Element(widget); }, createFragment() { return new Element(); - } -} + }, +}; diff --git a/src/core/element/plugins/attr.js b/src/core/element/plugins/attr.js index 3ae918f29..a680955c7 100644 --- a/src/core/element/plugins/attr.js +++ b/src/core/element/plugins/attr.js @@ -1,22 +1,25 @@ -export const registAttrFun = (Element) => { - Element.registerFunction('attr', function (key, value) { - var self = this; - if (BI.isObject(key)) { - BI.each(key, (k, v) => { - self.attr(k, v); - }); - return this; - } - if (BI.isNull(value)) { - return this.attribs[key]; - } - this.attribs[key] = value; - return this; - }); - Element.registerFunction('hasAttrib', function (key) { - return this.attribs[key] != null; - }); - Element.registerFunction('removeAttr', function (key) { - delete this.attribs[key]; - }); +import { isObject, each, isNull, isNotNull } from "../../2.base"; + +export const registAttrFun = Element => { + Element.registerFunction("attr", function (key, value) { + if (isObject(key)) { + each(key, (k, v) => { + this.attr(k, v); + }); + + return this; + } + if (isNull(value)) { + return this.attribs[key]; + } + this.attribs[key] = value; + + return this; + }); + Element.registerFunction("hasAttrib", function (key) { + return isNotNull(this.attribs[key]); + }); + Element.registerFunction("removeAttr", function (key) { + delete this.attribs[key]; + }); }; diff --git a/src/core/element/plugins/class.js b/src/core/element/plugins/class.js index ce46e6864..1c4c8eaba 100644 --- a/src/core/element/plugins/class.js +++ b/src/core/element/plugins/class.js @@ -1,23 +1,23 @@ -export const registClassFun = (Element) => { - Element.registerFunction('addClass', function (classList) { - var self = this; - BI.each(classList.split(' '), (i, cls) => { - if (cls && !self.classMap[cls]) { - self.classList.push(cls); - } - cls && (self.classMap[cls] = true); +export const registClassFun = Element => { + Element.registerFunction("addClass", function (classList) { + BI.each(classList.split(" "), (i, cls) => { + if (cls && !this.classMap[cls]) { + this.classList.push(cls); + } + cls && (this.classMap[cls] = true); + }); + + return this; }); - return this; - }); - Element.registerFunction('removeClass', function (classList) { - var self = this; - BI.each(classList.split(' '), (i, cls) => { - if (cls && self.classMap[cls]) { - delete self.classMap[cls]; - self.classList.splice(self.classList.indexOf(cls), 1); - } + Element.registerFunction("removeClass", function (classList) { + BI.each(classList.split(" "), (i, cls) => { + if (cls && this.classMap[cls]) { + delete this.classMap[cls]; + this.classList.splice(this.classList.indexOf(cls), 1); + } + }); + + return this; }); - return this; - }); }; diff --git a/src/core/element/plugins/css.js b/src/core/element/plugins/css.js index e1826a155..f5372da0e 100644 --- a/src/core/element/plugins/css.js +++ b/src/core/element/plugins/css.js @@ -1,22 +1,26 @@ -export const registCssFun = (Element) => { - Element.registerFunction('css', function (key, value) { - var self = this; - if (BI.isObject(key)) { - BI.each(key, (k, v) => { - self.css(k, v); - }); - return this; - } - key = BI.trim(BI.camelize(key)); - return css(this, key, value); - }); +import { isNull, isObject, each, trim, camelize } from "../../2.base"; + +export const registCssFun = Element => { + Element.registerFunction("css", function (key, value) { + if (isObject(key)) { + each(key, (k, v) => { + this.css(k, v); + }); + + return this; + } + key = trim(camelize(key)); + + return css(this, key, value); + }); }; const css = (elem, key, value) => { - key = BI.trim(BI.camelize(key)); - if (BI.isNull(value)) { - return elem.styles[key]; - } - elem.styles[key] = value; - return elem; + key = trim(camelize(key)); + if (isNull(value)) { + return elem.styles[key]; + } + elem.styles[key] = value; + + return elem; }; diff --git a/src/core/element/plugins/data.js b/src/core/element/plugins/data.js index e141c96c3..0e7cbb2d5 100644 --- a/src/core/element/plugins/data.js +++ b/src/core/element/plugins/data.js @@ -1,12 +1,15 @@ -export const registDataFun = (Element) => { - Element.registerFunction('data', function (key, value) { - if (!this._data) { - this._data = {}; - } - if (BI.isNull(value)) { - return this._data[key]; - } - this._data[key] = value; - return this; - }); +import { isNull } from "../../2.base"; + +export const registDataFun = Element => { + Element.registerFunction("data", function (key, value) { + if (!this._data) { + this._data = {}; + } + if (isNull(value)) { + return this._data[key]; + } + this._data[key] = value; + + return this; + }); }; diff --git a/src/core/element/plugins/empty.js b/src/core/element/plugins/empty.js index dbe5e0c1d..3cfe0177c 100644 --- a/src/core/element/plugins/empty.js +++ b/src/core/element/plugins/empty.js @@ -1,9 +1,10 @@ -export const registEmptyFun = (Element) => { - Element.registerFunction('empty', function (text) { - this.children = []; - return this; - }); - Element.registerFunction('destroy', function (text) { - return this; - }); +export const registEmptyFun = Element => { + Element.registerFunction("empty", function (text) { + this.children = []; + + return this; + }); + Element.registerFunction("destroy", function (text) { + return this; + }); }; diff --git a/src/core/element/plugins/event.js b/src/core/element/plugins/event.js index 38004ed88..66d89de97 100644 --- a/src/core/element/plugins/event.js +++ b/src/core/element/plugins/event.js @@ -1,32 +1,33 @@ -var returnThis = function () { - return this; -}; -export const registEventFun = (Element) => { - [ - 'mousedown', - 'mouseup', - 'mousewheel', - 'keydown', - 'keyup', - 'focus', - 'focusin', - 'focusout', - 'click', - 'on', - 'off', - 'bind', - 'unbind', - 'trigger', - 'hover', - 'scroll', - 'scrollLeft', - 'scrollTop', - 'resize', - 'show', - 'hide', - 'dblclick', - 'blur', - ].forEach((event) => { - Element.registerFunction(event, returnThis); - }); +function returnThis () { + return this; +} + +export const registEventFun = Element => { + [ + "mousedown", + "mouseup", + "mousewheel", + "keydown", + "keyup", + "focus", + "focusin", + "focusout", + "click", + "on", + "off", + "bind", + "unbind", + "trigger", + "hover", + "scroll", + "scrollLeft", + "scrollTop", + "resize", + "show", + "hide", + "dblclick", + "blur" + ].forEach(event => { + Element.registerFunction(event, returnThis); + }); }; diff --git a/src/core/element/plugins/html.js b/src/core/element/plugins/html.js index b115f9388..18cf233d6 100644 --- a/src/core/element/plugins/html.js +++ b/src/core/element/plugins/html.js @@ -1,15 +1,19 @@ -export const registHtmlFun = (Element) => { - Element.registerFunction('html', function (text) { - if (text && text.charAt(0) === '<') { - BI.createWidget({ - type: 'bi.html', - element: this.widget, - html: text, - }); - this.originalHtml = text; - } else { - this.text = BI.htmlDecode(text); - } - return this; - }); +import { createWidget } from "../../5.inject"; +import { htmlDecode } from "../../func"; + +export const registHtmlFun = Element => { + Element.registerFunction("html", function (text) { + if (text && text.charAt(0) === "<") { + createWidget({ + type: "bi.html", + element: this.widget, + html: text, + }); + this.originalHtml = text; + } else { + this.text = htmlDecode(text); + } + + return this; + }); }; diff --git a/src/core/element/plugins/index.js b/src/core/element/plugins/index.js index c32aab4dc..79e2f692c 100644 --- a/src/core/element/plugins/index.js +++ b/src/core/element/plugins/index.js @@ -1,31 +1,31 @@ -import { registAttrFun } from './attr'; -import { registClassFun } from './class'; -import { registCssFun } from './css'; -import { registDataFun } from './data'; -import { registEmptyFun } from './empty'; -import { registEventFun } from './event'; -import { registHtmlFun } from './html'; -import { registKeywordMarkFun } from './keywordMark'; -import { registRenderToHtmlFun } from './renderToHtml'; -import { registRenderToStringFun } from './renderToString'; -import { registTextFun } from './text'; -import { registValFun } from './val'; +import { registAttrFun } from "./attr"; +import { registClassFun } from "./class"; +import { registCssFun } from "./css"; +import { registDataFun } from "./data"; +import { registEmptyFun } from "./empty"; +import { registEventFun } from "./event"; +import { registHtmlFun } from "./html"; +import { registKeywordMarkFun } from "./keywordMark"; +import { registRenderToHtmlFun } from "./renderToHtml"; +import { registRenderToStringFun } from "./renderToString"; +import { registTextFun } from "./text"; +import { registValFun } from "./val"; -export const registFunction = (Element) => { - var functionMap = {}; - Element.registerFunction = (key, fn) => { - Element.prototype[key] = functionMap[key] = fn; - }; - registAttrFun(Element); - registClassFun(Element); - registCssFun(Element); - registDataFun(Element); - registEmptyFun(Element); - registEventFun(Element); - registHtmlFun(Element); - registKeywordMarkFun(Element); - registRenderToStringFun(Element); - registRenderToHtmlFun(Element); - registTextFun(Element); - registValFun(Element); +export const registFunction = Element => { + const functionMap = {}; + Element.registerFunction = (key, fn) => { + Element.prototype[key] = functionMap[key] = fn; + }; + registAttrFun(Element); + registClassFun(Element); + registCssFun(Element); + registDataFun(Element); + registEmptyFun(Element); + registEventFun(Element); + registHtmlFun(Element); + registKeywordMarkFun(Element); + registRenderToStringFun(Element); + registRenderToHtmlFun(Element); + registTextFun(Element); + registValFun(Element); }; diff --git a/src/core/element/plugins/keywordMark.js b/src/core/element/plugins/keywordMark.js index a7eab83dd..f0fcca96e 100644 --- a/src/core/element/plugins/keywordMark.js +++ b/src/core/element/plugins/keywordMark.js @@ -1,6 +1,7 @@ -export const registKeywordMarkFun = (Element) => { - Element.registerFunction('__textKeywordMarked__', function (text) { - this[0].textContent = text; - return this; - }); +export const registKeywordMarkFun = Element => { + Element.registerFunction("__textKeywordMarked__", function (text) { + this[0].textContent = text; + + return this; + }); }; diff --git a/src/core/element/plugins/renderToHtml.js b/src/core/element/plugins/renderToHtml.js index 525afe062..a9db9f755 100644 --- a/src/core/element/plugins/renderToHtml.js +++ b/src/core/element/plugins/renderToHtml.js @@ -1,65 +1,69 @@ -var skipArray = []; -var pxStyle = ['font-size', 'width', 'height']; -var _renderToHtml = function (root) { - var str = ''; - if (BI.isNull(root.originalHtml)) { - if (root.tag !== 'body') { - str += `<${root.tag}`; - if (root.classList.length > 0) { - str += ' class="'; - BI.each(root.classList, (i, cls) => { - str += ` ${cls}`; - }); - str += '"'; - } - str += ' style="'; - BI.each(root.originalStyles, (key, stl) => { - if ( - skipArray.contains(key) || - (key == 'height' && root.classList.contains('bi-design-components-data-data-table-cell')) - ) { - return; - } - key = BI.hyphenate(key); - if (key === 'font-family') { - stl = stl.replace(/\"/g, ''); - } - if (pxStyle.contains(key) && BI.isNumeric(stl)) { - stl += 'px'; - } - if (BI.isKey(stl)) { - str += ` ${key}:${stl};`; +import { each, isNull, hyphenate, isNumeric, isKey } from "../../2.base"; + +const skipArray = []; +const pxStyle = ["font-size", "width", "height"]; +function _renderToHtml(root) { + let str = ""; + if (isNull(root.originalHtml)) { + if (root.tag !== "body") { + str += `<${root.tag}`; + if (root.classList.length > 0) { + str += " class=\""; + each(root.classList, (i, cls) => { + str += ` ${cls}`; + }); + str += "\""; + } + str += " style=\""; + each(root.originalStyles, (key, stl) => { + if ( + skipArray.contains(key) || + (key === "height" && root.classList.contains("bi-design-components-data-data-table-cell")) + ) { + return; + } + key = hyphenate(key); + if (key === "font-family") { + stl = stl.replace(/"/g, ""); + } + if (pxStyle.contains(key) && isNumeric(stl)) { + stl += "px"; + } + if (isKey(stl)) { + str += ` ${key}:${stl};`; + } + }); + str += "\""; + each(root.attribs, (key, attr) => { + if (isKey(attr)) { + str += ` ${key}=${attr}`; + } + }); + if (root.textContent) { + str += ` title=${root.textContent}`; + } + str += ">"; } - }); - str += '"'; - BI.each(root.attribs, (key, attr) => { - if (BI.isKey(attr)) { - str += ` ${key}=${attr}`; + // 特殊处理,spread_table的行列元素是不取配置里的高度的,使用stretch拉伸的(leaves取了高度),但是功能代码里给单元格默认高度了,导致拉伸不了 + // 而spread_grid_table的行列元素是取配置里的高度的,拉不拉伸都一样 + each(root.children, (i, child) => { + str += _renderToHtml(child); + }); + } else { + str += root.originalHtml; + } + if (root.tag !== "body") { + if (root.textContent) { + str += root.textContent; } - }); - if (root.textContent) { - str += ` title=${root.textContent}`; - } - str += '>'; + str += ``; } - // 特殊处理,spread_table的行列元素是不取配置里的高度的,使用stretch拉伸的(leaves取了高度),但是功能代码里给单元格默认高度了,导致拉伸不了 - // 而spread_grid_table的行列元素是取配置里的高度的,拉不拉伸都一样 - BI.each(root.children, (i, child) => { - str += _renderToHtml(child); + + return str; +} + +export const registRenderToHtmlFun = Element => { + Element.registerFunction("renderToHtml", function () { + return _renderToHtml(this); }); - } else { - str += root.originalHtml; - } - if (root.tag !== 'body') { - if (root.textContent) { - str += root.textContent; - } - str += ``; - } - return str; -}; -export const registRenderToHtmlFun = (Element) => { - Element.registerFunction('renderToHtml', function () { - return _renderToHtml(this); - }); }; diff --git a/src/core/element/plugins/renderToString.js b/src/core/element/plugins/renderToString.js index f0073f258..6ab9734dd 100644 --- a/src/core/element/plugins/renderToString.js +++ b/src/core/element/plugins/renderToString.js @@ -1,50 +1,54 @@ -var skipArray = ['width', 'height']; -var _renderToString = function (root) { - var str = ''; - if (root.nodeName !== 'body') { - str += `<${root.nodeName}`; - if (root.classList.length > 0) { - str += ' class="'; - BI.each(root.classList, (i, cls) => { - str += ` ${cls}`; - }); - str += '"'; +import { each, hyphenate } from "../../2.base"; + +const skipArray = ["width", "height"]; +function _renderToString(root) { + let str = ""; + if (root.nodeName !== "body") { + str += `<${root.nodeName}`; + if (root.classList.length > 0) { + str += " class=\""; + each(root.classList, (i, cls) => { + str += ` ${cls}`; + }); + str += "\""; + } + str += " style=\""; + each(root.styles, (key, stl) => { + if (skipArray.includes(key)) { + return; + } + key = hyphenate(key); + str += ` ${key}:${stl};`; + }); + str += ` width:${root.width}px;`; + str += ` height:${root.height}px;`; + str += " position: fixed;"; + str += ` left: ${root.position.x}px;`; + str += ` top: ${root.position.y}px;`; + str += "\""; + each(root.attribs, (key, attr) => { + str += ` ${key}:${attr}`; + }); + str += ">"; } - str += ' style="'; - BI.each(root.styles, (key, stl) => { - if (skipArray.includes(key)) { - return; - } - key = BI.hyphenate(key); - str += ` ${key}:${stl};`; + each(root.children, (i, child) => { + str += _renderToString(child); }); - str += ` width:${root.width}px;`; - str += ` height:${root.height}px;`; - str += ' position: fixed;'; - str += ` left: ${root.position.x}px;`; - str += ` top: ${root.position.y}px;`; - str += '"'; - BI.each(root.attribs, (key, attr) => { - str += ` ${key}:${attr}`; - }); - str += '>'; - } - BI.each(root.children, (i, child) => { - str += _renderToString(child); - }); - // if (root.htmlContent) { - // str += root.htmlContent; - // } - if (root.nodeName !== 'body') { - if (root.text) { - str += root.text; + // if (root.htmlContent) { + // str += root.htmlContent; + // } + if (root.nodeName !== "body") { + if (root.text) { + str += root.text; + } + str += ``; } - str += ``; - } - return str; -}; -export const registRenderToStringFun = (Element) => { - Element.registerFunction('renderToString', function () { - return _renderToString(this); - }); + + return str; +} + +export const registRenderToStringFun = Element => { + Element.registerFunction("renderToString", function () { + return _renderToString(this); + }); }; diff --git a/src/core/element/plugins/text.js b/src/core/element/plugins/text.js index 555195251..8e51fd178 100644 --- a/src/core/element/plugins/text.js +++ b/src/core/element/plugins/text.js @@ -1,10 +1,12 @@ -export const registTextFun = (Element) => { - Element.registerFunction('setText', function (text) { - this.text = text; - return this; - }); - Element.registerFunction('setValue', function (text) { - this.text = text; - return this; - }); +export const registTextFun = Element => { + Element.registerFunction("setText", function (text) { + this.text = text; + + return this; + }); + Element.registerFunction("setValue", function (text) { + this.text = text; + + return this; + }); }; diff --git a/src/core/element/plugins/val.js b/src/core/element/plugins/val.js index f4b868918..e1e515c19 100644 --- a/src/core/element/plugins/val.js +++ b/src/core/element/plugins/val.js @@ -1,9 +1,11 @@ -export const registValFun = (Element) => { - Element.registerFunction('val', function (value) { - if (BI.isNotNull(value)) { - this.text = `${value}`; - return this; - } - return this.text; - }); +export const registValFun = Element => { + Element.registerFunction("val", function (value) { + if (BI.isNotNull(value)) { + this.text = `${value}`; + + return this; + } + + return this.text; + }); }; diff --git a/src/core/index.js b/src/core/index.js index 37c581af2..a492a0d96 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -12,6 +12,8 @@ import * as structure from "./structure"; import { StyleLoaderManager } from "./loader/loader.style"; import { ShowListener } from "./listener/listener.show"; import { useInWorker } from "./worker"; +import * as constant from "./constant"; +import * as logic from "./logic"; export * from "./decorator"; export * from "./2.base"; @@ -24,9 +26,8 @@ export * from "./controller"; export * from "./func"; export * from "./structure"; export * from "./h"; - -// 有了后删掉 -export const emptyFn = () => { }; +export * from "./constant"; +export * from "./logic"; export { StyleLoaderManager, @@ -42,12 +43,14 @@ Object.assign(BI, { ...inject, Plugin, ...behavior, + ...constant, component: inject.shortcut, ...action, ...controllers, ...func, StyleLoaderManager, ShowListener, + ...logic, ...structure, useInWorker, ...h, diff --git a/src/core/listener/listener.show.js b/src/core/listener/listener.show.js index 25ddc7ea2..f761b9d91 100644 --- a/src/core/listener/listener.show.js +++ b/src/core/listener/listener.show.js @@ -1,14 +1,12 @@ /** * guy * 检测某个Widget的EventChange事件然后去show某个card - * @type {*|void|Object} - * @class BI.ShowListener - * @extends BI.OB */ import { OB } from "../3.ob"; -import { isArray, isNull, nextTick, } from "../2.base"; +import { isArray, isNull, nextTick } from "../2.base"; import { createWidget } from "../5.inject"; import { Controller } from "../controller/0.controller"; +import { Events, emptyFn } from "../constant"; export class ShowListener extends OB { static EVENT_CHANGE = "EVENT_CHANGE"; @@ -17,12 +15,10 @@ export class ShowListener extends OB { return { eventObj: createWidget(), cardLayout: null, - cardNameCreator: (v) => { - return v; - }, - cardCreator: BI.emptyFn, - afterCardCreated: BI.emptyFn, - afterCardShow: BI.emptyFn + cardNameCreator: v => v, + cardCreator: emptyFn, + afterCardCreated: emptyFn, + afterCardShow: emptyFn, }; } @@ -30,13 +26,13 @@ export class ShowListener extends OB { const { eventObj, cardLayout, afterCardCreated, cardNameCreator, cardCreator, afterCardShow } = this.options; if (eventObj) { eventObj.on(Controller.EVENT_CHANGE, (type, v, ob) => { - if (type === BI.Events.CLICK) { + if (type === Events.CLICK) { v = v || eventObj.getValue(); v = isArray(v) ? (v.length > 1 ? v.toString() : v[0]) : v; if (isNull(v)) { throw new Error("不能为null"); } - var cardName = cardNameCreator(v); + const cardName = cardNameCreator(v); if (!cardLayout.isCardExisted(cardName)) { const card = cardCreator(cardName); cardLayout.addCardByName(cardName, card); diff --git a/src/core/loader/loader.style.js b/src/core/loader/loader.style.js index 1c65a2ede..f89aea175 100644 --- a/src/core/loader/loader.style.js +++ b/src/core/loader/loader.style.js @@ -2,13 +2,13 @@ * style加载管理器 * * Created by GUY on 2015/9/7. - * @class */ +import { extend, isNotNull } from "../2.base"; import { OB } from "../3.ob"; export class StyleLoaderManager extends OB { _defaultConfig() { - return BI.extend(super._defaultConfig(arguments), {}); + return extend(super._defaultConfig(arguments), {}); } _init() { @@ -17,7 +17,7 @@ export class StyleLoaderManager extends OB { } loadStyle(name, styleString) { - if(!_global.document) { + if (!_global.document) { return; } const d = document, styles = d.createElement("style"); @@ -38,7 +38,7 @@ export class StyleLoaderManager extends OB { } has(name) { - return this.stylesManager[name] != null; + return isNotNull(this.stylesManager[name]); } removeStyle(name) { @@ -47,6 +47,7 @@ export class StyleLoaderManager extends OB { } this.stylesManager[name].parentNode.removeChild(this.stylesManager[name]); delete this.stylesManager[name]; + return this; } } diff --git a/src/core/logic/index.js b/src/core/logic/index.js new file mode 100644 index 000000000..0397ce345 --- /dev/null +++ b/src/core/logic/index.js @@ -0,0 +1,83 @@ +import { Logic } from "./logic"; +import { VerticalLayoutLogic, HorizontalLayoutLogic, TableLayoutLogic, HorizontalFillLayoutLogic } from "./logic.layout"; + +export const LogicFactory = { + Type: { + Vertical: "vertical", + Horizontal: "horizontal", + Table: "table", + HorizontalFill: "horizontal_fill", + }, + createLogic (key, options) { + let LogicCls; + switch (key) { + case LogicFactory.Type.Vertical: + LogicCls = VerticalLayoutLogic; + break; + case LogicFactory.Type.Horizontal: + LogicCls = HorizontalLayoutLogic; + break; + case LogicFactory.Type.Table: + LogicCls = TableLayoutLogic; + break; + case LogicFactory.Type.HorizontalFill: + LogicCls = HorizontalFillLayoutLogic; + break; + default: + LogicCls = Logic; + break; + } + + return new LogicCls(options).createLogic(); + }, + + createLogicTypeByDirection (direction) { + switch (direction) { + case BI.Direction.Top: + case BI.Direction.Bottom: + case BI.Direction.Custom: + return BI.LogicFactory.Type.Vertical; + case BI.Direction.Left: + case BI.Direction.Right: + return BI.LogicFactory.Type.Horizontal; + default: + } + }, + + createLogicItemsByDirection (direction) { + let items = Array.prototype.slice.call(arguments, 1); + items = BI.map(items, (i, item) => { + if (BI.isWidget(item)) { + return { + el: item, + width: item.options.width, + height: item.options.height, + }; + } + + return item; + }); + switch (direction) { + case BI.Direction.Bottom: + items.reverse(); + break; + case BI.Direction.Right: + items.reverse(); + break; + case BI.Direction.Custom: + items = items.slice(1); + break; + default: + } + + return items; + }, +}; + +export { + Logic, + VerticalLayoutLogic, + HorizontalLayoutLogic, + TableLayoutLogic, + HorizontalFillLayoutLogic +}; diff --git a/src/core/logic/logic.js b/src/core/logic/logic.js index fab052e19..fd7223510 100644 --- a/src/core/logic/logic.js +++ b/src/core/logic/logic.js @@ -1,80 +1,8 @@ -/** - * @class BI.Logic - * @extends BI.OB - */ -BI.Logic = BI.inherit(BI.OB, { - createLogic: function () { - return this.options || {}; - } -}); -BI.LogicFactory = { - Type: { - Vertical: "vertical", - Horizontal: "horizontal", - Table: "table", - HorizontalFill: "horizontal_fill" - }, - createLogic: function (key, options) { - var logic; - switch (key) { - case BI.LogicFactory.Type.Vertical: - logic = BI.VerticalLayoutLogic; - break; - case BI.LogicFactory.Type.Horizontal: - logic = BI.HorizontalLayoutLogic; - break; - case BI.LogicFactory.Type.Table: - logic = BI.TableLayoutLogic; - break; - case BI.LogicFactory.Type.HorizontalFill: - logic = BI.HorizontalFillLayoutLogic; - break; - default: - logic = BI.Logic; - break; - } - return new logic(options).createLogic(); - }, +import { OB } from "../3.ob"; - createLogicTypeByDirection: function (direction) { - switch (direction) { - case BI.Direction.Top: - case BI.Direction.Bottom: - case BI.Direction.Custom: - return BI.LogicFactory.Type.Vertical; - case BI.Direction.Left: - case BI.Direction.Right: - return BI.LogicFactory.Type.Horizontal; - } - }, - - createLogicItemsByDirection: function (direction) { - var layout; - var items = Array.prototype.slice.call(arguments, 1); - items = BI.map(items, function (i, item) { - if (BI.isWidget(item)) { - return { - el: item, - width: item.options.width, - height: item.options.height - }; - } - return item; - }); - switch (direction) { - case BI.Direction.Bottom: - layout = BI.LogicFactory.Type.Vertical; - items.reverse(); - break; - case BI.Direction.Right: - layout = BI.LogicFactory.Type.Horizontal; - items.reverse(); - break; - case BI.Direction.Custom: - items = items.slice(1); - break; - } - return items; +export class Logic extends OB { + createLogic() { + return this.options || {}; } -}; +} diff --git a/src/core/logic/logic.layout.js b/src/core/logic/logic.layout.js index babd2306c..1251c6aee 100644 --- a/src/core/logic/logic.layout.js +++ b/src/core/logic/logic.layout.js @@ -1,13 +1,13 @@ +import { Logic } from "./logic"; +import { isNotNull, each, pickBy } from "../2.base"; + /** * guy * 上下布局逻辑 * 上下布局的时候要考虑到是动态布局还是静态布局 - * - * @class BI.VerticalLayoutLogic - * @extends BI.Logic */ -BI.VerticalLayoutLogic = BI.inherit(BI.Logic, { - props: function () { +export class VerticalLayoutLogic extends Logic { + props() { return { dynamic: false, scrollable: null, @@ -21,18 +21,20 @@ BI.VerticalLayoutLogic = BI.inherit(BI.Logic, { tgap: 0, bgap: 0, innerVgap: 0, - innerHgap: 0 + innerHgap: 0, }; - }, + } - createLogic: function () { - var layout, o = this.options; + createLogic() { + let layout; + const o = this.options; if (o.dynamic) { layout = "bi.vertical"; } else { layout = "bi.vtape"; } - return BI._.pickBy({ + + return pickBy({ type: layout, scrollable: o.scrollable, scrolly: o.scrolly, @@ -49,22 +51,19 @@ BI.VerticalLayoutLogic = BI.inherit(BI.Logic, { horizontalAlign: o.horizontalAlign, verticalAlign: o.verticalAlign, columnSize: o.columnSize, - rowSize: o.rowSize - }, BI.isNotNull); + rowSize: o.rowSize, + }, isNotNull); } -}); +} /** * guy * 左右布局逻辑 * 左右布局的时候要考虑到是动态布局还是静态布局 - * - * @class BI.HorizontalLayoutLogic - * @extends BI.Logic */ -BI.HorizontalLayoutLogic = BI.inherit(BI.Logic, { - props: function () { +export class HorizontalLayoutLogic extends Logic { + props() { return { dynamic: false, scrollable: null, @@ -78,18 +77,20 @@ BI.HorizontalLayoutLogic = BI.inherit(BI.Logic, { tgap: 0, bgap: 0, innerVgap: 0, - innerHgap: 0 + innerHgap: 0, }; - }, + } - createLogic: function () { - var layout, o = this.options; + createLogic() { + let layout; + const o = this.options; if (o.dynamic) { layout = "bi.vertical_adapt"; } else { layout = "bi.htape"; } - return BI._.pickBy({ + + return pickBy({ type: layout, scrollable: o.scrollable, scrolly: o.scrolly, @@ -106,21 +107,18 @@ BI.HorizontalLayoutLogic = BI.inherit(BI.Logic, { horizontalAlign: o.horizontalAlign, verticalAlign: o.verticalAlign, columnSize: o.columnSize, - rowSize: o.rowSize - }, BI.isNotNull); + rowSize: o.rowSize, + }, isNotNull); } -}); +} /** * guy * 表格布局逻辑 * 表格布局的时候要考虑到是动态布局还是静态布局 - * - * @class BI.TableLayoutLogic - * @extends BI.OB */ -BI.TableLayoutLogic = BI.inherit(BI.Logic, { - props: function () { +export class TableLayoutLogic extends Logic { + props() { return { dynamic: false, scrollable: null, @@ -132,18 +130,20 @@ BI.TableLayoutLogic = BI.inherit(BI.Logic, { rowSize: [], hgap: 0, vgap: 0, - items: [] + items: [], }; - }, + } - createLogic: function () { - var layout, o = this.options; + createLogic() { + let layout; + const o = this.options; if (o.dynamic) { layout = "bi.table"; } else { layout = "bi.window"; } - return BI._.pickBy({ + + return pickBy({ type: layout, scrollable: o.scrollable, scrolly: o.scrolly, @@ -156,20 +156,17 @@ BI.TableLayoutLogic = BI.inherit(BI.Logic, { horizontalAlign: o.horizontalAlign, verticalAlign: o.verticalAlign, columnSize: o.columnSize, - rowSize: o.rowSize - }, BI.isNotNull); + rowSize: o.rowSize, + }, isNotNull); } -}); +} /** * guy * 左右充满布局逻辑 - * - * @class BI.HorizontalFillLayoutLogic - * @extends BI.Logic */ -BI.HorizontalFillLayoutLogic = BI.inherit(BI.Logic, { - props: function () { +export class HorizontalFillLayoutLogic extends Logic { + props() { return { dynamic: false, scrollable: null, @@ -183,14 +180,15 @@ BI.HorizontalFillLayoutLogic = BI.inherit(BI.Logic, { tgap: 0, bgap: 0, innerVgap: 0, - innerHgap: 0 + innerHgap: 0, }; - }, + } - createLogic: function () { - var layout, o = this.options; - var columnSize = []; - BI.each(o.items, function (i, item) { + createLogic() { + let layout; + const o = this.options; + const columnSize = []; + each(o.items, (i, item) => { columnSize.push(item.width || 0); }); if (o.dynamic) { @@ -198,7 +196,8 @@ BI.HorizontalFillLayoutLogic = BI.inherit(BI.Logic, { } else { layout = "bi.htape"; } - return BI._.pickBy({ + + return pickBy({ type: layout, scrollable: o.scrollable, scrolly: o.scrolly, @@ -214,8 +213,8 @@ BI.HorizontalFillLayoutLogic = BI.inherit(BI.Logic, { items: o.items, horizontalAlign: o.horizontalAlign, verticalAlign: o.verticalAlign, - columnSize: columnSize, - rowSize: o.rowSize - }, BI.isNotNull); + columnSize, + rowSize: o.rowSize, + }, isNotNull); } -}); +} From 8fcb09c1e3c2805906ed44cd4cda7426d3a2a65b Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Fri, 6 Jan 2023 11:31:15 +0800 Subject: [PATCH 042/300] =?UTF-8?q?KERNEL-14035=20refactor:=20=E6=8C=82?= =?UTF-8?q?=E8=BD=BDElement?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/element/index.js | 5 +++-- src/core/index.js | 5 ++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/core/element/index.js b/src/core/element/index.js index 070afb0f3..da27b0719 100644 --- a/src/core/element/index.js +++ b/src/core/element/index.js @@ -1,8 +1,7 @@ import { Element } from "./element"; import { isString, isWidget } from "../2.base"; -BI.Element = Element; -BI.Element.renderEngine = { +Element.renderEngine = { createElement: widget => { if (isWidget(widget)) { const o = widget.options; @@ -30,3 +29,5 @@ BI.Element.renderEngine = { return new Element(); }, }; + +export { Element }; diff --git a/src/core/index.js b/src/core/index.js index a492a0d96..49d7b2125 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -14,6 +14,7 @@ import { ShowListener } from "./listener/listener.show"; import { useInWorker } from "./worker"; import * as constant from "./constant"; import * as logic from "./logic"; +import { Element } from "./element"; export * from "./decorator"; export * from "./2.base"; @@ -33,7 +34,8 @@ export { StyleLoaderManager, ShowListener, Plugin, - useInWorker + useInWorker, + Element }; Object.assign(BI, { @@ -47,6 +49,7 @@ Object.assign(BI, { component: inject.shortcut, ...action, ...controllers, + Element, ...func, StyleLoaderManager, ShowListener, From c5ea536fd7ccc77692746aa089d898fd47a94c0f Mon Sep 17 00:00:00 2001 From: Treecat Date: Fri, 6 Jan 2023 15:31:54 +0800 Subject: [PATCH 043/300] =?UTF-8?q?KERNEL-14022=20refact:=20=E6=8C=89?= =?UTF-8?q?=E9=92=AE=E5=B9=B2=E6=8E=89=20apply?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/single/button/button.basic.js | 4 ++-- src/base/single/button/button.node.js | 4 ++-- src/base/single/button/buttons/button.icon.js | 5 ++--- src/base/single/button/buttons/button.image.js | 6 +++--- src/base/single/button/buttons/button.js | 8 ++++---- src/base/single/button/buttons/button.text.js | 14 +++++++------- .../button/listitem/blankiconicontextitem.js | 8 ++++---- .../button/listitem/blankicontexticonitem.js | 2 +- .../single/button/listitem/blankicontextitem.js | 2 +- .../single/button/listitem/icontexticonitem.js | 2 +- src/base/single/button/listitem/icontextitem.js | 4 ++-- src/base/single/button/listitem/texticonitem.js | 6 +++--- src/base/single/button/listitem/textitem.js | 8 ++++---- src/base/single/button/node/icontexticonnode.js | 2 +- src/base/single/button/node/icontextnode.js | 4 ++-- src/base/single/button/node/texticonnode.js | 2 +- src/base/single/button/node/textnode.js | 6 +++--- src/case/button/icon/icon.change.js | 6 +++--- src/case/button/icon/icon.trigger.js | 2 +- src/case/button/icon/iconhalf/icon.half.js | 2 +- src/case/button/item.multiselect.js | 6 +++--- src/case/button/item.singleselect.icontext.js | 6 +++--- src/case/button/item.singleselect.js | 6 +++--- src/case/button/item.singleselect.radio.js | 8 ++++---- src/case/button/node/node.arrow.js | 6 +++--- src/case/button/node/node.first.plus.js | 4 ++-- src/case/button/node/node.icon.arrow.js | 8 ++++---- src/case/button/node/node.last.plus.js | 8 ++++---- src/case/button/node/node.mid.plus.js | 6 +++--- src/case/button/node/node.multilayer.icon.arrow.js | 14 +++++++------- src/case/button/node/node.plus.js | 4 ++-- src/case/button/node/siwtcher.tree.node.js | 4 ++-- src/case/button/node/treenode.js | 8 ++++---- src/case/button/switch.js | 6 +++--- src/case/button/treeitem/item.first.treeleaf.js | 4 ++-- src/case/button/treeitem/item.icon.treeleaf.js | 6 +++--- src/case/button/treeitem/item.last.treeleaf.js | 4 ++-- src/case/button/treeitem/item.mid.treeleaf.js | 2 +- .../treeitem/item.multilayer.icon.treeleaf.js | 12 ++++++------ src/case/button/treeitem/item.treetextleaf.js | 2 +- 40 files changed, 110 insertions(+), 111 deletions(-) diff --git a/src/base/single/button/button.basic.js b/src/base/single/button/button.basic.js index f2f09216c..ce2d1dfa8 100644 --- a/src/base/single/button/button.basic.js +++ b/src/base/single/button/button.basic.js @@ -439,7 +439,7 @@ export class BasicButton extends Single { } _setEnable(enable) { - super._setEnable.apply(this, arguments); + super._setEnable(...arguments); if (enable === true) { this.element.removeClass("base-disabled disabled"); } else if (enable === false) { @@ -454,7 +454,7 @@ export class BasicButton extends Single { empty() { Widget._renderEngine.createElement(document).unbind(`mouseup.${this.getName()}`); - super.empty.apply(this, arguments); + super.empty(...arguments); } } diff --git a/src/base/single/button/button.node.js b/src/base/single/button/button.node.js index 7b8cc4632..d48bab2fb 100644 --- a/src/base/single/button/button.node.js +++ b/src/base/single/button/button.node.js @@ -27,11 +27,11 @@ export class NodeButton extends BasicButton { if (this.isOpened()) { this.setOpened(this.isOpened()); } - super._initRef.apply(this, arguments); + super._initRef(...arguments); } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); this.setOpened(!this.isOpened()); } diff --git a/src/base/single/button/buttons/button.icon.js b/src/base/single/button/buttons/button.icon.js index 9e8228a55..5f3100a9b 100644 --- a/src/base/single/button/buttons/button.icon.js +++ b/src/base/single/button/buttons/button.icon.js @@ -8,7 +8,6 @@ import { shortcut, extend, isNumber, createWidget, isNull } from "../../../../co */ @shortcut() export class IconButton extends BasicButton { - static EVENT_CHANGE = "EVENT_CHANGE"; static xtype = "bi.icon_button"; @@ -16,7 +15,7 @@ export class IconButton extends BasicButton { const conf = super._defaultConfig(arguments); return extend(conf, { - _baseCls: (conf._baseCls || "") + " bi-icon-button horizon-center", + _baseCls: `${conf._baseCls || ""} bi-icon-button horizon-center`, hgap: 0, vgap: 0, tgap: 0, @@ -68,7 +67,7 @@ export class IconButton extends BasicButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { this.fireEvent(IconButton.EVENT_CHANGE, this); } diff --git a/src/base/single/button/buttons/button.image.js b/src/base/single/button/buttons/button.image.js index c6486e359..e8fcf6ede 100644 --- a/src/base/single/button/buttons/button.image.js +++ b/src/base/single/button/buttons/button.image.js @@ -50,12 +50,12 @@ export class ImageButton extends BasicButton { } setWidth(w) { - super.setWidth.apply(this, arguments); + super.setWidth(...arguments); this.options.width = w; } setHeight(h) { - super.setHeight.apply(this, arguments); + super.setHeight(...arguments); this.options.height = h; } @@ -85,7 +85,7 @@ export class ImageButton extends BasicButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { this.fireEvent(ImageButton.EVENT_CHANGE, this); } diff --git a/src/base/single/button/buttons/button.js b/src/base/single/button/buttons/button.js index 674400853..edc4cf32d 100644 --- a/src/base/single/button/buttons/button.js +++ b/src/base/single/button/buttons/button.js @@ -188,14 +188,14 @@ export class Button extends BasicButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { this.fireEvent(Button.EVENT_CHANGE, this); } } _setEnable(enable) { - super._setEnable.apply(this, arguments); + super._setEnable(...arguments); if (enable === true) { this.element.attr("tabIndex", 1); } else if (enable === false) { @@ -236,12 +236,12 @@ export class Button extends BasicButton { } setText(text) { - super.setText.apply(this, arguments); + super.setText(...arguments); this.text.setText(text); } setValue(text) { - super.setValue.apply(this, arguments); + super.setValue(...arguments); if (!this.isReadOnly()) { this.text.setValue(text); } diff --git a/src/base/single/button/buttons/button.text.js b/src/base/single/button/buttons/button.text.js index 281047b55..107a8ba38 100644 --- a/src/base/single/button/buttons/button.text.js +++ b/src/base/single/button/buttons/button.text.js @@ -1,5 +1,5 @@ import { BasicButton } from "../button.basic"; -import { shortcut, extend, createWidget } from "../../../../core"; +import { shortcut, extend, createWidget, isArray } from "../../../../core"; /** * guy @@ -53,9 +53,9 @@ export class TextButton extends BasicButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { - this.fireEvent(BI.TextButton.EVENT_CHANGE, this.getValue(), this); + this.fireEvent(TextButton.EVENT_CHANGE, this.getValue(), this); } } @@ -76,8 +76,8 @@ export class TextButton extends BasicButton { } setText(text) { - super.setText.apply(this, arguments); - text = BI.isArray(text) ? text.join(",") : text; + super.setText(...arguments); + text = isArray(text) ? text.join(",") : text; this.text.setText(text); } @@ -86,9 +86,9 @@ export class TextButton extends BasicButton { } setValue(text) { - super.setValue.apply(this, arguments); + super.setValue(...arguments); if (!this.isReadOnly()) { - text = BI.isArray(text) ? text.join(",") : text; + text = isArray(text) ? text.join(",") : text; this.text.setValue(text); } } diff --git a/src/base/single/button/listitem/blankiconicontextitem.js b/src/base/single/button/listitem/blankiconicontextitem.js index 2a471e7b7..d57267110 100644 --- a/src/base/single/button/listitem/blankiconicontextitem.js +++ b/src/base/single/button/listitem/blankiconicontextitem.js @@ -1,5 +1,5 @@ import { BasicButton } from "../button.basic"; -import { shortcut } from "../../../../core"; +import { shortcut, extend } from "../../../../core"; /** * 带有一个占位 @@ -16,7 +16,7 @@ export class BlankIconIconTextItem extends BasicButton { _defaultConfig() { const conf = super._defaultConfig(arguments); - return BI.extend(conf, { + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-blank-icon-icon-text-item`, iconCls1: "", iconCls2: "", @@ -74,14 +74,14 @@ export class BlankIconIconTextItem extends BasicButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { this.fireEvent(BlankIconIconTextItem.EVENT_CHANGE, this.getValue(), this); } } setSelected(b) { - super.setSelected.apply(this, arguments); + super.setSelected(...arguments); this.icon1.setSelected(b); this.icon2.setSelected(b); } diff --git a/src/base/single/button/listitem/blankicontexticonitem.js b/src/base/single/button/listitem/blankicontexticonitem.js index 217906da8..1880cdcb3 100644 --- a/src/base/single/button/listitem/blankicontexticonitem.js +++ b/src/base/single/button/listitem/blankicontexticonitem.js @@ -75,7 +75,7 @@ export class BlankIconTextIconItem extends BasicButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { this.fireEvent(BI.BlankIconTextIconItem.EVENT_CHANGE, this.getValue(), this); } diff --git a/src/base/single/button/listitem/blankicontextitem.js b/src/base/single/button/listitem/blankicontextitem.js index fd2b34d32..30be259d2 100644 --- a/src/base/single/button/listitem/blankicontextitem.js +++ b/src/base/single/button/listitem/blankicontextitem.js @@ -67,7 +67,7 @@ export class BlankIconTextItem extends BasicButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { this.fireEvent(BlankIconTextItem.EVENT_CHANGE, this.getValue(), this); } diff --git a/src/base/single/button/listitem/icontexticonitem.js b/src/base/single/button/listitem/icontexticonitem.js index 1209e8054..3d95eac4e 100644 --- a/src/base/single/button/listitem/icontexticonitem.js +++ b/src/base/single/button/listitem/icontexticonitem.js @@ -72,7 +72,7 @@ export class IconTextIconItem extends BasicButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { this.fireEvent(IconTextIconItem.EVENT_CHANGE, this.getValue(), this); } diff --git a/src/base/single/button/listitem/icontextitem.js b/src/base/single/button/listitem/icontextitem.js index 70ce49654..b906cc6e7 100644 --- a/src/base/single/button/listitem/icontextitem.js +++ b/src/base/single/button/listitem/icontextitem.js @@ -65,9 +65,9 @@ export class IconTextItem extends BasicButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { - this.fireEvent(BI.IconTextItem.EVENT_CHANGE, this.getValue(), this); + this.fireEvent(IconTextItem.EVENT_CHANGE, this.getValue(), this); } } diff --git a/src/base/single/button/listitem/texticonitem.js b/src/base/single/button/listitem/texticonitem.js index db9b30478..c17811c92 100644 --- a/src/base/single/button/listitem/texticonitem.js +++ b/src/base/single/button/listitem/texticonitem.js @@ -39,8 +39,8 @@ export class TextIconItem extends BasicButton { items: [{ el: { type: "bi.label", - ref (_ref) { - self.text = _ref; + ref: _ref => { + this.text = _ref; }, cls: "list-item-text", textAlign: "left", @@ -65,7 +65,7 @@ export class TextIconItem extends BasicButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { this.fireEvent(TextIconItem.EVENT_CHANGE, this.getValue(), this); } diff --git a/src/base/single/button/listitem/textitem.js b/src/base/single/button/listitem/textitem.js index a1bb719b5..698843370 100644 --- a/src/base/single/button/listitem/textitem.js +++ b/src/base/single/button/listitem/textitem.js @@ -1,5 +1,5 @@ import { BasicButton } from "../button.basic"; -import { extend, shortcut } from "../../../../core"; +import { extend, shortcut, createWidget } from "../../../../core"; /** * guy @@ -30,7 +30,7 @@ export class TextItem extends BasicButton { render() { const o = this.options; - this.text = BI.createWidget({ + this.text = createWidget({ type: "bi.label", element: this, textAlign: o.textAlign, @@ -49,9 +49,9 @@ export class TextItem extends BasicButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { - this.fireEvent(BI.TextItem.EVENT_CHANGE, this.getValue(), this); + this.fireEvent(TextItem.EVENT_CHANGE, this.getValue(), this); } } diff --git a/src/base/single/button/node/icontexticonnode.js b/src/base/single/button/node/icontexticonnode.js index a08b63c8d..77a737b48 100644 --- a/src/base/single/button/node/icontexticonnode.js +++ b/src/base/single/button/node/icontexticonnode.js @@ -69,7 +69,7 @@ export class IconTextIconNode extends NodeButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { this.fireEvent(IconTextIconNode.EVENT_CHANGE, this.getValue(), this); } diff --git a/src/base/single/button/node/icontextnode.js b/src/base/single/button/node/icontextnode.js index 5135030db..54c2b60bf 100644 --- a/src/base/single/button/node/icontextnode.js +++ b/src/base/single/button/node/icontextnode.js @@ -62,9 +62,9 @@ export class IconTextNode extends NodeButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { - this.fireEvent(BI.IconTextNode.EVENT_CHANGE, this.getValue(), this); + this.fireEvent(IconTextNode.EVENT_CHANGE, this.getValue(), this); } } diff --git a/src/base/single/button/node/texticonnode.js b/src/base/single/button/node/texticonnode.js index cc3f2dea8..e4ca824a1 100644 --- a/src/base/single/button/node/texticonnode.js +++ b/src/base/single/button/node/texticonnode.js @@ -61,7 +61,7 @@ export default class TextIconNode extends NodeButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { this.fireEvent(TextIconNode.EVENT_CHANGE, this.getValue(), this); } diff --git a/src/base/single/button/node/textnode.js b/src/base/single/button/node/textnode.js index e6e990cf7..c7b56766d 100644 --- a/src/base/single/button/node/textnode.js +++ b/src/base/single/button/node/textnode.js @@ -1,5 +1,5 @@ import { NodeButton } from "../button.node"; -import { extend, shortcut } from "../../../../core"; +import { extend, shortcut, createWidget } from "../../../../core"; /** * guy @@ -31,7 +31,7 @@ export class TextNode extends NodeButton { render() { const o = this.options; - this.text = BI.createWidget({ + this.text = createWidget({ type: "bi.label", element: this, textAlign: o.textAlign, @@ -50,7 +50,7 @@ export class TextNode extends NodeButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { this.fireEvent(TextNode.EVENT_CHANGE, this.getValue(), this); } diff --git a/src/case/button/icon/icon.change.js b/src/case/button/icon/icon.change.js index 3e5ad6c46..f477373e5 100644 --- a/src/case/button/icon/icon.change.js +++ b/src/case/button/icon/icon.change.js @@ -45,7 +45,7 @@ export class IconChangeButton extends Single { o.iconCls = isFunction(o.iconCls) ? this.__watch(o.iconCls, (context, newValue) => { this.setIcon(newValue); }) : o.iconCls; - super._init.apply(this, arguments); + super._init(...arguments); this.button = createWidget({ type: "bi.icon_button", element: this, @@ -69,10 +69,10 @@ export class IconChangeButton extends Single { }); this.button.on(Controller.EVENT_CHANGE, (...args) => { - this.fireEvent(Controller.EVENT_CHANGE, args); + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); this.button.on(IconButton.EVENT_CHANGE, (...args) => { - this.fireEvent(IconChangeButton.EVENT_CHANGE, args); + this.fireEvent(IconChangeButton.EVENT_CHANGE, ...args); }); } diff --git a/src/case/button/icon/icon.trigger.js b/src/case/button/icon/icon.trigger.js index 1c799edd4..a9afa3d8a 100644 --- a/src/case/button/icon/icon.trigger.js +++ b/src/case/button/icon/icon.trigger.js @@ -11,7 +11,7 @@ import { shortcut, extend } from "../../../core"; @shortcut() export class TriggerIconButton extends IconButton { static xtype = "bi.trigger_icon_button"; - EVENT_CHANGE = IconButton.EVENT_CHANGE; + static EVENT_CHANGE = IconButton.EVENT_CHANGE; _defaultConfig() { const conf = super._defaultConfig(arguments); diff --git a/src/case/button/icon/iconhalf/icon.half.js b/src/case/button/icon/iconhalf/icon.half.js index 1efe6c110..7a72e5823 100644 --- a/src/case/button/icon/iconhalf/icon.half.js +++ b/src/case/button/icon/iconhalf/icon.half.js @@ -38,7 +38,7 @@ export class HalfButton extends BasicButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { this.fireEvent(HalfButton.EVENT_CHANGE); } diff --git a/src/case/button/item.multiselect.js b/src/case/button/item.multiselect.js index df74642c9..dd5548f4a 100644 --- a/src/case/button/item.multiselect.js +++ b/src/case/button/item.multiselect.js @@ -77,14 +77,14 @@ export class MultiSelectItem extends BasicButton { } doClick() { - BI.MultiSelectItem.superclass.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { - this.fireEvent(BI.MultiSelectItem.EVENT_CHANGE, this.getValue(), this); + this.fireEvent(MultiSelectItem.EVENT_CHANGE, this.getValue(), this); } } setSelected(v) { - BI.MultiSelectItem.superclass.setSelected.apply(this, arguments); + super.setSelected(...arguments); this.checkbox.setSelected(v); } } diff --git a/src/case/button/item.singleselect.icontext.js b/src/case/button/item.singleselect.icontext.js index d92f59050..c32fc6b5a 100644 --- a/src/case/button/item.singleselect.icontext.js +++ b/src/case/button/item.singleselect.icontext.js @@ -43,13 +43,13 @@ export class SingleSelectIconTextItem extends Single { value: o.value, py: o.py, }); - this.text.on(Controller.EVENT_CHANGE, function () { - self.fireEvent(Controller.EVENT_CHANGE, arguments); + this.text.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); } _setEnable(enable) { - super._setEnable.apply(this, arguments); + super._setEnable(...arguments); if (enable === true) { this.element.attr("tabIndex", 1); } else if (enable === false) { diff --git a/src/case/button/item.singleselect.js b/src/case/button/item.singleselect.js index 9b3e682c7..e06f1c4a9 100644 --- a/src/case/button/item.singleselect.js +++ b/src/case/button/item.singleselect.js @@ -39,7 +39,7 @@ export class SingleSelectItem extends BasicButton { } _setEnable(enable) { - super._setEnable.apply(this, arguments); + super._setEnable(...arguments); if (enable === true) { this.element.attr("tabIndex", 1); } else if (enable === false) { @@ -56,14 +56,14 @@ export class SingleSelectItem extends BasicButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { this.fireEvent(SingleSelectItem.EVENT_CHANGE, this.isSelected(), this); } } setSelected(v) { - super.setSelected.apply(this, arguments); + super.setSelected(...arguments); } } diff --git a/src/case/button/item.singleselect.radio.js b/src/case/button/item.singleselect.radio.js index 19a04f120..8a314165d 100644 --- a/src/case/button/item.singleselect.radio.js +++ b/src/case/button/item.singleselect.radio.js @@ -62,7 +62,7 @@ export class SingleSelectRadioItem extends BasicButton { } _setEnable(enable) { - super._setEnable.apply(this, arguments); + super._setEnable(...arguments); if (enable === true) { this.element.attr("tabIndex", 1); } else if (enable === false) { @@ -79,14 +79,14 @@ export class SingleSelectRadioItem extends BasicButton { } doClick() { - BI.SingleSelectRadioItem.superclass.doClick.apply(this, arguments); + super.doClick(...arguments); if (this.isValid()) { - this.fireEvent(BI.SingleSelectRadioItem.EVENT_CHANGE, this.isSelected(), this); + this.fireEvent(SingleSelectRadioItem.EVENT_CHANGE, this.isSelected(), this); } } setSelected(v) { - BI.SingleSelectRadioItem.superclass.setSelected.apply(this, arguments); + super.setSelected(...arguments); this.radio.setSelected(v); } } diff --git a/src/case/button/node/node.arrow.js b/src/case/button/node/node.arrow.js index 08cc58605..aac112417 100644 --- a/src/case/button/node/node.arrow.js +++ b/src/case/button/node/node.arrow.js @@ -64,17 +64,17 @@ export class ArrowNode extends NodeButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); this.checkbox.setSelected(this.isOpened()); } setText(text) { - super.setText.apply(this, arguments); + super.setText(...arguments); this.text.setText(text); } setOpened(v) { - super.setOpened.apply(this, arguments); + super.setOpened(...arguments); this.checkbox.setSelected(v); } } diff --git a/src/case/button/node/node.first.plus.js b/src/case/button/node/node.first.plus.js index 60a266d49..5202c77ee 100644 --- a/src/case/button/node/node.first.plus.js +++ b/src/case/button/node/node.first.plus.js @@ -78,12 +78,12 @@ export class FirstPlusGroupNode extends NodeButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); this.checkbox.setSelected(this.isSelected()); } setOpened(v) { - super.setOpened.apply(this, arguments); + super.setOpened(...arguments); if (BI.isNotNull(this.checkbox)) { this.checkbox.setSelected(v); } diff --git a/src/case/button/node/node.icon.arrow.js b/src/case/button/node/node.icon.arrow.js index 2aa910a9b..c779795ec 100644 --- a/src/case/button/node/node.icon.arrow.js +++ b/src/case/button/node/node.icon.arrow.js @@ -1,5 +1,5 @@ import { NodeButton } from "../../../base/single/button/button.node"; -import { shortcut, extend, createWidget, Controller } from "../../../core"; +import { shortcut, extend, createWidget, Controller, isNotNull } from "../../../core"; /** * Created by User on 2016/3/31. @@ -96,13 +96,13 @@ export class IconArrowNode extends NodeButton { } doClick() { - BI.IconArrowNode.superclass.doClick.apply(this, arguments); + super.doClick(...arguments); this.checkbox.setSelected(this.isSelected()); } setOpened(v) { - BI.IconArrowNode.superclass.setOpened.apply(this, arguments); - if (BI.isNotNull(this.checkbox)) { + super.setOpened(...arguments); + if (isNotNull(this.checkbox)) { this.checkbox.setSelected(v); } } diff --git a/src/case/button/node/node.last.plus.js b/src/case/button/node/node.last.plus.js index 0dba75eaf..2f273f1d8 100644 --- a/src/case/button/node/node.last.plus.js +++ b/src/case/button/node/node.last.plus.js @@ -1,5 +1,5 @@ import { NodeButton } from "../../../base/single/button/button.node"; -import { shortcut, extend, createWidget, isNotNull } from "../../../core"; +import { shortcut, extend, createWidget, isNotNull, Controller } from "../../../core"; /** * 加号表示的组节点 @@ -46,7 +46,7 @@ export class LastPlusGroupNode extends NodeButton { py: o.py, keyword: o.keyword, }); - this.checkbox.on(BI.Controller.EVENT_CHANGE, type => { + this.checkbox.on(Controller.EVENT_CHANGE, type => { if (type === BI.Events.CLICK) { if (this.checkbox.isSelected()) { this.triggerExpand(); @@ -76,12 +76,12 @@ export class LastPlusGroupNode extends NodeButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); this.checkbox.setSelected(this.isSelected()); } setOpened(v) { - super.setOpened.apply(this, arguments); + super.setOpened(...arguments); if (isNotNull(this.checkbox)) { this.checkbox.setSelected(v); } diff --git a/src/case/button/node/node.mid.plus.js b/src/case/button/node/node.mid.plus.js index 94ce8b1b9..116a73a48 100644 --- a/src/case/button/node/node.mid.plus.js +++ b/src/case/button/node/node.mid.plus.js @@ -27,7 +27,7 @@ export class MidPlusGroupNode extends NodeButton { } _init() { - super._init.apply(this, arguments); + super._init(...arguments); const o = this.options; this.checkbox = createWidget({ type: "bi.mid_tree_node_checkbox", @@ -77,12 +77,12 @@ export class MidPlusGroupNode extends NodeButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); this.checkbox.setSelected(this.isSelected()); } setOpened(v) { - BI.MidPlusGroupNode.superclass.setOpened.apply(this, arguments); + super.setOpened(...arguments); if (BI.isNotNull(this.checkbox)) { this.checkbox.setSelected(v); } diff --git a/src/case/button/node/node.multilayer.icon.arrow.js b/src/case/button/node/node.multilayer.icon.arrow.js index c1a9b35da..958e88b79 100644 --- a/src/case/button/node/node.multilayer.icon.arrow.js +++ b/src/case/button/node/node.multilayer.icon.arrow.js @@ -1,5 +1,5 @@ import { NodeButton } from "../../../base/single/button/button.node"; -import { shortcut, extend, createWidget, Controller, count } from "../../../core"; +import { shortcut, extend, createWidget, Controller, count, makeArray } from "../../../core"; @shortcut() export class MultiLayerIconArrowNode extends NodeButton { @@ -22,7 +22,7 @@ export class MultiLayerIconArrowNode extends NodeButton { } _init() { - super._init.apply(this, arguments); + super._init(...arguments); const o = this.options; this.node = createWidget({ type: "bi.icon_arrow_node", @@ -42,7 +42,7 @@ export class MultiLayerIconArrowNode extends NodeButton { }); this.node.on(Controller.EVENT_CHANGE, (...args) => { this.setSelected(this.isSelected()); - this.fireEvent(Controller.EVENT_CHANGE, args); + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); const items = []; @@ -57,7 +57,7 @@ export class MultiLayerIconArrowNode extends NodeButton { createWidget({ type: "bi.horizontal_adapt", element: this, - columnSize: BI.makeArray(o.layer, 15), + columnSize: makeArray(o.layer, 15), items, }); } @@ -79,17 +79,17 @@ export class MultiLayerIconArrowNode extends NodeButton { } setSelected(b) { - super.setSelected.apply(this, arguments); + super.setSelected(...arguments); this.node.setSelected(b); } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); this.node.setSelected(this.isSelected()); } setOpened(v) { - super.setOpened.apply(this, arguments); + super.setOpened(...arguments); this.node.setOpened(v); } } diff --git a/src/case/button/node/node.plus.js b/src/case/button/node/node.plus.js index f3f08b0cf..b04624456 100644 --- a/src/case/button/node/node.plus.js +++ b/src/case/button/node/node.plus.js @@ -73,12 +73,12 @@ export class PlusGroupNode extends NodeButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); this.checkbox.setSelected(this.isSelected()); } setOpened(v) { - super.setOpened.apply(this, arguments); + super.setOpened(...arguments); if (this.checkbox) { this.checkbox.setSelected(v); } diff --git a/src/case/button/node/siwtcher.tree.node.js b/src/case/button/node/siwtcher.tree.node.js index 46519ecb5..fe89b6569 100644 --- a/src/case/button/node/siwtcher.tree.node.js +++ b/src/case/button/node/siwtcher.tree.node.js @@ -46,7 +46,7 @@ export class TreeNodeSwitcher extends NodeButton { } setOpened(b) { - super.setOpened.apply(this, arguments); + super.setOpened(...arguments); const [collapse, expand] = this.getIconCls(); if (b) { this.element.addClass(expand).removeClass(collapse); @@ -56,7 +56,7 @@ export class TreeNodeSwitcher extends NodeButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); this.fireEvent(TreeNodeSwitcher.EVENT_CHANGE, this); } } diff --git a/src/case/button/node/treenode.js b/src/case/button/node/treenode.js index b2977e50a..e0a931e7d 100644 --- a/src/case/button/node/treenode.js +++ b/src/case/button/node/treenode.js @@ -28,7 +28,7 @@ export class BasicTreeNode extends NodeButton { const checkbox = { type: "bi.tree_node_switcher", - __ref: _ref => { + ref: _ref => { this.switcher = _ref; }, iconHeight: o.height, @@ -97,16 +97,16 @@ export class BasicTreeNode extends NodeButton { if (this.options.selectable) { return; } - super.doClick.apply(this, arguments); + super.doClick(...arguments); } setOpened(v) { - super.setOpened.apply(this, arguments); + super.setOpened(...arguments); this.switcher.setOpened(v); } setValue() { - super.setValue.apply(this, arguments); + super.setValue(...arguments); } } diff --git a/src/case/button/switch.js b/src/case/button/switch.js index c05baa832..f40cf3cf4 100644 --- a/src/case/button/switch.js +++ b/src/case/button/switch.js @@ -72,7 +72,7 @@ export class Switch extends BasicButton { } _setEnable(enable) { - super._setEnable.apply(this, arguments); + super._setEnable(...arguments); if (enable === true) { this.element.attr("tabIndex", 1); } else if (enable === false) { @@ -81,7 +81,7 @@ export class Switch extends BasicButton { } setSelected(v) { - super.setSelected.apply(this, arguments); + super.setSelected(...arguments); this.layout.attr("items")[0].left = v ? 28 : 4; this.layout.resize(); this.options.showTip && this.openTip.setVisible(v); @@ -89,7 +89,7 @@ export class Switch extends BasicButton { } doClick() { - super.doClick.apply(this, arguments); + super.doClick(...arguments); this.fireEvent(Switch.EVENT_CHANGE, this.isSelected()); } } diff --git a/src/case/button/treeitem/item.first.treeleaf.js b/src/case/button/treeitem/item.first.treeleaf.js index d09376bc0..f379f65c0 100644 --- a/src/case/button/treeitem/item.first.treeleaf.js +++ b/src/case/button/treeitem/item.first.treeleaf.js @@ -19,7 +19,7 @@ export class FirstTreeLeafItem extends BasicButton { } _init() { - super._init.apply(this, arguments); + super._init(...arguments); const o = this.options; this.text = createWidget({ type: "bi.label", @@ -55,7 +55,7 @@ export class FirstTreeLeafItem extends BasicButton { }); createWidget(extend({ element: this, - }, BI.LogicFactory.createLogic(type, BI.extend(o.logic, { + }, BI.LogicFactory.createLogic(type, extend(o.logic, { items, })))); } diff --git a/src/case/button/treeitem/item.icon.treeleaf.js b/src/case/button/treeitem/item.icon.treeleaf.js index 280270774..56b94723b 100644 --- a/src/case/button/treeitem/item.icon.treeleaf.js +++ b/src/case/button/treeitem/item.icon.treeleaf.js @@ -19,7 +19,7 @@ export class IconTreeLeafItem extends BasicButton { } _init() { - super._init.apply(this, arguments); + super._init(...arguments); const o = this.options; const icon = createWidget({ @@ -52,9 +52,9 @@ export class IconTreeLeafItem extends BasicButton { }, { el: this.text, }); - createWidget(BI.extend({ + createWidget(extend({ element: this, - }, BI.LogicFactory.createLogic(type, BI.extend(o.logic, { + }, BI.LogicFactory.createLogic(type, extend(o.logic, { items, hgap: 5, })))); diff --git a/src/case/button/treeitem/item.last.treeleaf.js b/src/case/button/treeitem/item.last.treeleaf.js index 887b95a2f..e8317f892 100644 --- a/src/case/button/treeitem/item.last.treeleaf.js +++ b/src/case/button/treeitem/item.last.treeleaf.js @@ -19,7 +19,7 @@ export class LastTreeLeafItem extends BasicButton { } _init() { - super._init.apply(this, arguments); + super._init(...arguments); const o = this.options; this.text = createWidget({ type: "bi.label", @@ -53,7 +53,7 @@ export class LastTreeLeafItem extends BasicButton { }, { el: this.text, }); - createWidget(BI.extend({ + createWidget(extend({ element: this, }, BI.LogicFactory.createLogic(type, extend(o.logic, { items, diff --git a/src/case/button/treeitem/item.mid.treeleaf.js b/src/case/button/treeitem/item.mid.treeleaf.js index 69e7bee6b..dfc00d4db 100644 --- a/src/case/button/treeitem/item.mid.treeleaf.js +++ b/src/case/button/treeitem/item.mid.treeleaf.js @@ -19,7 +19,7 @@ export class MidTreeLeafItem extends BasicButton { } _init() { - super._init.apply(this, arguments); + super._init(...arguments); const o = this.options; this.text = createWidget({ type: "bi.label", diff --git a/src/case/button/treeitem/item.multilayer.icon.treeleaf.js b/src/case/button/treeitem/item.multilayer.icon.treeleaf.js index 2d5e043fb..b39108611 100644 --- a/src/case/button/treeitem/item.multilayer.icon.treeleaf.js +++ b/src/case/button/treeitem/item.multilayer.icon.treeleaf.js @@ -1,5 +1,5 @@ import { BasicButton } from "../../../base/single/button/button.basic"; -import { shortcut, extend, createWidget, Controller, makeArray } from "../../../core"; +import { shortcut, extend, createWidget, Controller, makeArray, count } from "../../../core"; /** * @class BI.MultiLayerIconTreeLeafItem @@ -21,7 +21,7 @@ export class MultiLayerIconTreeLeafItem extends BasicButton { } _init() { - super._init.apply(this, arguments); + super._init(...arguments); const o = this.options; this.item = createWidget({ type: "bi.icon_tree_leaf_item", @@ -44,11 +44,11 @@ export class MultiLayerIconTreeLeafItem extends BasicButton { if (type === BI.Events.CLICK) {// 本身实现click功能 return; } - this.fireEvent(Controller.EVENT_CHANGE, args); + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); const items = []; - BI.count(0, o.layer, () => { + count(0, o.layer, () => { items.push({ type: "bi.layout", width: 15, @@ -89,12 +89,12 @@ export class MultiLayerIconTreeLeafItem extends BasicButton { } doClick () { - BI.MultiLayerIconTreeLeafItem.superclass.doClick.apply(this, arguments); + super.doClick(...arguments); this.item.setSelected(this.isSelected()); } setSelected(v) { - BI.MultiLayerIconTreeLeafItem.superclass.setSelected.apply(this, arguments); + super.setSelected(...arguments); this.item.setSelected(v); } diff --git a/src/case/button/treeitem/item.treetextleaf.js b/src/case/button/treeitem/item.treetextleaf.js index 2dca402e8..7bc273210 100644 --- a/src/case/button/treeitem/item.treetextleaf.js +++ b/src/case/button/treeitem/item.treetextleaf.js @@ -24,7 +24,7 @@ export class TreeTextLeafItem extends BasicButton { } _init() { - super._init.apply(this, arguments); + super._init(...arguments); const o = this.options; this.text = createWidget({ type: "bi.label", From 7446b7e786a0ffb2703d48ab3259e9015c69135b Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Fri, 6 Jan 2023 15:37:14 +0800 Subject: [PATCH 044/300] KERNEL-14035 refactor: core/utils --- src/core/index.js | 3 + src/core/utils/chinesePY.js | 50 +++-- src/core/utils/color.js | 163 ++++++++-------- src/core/utils/events/eventlistener.js | 25 ++- src/core/utils/events/index.js | 3 + src/core/utils/events/mousemovetracker.js | 172 ++++++++-------- src/core/utils/events/wheelhandler.js | 228 ++++++++++------------ src/core/utils/i18n.js | 83 ++++---- src/core/utils/index.js | 4 + 9 files changed, 368 insertions(+), 363 deletions(-) create mode 100644 src/core/utils/events/index.js create mode 100644 src/core/utils/index.js diff --git a/src/core/index.js b/src/core/index.js index 49d7b2125..34ab918cd 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -15,6 +15,7 @@ import { useInWorker } from "./worker"; import * as constant from "./constant"; import * as logic from "./logic"; import { Element } from "./element"; +import * as utils from "./utils"; export * from "./decorator"; export * from "./2.base"; @@ -29,6 +30,7 @@ export * from "./structure"; export * from "./h"; export * from "./constant"; export * from "./logic"; +export * from "./utils"; export { StyleLoaderManager, @@ -57,4 +59,5 @@ Object.assign(BI, { ...structure, useInWorker, ...h, + ...utils, }); diff --git a/src/core/utils/chinesePY.js b/src/core/utils/chinesePY.js index 3ef5567db..dfa98ebe0 100644 --- a/src/core/utils/chinesePY.js +++ b/src/core/utils/chinesePY.js @@ -376,41 +376,42 @@ const oMultiDiff = { 40765: "YQ", 40784: "QJ", 40840: "YK", - 40863: "QJG" + 40863: "QJG", }; -const _checkPYCh = function (ch) { - var uni = ch.charCodeAt(0); +function _checkPYCh(ch) { + const uni = ch.charCodeAt(0); // 如果不在汉字处理范围之内,返回原字符,也可以调用自己的处理函数 if (uni > 40869 || uni < 19968) { return ch; } // dealWithOthers(ch); + return (oMultiDiff[uni] ? oMultiDiff[uni] : (_ChineseFirstPY.charAt(uni - 19968))); -}; +} -const _mkPYRslt = function (arr, options) { - var ignoreMulti = options.ignoreMulti; - var splitChar = options.splitChar; - var arrRslt = [""], k, multiLen = 0; - for (var i = 0, len = arr.length; i < len; i++) { - var str = arr[i]; - var strlen = str.length; +function _mkPYRslt(arr, options) { + const ignoreMulti = options.ignoreMulti; + const splitChar = options.splitChar; + let arrRslt = [""], k, multiLen = 0; + for (let i = 0, len = arr.length; i < len; i++) { + const str = arr[i]; + const strlen = str.length; // 多音字过多的情况下,指数增长会造成浏览器卡死,超过20完全卡死,18勉强能用,考虑到不同性能最好是16或者14 // 超过14个多音字之后,后面的都用第一个拼音 - if (strlen == 1 || multiLen > 14 || ignoreMulti) { - var tmpStr = str.substring(0, 1); + if (strlen === 1 || multiLen > 14 || ignoreMulti) { + const tmpStr = str.substring(0, 1); for (k = 0; k < arrRslt.length; k++) { arrRslt[k] += tmpStr; } } else { - var tmpArr = arrRslt.slice(0); + const tmpArr = arrRslt.slice(0); arrRslt = []; multiLen++; for (k = 0; k < strlen; k++) { // 复制一个相同的arrRslt - var tmp = tmpArr.slice(0); + const tmp = tmpArr.slice(0); // 把当前字符str[k]添加到每个元素末尾 - for (var j = 0; j < tmp.length; j++) { + for (let j = 0; j < tmp.length; j++) { tmp[j] += str.charAt(k); } // 把复制并修改后的数组连接到arrRslt上 @@ -418,28 +419,25 @@ const _mkPYRslt = function (arr, options) { } } } + // BI-56386 这边直接将所有多音字组合拼接是有风险的,因为丢失了每一组的起始索引信息, 外部使用indexOf等方法会造成错位 // 一旦错位就可能认为不符合条件, 但实际上还是有可能符合条件的,故此处以一个无法搜索的不可见字符作为连接 return arrRslt.join(splitChar || "").toLowerCase(); -}; - +} export function makeFirstPY(str, options) { options = options || {}; if (typeof (str) !== "string") { - return "" + str; + return `${str}`; } - var arrResult = []; // 保存中间结果的数组 - for (var i = 0, len = str.length; i < len; i++) { + const arrResult = []; // 保存中间结果的数组 + for (let i = 0, len = str.length; i < len; i++) { // 获得unicode码 - var ch = str.charAt(i); + const ch = str.charAt(i); // 检查该unicode码是否在处理范围之内,在则返回该码对映汉字的拼音首字母,不在则调用其它函数处理 arrResult.push(_checkPYCh(ch)); } + // 处理arrResult,返回所有可能的拼音首字母串数组 return _mkPYRslt(arrResult, options); } - -Object.assign(BI, { - makeFirstPY -}); diff --git a/src/core/utils/color.js b/src/core/utils/color.js index 1c14c3739..2eff91b95 100644 --- a/src/core/utils/color.js +++ b/src/core/utils/color.js @@ -1,190 +1,201 @@ -BI.DOM = BI.DOM || {}; -BI.extend(BI.DOM, { - isColor: function (color) { +import { parseInt, parseFloat, isNull, isKey } from "../2.base"; + +export const DOM = { + isColor(color) { return color && (this.isRGBColor(color) || this.isHexColor(color)); }, - isRGBColor: function (color) { + isRGBColor(color) { if (!color) { return false; } + return color.substr(0, 3) === "rgb"; }, - isHexColor: function (color) { + isHexColor(color) { if (!color) { return false; } + return color[0] === "#" && color.length === 7; }, - isDarkColor: function (hex) { + isDarkColor(hex) { if (!hex || !this.isHexColor(hex)) { return false; } - var rgb = this.rgb2json(this.hex2rgb(hex)); - var grayLevel = Math.round(rgb.r * 0.299 + rgb.g * 0.587 + rgb.b * 0.114); + const rgb = this.rgb2json(this.hex2rgb(hex)); + const grayLevel = Math.round(rgb.r * 0.299 + rgb.g * 0.587 + rgb.b * 0.114); if (grayLevel < 192/** 网上给的是140**/) { return true; } + return false; }, // 获取对比颜色 - getContrastColor: function (color) { + getContrastColor(color) { if (!color || !this.isColor(color)) { return ""; } if (this.isDarkColor(color)) { return "#FFFFFF"; } + return "#3D4D66"; }, - rgb2hex: function (rgbColour) { - if (!rgbColour || rgbColour.substr(0, 3) != "rgb") { + rgb2hex(rgbColour) { + if (!rgbColour || rgbColour.substr(0, 3) !== "rgb") { return ""; } - var rgbValues = rgbColour.match(/\d+(\.\d+)?/g); - var red = BI.parseInt(rgbValues[0]); - var green = BI.parseInt(rgbValues[1]); - var blue = BI.parseInt(rgbValues[2]); + const rgbValues = rgbColour.match(/\d+(\.\d+)?/g); + const red = parseInt(rgbValues[0]); + const green = parseInt(rgbValues[1]); + const blue = parseInt(rgbValues[2]); - var hexColour = "#" + this.int2hex(red) + this.int2hex(green) + this.int2hex(blue); + const hexColour = `#${this.int2hex(red)}${this.int2hex(green)}${this.int2hex(blue)}`; return hexColour; }, - _hue2rgb: function (m1, m2, h) { + _hue2rgb(m1, m2, h) { h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h); if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; if (h * 2 < 1) return m2; if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6; + return m1; }, - hsl2rgb: function (hsl) { - var m1, m2, r, g, b; - var h = hsl[0], s = hsl[1], l = hsl[2]; - m2 = (l <= 0.5) ? l * (s + 1) : l + s - l * s; - m1 = l * 2 - m2; + hsl2rgb(hsl) { + const h = hsl[0], s = hsl[1], l = hsl[2]; + const m2 = (l <= 0.5) ? l * (s + 1) : l + s - l * s; + const m1 = l * 2 - m2; + return [this._hue2rgb(m1, m2, h + 0.33333), this._hue2rgb(m1, m2, h), this._hue2rgb(m1, m2, h - 0.33333)]; }, - rgb2hsl: function (rgb) { - var min, max, delta, h, s, l; - var r = rgb[0], g = rgb[1], b = rgb[2]; - min = Math.min(r, Math.min(g, b)); - max = Math.max(r, Math.max(g, b)); - delta = max - min; - l = (min + max) / 2; + rgb2hsl(rgb) { + let h, s; + const r = rgb[0], g = rgb[1], b = rgb[2]; + const min = Math.min(r, Math.min(g, b)); + const max = Math.max(r, Math.max(g, b)); + const delta = max - min; + const l = (min + max) / 2; s = 0; if (l > 0 && l < 1) { s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l)); } h = 0; if (delta > 0) { - if (max == r && max != g) h += (g - b) / delta; - if (max == g && max != b) h += (2 + (b - r) / delta); - if (max == b && max != r) h += (4 + (r - g) / delta); + if (max === r && max !== g) h += (g - b) / delta; + if (max === g && max !== b) h += (2 + (b - r) / delta); + if (max === b && max !== r) h += (4 + (r - g) / delta); h /= 6; } + return [h, s, l]; }, - rgb2json: function (rgbColour) { + rgb2json(rgbColour) { if (!rgbColour) { return {}; } if (!this.isRGBColor(rgbColour)) { return {}; } - var rgbValues = rgbColour.match(/\d+(\.\d+)?/g); + const rgbValues = rgbColour.match(/\d+(\.\d+)?/g); + return { - r: BI.parseInt(rgbValues[0]), - g: BI.parseInt(rgbValues[1]), - b: BI.parseInt(rgbValues[2]) + r: parseInt(rgbValues[0]), + g: parseInt(rgbValues[1]), + b: parseInt(rgbValues[2]), }; }, - rgba2json: function (rgbColour) { + rgba2json(rgbColour) { if (!rgbColour) { return {}; } - var rgbValues = rgbColour.match(/\d+(\.\d+)?/g); + const rgbValues = rgbColour.match(/\d+(\.\d+)?/g); + return { - r: BI.parseInt(rgbValues[0]), - g: BI.parseInt(rgbValues[1]), - b: BI.parseInt(rgbValues[2]), - a: BI.parseFloat(rgbValues[3]) + r: parseInt(rgbValues[0]), + g: parseInt(rgbValues[1]), + b: parseInt(rgbValues[2]), + a: parseFloat(rgbValues[3]), }; }, - json2rgb: function (rgb) { - if (!BI.isKey(rgb.r) || !BI.isKey(rgb.g) || !BI.isKey(rgb.b)) { + json2rgb(rgb) { + if (!isKey(rgb.r) || !isKey(rgb.g) || !isKey(rgb.b)) { return ""; } - return "rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")"; + + return `rgb(${rgb.r},${rgb.g},${rgb.b})`; }, - json2rgba: function (rgba) { - if (!BI.isKey(rgba.r) || !BI.isKey(rgba.g) || !BI.isKey(rgba.b)) { + json2rgba(rgba) { + if (!isKey(rgba.r) || !isKey(rgba.g) || !isKey(rgba.b)) { return ""; } - return "rgba(" + rgba.r + "," + rgba.g + "," + rgba.b + "," + rgba.a + ")"; + + return `rgba(${rgba.r},${rgba.g},${rgba.b},${rgba.a})`; }, - int2hex: function (strNum) { - var hexdig = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; + int2hex(strNum) { + const hexdig = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; - return hexdig[strNum >>> 4] + "" + hexdig[strNum & 15]; + return `${hexdig[strNum >>> 4]}${hexdig[strNum & 15]}`; }, - hex2rgb: function (color) { + hex2rgb(color) { if (!color) { return ""; } if (!this.isHexColor(color)) { return color; } - var tempValue = "rgb(", colorArray; + let tempValue = "rgb(", colorArray; if (color.length === 7) { - colorArray = [BI.parseInt("0x" + color.substring(1, 3)), - BI.parseInt("0x" + color.substring(3, 5)), - BI.parseInt("0x" + color.substring(5, 7))]; + colorArray = [parseInt(`0x${color.substring(1, 3)}`), + parseInt(`0x${color.substring(3, 5)}`), + parseInt(`0x${color.substring(5, 7)}`)]; } else if (color.length === 4) { - colorArray = [BI.parseInt("0x" + color.substring(1, 2)), - BI.parseInt("0x" + color.substring(2, 3)), - BI.parseInt("0x" + color.substring(3, 4))]; + colorArray = [parseInt(`0x${color.substring(1, 2)}`), + parseInt(`0x${color.substring(2, 3)}`), + parseInt(`0x${color.substring(3, 4)}`)]; } - tempValue += colorArray[0] + ","; - tempValue += colorArray[1] + ","; - tempValue += colorArray[2] + ")"; + tempValue += `${colorArray[0]},`; + tempValue += `${colorArray[1]},`; + tempValue += `${colorArray[2]})`; return tempValue; }, - rgba2rgb: function (rgbColor, bgColor) { - if (BI.isNull(bgColor)) { + rgba2rgb(rgbColor, bgColor) { + if (isNull(bgColor)) { bgColor = 1; } - if (rgbColor.substr(0, 4) != "rgba") { + if (rgbColor.substr(0, 4) !== "rgba") { return ""; } - var rgbValues = rgbColor.match(/\d+(\.\d+)?/g); + const rgbValues = rgbColor.match(/\d+(\.\d+)?/g); if (rgbValues.length < 4) { return ""; } - var R = BI.parseFloat(rgbValues[0]); - var G = BI.parseFloat(rgbValues[1]); - var B = BI.parseFloat(rgbValues[2]); - var A = BI.parseFloat(rgbValues[3]); + const R = parseFloat(rgbValues[0]); + const G = parseFloat(rgbValues[1]); + const B = parseFloat(rgbValues[2]); + const A = parseFloat(rgbValues[3]); - return "rgb(" + Math.floor(255 * (bgColor * (1 - A)) + R * A) + "," + - Math.floor(255 * (bgColor * (1 - A)) + G * A) + "," + - Math.floor(255 * (bgColor * (1 - A)) + B * A) + ")"; - } -}); + return `rgb(${Math.floor(255 * (bgColor * (1 - A)) + R * A)},${ + Math.floor(255 * (bgColor * (1 - A)) + G * A)},${ + Math.floor(255 * (bgColor * (1 - A)) + B * A)})`; + }, +}; diff --git a/src/core/utils/events/eventlistener.js b/src/core/utils/events/eventlistener.js index 5b8201dca..b8067c114 100644 --- a/src/core/utils/events/eventlistener.js +++ b/src/core/utils/events/eventlistener.js @@ -1,18 +1,22 @@ -BI.EventListener = { +import { emptyFn } from "../../constant"; + +export const EventListener = { listen: function listen (target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); + return { remove: function remove () { target.removeEventListener(eventType, callback, false); - } + }, }; } else if (target.attachEvent) { - target.attachEvent("on" + eventType, callback); + target.attachEvent(`on${eventType}`, callback); + return { remove: function remove () { - target.detachEvent("on" + eventType, callback); - } + target.detachEvent(`on${eventType}`, callback); + }, }; } }, @@ -20,18 +24,19 @@ BI.EventListener = { capture: function capture (target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, true); + return { remove: function remove () { target.removeEventListener(eventType, callback, true); - } + }, }; } + return { - remove: BI.emptyFn + remove: emptyFn, }; - }, registerDefault: function registerDefault () { - } -}; \ No newline at end of file + }, +}; diff --git a/src/core/utils/events/index.js b/src/core/utils/events/index.js new file mode 100644 index 000000000..9639166d4 --- /dev/null +++ b/src/core/utils/events/index.js @@ -0,0 +1,3 @@ +export { EventListener } from "./eventlistener"; +export { MouseMoveTracker } from "./mousemovetracker"; +export { WheelHandler } from "./wheelhandler"; diff --git a/src/core/utils/events/mousemovetracker.js b/src/core/utils/events/mousemovetracker.js index 212072ebc..63c02e13a 100644 --- a/src/core/utils/events/mousemovetracker.js +++ b/src/core/utils/events/mousemovetracker.js @@ -1,107 +1,107 @@ -!(function () { - var cancelAnimationFrame = - _global.cancelAnimationFrame || - _global.webkitCancelAnimationFrame || - _global.mozCancelAnimationFrame || - _global.oCancelAnimationFrame || - _global.msCancelAnimationFrame || - _global.clearTimeout; +import { EventListener } from "./eventlistener"; +import { bind } from "../../2.base"; - var requestAnimationFrame = _global.requestAnimationFrame || _global.webkitRequestAnimationFrame || _global.mozRequestAnimationFrame || _global.oRequestAnimationFrame || _global.msRequestAnimationFrame || _global.setTimeout; +const cancelAnimationFrame = + _global.cancelAnimationFrame || + _global.webkitCancelAnimationFrame || + _global.mozCancelAnimationFrame || + _global.oCancelAnimationFrame || + _global.msCancelAnimationFrame || + _global.clearTimeout; +const requestAnimationFrame = _global.requestAnimationFrame || _global.webkitRequestAnimationFrame || _global.mozRequestAnimationFrame || _global.oRequestAnimationFrame || _global.msRequestAnimationFrame || _global.setTimeout; - BI.MouseMoveTracker = function (onMove, onMoveEnd, domNode) { +export class MouseMoveTracker { + constructor(onMove, onMoveEnd, domNode) { this._isDragging = false; this._animationFrameID = null; this._domNode = domNode; this._onMove = onMove; this._onMoveEnd = onMoveEnd; + + this._onMouseMove = bind(this._onMouseMove, this); + this._onMouseUp = bind(this._onMouseUp, this); + this._didMouseMove = bind(this._didMouseMove, this); + } - this._onMouseMove = BI.bind(this._onMouseMove, this); - this._onMouseUp = BI.bind(this._onMouseUp, this); - this._didMouseMove = BI.bind(this._didMouseMove, this); - }; - BI.MouseMoveTracker.prototype = { - constructor: BI.MouseMoveTracker, - captureMouseMoves: function (/* object*/ event) { - if (!this._eventMoveToken && !this._eventUpToken) { - this._eventMoveToken = BI.EventListener.listen( - this._domNode, - "mousemove", - this._onMouseMove - ); - this._eventUpToken = BI.EventListener.listen( - this._domNode, - "mouseup", - this._onMouseUp - ); - } + captureMouseMoves(event) { + if (!this._eventMoveToken && !this._eventUpToken) { + this._eventMoveToken = EventListener.listen( + this._domNode, + "mousemove", + this._onMouseMove + ); + this._eventUpToken = EventListener.listen( + this._domNode, + "mouseup", + this._onMouseUp + ); + } - if (!this._isDragging) { - this._deltaX = 0; - this._deltaY = 0; - this._isDragging = true; - this._x = event.clientX; - this._y = event.clientY; - } - // event.preventDefault ? event.preventDefault() : (event.returnValue = false); - }, + if (!this._isDragging) { + this._deltaX = 0; + this._deltaY = 0; + this._isDragging = true; + this._x = event.clientX; + this._y = event.clientY; + } + // event.preventDefault ? event.preventDefault() : (event.returnValue = false); + } - releaseMouseMoves: function () { - if (this._eventMoveToken && this._eventUpToken) { - this._eventMoveToken.remove(); - this._eventMoveToken = null; - this._eventUpToken.remove(); - this._eventUpToken = null; - } + releaseMouseMoves() { + if (this._eventMoveToken && this._eventUpToken) { + this._eventMoveToken.remove(); + this._eventMoveToken = null; + this._eventUpToken.remove(); + this._eventUpToken = null; + } - if (this._animationFrameID !== null) { - cancelAnimationFrame(this._animationFrameID); - this._animationFrameID = null; - } + if (this._animationFrameID !== null) { + cancelAnimationFrame(this._animationFrameID); + this._animationFrameID = null; + } - if (this._isDragging) { - this._isDragging = false; - this._x = null; - this._y = null; - } - }, + if (this._isDragging) { + this._isDragging = false; + this._x = null; + this._y = null; + } + } - isDragging: function () /* boolean*/ { - return this._isDragging; - }, + isDragging() /* boolean*/ { + return this._isDragging; + } - _onMouseMove: function (/* object*/ event) { - var x = event.clientX; - var y = event.clientY; + _onMouseMove(/* object*/ event) { + const x = event.clientX; + const y = event.clientY; - this._deltaX += (x - this._x); - this._deltaY += (y - this._y); + this._deltaX += (x - this._x); + this._deltaY += (y - this._y); - if (this._animationFrameID === null) { - // The mouse may move faster then the animation frame does. - // Use `requestAnimationFrame` to avoid over-updating. - this._animationFrameID = - requestAnimationFrame(this._didMouseMove); - } + if (this._animationFrameID === null) { + // The mouse may move faster then the animation frame does. + // Use `requestAnimationFrame` to avoid over-updating. + this._animationFrameID = + requestAnimationFrame(this._didMouseMove); + } - this._x = x; - this._y = y; - event.preventDefault ? event.preventDefault() : (event.returnValue = false); - }, + this._x = x; + this._y = y; + event.preventDefault ? event.preventDefault() : (event.returnValue = false); + } - _didMouseMove: function () { - this._animationFrameID = null; - this._onMove(this._deltaX, this._deltaY); - this._deltaX = 0; - this._deltaY = 0; - }, + _didMouseMove() { + this._animationFrameID = null; + this._onMove(this._deltaX, this._deltaY); + this._deltaX = 0; + this._deltaY = 0; + } - _onMouseUp: function () { - if (this._animationFrameID) { - this._didMouseMove(); - } - this._onMoveEnd(); + _onMouseUp() { + if (this._animationFrameID) { + this._didMouseMove(); } - }; -})(); + this._onMoveEnd(); + } +} diff --git a/src/core/utils/events/wheelhandler.js b/src/core/utils/events/wheelhandler.js index 4d3ea6588..366b5afa6 100644 --- a/src/core/utils/events/wheelhandler.js +++ b/src/core/utils/events/wheelhandler.js @@ -1,149 +1,131 @@ -!(function () { - var PIXEL_STEP = 10; - var LINE_HEIGHT = 40; - var PAGE_HEIGHT = 800; - var requestAnimationFrame = _global.requestAnimationFrame || _global.webkitRequestAnimationFrame || _global.mozRequestAnimationFrame || _global.oRequestAnimationFrame || _global.msRequestAnimationFrame || _global.setTimeout; - - function normalizeWheel (/* object*/event) /* object*/ { - var sX = 0, - sY = 0, - // spinX, spinY - pX = 0, - pY = 0; // pixelX, pixelY - - // Legacy - if ("detail" in event) { - sY = event.detail; - } - if ("wheelDelta" in event) { - sY = -event.wheelDelta / 120; - } - if ("wheelDeltaY" in event) { - sY = -event.wheelDeltaY / 120; - } - if ("wheelDeltaX" in event) { - sX = -event.wheelDeltaX / 120; - } - - // side scrolling on FF with DOMMouseScroll - if ("axis" in event && event.axis === event.HORIZONTAL_AXIS) { - sX = sY; - sY = 0; - } +import { bind } from "../../2.base"; + +const PIXEL_STEP = 10; +const LINE_HEIGHT = 40; +const PAGE_HEIGHT = 800; +const requestAnimationFrame = _global.requestAnimationFrame || _global.webkitRequestAnimationFrame || _global.mozRequestAnimationFrame || _global.oRequestAnimationFrame || _global.msRequestAnimationFrame || _global.setTimeout; + +function normalizeWheel (/* object*/event) /* object*/ { + let sX = 0, + sY = 0, + // spinX, spinY + pX = 0, + pY = 0; // pixelX, pixelY + + // Legacy + if ("detail" in event) { + sY = event.detail; + } + if ("wheelDelta" in event) { + sY = -event.wheelDelta / 120; + } + if ("wheelDeltaY" in event) { + sY = -event.wheelDeltaY / 120; + } + if ("wheelDeltaX" in event) { + sX = -event.wheelDeltaX / 120; + } - pX = sX * PIXEL_STEP; - pY = sY * PIXEL_STEP; + // side scrolling on FF with DOMMouseScroll + if ("axis" in event && event.axis === event.HORIZONTAL_AXIS) { + sX = sY; + sY = 0; + } - if ("deltaY" in event) { - pY = event.deltaY; - } - if ("deltaX" in event) { - pX = event.deltaX; - } + pX = sX * PIXEL_STEP; + pY = sY * PIXEL_STEP; - if ((pX || pY) && event.deltaMode) { - if (event.deltaMode === 1) { - // delta in LINE units - pX *= LINE_HEIGHT; - pY *= LINE_HEIGHT; - } else { - // delta in PAGE units - pX *= PAGE_HEIGHT; - pY *= PAGE_HEIGHT; - } - } + if ("deltaY" in event) { + pY = event.deltaY; + } + if ("deltaX" in event) { + pX = event.deltaX; + } - // Fall-back if spin cannot be determined - if (pX && !sX) { - sX = pX < 1 ? -1 : 1; - } - if (pY && !sY) { - sY = pY < 1 ? -1 : 1; + if ((pX || pY) && event.deltaMode) { + if (event.deltaMode === 1) { + // delta in LINE units + pX *= LINE_HEIGHT; + pY *= LINE_HEIGHT; + } else { + // delta in PAGE units + pX *= PAGE_HEIGHT; + pY *= PAGE_HEIGHT; } + } - return { - spinX: sX, - spinY: sY, - pixelX: pX, - pixelY: pY - }; + // Fall-back if spin cannot be determined + if (pX && !sX) { + sX = pX < 1 ? -1 : 1; } + if (pY && !sY) { + sY = pY < 1 ? -1 : 1; + } + + return { + spinX: sX, + spinY: sY, + pixelX: pX, + pixelY: pY, + }; +} - BI.WheelHandler = function (onWheel, handleScrollX, handleScrollY, stopPropagation) { +export class WheelHandler { + constructor(onWheel, handleScrollX, handleScrollY, stopPropagation) { this._animationFrameID = null; this._deltaX = 0; this._deltaY = 0; - this._didWheel = BI.bind(this._didWheel, this); + this._didWheel = bind(this._didWheel, this); if (typeof handleScrollX !== "function") { - handleScrollX = handleScrollX ? - function () { - return true; - } : - function () { - return false; - }; + handleScrollX = handleScrollX ? () => true : () => false; } - + if (typeof handleScrollY !== "function") { - handleScrollY = handleScrollY ? - function () { - return true; - } : - function () { - return false; - }; + handleScrollY = handleScrollY ? () => true : () => false; } - + if (typeof stopPropagation !== "function") { - stopPropagation = stopPropagation ? - function () { - return true; - } : - function () { - return false; - }; + stopPropagation = stopPropagation ? () => true : () => false; } - + this._handleScrollX = handleScrollX; this._handleScrollY = handleScrollY; this._stopPropagation = stopPropagation; this._onWheelCallback = onWheel; - this.onWheel = BI.bind(this.onWheel, this); - }; - BI.WheelHandler.prototype = { - constructor: BI.WheelHandler, - onWheel: function (/* object*/ event) { - var normalizedEvent = normalizeWheel(event); - var deltaX = this._deltaX + normalizedEvent.pixelX; - var deltaY = this._deltaY + normalizedEvent.pixelY; - var handleScrollX = this._handleScrollX(deltaX, deltaY); - var handleScrollY = this._handleScrollY(deltaY, deltaX); - if (!handleScrollX && !handleScrollY) { - return; - } - - this._deltaX += handleScrollX ? normalizedEvent.pixelX : 0; - this._deltaY += handleScrollY ? normalizedEvent.pixelY : 0; - event.preventDefault ? event.preventDefault() : (event.returnValue = false); + this.onWheel = bind(this.onWheel, this); + } + + onWheel(event) { + const normalizedEvent = normalizeWheel(event); + const deltaX = this._deltaX + normalizedEvent.pixelX; + const deltaY = this._deltaY + normalizedEvent.pixelY; + const handleScrollX = this._handleScrollX(deltaX, deltaY); + const handleScrollY = this._handleScrollY(deltaY, deltaX); + if (!handleScrollX && !handleScrollY) { + return; + } - var changed; - if (this._deltaX !== 0 || this._deltaY !== 0) { - if (this._stopPropagation()) { - event.stopPropagation ? event.stopPropagation() : (event.cancelBubble = true); - } - changed = true; - } + this._deltaX += handleScrollX ? normalizedEvent.pixelX : 0; + this._deltaY += handleScrollY ? normalizedEvent.pixelY : 0; + event.preventDefault ? event.preventDefault() : (event.returnValue = false); - if (changed === true && this._animationFrameID === null) { - this._animationFrameID = requestAnimationFrame(this._didWheel); + let changed; + if (this._deltaX !== 0 || this._deltaY !== 0) { + if (this._stopPropagation()) { + event.stopPropagation ? event.stopPropagation() : (event.cancelBubble = true); } - }, + changed = true; + } - _didWheel: function () { - this._animationFrameID = null; - this._onWheelCallback(this._deltaX, this._deltaY); - this._deltaX = 0; - this._deltaY = 0; + if (changed === true && this._animationFrameID === null) { + this._animationFrameID = requestAnimationFrame(this._didWheel); } - }; -})(); \ No newline at end of file + } + + _didWheel() { + this._animationFrameID = null; + this._onWheelCallback(this._deltaX, this._deltaY); + this._deltaX = 0; + this._deltaY = 0; + } +} diff --git a/src/core/utils/i18n.js b/src/core/utils/i18n.js index 8611ec0a9..3fa951695 100644 --- a/src/core/utils/i18n.js +++ b/src/core/utils/i18n.js @@ -1,51 +1,50 @@ -!(function () { - var i18nStore = {}; +import { extend } from "../2.base"; +import { replaceAll } from "../func"; - var i18nFormatters = {}; +let i18nStore = {}; +const i18nFormatters = {}; - BI._.extend(BI, { - changeI18n: function (i18n) { - if (i18n) { - i18nStore = i18n; - } - }, - addI18n: function (i18n) { - BI.extend(i18nStore, i18n); - }, +export function changeI18n(i18n) { + if (i18n) { + i18nStore = i18n; + } +} - i18nText: function (key) { - var localeText = i18nStore[key] || (BI.i18n && BI.i18n[key]) || ""; - if (!localeText) { - localeText = key; - } - var len = arguments.length; - if (len > 1) { - if (localeText.indexOf("{R1") > -1) { - for (var i = 1; i < len; i++) { - var reg = new RegExp(`{R${i},(.*?)}`, "g"); +export function addI18n(i18n) { + extend(i18nStore, i18n); +} + +export function i18nText(key) { + let localeText = i18nStore[key] || (BI.i18n && BI.i18n[key]) || ""; + if (!localeText) { + localeText = key; + } + const len = arguments.length; + if (len > 1) { + if (localeText.indexOf("{R1") > -1) { + for (let i = 1; i < len; i++) { + const reg = new RegExp(`{R${i},(.*?)}`, "g"); - var result = reg.exec(localeText); + const result = reg.exec(localeText); - if (result) { - var formatName = result[1]; - localeText = BI.replaceAll(localeText, reg, i18nFormatters[formatName](key, arguments[i])); - } else { - localeText = BI.replaceAll(localeText, `{R${i}}`, arguments[i] + ""); - } - } + if (result) { + const formatName = result[1]; + localeText = replaceAll(localeText, reg, i18nFormatters[formatName](key, arguments[i])); } else { - var args = Array.prototype.slice.call(arguments); - var count = 1; - return BI.replaceAll(localeText, "\\{\\s*\\}", function () { - return args[count++] + ""; - }); + localeText = replaceAll(localeText, `{R${i}}`, `${arguments[i]}`); } } - return localeText; - }, - - addI18nFormatter: function (formatName, fn) { - i18nFormatters[formatName] = fn; + } else { + const args = Array.prototype.slice.call(arguments); + let count = 1; + + return replaceAll(localeText, "\\{\\s*\\}", () => `${args[count++]}`); } - }); -})(); + } + + return localeText; +} + +export function addI18nFormatter(formatName, fn) { + i18nFormatters[formatName] = fn; +} diff --git a/src/core/utils/index.js b/src/core/utils/index.js new file mode 100644 index 000000000..059be17e4 --- /dev/null +++ b/src/core/utils/index.js @@ -0,0 +1,4 @@ +export * from "./events"; +export * from "./i18n"; +export { makeFirstPY } from "./chinesePY"; +export { DOM } from "./color"; From 50db461708aa7f1d42fd1fe0aad12afd63b1c5f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Fri, 6 Jan 2023 15:41:36 +0800 Subject: [PATCH 045/300] =?UTF-8?q?KERNEL-13972=20refactor:=20base/collect?= =?UTF-8?q?ion=E3=80=81base/tree=20es6=E5=8C=96=E5=92=8C=E4=BF=AE=E6=94=B9?= =?UTF-8?q?bi.xxx?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/collection/collection.js | 347 ++++++++-------- src/base/grid/grid.js | 90 ++-- src/base/index.js | 12 +- src/base/layer/index.js | 2 +- src/base/layer/layer.drawer.js | 361 ++++++++-------- src/base/layer/layer.popover.js | 358 ++++++++-------- src/base/layer/layer.popup.js | 639 ++++++++++++++--------------- src/base/layer/layer.searcher.js | 193 +++++---- src/base/list/index.js | 2 +- src/base/list/listview.js | 166 ++++---- src/base/list/virtualgrouplist.js | 285 +++++++------ src/base/list/virtuallist.js | 325 ++++++++------- src/base/pager/pager.js | 125 +++--- src/base/single/a/a.js | 36 +- src/base/single/index.js | 2 +- src/base/single/tip/0.tip.js | 24 +- src/base/single/tip/index.js | 2 +- src/base/single/tip/tip.toast.js | 181 ++++---- src/base/single/tip/tip.tooltip.js | 133 +++--- src/base/tree/customtree.js | 137 ++++--- src/core/index.js | 6 +- 21 files changed, 1704 insertions(+), 1722 deletions(-) diff --git a/src/base/collection/collection.js b/src/base/collection/collection.js index f45437627..2b57f9de3 100644 --- a/src/base/collection/collection.js +++ b/src/base/collection/collection.js @@ -5,9 +5,12 @@ * @class BI.CollectionView * @extends BI.Widget */ -BI.CollectionView = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.CollectionView.superclass._defaultConfig.apply(this, arguments), { +import { Widget, shortcut, extend, emptyFn, debounce, _lazyCreateWidget, isFunction, SectionManager, + isNull, each, clamp, toArray, invert, min, max, nextTick } from "../../core"; +@shortcut() +export class CollectionView extends Widget { + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-collection", // width: 400, //必设 // height: 300, //必设 @@ -17,97 +20,100 @@ BI.CollectionView = BI.inherit(BI.Widget, { overflowX: true, overflowY: true, el: { - type: "bi.vertical" + type: "bi.vertical", }, - cellSizeAndPositionGetter: BI.emptyFn, + cellSizeAndPositionGetter: emptyFn, horizontalOverscanSize: 0, verticalOverscanSize: 0, scrollLeft: 0, scrollTop: 0, items: [], - itemFormatter: function (item, index) { - return item; - }, + itemFormatter: (item, index) => item, }); - }, + } + + static EVENT_SCROLL = "EVENT_SCROLL"; + static xtype = "bi.collection_view"; - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; + const { overflowX, overflowY, el } = this.options; this.renderedCells = []; this.renderedKeys = []; this.renderRange = {}; this._scrollLock = false; - this._debounceRelease = BI.debounce(function () { - self._scrollLock = false; + this._debounceRelease = debounce(() => { + this._scrollLock = false; }, 1000 / 60); - this.container = BI._lazyCreateWidget({ + this.container = _lazyCreateWidget({ type: "bi.absolute", }); - this.element.scroll(function () { - if (self._scrollLock === true) { + this.element.scroll(() => { + if (this._scrollLock === true) { return; } - o.scrollLeft = self.element.scrollLeft(); - o.scrollTop = self.element.scrollTop(); - self._calculateChildrenToRender(); - self.fireEvent(BI.CollectionView.EVENT_SCROLL, { + o.scrollLeft = this.element.scrollLeft(); + o.scrollTop = this.element.scrollTop(); + this._calculateChildrenToRender(); + this.fireEvent(CollectionView.EVENT_SCROLL, { scrollLeft: o.scrollLeft, scrollTop: o.scrollTop, }); }); // 兼容一下 - var scrollable = o.scrollable, scrollx = o.scrollx, scrolly = o.scrolly; - if (o.overflowX === false) { - if (o.overflowY === false) { + let scrollable = o.scrollable; + const scrollx = o.scrollx, scrolly = o.scrolly; + if (overflowX === false) { + if (overflowY === false) { scrollable = false; } else { scrollable = "y"; } } else { - if (o.overflowY === false) { + if (overflowY === false) { scrollable = "x"; } } - BI._lazyCreateWidget(o.el, { + _lazyCreateWidget(el, { type: "bi.vertical", element: this, - scrollable: scrollable, - scrolly: scrolly, - scrollx: scrollx, + scrollable, + scrolly, + scrollx, items: [this.container], }); - o.items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + o.items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; if (o.items.length > 0) { this._calculateSizeAndPositionData(); this._populate(); } - }, + } // mounted之后绑定事件 - mounted: function () { - var o = this.options; - if (o.scrollLeft !== 0 || o.scrollTop !== 0) { - this.element.scrollTop(o.scrollTop); - this.element.scrollLeft(o.scrollLeft); + mounted() { + const { scrollLeft, scrollTop } = this.options; + if (scrollLeft !== 0 || scrollTop !== 0) { + this.element.scrollTop(scrollTop); + this.element.scrollLeft(scrollLeft); } - }, - - _calculateSizeAndPositionData: function () { - var o = this.options; - var cellMetadata = []; - var sectionManager = new BI.SectionManager(); - var height = 0; - var width = 0; - - for (var index = 0, len = o.items.length; index < len; index++) { - var cellMetadatum = o.cellSizeAndPositionGetter(index); - - if (BI.isNull(cellMetadatum.height) || isNaN(cellMetadatum.height) || - BI.isNull(cellMetadatum.width) || isNaN(cellMetadatum.width) || - BI.isNull(cellMetadatum.x) || isNaN(cellMetadatum.x) || - BI.isNull(cellMetadatum.y) || isNaN(cellMetadatum.y)) { + } + + _calculateSizeAndPositionData() { + const { items, cellSizeAndPositionGetter } = this.options; + const cellMetadata = []; + const sectionManager = new SectionManager(); + let height = 0; + let width = 0; + + for (let index = 0, len = items.length; index < len; index++) { + const cellMetadatum = cellSizeAndPositionGetter(index); + + if (isNull(cellMetadatum.height) || isNaN(cellMetadatum.height) || + isNull(cellMetadatum.width) || isNaN(cellMetadatum.width) || + isNull(cellMetadatum.x) || isNaN(cellMetadatum.x) || + isNull(cellMetadatum.y) || isNaN(cellMetadatum.y)) { throw Error(); } @@ -123,110 +129,110 @@ BI.CollectionView = BI.inherit(BI.Widget, { this._sectionManager = sectionManager; this._height = height; this._width = width; - }, + } - _cellRenderers: function (height, width, x, y) { + _cellRenderers(height, width, x, y) { this._lastRenderedCellIndices = this._sectionManager.getCellIndices(height, width, x, y); return this._cellGroupRenderer(); - }, + } - _cellGroupRenderer: function () { - var self = this; - var rendered = []; - BI.each(this._lastRenderedCellIndices, function (i, index) { - var cellMetadata = self._sectionManager.getCellMetadata(index); + _cellGroupRenderer() { + const rendered = []; + each(this._lastRenderedCellIndices, (i, index) => { + const cellMetadata = this._sectionManager.getCellMetadata(index); rendered.push(cellMetadata); }); return rendered; - }, - - _calculateChildrenToRender: function () { - var self = this, o = this.options; - var scrollLeft = BI.clamp(o.scrollLeft, 0, this._getMaxScrollLeft()); - var scrollTop = BI.clamp(o.scrollTop, 0, this._getMaxScrollTop()); - var left = Math.max(0, scrollLeft - o.horizontalOverscanSize); - var top = Math.max(0, scrollTop - o.verticalOverscanSize); - var right = Math.min(this._width, scrollLeft + o.width + o.horizontalOverscanSize); - var bottom = Math.min(this._height, scrollTop + o.height + o.verticalOverscanSize); + } + + _calculateChildrenToRender() { + const o = this.options; + const { horizontalOverscanSize, verticalOverscanSize, width, height, itemFormatter, items } = this.options; + const scrollLeft = clamp(o.scrollLeft, 0, this._getMaxScrollLeft()); + const scrollTop = clamp(o.scrollTop, 0, this._getMaxScrollTop()); + const left = Math.max(0, scrollLeft - horizontalOverscanSize); + const top = Math.max(0, scrollTop - verticalOverscanSize); + const right = Math.min(this._width, scrollLeft + width + horizontalOverscanSize); + const bottom = Math.min(this._height, scrollTop + height + verticalOverscanSize); if (right > 0 && bottom > 0) { // 如果滚动的区间并没有超出渲染的范围 if (top >= this.renderRange.minY && bottom <= this.renderRange.maxY && left >= this.renderRange.minX && right <= this.renderRange.maxX) { return; } - var childrenToDisplay = this._cellRenderers(bottom - top, right - left, left, top); - var renderedCells = [], renderedKeys = {}, renderedWidgets = {}; + const childrenToDisplay = this._cellRenderers(bottom - top, right - left, left, top); + const renderedCells = [], renderedKeys = {}, renderedWidgets = {}; // 存储所有的left和top - var lefts = {}, tops = {}; - for (var i = 0, len = childrenToDisplay.length; i < len; i++) { - var datum = childrenToDisplay[i]; + let lefts = {}, tops = {}; + for (let i = 0, len = childrenToDisplay.length; i < len; i++) { + const datum = childrenToDisplay[i]; lefts[datum.x] = datum.x; lefts[datum.x + datum.width] = datum.x + datum.width; tops[datum.y] = datum.y; tops[datum.y + datum.height] = datum.y + datum.height; } - lefts = BI.toArray(lefts); - tops = BI.toArray(tops); - var leftMap = BI.invert(lefts); - var topMap = BI.invert(tops); + lefts = toArray(lefts); + tops = toArray(tops); + const leftMap = invert(lefts); + const topMap = invert(tops); // 存储上下左右四个边界 - var leftBorder = {}, rightBorder = {}, topBorder = {}, bottomBorder = {}; + const leftBorder = {}, rightBorder = {}, topBorder = {}, bottomBorder = {}; function assertMinBorder(border, offset) { - if (BI.isNull(border[offset])) { + if (isNull(border[offset])) { border[offset] = Number.MAX_VALUE; } } function assertMaxBorder(border, offset) { - if (BI.isNull(border[offset])) { + if (isNull(border[offset])) { border[offset] = 0; } } - for (var i = 0, len = childrenToDisplay.length; i < len; i++) { - var datum = childrenToDisplay[i]; - var index = this.renderedKeys[datum.index] && this.renderedKeys[datum.index][1]; - var child; + for (let i = 0, len = childrenToDisplay.length; i < len; i++) { + const datum = childrenToDisplay[i]; + const index = this.renderedKeys[datum.index] && this.renderedKeys[datum.index][1]; + let child; if (index >= 0) { this.renderedCells[index].el.setWidth(datum.width); this.renderedCells[index].el.setHeight(datum.height); // 这里只使用px - this.renderedCells[index].el.element.css("left", datum.x + "px"); - this.renderedCells[index].el.element.css("top", datum.y + "px"); + this.renderedCells[index].el.element.css("left", `${datum.x}px`); + this.renderedCells[index].el.element.css("top", `${datum.y}px`); renderedCells.push(child = this.renderedCells[index]); } else { - var item = o.itemFormatter(o.items[datum.index], datum.index); - child = BI._lazyCreateWidget(BI.extend({ + const item = itemFormatter(items[datum.index], datum.index); + child = _lazyCreateWidget(extend({ type: "bi.label", width: datum.width, height: datum.height, }, item, { - cls: (item.cls || "") + " collection-cell" + (datum.y === 0 ? " first-row" : "") + (datum.x === 0 ? " first-col" : ""), + cls: `${item.cls || ""} collection-cell${datum.y === 0 ? " first-row" : ""}${datum.x === 0 ? " first-col" : ""}`, _left: datum.x, _top: datum.y, })); renderedCells.push({ el: child, - left: datum.x + "px", - top: datum.y + "px", + left: `${datum.x}px`, + top: `${datum.y}px`, _left: datum.x, _top: datum.y, // _width: datum.width, // _height: datum.height }); } - var startTopIndex = topMap[datum.y] | 0; - var endTopIndex = topMap[datum.y + datum.height] | 0; - for (var k = startTopIndex; k <= endTopIndex; k++) { - var t = tops[k]; + const startTopIndex = topMap[datum.y] | 0; + const endTopIndex = topMap[datum.y + datum.height] | 0; + for (let k = startTopIndex; k <= endTopIndex; k++) { + const t = tops[k]; assertMinBorder(leftBorder, t); assertMaxBorder(rightBorder, t); leftBorder[t] = Math.min(leftBorder[t], datum.x); rightBorder[t] = Math.max(rightBorder[t], datum.x + datum.width); } - var startLeftIndex = leftMap[datum.x] | 0; - var endLeftIndex = leftMap[datum.x + datum.width] | 0; - for (var k = startLeftIndex; k <= endLeftIndex; k++) { - var l = lefts[k]; + const startLeftIndex = leftMap[datum.x] | 0; + const endLeftIndex = leftMap[datum.x + datum.width] | 0; + for (let k = startLeftIndex; k <= endLeftIndex; k++) { + const l = lefts[k]; assertMinBorder(topBorder, l); assertMaxBorder(bottomBorder, l); topBorder[l] = Math.min(topBorder[l], datum.y); @@ -237,15 +243,15 @@ BI.CollectionView = BI.inherit(BI.Widget, { renderedWidgets[i] = child; } // 已存在的, 需要添加的和需要删除的 - var existSet = {}, addSet = {}, deleteArray = []; - BI.each(renderedKeys, function (i, key) { - if (self.renderedKeys[i]) { + const existSet = {}, addSet = {}, deleteArray = []; + each(renderedKeys, (i, key) => { + if (this.renderedKeys[i]) { existSet[i] = key; } else { addSet[i] = key; } }); - BI.each(this.renderedKeys, function (i, key) { + each(this.renderedKeys, (i, key) => { if (existSet[i]) { return; } @@ -254,12 +260,12 @@ BI.CollectionView = BI.inherit(BI.Widget, { } deleteArray.push(key[1]); }); - BI.each(deleteArray, function (i, index) { + each(deleteArray, (i, index) => { // 性能优化,不调用destroy方法防止触发destroy事件 - self.renderedCells[index].el._destroy(); + this.renderedCells[index].el._destroy(); }); - var addedItems = []; - BI.each(addSet, function (index, key) { + const addedItems = []; + each(addSet, (index, key) => { addedItems.push(renderedCells[key[1]]); }); this.container.addItems(addedItems); @@ -270,21 +276,22 @@ BI.CollectionView = BI.inherit(BI.Widget, { this.renderedKeys = renderedKeys; // Todo 左右比较特殊 - var minX = BI.min(leftBorder); - var maxX = BI.max(rightBorder); + const minX = min(leftBorder); + const maxX = max(rightBorder); - var minY = BI.max(topBorder); - var maxY = BI.min(bottomBorder); + const minY = max(topBorder); + const maxY = min(bottomBorder); - this.renderRange = { minX: minX, minY: minY, maxX: maxX, maxY: maxY }; + this.renderRange = { minX, minY, maxX, maxY }; } - }, + } - _isOverflowX: function () { - var o = this.options; + _isOverflowX() { + const o = this.options; + const { overflowX } = this.options; // 兼容一下 - var scrollable = o.scrollable, scrollx = o.scrollx; - if (o.overflowX === false) { + const scrollable = o.scrollable, scrollx = o.scrollx; + if (overflowX === false) { return false; } if (scrollx) { @@ -293,14 +300,16 @@ BI.CollectionView = BI.inherit(BI.Widget, { if (scrollable === true || scrollable === "xy" || scrollable === "x") { return true; } + return false; - }, + } - _isOverflowY: function () { - var o = this.options; + _isOverflowY() { + const o = this.options; + const { overflowX } = this.options; // 兼容一下 - var scrollable = o.scrollable, scrolly = o.scrolly; - if (o.overflowX === false) { + const scrollable = o.scrollable, scrolly = o.scrolly; + if (overflowX === false) { return false; } if (scrolly) { @@ -309,19 +318,20 @@ BI.CollectionView = BI.inherit(BI.Widget, { if (scrollable === true || scrollable === "xy" || scrollable === "y") { return true; } + return false; - }, + } - _getMaxScrollLeft: function () { + _getMaxScrollLeft() { return Math.max(0, this._width - this.options.width + (this._isOverflowX() ? BI.DOM.getScrollWidth() : 0)); - }, + } - _getMaxScrollTop: function () { + _getMaxScrollTop() { return Math.max(0, this._height - this.options.height + (this._isOverflowY() ? BI.DOM.getScrollWidth() : 0)); - }, + } - _populate: function (items) { - var o = this.options; + _populate(items) { + const { scrollTop, scrollLeft } = this.options; this._reRange(); if (items && items !== this.options.items) { this.options.items = items; @@ -333,83 +343,80 @@ BI.CollectionView = BI.inherit(BI.Widget, { this._debounceRelease(); // 元素未挂载时不能设置scrollTop try { - this.element.scrollTop(o.scrollTop); - this.element.scrollLeft(o.scrollLeft); + this.element.scrollTop(scrollTop); + this.element.scrollLeft(scrollLeft); } catch (e) { } this._calculateChildrenToRender(); - }, - - setScrollLeft: function (scrollLeft) { + } + setScrollLeft(scrollLeft) { if (this.options.scrollLeft === scrollLeft) { return; } this._scrollLock = true; - this.options.scrollLeft = BI.clamp(scrollLeft || 0, 0, this._getMaxScrollLeft()); + this.options.scrollLeft = clamp(scrollLeft || 0, 0, this._getMaxScrollLeft()); this._debounceRelease(); this.element.scrollLeft(this.options.scrollLeft); this._calculateChildrenToRender(); - }, + } - setScrollTop: function (scrollTop) { + setScrollTop(scrollTop) { if (this.options.scrollTop === scrollTop) { return; } this._scrollLock = true; - this.options.scrollTop = BI.clamp(scrollTop || 0, 0, this._getMaxScrollTop()); + this.options.scrollTop = clamp(scrollTop || 0, 0, this._getMaxScrollTop()); this._debounceRelease(); this.element.scrollTop(this.options.scrollTop); this._calculateChildrenToRender(); - }, + } - setOverflowX: function (b) { - var self = this; + setOverflowX(b) { if (this.options.overflowX !== !!b) { this.options.overflowX = !!b; - BI.nextTick(function () { - self.element.css({ overflowX: b ? "auto" : "hidden" }); + nextTick(() => { + this.element.css({ overflowX: b ? "auto" : "hidden" }); }); } - }, + } - setOverflowY: function (b) { - var self = this; + setOverflowY(b) { if (this.options.overflowY !== !!b) { this.options.overflowY = !!b; - BI.nextTick(function () { - self.element.css({ overflowY: b ? "auto" : "hidden" }); + nextTick(() => { + this.element.css({ overflowY: b ? "auto" : "hidden" }); }); } - }, + } - getScrollLeft: function () { + getScrollLeft() { return this.options.scrollLeft; - }, + } - getScrollTop: function () { + getScrollTop() { return this.options.scrollTop; - }, + } - getMaxScrollLeft: function () { + getMaxScrollLeft() { return this._getMaxScrollLeft(); - }, + } - getMaxScrollTop: function () { + getMaxScrollTop() { return this._getMaxScrollTop(); - }, + } // 重新计算children - _reRange: function () { + _reRange() { this.renderRange = {}; - }, + } - _clearChildren: function () { + _clearChildren() { this.container._children = {}; this.container.attr("items", []); - }, + } - restore: function () { - BI.each(this.renderedCells, function (i, cell) { + restore() { + each(this.renderedCells, (i, cell) => { cell.el._destroy(); }); this._clearChildren(); @@ -417,14 +424,12 @@ BI.CollectionView = BI.inherit(BI.Widget, { this.renderedKeys = []; this.renderRange = {}; this._scrollLock = false; - }, + } - populate: function (items) { + populate(items) { if (items && items !== this.options.items) { this.restore(); } this._populate(items); - }, -}); -BI.CollectionView.EVENT_SCROLL = "EVENT_SCROLL"; -BI.shortcut("bi.collection_view", BI.CollectionView); + } +} diff --git a/src/base/grid/grid.js b/src/base/grid/grid.js index 3798a8e46..150723808 100644 --- a/src/base/grid/grid.js +++ b/src/base/grid/grid.js @@ -5,11 +5,12 @@ * @class BI.GridView * @extends BI.Widget */ -import { Widget, shortcut } from "../../core"; +import { Widget, shortcut, extend, emptyFn, debounce, _lazyCreateWidget, + isFunction, each, isNumber, ScalingCellSizeAndPositionManager, clamp, isEmpty, nextTick } from "../../core"; @shortcut() -export default class GridView extends Widget { +export class GridView extends Widget { _defaultConfig() { - return BI.extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-grid-view", // width: 400, //必设 // height: 300, //必设 @@ -19,20 +20,18 @@ export default class GridView extends Widget { overflowX: true, overflowY: true, el: { - type: "bi.vertical" + type: "bi.vertical", }, overscanColumnCount: 0, overscanRowCount: 0, - rowHeightGetter: BI.emptyFn, // number类型或function类型 - columnWidthGetter: BI.emptyFn, // number类型或function类型 + rowHeightGetter: emptyFn, // number类型或function类型 + columnWidthGetter: emptyFn, // number类型或function类型 // estimatedColumnSize: 100, //columnWidthGetter为function时必设 // estimatedRowSize: 30, //rowHeightGetter为function时必设 scrollLeft: 0, scrollTop: 0, items: [], - itemFormatter: (item, row, col) => { - return item; - }, + itemFormatter: (item, row, col) => item, }); } @@ -46,10 +45,10 @@ export default class GridView extends Widget { this.renderedKeys = []; this.renderRange = {}; this._scrollLock = false; - this._debounceRelease = BI.debounce(() => { + this._debounceRelease = debounce(() => { this._scrollLock = false; }, 1000 / 60); - this.container = BI._lazyCreateWidget({ + this.container = _lazyCreateWidget({ type: "bi.absolute", }); this.element.scroll(() => { @@ -65,7 +64,8 @@ export default class GridView extends Widget { }); }); // 兼容一下 - let scrollable = o.scrollable, scrollx = o.scrollx, scrolly = o.scrolly; + let scrollable = o.scrollable; + const scrollx = o.scrollx, scrolly = o.scrolly; if (overflowX === false) { if (overflowY === false) { scrollable = false; @@ -77,15 +77,15 @@ export default class GridView extends Widget { scrollable = "x"; } } - BI._lazyCreateWidget(el, { + _lazyCreateWidget(el, { type: "bi.vertical", element: this, - scrollable: scrollable, - scrolly: scrolly, - scrollx: scrollx, + scrollable, + scrolly, + scrollx, items: [this.container], }); - o.items = BI.isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + o.items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { this.populate(newValue); }) : o.items; if (o.items.length > 0) { @@ -104,27 +104,27 @@ export default class GridView extends Widget { } destroyed() { - BI.each(this.renderedCells, (i, cell) => { + each(this.renderedCells, (i, cell) => { cell.el._destroy(); - }) + }); } _calculateSizeAndPositionData() { const { columnCount, items, rowCount, columnWidthGetter, estimatedColumnSize, rowHeightGetter, estimatedRowSize } = this.options; this.rowCount = 0; this.columnCount = 0; - if (BI.isNumber(columnCount)) { + if (isNumber(columnCount)) { this.columnCount = columnCount; } else if (items.length > 0) { this.columnCount = items[0].length; } - if (BI.isNumber(rowCount)) { + if (isNumber(rowCount)) { this.rowCount = rowCount; } else { this.rowCount = items.length; } - this._columnSizeAndPositionManager = new BI.ScalingCellSizeAndPositionManager(this.columnCount, columnWidthGetter, estimatedColumnSize); - this._rowSizeAndPositionManager = new BI.ScalingCellSizeAndPositionManager(this.rowCount, rowHeightGetter, estimatedRowSize); + this._columnSizeAndPositionManager = new ScalingCellSizeAndPositionManager(this.columnCount, columnWidthGetter, estimatedColumnSize); + this._rowSizeAndPositionManager = new ScalingCellSizeAndPositionManager(this.rowCount, rowHeightGetter, estimatedRowSize); } _getOverscanIndices(cellCount, overscanCellsCount, startIndex, stopIndex) { @@ -139,8 +139,8 @@ export default class GridView extends Widget { const { itemFormatter, items } = this.options; - const width = o.width, height = o.height, scrollLeft = BI.clamp(o.scrollLeft, 0, this._getMaxScrollLeft()), - scrollTop = BI.clamp(o.scrollTop, 0, this._getMaxScrollTop()), + const width = o.width, height = o.height, scrollLeft = clamp(o.scrollLeft, 0, this._getMaxScrollLeft()), + scrollTop = clamp(o.scrollTop, 0, this._getMaxScrollTop()), overscanColumnCount = o.overscanColumnCount, overscanRowCount = o.overscanRowCount; if (height > 0 && width > 0) { @@ -150,7 +150,7 @@ export default class GridView extends Widget { const renderedCells = [], renderedKeys = {}, renderedWidgets = {}; let minX = this._getMaxScrollLeft(), minY = this._getMaxScrollTop(), maxX = 0, maxY = 0; // 没有可见的单元格就干掉所有渲染过的 - if (!BI.isEmpty(visibleColumnIndices) && !BI.isEmpty(visibleRowIndices)) { + if (!isEmpty(visibleColumnIndices) && !isEmpty(visibleRowIndices)) { const horizontalOffsetAdjustment = this._columnSizeAndPositionManager.getOffsetAdjustment(width, scrollLeft); const verticalOffsetAdjustment = this._rowSizeAndPositionManager.getOffsetAdjustment(height, scrollTop); @@ -187,7 +187,7 @@ export default class GridView extends Widget { const rowDatum = this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowIndex); for (let columnIndex = columnStartIndex; columnIndex <= columnStopIndex; columnIndex++) { - const key = rowIndex + "-" + columnIndex; + const key = `${rowIndex}-${columnIndex}`; const columnDatum = this._columnSizeAndPositionManager.getSizeAndPositionOfCell(columnIndex); const index = this.renderedKeys[key] && this.renderedKeys[key][2]; @@ -196,18 +196,18 @@ export default class GridView extends Widget { this.renderedCells[index].el.setWidth(columnDatum.size); this.renderedCells[index].el.setHeight(rowDatum.size); // 这里只使用px - this.renderedCells[index].el.element.css("left", columnDatum.offset + horizontalOffsetAdjustment + "px"); - this.renderedCells[index].el.element.css("top", rowDatum.offset + verticalOffsetAdjustment + "px"); + this.renderedCells[index].el.element.css("left", `${columnDatum.offset + horizontalOffsetAdjustment}px`); + this.renderedCells[index].el.element.css("top", `${rowDatum.offset + verticalOffsetAdjustment}px`); child = this.renderedCells[index].el; renderedCells.push(this.renderedCells[index]); } else { const item = itemFormatter(items[rowIndex][columnIndex], rowIndex, columnIndex); - child = BI._lazyCreateWidget(BI.extend({ + child = _lazyCreateWidget(extend({ type: "bi.label", width: columnDatum.size, height: rowDatum.size, }, item, { - cls: (item.cls || "") + " grid-cell" + (rowIndex === 0 ? " first-row" : "") + (columnIndex === 0 ? " first-col" : ""), + cls: `${item.cls || ""} grid-cell${rowIndex === 0 ? " first-row" : ""}${columnIndex === 0 ? " first-col" : ""}`, _rowIndex: rowIndex, _columnIndex: columnIndex, _left: columnDatum.offset + horizontalOffsetAdjustment, @@ -215,8 +215,8 @@ export default class GridView extends Widget { }), this); renderedCells.push({ el: child, - left: columnDatum.offset + horizontalOffsetAdjustment + "px", - top: rowDatum.offset + verticalOffsetAdjustment + "px", + left: `${columnDatum.offset + horizontalOffsetAdjustment}px`, + top: `${rowDatum.offset + verticalOffsetAdjustment}px`, _left: columnDatum.offset + horizontalOffsetAdjustment, _top: rowDatum.offset + verticalOffsetAdjustment, // _width: columnDatum.size, @@ -235,14 +235,14 @@ export default class GridView extends Widget { } // 已存在的, 需要添加的和需要删除的 const existSet = {}, addSet = {}, deleteArray = []; - BI.each(renderedKeys, (i, key) => { + each(renderedKeys, (i, key) => { if (this.renderedKeys[i]) { existSet[i] = key; } else { addSet[i] = key; } }); - BI.each(this.renderedKeys, (i, key) => { + each(this.renderedKeys, (i, key) => { if (existSet[i]) { return; } @@ -251,12 +251,12 @@ export default class GridView extends Widget { } deleteArray.push(key[2]); }); - BI.each(deleteArray, (i, index) => { + each(deleteArray, (i, index) => { // 性能优化,不调用destroy方法防止触发destroy事件 this.renderedCells[index].el._destroy(); }); const addedItems = []; - BI.each(addSet, (index, key) => { + each(addSet, (index, key) => { addedItems.push(renderedCells[key[2]]); }); // 与listview一样, 给上下文 @@ -266,12 +266,12 @@ export default class GridView extends Widget { this.container.attr("items", renderedCells); this.renderedCells = renderedCells; this.renderedKeys = renderedKeys; - this.renderRange = { minX: minX, minY: minY, maxX: maxX, maxY: maxY }; + this.renderRange = { minX, minY, maxX, maxY }; } } _isOverflowX() { - const { scrollable, scrollx, overflowX } = this.options; + const { scrollable, scrollx, overflowX } = this.options; // 兼容一下 if (overflowX === false) { return false; @@ -282,6 +282,7 @@ export default class GridView extends Widget { if (scrollable === true || scrollable === "xy" || scrollable === "x") { return true; } + return false; } @@ -298,6 +299,7 @@ export default class GridView extends Widget { if (scrollable === true || scrollable === "xy" || scrollable === "y") { return true; } + return false; } @@ -342,7 +344,7 @@ export default class GridView extends Widget { return; } this._scrollLock = true; - this.options.scrollLeft = BI.clamp(scrollLeft || 0, 0, this._getMaxScrollLeft()); + this.options.scrollLeft = clamp(scrollLeft || 0, 0, this._getMaxScrollLeft()); this._debounceRelease(); this.element.scrollLeft(this.options.scrollLeft); this._calculateChildrenToRender(); @@ -353,7 +355,7 @@ export default class GridView extends Widget { return; } this._scrollLock = true; - this.options.scrollTop = BI.clamp(scrollTop || 0, 0, this._getMaxScrollTop()); + this.options.scrollTop = clamp(scrollTop || 0, 0, this._getMaxScrollTop()); this._debounceRelease(); this.element.scrollTop(this.options.scrollTop); this._calculateChildrenToRender(); @@ -370,7 +372,7 @@ export default class GridView extends Widget { setOverflowX(b) { if (this.options.overflowX !== !!b) { this.options.overflowX = !!b; - BI.nextTick(() => { + nextTick(() => { this.element.css({ overflowX: b ? "auto" : "hidden" }); }); } @@ -379,7 +381,7 @@ export default class GridView extends Widget { setOverflowY(b) { if (this.options.overflowY !== !!b) { this.options.overflowY = !!b; - BI.nextTick(() => { + nextTick(() => { this.element.css({ overflowY: b ? "auto" : "hidden" }); }); } @@ -418,7 +420,7 @@ export default class GridView extends Widget { } restore() { - BI.each(this.renderedCells, (i, cell) => { + each(this.renderedCells, (i, cell) => { cell.el._destroy(); }); this._clearChildren(); diff --git a/src/base/index.js b/src/base/index.js index 1db6a6206..9188548ef 100644 --- a/src/base/index.js +++ b/src/base/index.js @@ -2,11 +2,13 @@ import { Pane } from "./1.pane"; import * as single from "./single"; import * as layer from "./layer"; import * as list from "./list"; -import GridView from "./grid/grid"; -import Pager from "./pager/pager"; +import { GridView } from "./grid/grid"; +import { Pager } from "./pager/pager"; import * as combination from "./combination"; import { Msg } from "./foundation/message"; import * as base from "./0.base"; +import { CollectionView } from "./collection/collection"; +import { CustomTree } from "./tree/customtree"; Object.assign(BI, { Pane, @@ -18,6 +20,8 @@ Object.assign(BI, { ...combination, Msg, ...base, + CollectionView, + CustomTree, }); export * from "./0.base"; @@ -30,4 +34,6 @@ export { GridView, Pager, Msg, -} \ No newline at end of file + CollectionView, + CustomTree +}; diff --git a/src/base/layer/index.js b/src/base/layer/index.js index 8f04625d9..3f2423948 100644 --- a/src/base/layer/index.js +++ b/src/base/layer/index.js @@ -1,4 +1,4 @@ export { Drawer } from "./layer.drawer"; export { Popover, BarPopover } from "./layer.popover"; export { PopupView } from "./layer.popup"; -export { SearcherView } from "./layer.searcher"; \ No newline at end of file +export { SearcherView } from "./layer.searcher"; diff --git a/src/base/layer/layer.drawer.js b/src/base/layer/layer.drawer.js index 75ef6b04b..b8e6bf2b7 100644 --- a/src/base/layer/layer.drawer.js +++ b/src/base/layer/layer.drawer.js @@ -4,13 +4,13 @@ * @extends BI.Widget */ -import { Widget, shortcut } from "../../core"; +import { Widget, shortcut, isPlainObject, extend } from "../../core"; @shortcut() export class Drawer extends Widget { SIZE = { - SMALL: "small", - NORMAL: "normal", - BIG: "big", + SMALL: "small", + NORMAL: "normal", + BIG: "big", } props = { baseCls: "bi-drawer bi-card", @@ -28,202 +28,202 @@ export class Drawer extends Widget { static EVENT_CLOSE = "EVENT_CLOSE"; static EVENT_OPEN = "EVENT_OPEN"; _getSuitableSize() { - const { size, height, placement, width } = this.options; - let sizeValue = 0; - switch (size) { - case "big": + const { size, height, placement, width } = this.options; + let sizeValue = 0; + switch (size) { + case "big": sizeValue = 736; - break; - case "small": + break; + case "small": sizeValue = 200; - break; - case "normal": - default: + break; + case "normal": + default: sizeValue = 378; - break; - } - if (placement === "top" || placement === "bottom") { - return { - height: height || sizeValue, - }; - } - if (placement === "left" || placement === "right") { - return { - width: width || sizeValue, - }; - } + break; + } + if (placement === "top" || placement === "bottom") { + return { + height: height || sizeValue, + }; + } + if (placement === "left" || placement === "right") { + return { + width: width || sizeValue, + }; + } } render() { - const { header, headerHeight, closable, body, bodyHgap, bodyTgap, bodyBgap } = this.options; - const items = [{ - el: { - type: "bi.htape", - cls: "bi-message-title bi-header-background", - items: [{ - type: "bi.absolute", - items: [{ - el: BI.isPlainObject(header) ? BI.extend({}, header, { - extraCls: "bi-font-bold", - }) : { - type: "bi.label", - cls: "bi-font-bold", - height: headerHeight, - text: header, - title: header, - textAlign: "left", - }, - left: 20, - top: 0, - right: 0, - bottom: 0, - }], - }, { - el: closable ? { - type: "bi.icon_button", - cls: "bi-message-close close-font", - height: headerHeight, - handler: () => { - this.close(); - }, - } : { - type: "bi.layout", - }, - width: 56, - }], - height: headerHeight, - }, - height: headerHeight, - }, { - el: { - type: "bi.vertical", - scrolly: true, - cls: "drawer-body", - ref: (_ref) => { - this.body = _ref; - }, - items: [{ - el: body, - }], - }, - hgap: bodyHgap, - tgap: bodyTgap, - bgap: bodyBgap, - }]; + const { header, headerHeight, closable, body, bodyHgap, bodyTgap, bodyBgap } = this.options; + const items = [{ + el: { + type: "bi.htape", + cls: "bi-message-title bi-header-background", + items: [{ + type: "bi.absolute", + items: [{ + el: isPlainObject(header) ? extend({}, header, { + extraCls: "bi-font-bold", + }) : { + type: "bi.label", + cls: "bi-font-bold", + height: headerHeight, + text: header, + title: header, + textAlign: "left", + }, + left: 20, + top: 0, + right: 0, + bottom: 0, + }], + }, { + el: closable ? { + type: "bi.icon_button", + cls: "bi-message-close close-font", + height: headerHeight, + handler: () => { + this.close(); + }, + } : { + type: "bi.layout", + }, + width: 56, + }], + height: headerHeight, + }, + height: headerHeight, + }, { + el: { + type: "bi.vertical", + scrolly: true, + cls: "drawer-body", + ref: _ref => { + this.body = _ref; + }, + items: [{ + el: body, + }], + }, + hgap: bodyHgap, + tgap: bodyTgap, + bgap: bodyBgap, + }]; - return BI.extend({ - type: "bi.vtape", - items: items, - }, this._getSuitableSize()); + return extend({ + type: "bi.vtape", + items, + }, this._getSuitableSize()); } mounted() { - const { placement } = this.options; - switch (placement) { - case "right": - this.element.css({ - top: 0, - left: "100%", - bottom: 0, - }); - break; - case "left": - this.element.css({ - top: 0, - right: "100%", - bottom: 0, - }); - break; - case "top": - this.element.css({ - left: 0, - right: 0, - bottom: "100%", - }); - break; - case "bottom": - this.element.css({ - left: 0, - right: 0, - top: "100%", - }); - break; - default: - break; - } + const { placement } = this.options; + switch (placement) { + case "right": + this.element.css({ + top: 0, + left: "100%", + bottom: 0, + }); + break; + case "left": + this.element.css({ + top: 0, + right: "100%", + bottom: 0, + }); + break; + case "top": + this.element.css({ + left: 0, + right: 0, + bottom: "100%", + }); + break; + case "bottom": + this.element.css({ + left: 0, + right: 0, + top: "100%", + }); + break; + default: + break; + } } show(callback) { - const { placement } = this.options; - requestAnimationFrame(() => { - const size = this._getSuitableSize(); - switch (placement) { - case "right": - this.element.css({ - left: "calc(100% - " + size.width + "px)", - }); - break; - case "left": - this.element.css({ - right: "calc(100% - " + size.width + "px)", - }); - break; - case "top": - this.element.css({ - bottom: "calc(100% - " + size.height + "px)", - }); - break; - case "bottom": - this.element.css({ - top: "calc(100% - " + size.height + "px)", - }); - break; - default: - break; - } - callback && callback(); - }); + const { placement } = this.options; + requestAnimationFrame(() => { + const size = this._getSuitableSize(); + switch (placement) { + case "right": + this.element.css({ + left: `calc(100% - ${size.width}px)`, + }); + break; + case "left": + this.element.css({ + right: `calc(100% - ${size.width}px)`, + }); + break; + case "top": + this.element.css({ + bottom: `calc(100% - ${size.height}px)`, + }); + break; + case "bottom": + this.element.css({ + top: `calc(100% - ${size.height}px)`, + }); + break; + default: + break; + } + callback && callback(); + }); } hide(callback) { - const { placement } = this.options; - requestAnimationFrame(() => { - switch (placement) { - case "right": - this.element.css({ - left: "100%", - }); - break; - case "left": - this.element.css({ - right: "100%", - }); - break; - case "top": - this.element.css({ - bottom: "100%", - }); - break; - case "bottom": - this.element.css({ - top: "100%", - }); - break; - default: - break; - } - setTimeout(callback, 300); - }); + const { placement } = this.options; + requestAnimationFrame(() => { + switch (placement) { + case "right": + this.element.css({ + left: "100%", + }); + break; + case "left": + this.element.css({ + right: "100%", + }); + break; + case "top": + this.element.css({ + bottom: "100%", + }); + break; + case "bottom": + this.element.css({ + top: "100%", + }); + break; + default: + break; + } + setTimeout(callback, 300); + }); } open() { - this.show(() => { - this.fireEvent(Drawer.EVENT_OPEN); - }); + this.show(() => { + this.fireEvent(Drawer.EVENT_OPEN); + }); } close() { - this.hide(() => { - this.fireEvent(Drawer.EVENT_CLOSE); - }); + this.hide(() => { + this.fireEvent(Drawer.EVENT_CLOSE); + }); } setZindex(zindex) { @@ -232,6 +232,5 @@ export class Drawer extends Widget { destroyed() { } - } diff --git a/src/base/layer/layer.popover.js b/src/base/layer/layer.popover.js index cd91db05e..5462b227f 100644 --- a/src/base/layer/layer.popover.js +++ b/src/base/layer/layer.popover.js @@ -4,7 +4,7 @@ * @extends BI.Widget */ -import { Widget, shortcut } from "../../core"; +import { Widget, shortcut, clamp, isPlainObject, extend, isNotNull } from "../../core"; @shortcut() export class Popover extends Widget { _constant = { @@ -41,182 +41,182 @@ export class Popover extends Widget { static EVENT_CONFIRM = "EVENT_CONFIRM"; render() { - // var self = this; - const { header, headerHeight, closable, logic, footer, footerHeight, body, bodyTgap, bodyHgap } = this.options; - const c = this._constant; - this.startX = 0; - this.startY = 0; - const size = this._calculateSize(); - this.tracker = new BI.MouseMoveTracker((deltaX, deltaY) => { - const W = BI.Widget._renderEngine.createElement("body").width(); - const H = BI.Widget._renderEngine.createElement("body").height(); - this.startX += deltaX; - this.startY += deltaY; - this.element.css({ - left: BI.clamp(this.startX, 0, W - this.element.width()) + "px", - top: BI.clamp(this.startY, 0, H - this.element.height()) + "px", - }); - // BI-12134 没有什么特别好的方法 - BI.Resizers._resize({ - target: this.element[0], - }); - }, () => { - this.tracker.releaseMouseMoves(); - }, _global); - const items = [{ - el: { - type: "bi.htape", - cls: "bi-message-title bi-header-background", - items: [{ - el: { - type: "bi.absolute", - ref: (_ref) => { - this.dragger = _ref; - }, - items: [{ - el: BI.isPlainObject(header) ? BI.extend({}, header, { - extraCls: "bi-font-bold", - }) : { - type: "bi.label", - cls: "bi-font-bold", - height: headerHeight, - text: header, - title: header, - textAlign: "left", - }, - top: 0, - bottom: 0, - left: BI.SIZE_CONSANTS.H_GAP_SIZE, - right: closable ? 0 : BI.SIZE_CONSANTS.H_GAP_SIZE, - }], - }, - }, closable ? { - el: { - type: "bi.icon_button", - cls: "bi-message-close close-font", - height: headerHeight, - handler: () => { - this.close(); - }, - }, - width: 56, - } : null], - height: headerHeight, - }, - height: headerHeight, - }, logic.dynamic ? { - el: { - type: "bi.vertical", - scrolly: true, - cls: "popover-body", - ref: (_ref) => { - this.body = _ref; - }, - css: { - "max-height": this._getSuitableBodyHeight(c.MAX_HEIGHT - headerHeight - (footer ? footerHeight : 0) - bodyTgap), - "min-height": this._getSuitableBodyHeight(size.height - headerHeight - (footer ? footerHeight : 0) - bodyTgap), - }, - items: [{ - el: body, - }], - hgap: bodyHgap, - tgap: bodyTgap, - }, - } : { - el: { - type: "bi.absolute", - items: [{ - el: body, - left: bodyHgap, - top: bodyTgap, - right: bodyHgap, - bottom: 0, - }], - }, - }]; - if (footer) { - items.push({ - el: { - type: "bi.absolute", - items: [{ - el: footer, - left: BI.SIZE_CONSANTS.H_GAP_SIZE, - top: 0, - right: BI.SIZE_CONSANTS.H_GAP_SIZE, - bottom: 0, - }], - height: footerHeight, - }, - height: footerHeight, - }); - } + // var self = this; + const { header, headerHeight, closable, logic, footer, footerHeight, body, bodyTgap, bodyHgap } = this.options; + const c = this._constant; + this.startX = 0; + this.startY = 0; + const size = this._calculateSize(); + this.tracker = new BI.MouseMoveTracker((deltaX, deltaY) => { + const W = Widget._renderEngine.createElement("body").width(); + const H = Widget._renderEngine.createElement("body").height(); + this.startX += deltaX; + this.startY += deltaY; + this.element.css({ + left: `${clamp(this.startX, 0, W - this.element.width())}px`, + top: `${clamp(this.startY, 0, H - this.element.height())}px`, + }); + // BI-12134 没有什么特别好的方法 + BI.Resizers._resize({ + target: this.element[0], + }); + }, () => { + this.tracker.releaseMouseMoves(); + }, _global); + const items = [{ + el: { + type: "bi.htape", + cls: "bi-message-title bi-header-background", + items: [{ + el: { + type: "bi.absolute", + ref: _ref => { + this.dragger = _ref; + }, + items: [{ + el: isPlainObject(header) ? extend({}, header, { + extraCls: "bi-font-bold", + }) : { + type: "bi.label", + cls: "bi-font-bold", + height: headerHeight, + text: header, + title: header, + textAlign: "left", + }, + top: 0, + bottom: 0, + left: BI.SIZE_CONSANTS.H_GAP_SIZE, + right: closable ? 0 : BI.SIZE_CONSANTS.H_GAP_SIZE, + }], + }, + }, closable ? { + el: { + type: "bi.icon_button", + cls: "bi-message-close close-font", + height: headerHeight, + handler: () => { + this.close(); + }, + }, + width: 56, + } : null], + height: headerHeight, + }, + height: headerHeight, + }, logic.dynamic ? { + el: { + type: "bi.vertical", + scrolly: true, + cls: "popover-body", + ref: _ref => { + this.body = _ref; + }, + css: { + "max-height": this._getSuitableBodyHeight(c.MAX_HEIGHT - headerHeight - (footer ? footerHeight : 0) - bodyTgap), + "min-height": this._getSuitableBodyHeight(size.height - headerHeight - (footer ? footerHeight : 0) - bodyTgap), + }, + items: [{ + el: body, + }], + hgap: bodyHgap, + tgap: bodyTgap, + }, + } : { + el: { + type: "bi.absolute", + items: [{ + el: body, + left: bodyHgap, + top: bodyTgap, + right: bodyHgap, + bottom: 0, + }], + }, + }]; + if (footer) { + items.push({ + el: { + type: "bi.absolute", + items: [{ + el: footer, + left: BI.SIZE_CONSANTS.H_GAP_SIZE, + top: 0, + right: BI.SIZE_CONSANTS.H_GAP_SIZE, + bottom: 0, + }], + height: footerHeight, + }, + height: footerHeight, + }); + } - return BI.extend({ - items: items, - width: this._getSuitableWidth(size.width), - }, logic.dynamic ? { - type: "bi.vertical", - scrolly: false, - } : { - type: "bi.vtape", - height: this._getSuitableHeight(size.height), - }); + return extend({ + items, + width: this._getSuitableWidth(size.width), + }, logic.dynamic ? { + type: "bi.vertical", + scrolly: false, + } : { + type: "bi.vtape", + height: this._getSuitableHeight(size.height), + }); } - // mounted之后绑定事件 + // mounted之后绑定事件 mounted() { - this.dragger.element.mousedown((e) => { - if (this.options.draggable !== false) { - this.startX = this.element[0].offsetLeft; - this.startY = this.element[0].offsetTop; - this.tracker.captureMouseMoves(e); - } - }); + this.dragger.element.mousedown(e => { + if (this.options.draggable !== false) { + this.startX = this.element[0].offsetLeft; + this.startY = this.element[0].offsetTop; + this.tracker.captureMouseMoves(e); + } + }); } _getSuitableBodyHeight(height) { const { headerHeight, footer, footerHeight, bodyTgap } = this.options; - return BI.clamp(height, 0, BI.Widget._renderEngine.createElement("body")[0].clientHeight - headerHeight - (footer ? footerHeight : 0) - bodyTgap); + return clamp(height, 0, Widget._renderEngine.createElement("body")[0].clientHeight - headerHeight - (footer ? footerHeight : 0) - bodyTgap); } _getSuitableHeight(height) { - return BI.clamp(height, 0, BI.Widget._renderEngine.createElement("body")[0].clientHeight); + return clamp(height, 0, Widget._renderEngine.createElement("body")[0].clientHeight); } _getSuitableWidth(width) { - return BI.clamp(width, 0, BI.Widget._renderEngine.createElement("body").width()); + return clamp(width, 0, Widget._renderEngine.createElement("body").width()); } _calculateSize() { - const { size, width, height } = this.options; - const sizeValue = {}; - if (BI.isNotNull(size)) { - switch (size) { - case this._constant.SIZE.SMALL: + const { size, width, height } = this.options; + const sizeValue = {}; + if (isNotNull(size)) { + switch (size) { + case this._constant.SIZE.SMALL: sizeValue.width = 450; sizeValue.height = 200; sizeValue.type = "small"; - break; - case this._constant.SIZE.BIG: + break; + case this._constant.SIZE.BIG: sizeValue.width = 900; sizeValue.height = 500; sizeValue.type = "big"; - break; - default: + break; + default: sizeValue.width = 550; sizeValue.height = 500; sizeValue.type = "default"; - } - } + } + } - return { - width: width || sizeValue.width, - height: height || sizeValue.height, - type: sizeValue.type || "default", - }; + return { + width: width || sizeValue.width, + height: height || sizeValue.height, + type: sizeValue.type || "default", + }; } setDraggable(b) { - this.options.draggable = b; + this.options.draggable = b; } hide() { @@ -224,13 +224,13 @@ export class Popover extends Widget { } open() { - this.show(); - this.fireEvent(Popover.EVENT_OPEN, arguments); + this.show(); + this.fireEvent(Popover.EVENT_OPEN, arguments); } close() { - this.hide(); - this.fireEvent(Popover.EVENT_CLOSE, arguments); + this.hide(); + this.fireEvent(Popover.EVENT_CLOSE, arguments); } setZindex(zindex) { @@ -243,36 +243,36 @@ export class BarPopover extends Popover { static xtype = "bi.bar_popover"; _defaultConfig() { - return BI.extend(super._defaultConfig(arguments), { - btns: [BI.i18nText("BI-Basic_OK"), BI.i18nText("BI-Basic_Cancel")], - }); + return extend(super._defaultConfig(arguments), { + btns: [BI.i18nText("BI-Basic_OK"), BI.i18nText("BI-Basic_Cancel")], + }); } beforeCreate() { - const { footer, warningTitle } = this.options; - footer || (this.options.footer = { - type: "bi.right_vertical_adapt", - lgap: 10, - items: [{ - type: "bi.button", - text: this.options.btns[1], - value: 1, - level: "ignore", - handler: (v) => { - this.fireEvent(Popover.EVENT_CANCEL, v); - this.close(v); - }, - }, { - type: "bi.button", - text: this.options.btns[0], - warningTitle: warningTitle, - value: 0, - handler: (v) => { - this.fireEvent(Popover.EVENT_CONFIRM, v); - this.close(v); - }, - }], - }); + const { footer, warningTitle } = this.options; + footer || (this.options.footer = { + type: "bi.right_vertical_adapt", + lgap: 10, + items: [{ + type: "bi.button", + text: this.options.btns[1], + value: 1, + level: "ignore", + handler: v => { + this.fireEvent(Popover.EVENT_CANCEL, v); + this.close(v); + }, + }, { + type: "bi.button", + text: this.options.btns[0], + warningTitle, + value: 0, + handler: v => { + this.fireEvent(Popover.EVENT_CONFIRM, v); + this.close(v); + }, + }], + }); } } diff --git a/src/base/layer/layer.popup.js b/src/base/layer/layer.popup.js index fd79d015f..359ab2df0 100644 --- a/src/base/layer/layer.popup.js +++ b/src/base/layer/layer.popup.js @@ -4,19 +4,19 @@ * @extends BI.Widget */ -import { Widget, shortcut } from "../../core"; +import { Widget, shortcut, extend, Controller, createWidget, createItems, clamp } from "../../core"; @shortcut() export class PopupView extends Widget { _const = { - TRIANGLE_LENGTH: 12, + TRIANGLE_LENGTH: 12, } static xtype = "bi.popup_view"; static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig(props) { - return BI.extend(super._defaultConfig(arguments), { - _baseCls: "bi-popup-view" + (props.primary ? " bi-primary" : ""), + return extend(super._defaultConfig(arguments), { + _baseCls: `bi-popup-view${props.primary ? " bi-primary" : ""}`, // 品牌色 primary: false, maxWidth: "auto", @@ -55,100 +55,100 @@ export class PopupView extends Widget { }); } render() { - const { minWidth, maxWidth, stopPropagation, stopEvent, - direction, logic, lgap, rgap, tgap, bgap, vgap, hgap, primary, showArrow } = this.options; - function fn (e) { - e.stopPropagation(); - } - function stop (e) { - e.stopEvent(); + const { minWidth, maxWidth, stopPropagation, stopEvent, + direction, logic, lgap, rgap, tgap, bgap, vgap, hgap, primary, showArrow } = this.options; + function fn (e) { + e.stopPropagation(); + } + function stop (e) { + e.stopEvent(); - return false; - } - this.element.css({ - "z-index": BI.zIndex_popup, - "min-width": BI.pixFormat(minWidth), - "max-width": BI.pixFormat(maxWidth), - }).bind({ click: fn }); + return false; + } + this.element.css({ + "z-index": BI.zIndex_popup, + "min-width": BI.pixFormat(minWidth), + "max-width": BI.pixFormat(maxWidth), + }).bind({ click: fn }); - this.element.bind("mousewheel", fn); + this.element.bind("mousewheel", fn); - stopPropagation && this.element.bind({ mousedown: fn, mouseup: fn, mouseover: fn }); - stopEvent && this.element.bind({ mousedown: stop, mouseup: stop, mouseover: stop }); - this.tool = this._createTool(); - this.tab = this._createTab(); - this.view = this._createView(); - this.toolbar = this._createToolBar(); + stopPropagation && this.element.bind({ mousedown: fn, mouseup: fn, mouseover: fn }); + stopEvent && this.element.bind({ mousedown: stop, mouseup: stop, mouseover: stop }); + this.tool = this._createTool(); + this.tab = this._createTab(); + this.view = this._createView(); + this.toolbar = this._createToolBar(); - this.view.on(BI.Controller.EVENT_CHANGE, (type, ...args) => { - this.fireEvent.apply(this, [BI.Controller.EVENT_CHANGE, type, ...args]); - if (type === BI.Events.CLICK) { - this.fireEvent(PopupView.EVENT_CHANGE); - } - }); + this.view.on(Controller.EVENT_CHANGE, (type, ...args) => { + this.fireEvent(Controller.EVENT_CHANGE, type, ...args); + if (type === BI.Events.CLICK) { + this.fireEvent(PopupView.EVENT_CHANGE); + } + }); - BI.createWidget(BI.extend({ - element: this, - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(direction), BI.extend({}, logic, { - scrolly: false, - lgap, - rgap, - tgap, - bgap, - vgap, - hgap, - items: BI.LogicFactory.createLogicItemsByDirection(direction, BI.extend({ - cls: "list-view-outer bi-card list-view-shadow" + (primary ? " bi-primary" : ""), - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(direction), BI.extend({}, logic, { - items: BI.LogicFactory.createLogicItemsByDirection(direction, this.tool, this.tab, this.view, this.toolbar), - }))) - ), - })))); - if (showArrow) { - this.arrow = BI.createWidget({ - type: "bi.absolute", - cls: "bi-bubble-arrow", - items: [{ - type: "bi.layout", - cls: "bubble-arrow", - }], - }); - this.arrowWrapper = BI.createWidget({ - type: "bi.absolute", - cls: "bi-bubble-arrow-wrapper", - items: [{ - el: this.arrow, - }], - }); - // 因为三角符号的原因位置变大了,需要占位 - this.placeholder = BI.createWidget({ - type: "bi.layout", - }); - BI.createWidget({ - type: "bi.absolute", - element: this, - items: [{ - el: this.arrowWrapper, - left: 0, - top: 0, - }, { - el: this.placeholder, - }], - }); - } + createWidget(extend({ + element: this, + }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(direction), extend({}, logic, { + scrolly: false, + lgap, + rgap, + tgap, + bgap, + vgap, + hgap, + items: BI.LogicFactory.createLogicItemsByDirection(direction, extend({ + cls: `list-view-outer bi-card list-view-shadow${primary ? " bi-primary" : ""}`, + }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(direction), extend({}, logic, { + items: BI.LogicFactory.createLogicItemsByDirection(direction, this.tool, this.tab, this.view, this.toolbar), + }))) + ), + })))); + if (showArrow) { + this.arrow = createWidget({ + type: "bi.absolute", + cls: "bi-bubble-arrow", + items: [{ + type: "bi.layout", + cls: "bubble-arrow", + }], + }); + this.arrowWrapper = createWidget({ + type: "bi.absolute", + cls: "bi-bubble-arrow-wrapper", + items: [{ + el: this.arrow, + }], + }); + // 因为三角符号的原因位置变大了,需要占位 + this.placeholder = createWidget({ + type: "bi.layout", + }); + createWidget({ + type: "bi.absolute", + element: this, + items: [{ + el: this.arrowWrapper, + left: 0, + top: 0, + }, { + el: this.placeholder, + }], + }); + } } _createView() { - const { el, value, minHeight, innerVgap, innerHgap } = this.options; - this.button_group = BI.createWidget(el, { type: "bi.button_group", value: value }); - this.button_group.element.css({ - "min-height": BI.pixFormat(minHeight), - "padding-top": BI.pixFormat(innerVgap), - "padding-bottom": BI.pixFormat(innerVgap), - "padding-left": BI.pixFormat(innerHgap), - "padding-right": BI.pixFormat(innerHgap), - }); + const { el, value, minHeight, innerVgap, innerHgap } = this.options; + this.button_group = createWidget(el, { type: "bi.button_group", value }); + this.button_group.element.css({ + "min-height": BI.pixFormat(minHeight), + "padding-top": BI.pixFormat(innerVgap), + "padding-bottom": BI.pixFormat(innerVgap), + "padding-left": BI.pixFormat(innerHgap), + "padding-right": BI.pixFormat(innerHgap), + }); - return this.button_group; + return this.button_group; } _createTool() { @@ -157,7 +157,7 @@ export class PopupView extends Widget { return; } - return BI.createWidget(tool); + return createWidget(tool); } _createTab() { @@ -166,268 +166,267 @@ export class PopupView extends Widget { return; } - return BI.createWidget({ + return createWidget({ type: "bi.center", cls: "list-view-tab", height: 25, items: tabs, - value: value, + value, }); } _createToolBar() { - const { buttons } = this.options; - if (buttons.length === 0) { - return; - } + const { buttons } = this.options; + if (buttons.length === 0) { + return; + } - return BI.createWidget({ - type: "bi.center", - cls: "list-view-toolbar bi-high-light bi-split-top", - height: 24, - items: BI.createItems(buttons, { - once: false, - shadow: true, - isShadowShowingOnSelected: true, - }), - }); + return createWidget({ + type: "bi.center", + cls: "list-view-toolbar bi-high-light bi-split-top", + height: 24, + items: createItems(buttons, { + once: false, + shadow: true, + isShadowShowingOnSelected: true, + }), + }); } setDirection(direction, position) { - const { showArrow, tgap, vgap, bgap, rgap, hgap, lgap } = this.options; - if (showArrow) { - let style = {}, wrapperStyle = {}, placeholderStyle = {}; - const adjustXOffset = position.adjustXOffset || 0; - const adjustYOffset = position.adjustYOffset || 0; - const bodyBounds = BI.Widget._renderEngine.createElement("body").bounds(); - const bodyWidth = bodyBounds.width; - const bodyHeight = bodyBounds.height; - const popupWidth = this.element.outerWidth(); - const popupHeight = this.element.outerHeight(); - const offset = position.offset; - const offsetStyle = position.offsetStyle; - const middle = offsetStyle === "center" || offsetStyle === "middle"; + const { showArrow, tgap, vgap, bgap, rgap, hgap, lgap } = this.options; + if (showArrow) { + let style = {}, wrapperStyle = {}, placeholderStyle = {}; + const adjustXOffset = position.adjustXOffset || 0; + const adjustYOffset = position.adjustYOffset || 0; + const bodyBounds = Widget._renderEngine.createElement("body").bounds(); + const bodyWidth = bodyBounds.width; + const bodyHeight = bodyBounds.height; + const popupWidth = this.element.outerWidth(); + const popupHeight = this.element.outerHeight(); + const offset = position.offset; + const offsetStyle = position.offsetStyle; + const middle = offsetStyle === "center" || offsetStyle === "middle"; - const minLeft = Math.max(4, offset.left + 4 + popupWidth - bodyWidth); - const minRight = Math.max(4, popupWidth - (offset.left + 4)); - const minTop = Math.max(4, offset.top + 4 + popupHeight - bodyHeight); - const minBottom = Math.max(4, popupHeight - (offset.top + 4)); + const minLeft = Math.max(4, offset.left + 4 + popupWidth - bodyWidth); + const minRight = Math.max(4, popupWidth - (offset.left + 4)); + const minTop = Math.max(4, offset.top + 4 + popupHeight - bodyHeight); + const minBottom = Math.max(4, popupHeight - (offset.top + 4)); - const maxLeft = Math.min(popupWidth - 16 - 4, offset.left + position.width - 16 - 4); - const maxRight = Math.min(popupWidth - 16 - 4, bodyWidth - (offset.left + position.width - 16 - 4)); - const maxTop = Math.min(popupHeight - 16 - 4, offset.top + position.height - 16 - 4); - const maxBottom = Math.min(popupHeight - 16 - 4, bodyHeight - (offset.top + position.height - 16 - 4)); - switch (direction) { - case "bottom": - case "bottom,right": - direction = "bottom"; - style = { - // 5表示留出一定的空间 - left: BI.clamp(((middle ? popupWidth : position.width) - adjustXOffset) / 2 - 8, minLeft, maxLeft), - }; - wrapperStyle = { - top: tgap + vgap, - left: 0, - right: "", - bottom: "", - }; - placeholderStyle = { - left: 0, - right: 0, - height: this._const.TRIANGLE_LENGTH, - top: -this._const.TRIANGLE_LENGTH, - bottom: "", - }; - break; - case "bottom,left": - direction = "bottom"; - style = { - right: BI.clamp(((middle ? popupWidth : position.width) + adjustXOffset) / 2 - 8, minRight, maxRight), - }; - wrapperStyle = { - top: bgap + vgap, - left: "", - right: 0, - bottom: "", - }; - placeholderStyle = { - left: 0, - right: 0, - height: this._const.TRIANGLE_LENGTH, - top: -this._const.TRIANGLE_LENGTH, - bottom: "", - }; - break; - case "top": - case "top,right": - direction = "top"; - style = { - left: BI.clamp(((middle ? popupWidth : position.width) - adjustXOffset) / 2 - 8, minLeft, maxLeft), - }; - wrapperStyle = { - bottom: bgap + vgap, - left: 0, - right: "", - top: "", - }; - placeholderStyle = { - left: 0, - right: 0, - height: this._const.TRIANGLE_LENGTH, - top: "", - bottom: -this._const.TRIANGLE_LENGTH, - }; - break; - case "top,left": - direction = "top"; - style = { - right: BI.clamp(((middle ? popupWidth : position.width) + adjustXOffset) / 2 - 8, minRight, maxRight), - }; - wrapperStyle = { - bottom: bgap + vgap, - right: 0, - left: "", - top: "", - }; - placeholderStyle = { - left: 0, - right: 0, - height: this._const.TRIANGLE_LENGTH, - top: "", - bottom: -this._const.TRIANGLE_LENGTH, - }; - break; - case "left": - case "left,bottom": - direction = "left"; - style = { - top: BI.clamp(((middle ? popupHeight : position.height) - adjustYOffset) / 2 - 8, minTop, maxTop), - }; - wrapperStyle = { - right: rgap + hgap, - top: 0, - bottom: "", - left: "", - }; - placeholderStyle = { - top: 0, - bottom: 0, - width: this._const.TRIANGLE_LENGTH, - right: -this._const.TRIANGLE_LENGTH, - left: "", - }; - break; - case "left,top": - direction = "left"; - style = { - bottom: BI.clamp(((middle ? popupHeight : position.height) + adjustYOffset) / 2 - 8, minBottom, maxBottom), - }; - wrapperStyle = { - right: rgap + hgap, - bottom: 0, - top: "", - left: "", - }; - placeholderStyle = { - top: 0, - bottom: 0, - width: this._const.TRIANGLE_LENGTH, - right: -this._const.TRIANGLE_LENGTH, - left: "", - }; - break; - case "right": - case "right,bottom": - direction = "right"; - style = { - top: BI.clamp(((middle ? popupHeight : position.height) - adjustYOffset) / 2 - 8, minTop, maxTop), - }; - wrapperStyle = { - left: lgap + hgap, - top: 0, - bottom: "", - right: "", - }; - placeholderStyle = { - top: 0, - bottom: 0, - width: this._const.TRIANGLE_LENGTH, - left: -this._const.TRIANGLE_LENGTH, - right: "", - }; - break; - case "right,top": - direction = "right"; - style = { - bottom: BI.clamp(((middle ? popupHeight : position.height) + adjustYOffset) / 2 - 8, minBottom, maxBottom), - }; - wrapperStyle = { - left: lgap + hgap, - bottom: 0, - top: "", - right: "", - }; - placeholderStyle = { - top: 0, - bottom: 0, - width: this._const.TRIANGLE_LENGTH, - left: -this._const.TRIANGLE_LENGTH, - right: "", - }; - break; - case "right,innerRight": - break; - case "right,innerLeft": - break; - case "innerRight": - break; - case "innerLeft": - break; - default: - break; - } - this.element - .removeClass("left") - .removeClass("right") - .removeClass("top") - .removeClass("bottom") - .addClass(direction); - this.arrow.element.css(style); - this.arrowWrapper.element.css(wrapperStyle); - this.placeholder.element.css(placeholderStyle); - } + const maxLeft = Math.min(popupWidth - 16 - 4, offset.left + position.width - 16 - 4); + const maxRight = Math.min(popupWidth - 16 - 4, bodyWidth - (offset.left + position.width - 16 - 4)); + const maxTop = Math.min(popupHeight - 16 - 4, offset.top + position.height - 16 - 4); + const maxBottom = Math.min(popupHeight - 16 - 4, bodyHeight - (offset.top + position.height - 16 - 4)); + switch (direction) { + case "bottom": + case "bottom,right": + direction = "bottom"; + style = { + // 5表示留出一定的空间 + left: clamp(((middle ? popupWidth : position.width) - adjustXOffset) / 2 - 8, minLeft, maxLeft), + }; + wrapperStyle = { + top: tgap + vgap, + left: 0, + right: "", + bottom: "", + }; + placeholderStyle = { + left: 0, + right: 0, + height: this._const.TRIANGLE_LENGTH, + top: -this._const.TRIANGLE_LENGTH, + bottom: "", + }; + break; + case "bottom,left": + direction = "bottom"; + style = { + right: clamp(((middle ? popupWidth : position.width) + adjustXOffset) / 2 - 8, minRight, maxRight), + }; + wrapperStyle = { + top: bgap + vgap, + left: "", + right: 0, + bottom: "", + }; + placeholderStyle = { + left: 0, + right: 0, + height: this._const.TRIANGLE_LENGTH, + top: -this._const.TRIANGLE_LENGTH, + bottom: "", + }; + break; + case "top": + case "top,right": + direction = "top"; + style = { + left: clamp(((middle ? popupWidth : position.width) - adjustXOffset) / 2 - 8, minLeft, maxLeft), + }; + wrapperStyle = { + bottom: bgap + vgap, + left: 0, + right: "", + top: "", + }; + placeholderStyle = { + left: 0, + right: 0, + height: this._const.TRIANGLE_LENGTH, + top: "", + bottom: -this._const.TRIANGLE_LENGTH, + }; + break; + case "top,left": + direction = "top"; + style = { + right: clamp(((middle ? popupWidth : position.width) + adjustXOffset) / 2 - 8, minRight, maxRight), + }; + wrapperStyle = { + bottom: bgap + vgap, + right: 0, + left: "", + top: "", + }; + placeholderStyle = { + left: 0, + right: 0, + height: this._const.TRIANGLE_LENGTH, + top: "", + bottom: -this._const.TRIANGLE_LENGTH, + }; + break; + case "left": + case "left,bottom": + direction = "left"; + style = { + top: clamp(((middle ? popupHeight : position.height) - adjustYOffset) / 2 - 8, minTop, maxTop), + }; + wrapperStyle = { + right: rgap + hgap, + top: 0, + bottom: "", + left: "", + }; + placeholderStyle = { + top: 0, + bottom: 0, + width: this._const.TRIANGLE_LENGTH, + right: -this._const.TRIANGLE_LENGTH, + left: "", + }; + break; + case "left,top": + direction = "left"; + style = { + bottom: clamp(((middle ? popupHeight : position.height) + adjustYOffset) / 2 - 8, minBottom, maxBottom), + }; + wrapperStyle = { + right: rgap + hgap, + bottom: 0, + top: "", + left: "", + }; + placeholderStyle = { + top: 0, + bottom: 0, + width: this._const.TRIANGLE_LENGTH, + right: -this._const.TRIANGLE_LENGTH, + left: "", + }; + break; + case "right": + case "right,bottom": + direction = "right"; + style = { + top: clamp(((middle ? popupHeight : position.height) - adjustYOffset) / 2 - 8, minTop, maxTop), + }; + wrapperStyle = { + left: lgap + hgap, + top: 0, + bottom: "", + right: "", + }; + placeholderStyle = { + top: 0, + bottom: 0, + width: this._const.TRIANGLE_LENGTH, + left: -this._const.TRIANGLE_LENGTH, + right: "", + }; + break; + case "right,top": + direction = "right"; + style = { + bottom: clamp(((middle ? popupHeight : position.height) + adjustYOffset) / 2 - 8, minBottom, maxBottom), + }; + wrapperStyle = { + left: lgap + hgap, + bottom: 0, + top: "", + right: "", + }; + placeholderStyle = { + top: 0, + bottom: 0, + width: this._const.TRIANGLE_LENGTH, + left: -this._const.TRIANGLE_LENGTH, + right: "", + }; + break; + case "right,innerRight": + break; + case "right,innerLeft": + break; + case "innerRight": + break; + case "innerLeft": + break; + default: + break; + } + this.element + .removeClass("left") + .removeClass("right") + .removeClass("top") + .removeClass("bottom") + .addClass(direction); + this.arrow.element.css(style); + this.arrowWrapper.element.css(wrapperStyle); + this.placeholder.element.css(placeholderStyle); + } } getView() { - return this.view; + return this.view; } populate(items) { - this.view.populate.apply(this.view, arguments); + this.view.populate(...arguments); } resetWidth(w) { - this.options.width = w; - this.element.width(w); + this.options.width = w; + this.element.width(w); } resetHeight(h) { - const tbHeight = this.toolbar ? (this.toolbar.attr("height") || 24) : 0, - tabHeight = this.tab ? (this.tab.attr("height") || 24) : 0, - toolHeight = ((this.tool && this.tool.attr("height")) || 24) * ((this.tool && this.tool.isVisible()) ? 1 : 0); - const resetHeight = h - tbHeight - tabHeight - toolHeight - 2 * this.options.innerVgap; - this.view.resetHeight ? this.view.resetHeight(resetHeight) : - this.view.element.css({ "max-height": BI.pixFormat(resetHeight) }); + const tbHeight = this.toolbar ? (this.toolbar.attr("height") || 24) : 0, + tabHeight = this.tab ? (this.tab.attr("height") || 24) : 0, + toolHeight = ((this.tool && this.tool.attr("height")) || 24) * ((this.tool && this.tool.isVisible()) ? 1 : 0); + const resetHeight = h - tbHeight - tabHeight - toolHeight - 2 * this.options.innerVgap; + this.view.resetHeight ? this.view.resetHeight(resetHeight) : + this.view.element.css({ "max-height": BI.pixFormat(resetHeight) }); } setValue(selectedValues) { - this.tab && this.tab.setValue(selectedValues); - this.view.setValue(selectedValues); + this.tab && this.tab.setValue(selectedValues); + this.view.setValue(selectedValues); } getValue() { return this.view.getValue(); } - } diff --git a/src/base/layer/layer.searcher.js b/src/base/layer/layer.searcher.js index 9d4cfbb0e..2ef9d1cbb 100644 --- a/src/base/layer/layer.searcher.js +++ b/src/base/layer/layer.searcher.js @@ -6,106 +6,97 @@ * @extends BI.Pane */ -import { shortcut } from "../../core"; +import { shortcut, extend, createWidget, Controller, isNotEmptyArray } from "../../core"; import { Pane } from "../1.pane"; @shortcut() export class SearcherView extends Pane { - static xtype = "bi.searcher_view"; static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-searcher-view bi-card", - tipText: BI.i18nText("BI-No_Select"), - chooseType: BI.Selection.Single, - - matcher: { // 完全匹配的构造器 - type: "bi.button_group", - behaviors: { - redmark: () => { - return true; - }, - }, - items: [], - layouts: [{ - type: "bi.vertical", - }], - }, - searcher: { - type: "bi.button_group", - behaviors: { - redmark: () => { - return true; - }, - }, - items: [], - layouts: [{ - type: "bi.vertical", - }], - }, - }); + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-searcher-view bi-card`, + tipText: BI.i18nText("BI-No_Select"), + chooseType: BI.Selection.Single, + + matcher: { // 完全匹配的构造器 + type: "bi.button_group", + behaviors: { + redmark: () => true, + }, + items: [], + layouts: [{ + type: "bi.vertical", + }], + }, + searcher: { + type: "bi.button_group", + behaviors: { + redmark: () => true, + }, + items: [], + layouts: [{ + type: "bi.vertical", + }], + }, + }); } render() { - const { matcher, chooseType, value, searcher } = this.options; - - this.matcher = BI.createWidget(matcher, { - type: "bi.button_group", - chooseType, - behaviors: { - redmark: () => { - return true; - }, - }, - layouts: [{ - type: "bi.vertical", - }], - value, - }); - this.matcher.on(BI.Controller.EVENT_CHANGE, (type, val, ob, ...args) => { - this.fireEvent.apply(this, [BI.Controller.EVENT_CHANGE, type, val, ob, ...args]); - if (type === BI.Events.CLICK) { - this.fireEvent(SearcherView.EVENT_CHANGE, val, ob); - } - }); - this.spliter = BI.createWidget({ - type: "bi.vertical", - height: 1, - hgap: 10, - items: [{ - type: "bi.layout", - height: 1, - cls: "searcher-view-spliter bi-background", - }], - }); - this.searcher = BI.createWidget(searcher, { - type: "bi.button_group", - chooseType, - behaviors: { - redmark: () => { - return true; - }, - }, - layouts: [{ - type: "bi.vertical", - }], - value, - }); - this.searcher.on(BI.Controller.EVENT_CHANGE, (type, val, ob, ...args) => { - this.fireEvent.apply(this, [BI.Controller.EVENT_CHANGE, type, val, ob, ...args]); - if (type === BI.Events.CLICK) { - this.fireEvent(BI.SearcherView.EVENT_CHANGE, val, ob); - } - }); - - BI.createWidget({ - type: "bi.vertical", - element: this, - items: [this.matcher, this.spliter, this.searcher], - }); + const { matcher, chooseType, value, searcher } = this.options; + + this.matcher = createWidget(matcher, { + type: "bi.button_group", + chooseType, + behaviors: { + redmark: () => true, + }, + layouts: [{ + type: "bi.vertical", + }], + value, + }); + this.matcher.on(Controller.EVENT_CHANGE, (type, val, ob, ...args) => { + this.fireEvent(Controller.EVENT_CHANGE, type, val, ob, ...args); + if (type === BI.Events.CLICK) { + this.fireEvent(SearcherView.EVENT_CHANGE, val, ob); + } + }); + this.spliter = createWidget({ + type: "bi.vertical", + height: 1, + hgap: 10, + items: [{ + type: "bi.layout", + height: 1, + cls: "searcher-view-spliter bi-background", + }], + }); + this.searcher = createWidget(searcher, { + type: "bi.button_group", + chooseType, + behaviors: { + redmark: () => true, + }, + layouts: [{ + type: "bi.vertical", + }], + value, + }); + this.searcher.on(Controller.EVENT_CHANGE, (type, val, ob, ...args) => { + this.fireEvent(Controller.EVENT_CHANGE, type, val, ob, ...args); + if (type === BI.Events.CLICK) { + this.fireEvent(BI.SearcherView.EVENT_CHANGE, val, ob); + } + }); + + createWidget({ + type: "bi.vertical", + element: this, + items: [this.matcher, this.spliter, this.searcher], + }); } startSearch() { @@ -117,30 +108,30 @@ export class SearcherView extends Pane { } setValue(v) { - this.matcher.setValue(v); - this.searcher.setValue(v); + this.matcher.setValue(v); + this.searcher.setValue(v); } getValue() { - return this.matcher.getValue().concat(this.searcher.getValue()); + return this.matcher.getValue().concat(this.searcher.getValue()); } populate(searchResult, matchResult, keyword) { - searchResult || (searchResult = []); - matchResult || (matchResult = []); - this.setTipVisible(searchResult.length + matchResult.length === 0); - this.spliter.setVisible(BI.isNotEmptyArray(matchResult) && BI.isNotEmptyArray(searchResult)); - this.matcher.populate(matchResult, keyword); - this.searcher.populate(searchResult, keyword); + searchResult || (searchResult = []); + matchResult || (matchResult = []); + this.setTipVisible(searchResult.length + matchResult.length === 0); + this.spliter.setVisible(isNotEmptyArray(matchResult) && isNotEmptyArray(searchResult)); + this.matcher.populate(matchResult, keyword); + this.searcher.populate(searchResult, keyword); } empty() { - this.searcher.empty(); - this.matcher.empty(); + this.searcher.empty(); + this.matcher.empty(); } hasMatched() { - return this.matcher.getAllButtons().length > 0; + return this.matcher.getAllButtons().length > 0; } } diff --git a/src/base/list/index.js b/src/base/list/index.js index 0a1c500cd..fac027df7 100644 --- a/src/base/list/index.js +++ b/src/base/list/index.js @@ -1,3 +1,3 @@ export { ListView } from "./listview"; export { VirtualGroupList } from "./virtualgrouplist"; -export { VirtualList } from "./virtuallist"; \ No newline at end of file +export { VirtualList } from "./virtuallist"; diff --git a/src/base/list/listview.js b/src/base/list/listview.js index ce2870e75..f890a4986 100644 --- a/src/base/list/listview.js +++ b/src/base/list/listview.js @@ -5,27 +5,25 @@ * @class BI.ListView * @extends BI.Widget */ -import { Widget, shortcut } from "../../core"; +import { Widget, shortcut, extend, isFunction } from "../../core"; @shortcut() export class ListView extends Widget { - props() { - return { - baseCls: "bi-list-view", - overscanHeight: 100, - blockSize: 10, - scrollTop: 0, - el: {}, - items: [], - itemFormatter: (item, index) => { - return item; - }, - }; - } + props() { + return { + baseCls: "bi-list-view", + overscanHeight: 100, + blockSize: 10, + scrollTop: 0, + el: {}, + items: [], + itemFormatter: (item, index) => item, + }; + } - init() { - this.renderedIndex = -1; - this.cache = {}; - } + init() { + this.renderedIndex = -1; + this.cache = {}; + } static xtype = "bi.list_view"; @@ -34,10 +32,10 @@ export class ListView extends Widget { return { type: "bi.vertical", - items: [BI.extend({ + items: [extend({ type: "bi.vertical", scrolly: false, - ref: (_ref) => { + ref: _ref => { this.container = _ref; }, }, el)], @@ -47,69 +45,66 @@ export class ListView extends Widget { // mounted之后绑定事件 mounted() { - const o = this.options; - // 这里无法进行结构,因为存在赋值操作,如果使用结构则this.options的值不会跟随变化 - o.items = BI.isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { - this.populate(newValue); - }) : o.items; - this._populate(); - this.element.scroll((e) => { - o.scrollTop = this.element.scrollTop(); - this._calculateBlocksToRender(); - }); - let lastWidth = this.element.width(), - lastHeight = this.element.height(); - BI.ResizeDetector.addResizeListener(this, () => { - if (!this.element.is(":visible")) { - return; - } - const width = this.element.width(), - height = this.element.height(); - if (width !== lastWidth || height !== lastHeight) { - lastWidth = width; - lastHeight = height; - this._calculateBlocksToRender(); - } - }); + const o = this.options; + // 这里无法进行结构,因为存在赋值操作,如果使用结构则this.options的值不会跟随变化 + o.items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); + }) : o.items; + this._populate(); + this.element.scroll(e => { + o.scrollTop = this.element.scrollTop(); + this._calculateBlocksToRender(); + }); + let lastWidth = this.element.width(), + lastHeight = this.element.height(); + BI.ResizeDetector.addResizeListener(this, () => { + if (!this.element.is(":visible")) { + return; + } + const width = this.element.width(), + height = this.element.height(); + if (width !== lastWidth || height !== lastHeight) { + lastWidth = width; + lastHeight = height; + this._calculateBlocksToRender(); + } + }); } _renderMoreIf() { - const { scrollTop, overscanHeight, blockSize, items, itemFormatter } = this.options; - const height = this.element.height(); - const minContentHeight = scrollTop + height + overscanHeight; - let index = (this.cache[this.renderedIndex] && (this.cache[this.renderedIndex].index + blockSize)) || 0; - let cnt = this.renderedIndex + 1; - let lastHeight; + const { scrollTop, overscanHeight, blockSize, items, itemFormatter } = this.options; + const height = this.element.height(); + const minContentHeight = scrollTop + height + overscanHeight; + let index = (this.cache[this.renderedIndex] && (this.cache[this.renderedIndex].index + blockSize)) || 0; + let cnt = this.renderedIndex + 1; + let lastHeight; - const getElementHeight = () => { - return this.container.element.height(); - } + const getElementHeight = () => this.container.element.height(); - lastHeight = getElementHeight(); - while ((lastHeight) < minContentHeight && index < items.length) { - const itemsArr = items.slice(index, index + blockSize); - this.container.addItems(itemsArr.map((item, i) => { - return itemFormatter(item, index + i); - }), this); - const addedHeight = getElementHeight() - lastHeight; - this.cache[cnt] = { - index: index, - scrollTop: lastHeight, - height: addedHeight, - }; - this.renderedIndex = cnt; - cnt++; - index += blockSize; - lastHeight = getElementHeight(); - } + lastHeight = getElementHeight(); + while ((lastHeight) < minContentHeight && index < items.length) { + const itemsArr = items.slice(index, index + blockSize); + // eslint-disable-next-line no-loop-func + this.container.addItems(itemsArr.map((item, i) => itemFormatter(item, index + i)), this); + const addedHeight = getElementHeight() - lastHeight; + this.cache[cnt] = { + index, + scrollTop: lastHeight, + height: addedHeight, + }; + this.renderedIndex = cnt; + cnt++; + index += blockSize; + lastHeight = getElementHeight(); + } } _calculateBlocksToRender() { - // BI-115750 不可见状态下依赖元素实际尺寸构造的线段树会分段错误,所以不进行后续计算和线段树的初始化。 - // 这样从不可见状态变为可见状态能够重新触发线段树初始化 - if (!this.element.is(":visible")) { - return; - } - this._renderMoreIf(); + // BI-115750 不可见状态下依赖元素实际尺寸构造的线段树会分段错误,所以不进行后续计算和线段树的初始化。 + // 这样从不可见状态变为可见状态能够重新触发线段树初始化 + if (!this.element.is(":visible")) { + return; + } + this._renderMoreIf(); } _populate(items) { @@ -128,22 +123,21 @@ export class ListView extends Widget { } scrollTo(scrollTop) { - this.options.scrollTop = scrollTop; - this._calculateBlocksToRender(); - this.element.scrollTop(scrollTop); + this.options.scrollTop = scrollTop; + this._calculateBlocksToRender(); + this.element.scrollTop(scrollTop); } populate(items) { - if (items && this.options.items !== items) { - this.restore(); - } - this._populate(items); + if (items && this.options.items !== items) { + this.restore(); + } + this._populate(items); } beforeDestroy() { - BI.ResizeDetector.removeResizeListener(this); - this.restore(); + BI.ResizeDetector.removeResizeListener(this); + this.restore(); } - } diff --git a/src/base/list/virtualgrouplist.js b/src/base/list/virtualgrouplist.js index d89cb32a0..cb5d23e42 100644 --- a/src/base/list/virtualgrouplist.js +++ b/src/base/list/virtualgrouplist.js @@ -6,196 +6,187 @@ * @extends BI.Widget */ -import { Widget, shortcut } from "../../core"; +import { Widget, shortcut, extend, isFunction, isNumber, PrefixIntervalTree } from "../../core"; @shortcut() export class VirtualGroupList extends Widget { - props() { - return { - baseCls: "bi-virtual-group-list", - overscanHeight: 100, - blockSize: 10, - scrollTop: 0, - rowHeight: "auto", - items: [], - el: {}, - itemFormatter: (item, index) => { - return item; - }, - }; - } + props() { + return { + baseCls: "bi-virtual-group-list", + overscanHeight: 100, + blockSize: 10, + scrollTop: 0, + rowHeight: "auto", + items: [], + el: {}, + itemFormatter: (item, index) => item, + }; + } - init() { - this.renderedIndex = -1; - } + init() { + this.renderedIndex = -1; + } static xtype = "bi.virtual_group_list"; render() { - const { rowHeight, items, el } = this.options; + const { rowHeight, items, el } = this.options; - return { - type: "bi.vertical", - items: [{ - type: "bi.layout", - ref: () => { - this.topBlank = this; - }, - }, { - type: "bi.virtual_group", - height: rowHeight * items.length, - ref: () => { - this.container = this; - }, - layouts: [BI.extend({ - type: "bi.vertical", - scrolly: false, - }, el)], - }, { - type: "bi.layout", - ref: () => { - this.bottomBlank = this; - }, - }], - element: this, - }; + return { + type: "bi.vertical", + items: [{ + type: "bi.layout", + ref: () => { + this.topBlank = this; + }, + }, { + type: "bi.virtual_group", + height: rowHeight * items.length, + ref: () => { + this.container = this; + }, + layouts: [extend({ + type: "bi.vertical", + scrolly: false, + }, el)], + }, { + type: "bi.layout", + ref: () => { + this.bottomBlank = this; + }, + }], + element: this, + }; } // mounted之后绑定事件 mounted() { - // 这里无法进行结构,因为存在赋值操作,如果使用结构则this.options的值不会跟随变化 - const o = this.options; - o.items = BI.isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { - this.populate(newValue); - }) : o.items; - this._populate(); - this.ticking = false; - this.element.scroll(() => { - o.scrollTop = this.element.scrollTop(); - if (!this.ticking) { - requestAnimationFrame(() => { + // 这里无法进行结构,因为存在赋值操作,如果使用结构则this.options的值不会跟随变化 + const o = this.options; + o.items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); + }) : o.items; + this._populate(); + this.ticking = false; + this.element.scroll(() => { + o.scrollTop = this.element.scrollTop(); + if (!this.ticking) { + requestAnimationFrame(() => { + this._calculateBlocksToRender(); + this.ticking = false; + }); + this.ticking = true; + } + }); + BI.ResizeDetector.addResizeListener(this, () => { + if (this.element.is(":visible")) { this._calculateBlocksToRender(); - this.ticking = false; - }); - this.ticking = true; - } - }); - BI.ResizeDetector.addResizeListener(this, () => { - if (this.element.is(":visible")) { - this._calculateBlocksToRender(); - } - }); + } + }); } _isAutoHeight() { - return !BI.isNumber(this.options.rowHeight); + return !isNumber(this.options.rowHeight); } _renderMoreIf() { - const { scrollTop, overscanHeight, blockSize, items, itemFormatter } = this.options; - const height = this.element.height(); - const minContentHeight = scrollTop + height + overscanHeight; - let index = (this.renderedIndex + 1) * blockSize, cnt = this.renderedIndex + 1; - let lastHeight; - const getElementHeight = () => { - return this.container.element.height() + this.topBlank.element.height() + this.bottomBlank.element.height(); - } - lastHeight = this.renderedIndex === -1 ? 0 : getElementHeight(); - while (lastHeight < minContentHeight && index < items.length) { - const itemsArr = items.slice(index, index + blockSize); - this.container[this.renderedIndex === -1 ? "populate" : "addItems"](itemsArr.map((item, i) => { - return itemFormatter(item, index + i); - }), this); - const elementHeight = getElementHeight(); - const addedHeight = elementHeight - lastHeight; - this.tree.set(cnt, addedHeight); - this.renderedIndex = cnt; - cnt++; - index += blockSize; - lastHeight = this.renderedIndex === -1 ? 0 : elementHeight; - } + const { scrollTop, overscanHeight, blockSize, items, itemFormatter } = this.options; + const height = this.element.height(); + const minContentHeight = scrollTop + height + overscanHeight; + let index = (this.renderedIndex + 1) * blockSize, cnt = this.renderedIndex + 1; + let lastHeight; + const getElementHeight = () => this.container.element.height() + this.topBlank.element.height() + this.bottomBlank.element.height(); + lastHeight = this.renderedIndex === -1 ? 0 : getElementHeight(); + while (lastHeight < minContentHeight && index < items.length) { + const itemsArr = items.slice(index, index + blockSize); + // eslint-disable-next-line no-loop-func + this.container[this.renderedIndex === -1 ? "populate" : "addItems"](itemsArr.map((item, i) => itemFormatter(item, index + i)), this); + const elementHeight = getElementHeight(); + const addedHeight = elementHeight - lastHeight; + this.tree.set(cnt, addedHeight); + this.renderedIndex = cnt; + cnt++; + index += blockSize; + lastHeight = this.renderedIndex === -1 ? 0 : elementHeight; + } } _calculateBlocksToRender() { - // BI-115750 不可见状态下依赖元素实际尺寸构造的线段树会分段错误,所以不进行后续计算和线段树的初始化。 - // 这样从不可见状态变为可见状态能够重新触发线段树初始化 - if (!this.element.is(":visible")) { - return; - } - const { scrollTop, overscanHeight, blockSize, items, itemFormatter, rowHeight } = this.options; - this._isAutoHeight() && this._renderMoreIf(); - const height = this.element.height(); - const minContentHeightFrom = scrollTop - overscanHeight; - const minContentHeightTo = scrollTop + height + overscanHeight; - const start = this.tree.greatestLowerBound(minContentHeightFrom); - const end = this.tree.leastUpperBound(minContentHeightTo); - const itemsArr = []; - const topHeight = this.tree.sumTo(Math.max(-1, start - 1)); - this.topBlank.setHeight(topHeight + "px"); - if (this._isAutoHeight()) { - for (let i = (start < 0 ? 0 : start); i <= end && i <= this.renderedIndex; i++) { - const index = i * blockSize; - for (let j = index; j < index + blockSize && j < items.length; j++) { - itemsArr.push(items[j]); - } + // BI-115750 不可见状态下依赖元素实际尺寸构造的线段树会分段错误,所以不进行后续计算和线段树的初始化。 + // 这样从不可见状态变为可见状态能够重新触发线段树初始化 + if (!this.element.is(":visible")) { + return; } - this.bottomBlank.setHeight(this.tree.sumTo(this.renderedIndex) - this.tree.sumTo(Math.min(end, this.renderedIndex)) + "px"); - this.container.populate(itemsArr.map((item, i) => { - return itemFormatter(item, (start < 0 ? 0 : start) * blockSize + i); - })); - } else { - for (let i = (start < 0 ? 0 : start); i <= end; i++) { - const index = i * blockSize; - for (let j = index; j < index + blockSize && j < items.length; j++) { - itemsArr.push(items[j]); + const { scrollTop, overscanHeight, blockSize, items, itemFormatter, rowHeight } = this.options; + this._isAutoHeight() && this._renderMoreIf(); + const height = this.element.height(); + const minContentHeightFrom = scrollTop - overscanHeight; + const minContentHeightTo = scrollTop + height + overscanHeight; + const start = this.tree.greatestLowerBound(minContentHeightFrom); + const end = this.tree.leastUpperBound(minContentHeightTo); + const itemsArr = []; + const topHeight = this.tree.sumTo(Math.max(-1, start - 1)); + this.topBlank.setHeight(`${topHeight}px`); + if (this._isAutoHeight()) { + for (let i = (start < 0 ? 0 : start); i <= end && i <= this.renderedIndex; i++) { + const index = i * blockSize; + for (let j = index; j < index + blockSize && j < items.length; j++) { + itemsArr.push(items[j]); + } } + this.bottomBlank.setHeight(`${this.tree.sumTo(this.renderedIndex) - this.tree.sumTo(Math.min(end, this.renderedIndex))}px`); + this.container.populate(itemsArr.map((item, i) => itemFormatter(item, (start < 0 ? 0 : start) * blockSize + i))); + } else { + for (let i = (start < 0 ? 0 : start); i <= end; i++) { + const index = i * blockSize; + for (let j = index; j < index + blockSize && j < items.length; j++) { + itemsArr.push(items[j]); + } + } + this.container.element.height(rowHeight * items.length - topHeight); + this.container.populate(itemsArr.map((item, i) => itemFormatter(item, (start < 0 ? 0 : start) * blockSize + i))); } - this.container.element.height(rowHeight * items.length - topHeight); - this.container.populate(itemsArr.map((item, i) => { - return itemFormatter(item, (start < 0 ? 0 : start) * blockSize + i); - })); - } } _populate(items) { - const { blockSize, rowHeight, scrollTop } = this.options; - if (items && this.options.items !== items) { - // 重新populate一组items,需要重新对线段树分块 - this.options.items = items; - this._restore(); - } - this.tree = BI.PrefixIntervalTree.uniform(Math.ceil(this.options.items.length / blockSize), this._isAutoHeight() ? 0 : rowHeight * blockSize); + const { blockSize, rowHeight, scrollTop } = this.options; + if (items && this.options.items !== items) { + // 重新populate一组items,需要重新对线段树分块 + this.options.items = items; + this._restore(); + } + this.tree = PrefixIntervalTree.uniform(Math.ceil(this.options.items.length / blockSize), this._isAutoHeight() ? 0 : rowHeight * blockSize); - this._calculateBlocksToRender(); - try { - this.element.scrollTop(scrollTop); - } catch (e) { - } + this._calculateBlocksToRender(); + try { + this.element.scrollTop(scrollTop); + } catch (e) { + } } _restore() { - this.renderedIndex = -1; - // 依赖于cache的占位元素也要初始化 - this.topBlank.setHeight(0); - this.bottomBlank.setHeight(0); + this.renderedIndex = -1; + // 依赖于cache的占位元素也要初始化 + this.topBlank.setHeight(0); + this.bottomBlank.setHeight(0); } // 暂时只支持固定行高的场景 scrollTo(scrollTop) { - this.options.scrollTop = scrollTop; - this._calculateBlocksToRender(); - this.element.scrollTop(scrollTop); + this.options.scrollTop = scrollTop; + this._calculateBlocksToRender(); + this.element.scrollTop(scrollTop); } restore() { - this.options.scrollTop = 0; - this._restore(); + this.options.scrollTop = 0; + this._restore(); } populate(items) { - this._populate(items); + this._populate(items); } beforeDestroy() { - BI.ResizeDetector.removeResizeListener(this); - this.restore(); + BI.ResizeDetector.removeResizeListener(this); + this.restore(); } } diff --git a/src/base/list/virtuallist.js b/src/base/list/virtuallist.js index d2ce62311..ec09f1b8d 100644 --- a/src/base/list/virtuallist.js +++ b/src/base/list/virtuallist.js @@ -6,7 +6,7 @@ * @extends BI.Widget */ -import { Widget, shortcut } from "../../core"; +import { Widget, shortcut, isFunction, each, PrefixIntervalTree } from "../../core"; @shortcut() export class VirtualList extends Widget { props() { @@ -16,9 +16,7 @@ export class VirtualList extends Widget { blockSize: 10, scrollTop: 0, items: [], - itemFormatter: (item, index) => { - return item; - }, + itemFormatter: (item, index) => item, }; } @@ -30,189 +28,186 @@ export class VirtualList extends Widget { static xtype = "bi.virtual_list"; render() { - return { - type: "bi.vertical", - items: [{ - type: "bi.layout", - ref: (_ref) => { - this.topBlank = _ref; - }, - }, { - type: "bi.vertical", - scrolly: false, - ref: (_ref) => { - this.container = _ref; - }, - }, { - type: "bi.layout", - ref: (_ref) => { - this.bottomBlank = _ref; - }, - }], - }; + return { + type: "bi.vertical", + items: [{ + type: "bi.layout", + ref: _ref => { + this.topBlank = _ref; + }, + }, { + type: "bi.vertical", + scrolly: false, + ref: _ref => { + this.container = _ref; + }, + }, { + type: "bi.layout", + ref: _ref => { + this.bottomBlank = _ref; + }, + }], + }; } // mounted之后绑定事件 mounted() { - // 这里无法进行结构,因为存在赋值操作,如果使用结构则this.options的值不会跟随变化 - const o = this.options; - o.items = BI.isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { - this.populate(newValue); - }) : o.items; - this._populate(); - this.element.scroll((e) => { - o.scrollTop = this.element.scrollTop(); - this._calculateBlocksToRender(); - }); - BI.ResizeDetector.addResizeListener(this, () => { - if (this.element.is(":visible")) { - this._calculateBlocksToRender(); - } - }); + // 这里无法进行结构,因为存在赋值操作,如果使用结构则this.options的值不会跟随变化 + const o = this.options; + o.items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); + }) : o.items; + this._populate(); + this.element.scroll(e => { + o.scrollTop = this.element.scrollTop(); + this._calculateBlocksToRender(); + }); + BI.ResizeDetector.addResizeListener(this, () => { + if (this.element.is(":visible")) { + this._calculateBlocksToRender(); + } + }); } - _renderMoreIf() { - const { scrollTop, overscanHeight, blockSize, items, itemFormatter } = this.options; - const height = this.element.height(); - const minContentHeight = scrollTop + height + overscanHeight; - let index = (this.renderedIndex + 1) * blockSize, cnt = this.renderedIndex + 1; - let lastHeight; - const getElementHeight = () => { - return this.container.element.height() + this.topBlank.element.height() + this.bottomBlank.element.height(); - } - lastHeight = getElementHeight(); - while (lastHeight < minContentHeight && index < items.length) { - const itemsArr = items.slice(index, index + blockSize); - this.container.addItems(itemsArr.map((item, i) => { - return itemFormatter(item, index + i); - }), this); - const addedHeight = getElementHeight() - lastHeight; - this.tree.set(cnt, addedHeight); - this.renderedIndex = cnt; - cnt++; - index += blockSize; - lastHeight = getElementHeight(); - } - } - - _calculateBlocksToRender() { - const { scrollTop, overscanHeight, blockSize, items, itemFormatter } = this.options; - // BI-115750 不可见状态下依赖元素实际尺寸构造的线段树会分段错误,所以不进行后续计算和线段树的初始化。 - // 这样从不可见状态变为可见状态能够重新触发线段树初始化 - if (!this.element.is(":visible")) { - return; + _renderMoreIf() { + const { scrollTop, overscanHeight, blockSize, items, itemFormatter } = this.options; + const height = this.element.height(); + const minContentHeight = scrollTop + height + overscanHeight; + let index = (this.renderedIndex + 1) * blockSize, cnt = this.renderedIndex + 1; + let lastHeight; + const getElementHeight = () => this.container.element.height() + this.topBlank.element.height() + this.bottomBlank.element.height(); + lastHeight = getElementHeight(); + while (lastHeight < minContentHeight && index < items.length) { + const itemsArr = items.slice(index, index + blockSize); + // eslint-disable-next-line no-loop-func + this.container.addItems(itemsArr.map((item, i) => itemFormatter(item, index + i)), this); + const addedHeight = getElementHeight() - lastHeight; + this.tree.set(cnt, addedHeight); + this.renderedIndex = cnt; + cnt++; + index += blockSize; + lastHeight = getElementHeight(); + } } - this._renderMoreIf(); - const height = this.element.height(); - const minContentHeightFrom = scrollTop - overscanHeight; - const minContentHeightTo = scrollTop + height + overscanHeight; - const start = this.tree.greatestLowerBound(minContentHeightFrom); - const end = this.tree.leastUpperBound(minContentHeightTo); - const needDestroyed = [], needMount = []; - for (let i = 0; i < start; i++) { - let index = i * blockSize; - if (!this.cache[i]) { - this.cache[i] = {}; + + _calculateBlocksToRender() { + const { scrollTop, overscanHeight, blockSize, items, itemFormatter } = this.options; + // BI-115750 不可见状态下依赖元素实际尺寸构造的线段树会分段错误,所以不进行后续计算和线段树的初始化。 + // 这样从不可见状态变为可见状态能够重新触发线段树初始化 + if (!this.element.is(":visible")) { + return; } - if (!this.cache[i].destroyed) { - for (let j = index; j < index + blockSize && j < items.length; j++) { - needDestroyed.push(this.container._children[j]); - this.container._children[j] = null; + this._renderMoreIf(); + const height = this.element.height(); + const minContentHeightFrom = scrollTop - overscanHeight; + const minContentHeightTo = scrollTop + height + overscanHeight; + const start = this.tree.greatestLowerBound(minContentHeightFrom); + const end = this.tree.leastUpperBound(minContentHeightTo); + const needDestroyed = [], needMount = []; + for (let i = 0; i < start; i++) { + const index = i * blockSize; + if (!this.cache[i]) { + this.cache[i] = {}; + } + if (!this.cache[i].destroyed) { + for (let j = index; j < index + blockSize && j < items.length; j++) { + needDestroyed.push(this.container._children[j]); + this.container._children[j] = null; + } + this.cache[i].destroyed = true; } - this.cache[i].destroyed = true; } - } - for (let i = end + 1; i <= this.renderedIndex; i++) { - let index = i * blockSize; - if (!this.cache[i]) { - this.cache[i] = {}; - } - if (!this.cache[i].destroyed) { - for (let j = index; j < index + blockSize && j < items.length; j++) { - needDestroyed.push(this.container._children[j]); - this.container._children[j] = null; + for (let i = end + 1; i <= this.renderedIndex; i++) { + const index = i * blockSize; + if (!this.cache[i]) { + this.cache[i] = {}; + } + if (!this.cache[i].destroyed) { + for (let j = index; j < index + blockSize && j < items.length; j++) { + needDestroyed.push(this.container._children[j]); + this.container._children[j] = null; + } + this.cache[i].destroyed = true; + } } - this.cache[i].destroyed = true; - } - } - const firstFragment = BI.Widget._renderEngine.createFragment(), - lastFragment = BI.Widget._renderEngine.createFragment(); - let currentFragment = firstFragment; - for (let i = (start < 0 ? 0 : start); i <= end && i <= this.renderedIndex; i++) { - const index = i * blockSize; - if (!this.cache[i]) { - this.cache[i] = {}; + const firstFragment = Widget._renderEngine.createFragment(), + lastFragment = Widget._renderEngine.createFragment(); + let currentFragment = firstFragment; + for (let i = (start < 0 ? 0 : start); i <= end && i <= this.renderedIndex; i++) { + const index = i * blockSize; + if (!this.cache[i]) { + this.cache[i] = {}; + } + if (!this.cache[i].destroyed) { + currentFragment = lastFragment; + } + if (this.cache[i].destroyed === true) { + for (let j = index; j < index + blockSize && j < items.length; j++) { + const w = this.container._addElement(j, itemFormatter(items[j], j), this); + needMount.push(w); + currentFragment.appendChild(w.element[0]); + } + this.cache[i].destroyed = false; + } } - if (!this.cache[i].destroyed) { - currentFragment = lastFragment; + this.container.element.prepend(firstFragment); + this.container.element.append(lastFragment); + this.topBlank.setHeight(`${this.tree.sumTo(Math.max(-1, start - 1))}px`); + this.bottomBlank.setHeight(`${this.tree.sumTo(this.renderedIndex) - this.tree.sumTo(Math.min(end, this.renderedIndex))}px`); + each(needMount, (i, child) => { + child && child._mount(); + }); + each(needDestroyed, (i, child) => { + child && child._destroy(); + }); + } + _populate(items) { + const { blockSize, scrollTop } = this.options; + if (items && this.options.items !== items) { + this.options.items = items; } - if (this.cache[i].destroyed === true) { - for (let j = index; j < index + blockSize && j < items.length; j++) { - const w = this.container._addElement(j, itemFormatter(items[j], j), this); - needMount.push(w); - currentFragment.appendChild(w.element[0]); - } - this.cache[i].destroyed = false; + this.tree = PrefixIntervalTree.empty(Math.ceil(this.options.items.length / blockSize)); + + this._calculateBlocksToRender(); + try { + this.element.scrollTop(scrollTop); + } catch (e) { } } - this.container.element.prepend(firstFragment); - this.container.element.append(lastFragment); - this.topBlank.setHeight(this.tree.sumTo(Math.max(-1, start - 1)) + "px"); - this.bottomBlank.setHeight(this.tree.sumTo(this.renderedIndex) - this.tree.sumTo(Math.min(end, this.renderedIndex)) + "px"); - BI.each(needMount, (i, child) => { - child && child._mount(); - }); - BI.each(needDestroyed, (i, child) => { - child && child._destroy(); - }); - } - _populate(items) { - const { blockSize, scrollTop } = this.options; - if (items && this.options.items !== items) { - this.options.items = items; + + _clearChildren() { + each(this.container._children, (i, cell) => { + cell && cell._destroy(); + }); + this.container._children = {}; + this.container.attr("items", []); } - this.tree = BI.PrefixIntervalTree.empty(Math.ceil(this.options.items.length / blockSize)); - this._calculateBlocksToRender(); - try { + scrollTo(scrollTop) { + this.options.scrollTop = scrollTop; + this._calculateBlocksToRender(); this.element.scrollTop(scrollTop); - } catch (e) { } - } - - _clearChildren() { - BI.each(this.container._children, (i, cell) => { - cell && cell._destroy(); - }); - this.container._children = {}; - this.container.attr("items", []); - } - scrollTo(scrollTop) { - this.options.scrollTop = scrollTop; - this._calculateBlocksToRender(); - this.element.scrollTop(scrollTop); - } + restore() { + this.renderedIndex = -1; + this._clearChildren(); + this.cache = {}; + this.options.scrollTop = 0; + // 依赖于cache的占位元素也要初始化 + this.topBlank.setHeight(0); + this.bottomBlank.setHeight(0); + } - restore() { - this.renderedIndex = -1; - this._clearChildren(); - this.cache = {}; - this.options.scrollTop = 0; - // 依赖于cache的占位元素也要初始化 - this.topBlank.setHeight(0); - this.bottomBlank.setHeight(0); - } + populate(items) { + if (items && this.options.items !== items) { + this.restore(); + } + this._populate(items); + } - populate(items) { - if (items && this.options.items !== items) { + beforeDestroy() { + BI.ResizeDetector.removeResizeListener(this); this.restore(); } - this._populate(items); - } - - beforeDestroy() { - BI.ResizeDetector.removeResizeListener(this); - this.restore(); - } } diff --git a/src/base/pager/pager.js b/src/base/pager/pager.js index 4eba409e6..359d83616 100644 --- a/src/base/pager/pager.js +++ b/src/base/pager/pager.js @@ -5,11 +5,11 @@ * @class BI.Pager * @extends BI.Widget */ -import { Widget, shortcut } from "../../core"; +import { Widget, shortcut, extend, emptyFn, result, isKey, createWidget, map, stripEL, formatEL, Controller } from "../../core"; @shortcut() -export default class Pager extends Widget { +export class Pager extends Widget { _defaultConfig() { - return BI.extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-pager", behaviors: {}, layouts: [{ @@ -23,22 +23,19 @@ export default class Pager extends Widget { dynamicShowFirstLast: false, // 是否动态显示首页、尾页 dynamicShowPrevNext: false, // 是否动态显示上一页、下一页 pages: false, // 总页数 - curr: () => { - return 1; - }, // 初始化当前页 + curr: () => 1, // 初始化当前页 groups: 0, // 连续显示分页数 - jump: BI.emptyFn, // 分页的回调函数 + jump: emptyFn, // 分页的回调函数 first: false, // 是否显示首页 last: false, // 是否显示尾页 prev: "上一页", next: "下一页", firstPage: 1, - lastPage: () => { // 在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 - return 1; - }, - hasPrev: BI.emptyFn, // pages不可用时有效 - hasNext: BI.emptyFn, // pages不可用时有效 + lastPage: () => // 在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 + 1, + hasPrev: emptyFn, // pages不可用时有效 + hasNext: emptyFn, // pages不可用时有效 }); } @@ -46,7 +43,7 @@ export default class Pager extends Widget { static EVENT_CHANGE = "EVENT_CHANGE"; static EVENT_AFTER_POPULATE = "EVENT_AFTER_POPULATE"; render() { - this.currPage = BI.result(this.options, "curr"); + this.currPage = result(this.options, "curr"); // 翻页太灵敏 // this._lock = false; // this._debouce = BI.debounce(function () { @@ -59,13 +56,13 @@ export default class Pager extends Widget { const o = this.options, view = [], dict = {}; const { dynamicShow, dynamicShowPrevNext, hasPrev, dynamicShowFirstLast, hasNext, behaviors, layouts, jump } = this.options; this.empty(); - const pages = BI.result(o, "pages"); - const curr = BI.result(this, "currPage"); - let groups = BI.result(o, "groups"); - let first = BI.result(o, "first"); - let last = BI.result(o, "last"); - const prev = BI.result(o, "prev"); - const next = BI.result(o, "next"); + const pages = result(o, "pages"); + const curr = result(this, "currPage"); + let groups = result(o, "groups"); + let first = result(o, "first"); + let last = result(o, "last"); + const prev = result(o, "prev"); + const next = result(o, "next"); if (pages === false) { groups = 0; @@ -80,7 +77,7 @@ export default class Pager extends Widget { // 当前页非首页,则输出上一页 if (((!dynamicShow && !dynamicShowPrevNext) || curr > 1) && prev !== false) { - if (BI.isKey(prev)) { + if (isKey(prev)) { view.push({ text: prev, value: "prev", @@ -88,7 +85,7 @@ export default class Pager extends Widget { }); } else { view.push({ - el: BI.extend({ + el: extend({ disabled: pages === false ? hasPrev(curr) === false : !(curr > 1 && prev !== false), }, prev), }); @@ -162,7 +159,7 @@ export default class Pager extends Widget { dict.flow = !prev && groups === 0; if (((!dynamicShow && !dynamicShowPrevNext) && next) || (curr !== pages && next || dict.flow)) { view.push((function () { - if (BI.isKey(next)) { + if (isKey(next)) { if (pages === false) { return { text: next, value: "next", disabled: hasNext(curr) === false }; } @@ -175,62 +172,62 @@ export default class Pager extends Widget { } return { - el: BI.extend({ + el: extend({ disabled: pages === false ? hasNext(curr) === false : !(curr !== pages && next || dict.flow), }, next), }; }())); } - this.button_group = BI.createWidget({ + this.button_group = createWidget({ type: "bi.button_group", element: this, - items: BI.map(view, (idx, v) => { - v = BI.extend({ + items: map(view, (idx, v) => { + v = extend({ cls: "bi-list-item-select bi-border-radius", height: 23, hgap: v.el ? 0 : 10, stopPropagation: true, - }, BI.stripEL(v)); + }, stripEL(v)); - return BI.formatEL(v); + return formatEL(v); }), behaviors, layouts, }); - this.button_group.on(BI.Controller.EVENT_CHANGE, (type, value, obj, ...args) => { + this.button_group.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { // if (self._lock === true) { // return; // } // self._lock = true; // self._debouce(); if (type === BI.Events.CLICK) { - var v = this.button_group.getValue()[0]; + const v = this.button_group.getValue()[0]; switch (v) { - case "first": - this.currPage = 1; - break; - case "last": - this.currPage = pages; - break; - case "prev": - this.currPage--; - break; - case "next": - this.currPage++; - break; - default: - this.currPage = v; - break; + case "first": + this.currPage = 1; + break; + case "last": + this.currPage = pages; + break; + case "prev": + this.currPage--; + break; + case "next": + this.currPage++; + break; + default: + this.currPage = v; + break; } jump.apply(this, [{ - pages: pages, + pages, curr: this.currPage, }]); this._populate(); this.fireEvent(Pager.EVENT_CHANGE, obj); } - this.fireEvent.apply(this, [BI.Controller.EVENT_CHANGE, type, value, obj, ...args]); + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); }); this.fireEvent(Pager.EVENT_AFTER_POPULATE); } @@ -254,6 +251,7 @@ export default class Pager extends Widget { hasNext(v) { v || (v = 1); const { pages, hasNext } = this.options; + return pages === false ? hasNext(v) : v < pages; } @@ -263,8 +261,9 @@ export default class Pager extends Widget { v = v || 0; v = v < 1 ? 1 : v; if (pages === false) { - var lastPage = BI.result(o, "lastPage"), firstPage = 1; - this.currPage = v > lastPage ? lastPage : ((firstPage = BI.result(o, "firstPage")), (v < firstPage ? firstPage : v)); + const lastPage = result(o, "lastPage"); + let firstPage = 1; + this.currPage = v > lastPage ? lastPage : ((firstPage = result(o, "firstPage")), (v < firstPage ? firstPage : v)); } else { v = v > pages ? pages : v; this.currPage = v; @@ -275,27 +274,27 @@ export default class Pager extends Widget { getValue() { const val = this.button_group.getValue()[0]; switch (val) { - case "prev": - return -1; - case "next": - return 1; - case "first": - return BI.MIN; - case "last": - return BI.MAX; - default: - return val; + case "prev": + return -1; + case "next": + return 1; + case "first": + return BI.MIN; + case "last": + return BI.MAX; + default: + return val; } } attr(key, value) { - super.attr(arguments); + super.attr(...arguments); if (key === "curr") { - this.currPage = BI.result(this.options, "curr"); + this.currPage = result(this.options, "curr"); } } populate() { this._populate(); } -} \ No newline at end of file +} diff --git a/src/base/single/a/a.js b/src/base/single/a/a.js index c52006dd3..45a9c7846 100644 --- a/src/base/single/a/a.js +++ b/src/base/single/a/a.js @@ -6,32 +6,32 @@ * @extends BI.Text * @abstract */ -import { shortcut } from "../../../core"; +import { shortcut, extend, createWidget } from "../../../core"; import { Text } from "../1.text"; @shortcut() export class A extends Text { static xtype = "bi.a"; _defaultConfig() { - const conf = super._defaultConfig(arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-a display-block", - href: "", - target: "_blank", - el: null, - tagName: "a", - }); + const conf = super._defaultConfig(arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-a display-block`, + href: "", + target: "_blank", + el: null, + tagName: "a", + }); } render() { - const { href, target, el} = this.options; - super.render(); - this.element.attr({ href, target }); - if (el) { - BI.createWidget(el, { - element: this, - }); - } + const { href, target, el } = this.options; + super.render(); + this.element.attr({ href, target }); + if (el) { + createWidget(el, { + element: this, + }); + } } - } diff --git a/src/base/single/index.js b/src/base/single/index.js index 8fe2e22cc..15d1d54ce 100644 --- a/src/base/single/index.js +++ b/src/base/single/index.js @@ -8,4 +8,4 @@ export * from "./tip"; export * from "./label"; export * from "./input"; export * from "./editor"; -export * from "./button" +export * from "./button"; diff --git a/src/base/single/tip/0.tip.js b/src/base/single/tip/0.tip.js index a4b93f4e5..f94b581ab 100644 --- a/src/base/single/tip/0.tip.js +++ b/src/base/single/tip/0.tip.js @@ -8,18 +8,20 @@ */ import { Single } from "../0.single"; +import { extend } from "../../../core"; export class Tip extends Single { - _defaultConfig() { - const conf = super._defaultConfig(arguments); - return BI.extend(conf, { - _baseCls: (conf._baseCls || "") + " bi-tip", - zIndex: BI.zIndex_tip, - }); - } + _defaultConfig() { + const conf = super._defaultConfig(arguments); + + return extend(conf, { + _baseCls: `${conf._baseCls || ""} bi-tip`, + zIndex: BI.zIndex_tip, + }); + } - _init() { - super._init(); - this.element.css({ zIndex: this.options.zIndex }); - } + _init() { + super._init(); + this.element.css({ zIndex: this.options.zIndex }); + } } diff --git a/src/base/single/tip/index.js b/src/base/single/tip/index.js index 509c6be4c..cdbd3e751 100644 --- a/src/base/single/tip/index.js +++ b/src/base/single/tip/index.js @@ -1,3 +1,3 @@ export { Tip } from "./0.tip"; export { Toast } from "./tip.toast"; -export { Tooltip } from "./tip.tooltip"; \ No newline at end of file +export { Tooltip } from "./tip.tooltip"; diff --git a/src/base/single/tip/tip.toast.js b/src/base/single/tip/tip.toast.js index 2dce887e5..e42347d44 100644 --- a/src/base/single/tip/tip.toast.js +++ b/src/base/single/tip/tip.toast.js @@ -6,7 +6,7 @@ * @extends BI.Tip */ -import { shortcut } from "../../../core"; +import { shortcut, extend, isPlainObject } from "../../../core"; import { Tip } from "./0.tip"; @shortcut() export class Toast extends Tip { @@ -21,107 +21,106 @@ export class Toast extends Tip { static xtype = "bi.toast"; _defaultConfig() { - return BI.extend(super._defaultConfig(arguments), { - extraCls: "bi-toast", - text: "", - level: "success", // success或warning - autoClose: true, - closable: null, - textHeight: 20, - vgap: 10, - innerHgap: 4, - hgap: 8, - }); + return extend(super._defaultConfig(arguments), { + extraCls: "bi-toast", + text: "", + level: "success", // success或warning + autoClose: true, + closable: null, + textHeight: 20, + vgap: 10, + innerHgap: 4, + hgap: 8, + }); } render() { - const { closable, level, autoClose, textHeight, text, hgap, vgap, innerHgap } = this.options; - const { closableMinWidth, minWidth, maxWidth, closableMaxWidth } = this._const; - this.element.css({ - minWidth: BI.pixFormat(closable ? closableMinWidth : minWidth), - maxWidth: BI.pixFormat(closable ? closableMaxWidth : maxWidth), - }); - this.element.addClass("toast-" + level); - function fn(e) { - e.stopPropagation(); - e.stopEvent(); + const { closable, level, autoClose, textHeight, text, hgap, vgap, innerHgap } = this.options; + const { closableMinWidth, minWidth, maxWidth, closableMaxWidth } = this._const; + this.element.css({ + minWidth: BI.pixFormat(closable ? closableMinWidth : minWidth), + maxWidth: BI.pixFormat(closable ? closableMaxWidth : maxWidth), + }); + this.element.addClass(`toast-${level}`); + function fn(e) { + e.stopPropagation(); + e.stopEvent(); - return false; - } - this.element.bind({ - click: fn, - mousedown: fn, - mouseup: fn, - mouseover: fn, - mouseenter: fn, - mouseleave: fn, - mousemove: fn, - }); - let cls; - switch (level) { - case "success": - cls = "toast-success-font"; - break; - case "error": - cls = "toast-error-font"; - break; - case "warning": - cls = "toast-warning-font"; - break; - case "loading": - cls = "toast-loading-font anim-rotate"; - break; - case "normal": - default: - cls = "toast-message-font"; - break; - } + return false; + } + this.element.bind({ + click: fn, + mousedown: fn, + mouseup: fn, + mouseover: fn, + mouseenter: fn, + mouseleave: fn, + mousemove: fn, + }); + let cls; + switch (level) { + case "success": + cls = "toast-success-font"; + break; + case "error": + cls = "toast-error-font"; + break; + case "warning": + cls = "toast-warning-font"; + break; + case "loading": + cls = "toast-loading-font anim-rotate"; + break; + case "normal": + default: + cls = "toast-message-font"; + break; + } - function hasCloseIcon() { - return closable === true || (closable === null && autoClose === false); - } - const items = [{ - type: "bi.icon_label", - cls: cls + " toast-icon", - height: textHeight, - }, { - el: BI.isPlainObject(text) ? text : { - type: "bi.label", - whiteSpace: "normal", - text: text, - textHeight: textHeight, - textAlign: "left", - }, - }]; + function hasCloseIcon() { + return closable === true || (closable === null && autoClose === false); + } + const items = [{ + type: "bi.icon_label", + cls: `${cls} toast-icon`, + height: textHeight, + }, { + el: isPlainObject(text) ? text : { + type: "bi.label", + whiteSpace: "normal", + text, + textHeight, + textAlign: "left", + }, + }]; - const columnSize = ["", "fill"]; + const columnSize = ["", "fill"]; - if (hasCloseIcon()) { - items.push({ - type: "bi.icon_button", - cls: "close-font toast-icon", - handler: () => { - this.destroy(); - }, - height: textHeight, - }); - columnSize.push(""); - } + if (hasCloseIcon()) { + items.push({ + type: "bi.icon_button", + cls: "close-font toast-icon", + handler: () => { + this.destroy(); + }, + height: textHeight, + }); + columnSize.push(""); + } - return { - type: "bi.horizontal", - horizontalAlign: BI.HorizontalAlign.Stretch, - items: items, - hgap: hgap, - vgap: vgap, - innerHgap: innerHgap, - columnSize: columnSize, - }; + return { + type: "bi.horizontal", + horizontalAlign: BI.HorizontalAlign.Stretch, + items, + hgap, + vgap, + innerHgap, + columnSize, + }; } beforeDestroy() { - this.fireEvent(Toast.EVENT_DESTORY); + this.fireEvent(Toast.EVENT_DESTORY); } - } diff --git a/src/base/single/tip/tip.tooltip.js b/src/base/single/tip/tip.tooltip.js index d101bcab8..9c573e9fd 100644 --- a/src/base/single/tip/tip.tooltip.js +++ b/src/base/single/tip/tip.tooltip.js @@ -6,7 +6,7 @@ * @extends BI.Tip */ -import { shortcut } from "../../../core"; +import { shortcut, extend, createWidget, map } from "../../../core"; import { Tip } from "./0.tip"; @shortcut() export class Tooltip extends Tip { @@ -17,77 +17,76 @@ export class Tooltip extends Tip { static xtype = "bi.tooltip"; _defaultConfig() { - return BI.extend(super._defaultConfig(arguments), { - extraCls: "bi-tooltip", - text: "", - level: "success", // success或warning - stopEvent: false, - stopPropagation: false, - textAlign: "left", - }); + return extend(super._defaultConfig(arguments), { + extraCls: "bi-tooltip", + text: "", + level: "success", // success或warning + stopEvent: false, + stopPropagation: false, + textAlign: "left", + }); } render () { - const { level, stopPropagation, stopEvent, text, textAlign } = this.options; - this.element.addClass("tooltip-" + level); - function fn(e) { - stopPropagation && e.stopPropagation(); - stopEvent && e.stopEvent(); - } - this.element.bind({ - click: fn, - mousedown: fn, - mouseup: fn, - mouseover: fn, - mouseenter: fn, - mouseleave: fn, - mousemove: fn, - }); - - const texts = (text + "").split("\n"); - if (texts.length > 1) { - BI.createWidget({ - type: "bi.vertical", - element: this, - hgap: this._const.hgap, - innerVgap: this._const.vgap, - items: BI.map(texts, (i, text) => { - return { - type: "bi.label", - textAlign: textAlign, - whiteSpace: "normal", - text: text, - textHeight: 18, - title: null, - }; - }), - }); - } else { - this.text = BI.createWidget({ - type: "bi.label", - element: this, - textAlign: textAlign, - whiteSpace: "normal", - text: text, - title: null, - textHeight: 18, - hgap: this._const.hgap, - vgap: this._const.vgap, - }); - } - } + const { level, stopPropagation, stopEvent, text, textAlign } = this.options; + this.element.addClass(`tooltip-${level}`); + function fn(e) { + stopPropagation && e.stopPropagation(); + stopEvent && e.stopEvent(); + } + this.element.bind({ + click: fn, + mousedown: fn, + mouseup: fn, + mouseover: fn, + mouseenter: fn, + mouseleave: fn, + mousemove: fn, + }); - setWidth(width) { - this.element.width(BI.pixFormat(width - 2 * this._const.hgap)); - } + const texts = (`${text}`).split("\n"); + if (texts.length > 1) { + createWidget({ + type: "bi.vertical", + element: this, + hgap: this._const.hgap, + innerVgap: this._const.vgap, + items: map(texts, (i, text) => { + return { + type: "bi.label", + textAlign, + whiteSpace: "normal", + text, + textHeight: 18, + title: null, + }; + }), + }); + } else { + this.text = createWidget({ + type: "bi.label", + element: this, + textAlign, + whiteSpace: "normal", + text, + title: null, + textHeight: 18, + hgap: this._const.hgap, + vgap: this._const.vgap, + }); + } + } - setText(text) { - this.text && this.text.setText(text); - } + setWidth(width) { + this.element.width(BI.pixFormat(width - 2 * this._const.hgap)); + } - setLevel(level) { - this.element.removeClass("tooltip-success").removeClass("tooltip-warning"); - this.element.addClass("tooltip-" + level); - } + setText(text) { + this.text && this.text.setText(text); + } + setLevel(level) { + this.element.removeClass("tooltip-success").removeClass("tooltip-warning"); + this.element.addClass(`tooltip-${level}`); + } } diff --git a/src/base/tree/customtree.js b/src/base/tree/customtree.js index c20af875a..606e789ed 100644 --- a/src/base/tree/customtree.js +++ b/src/base/tree/customtree.js @@ -6,9 +6,15 @@ * @class BI.CustomTree * @extends BI.Single */ -BI.CustomTree = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.CustomTree.superclass._defaultConfig.apply(this, arguments), { +import { Widget, shortcut, extend, emptyFn, Tree, each, isNotEmptyArray, deepClone, stripEL, isWidget, + clone, isNotNull, isNull, createWidget, Controller } from "../../core"; +@shortcut() +export class CustomTree extends Widget { + static xtype = "bi.custom_tree"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-custom-tree", expander: { el: {}, @@ -18,7 +24,7 @@ BI.CustomTree = BI.inherit(BI.Widget, { }, items: [], - itemsCreator: BI.emptyFn, + itemsCreator: emptyFn, el: { type: "bi.button_tree", @@ -28,50 +34,49 @@ BI.CustomTree = BI.inherit(BI.Widget, { }], }, }); - }, - - _init: function () { - BI.CustomTree.superclass._init.apply(this, arguments); + } + _init() { + super._init(...arguments); this.initTree(this.options.items); - }, + } - _formatItems: function (nodes) { - var self = this, o = this.options; - nodes = BI.Tree.transformToTreeFormat(nodes); + _formatItems(nodes) { + const { expander, itemsCreator } = this.options; + nodes = Tree.transformToTreeFormat(nodes); - var items = []; - BI.each(nodes, function (i, node) { - if (BI.isNotEmptyArray(node.children) || node.isParent === true) { - var item = BI.extend({ + const items = []; + each(nodes, (i, node) => { + if (isNotEmptyArray(node.children) || node.isParent === true) { + const item = extend({ type: "bi.expander", el: { value: node.value, }, popup: { type: "bi.custom_tree" }, - }, BI.deepClone(o.expander), { + }, deepClone(expander), { id: node.id, pId: node.pId, }); - var el = BI.stripEL(node); - if (!BI.isWidget(el)) { - el = BI.clone(el); + let el = stripEL(node); + if (!isWidget(el)) { + el = clone(el); delete el.children; - BI.extend(item.el, el); + extend(item.el, el); } else { item.el = el; } - item.popup.expander = BI.deepClone(o.expander); + item.popup.expander = deepClone(expander); item.items = item.popup.items = node.children; - item.itemsCreator = item.popup.itemsCreator = function (op) { - if (BI.isNotNull(op.node)) {// 从子节点传过来的itemsCreator直接向上传递 - return o.itemsCreator.apply(self, arguments); + item.itemsCreator = item.popup.itemsCreator = (op, ...arg) => { + if (isNotNull(op.node)) {// 从子节点传过来的itemsCreator直接向上传递 + return itemsCreator(op, ...arg); } - var args = Array.prototype.slice.call(arguments, 0); + const args = Array.prototype.slice.call([op, ...arg], 0); args[0].node = node; - return o.itemsCreator.apply(self, args); + return itemsCreator.apply(this, args); }; - BI.isNull(item.popup.el) && (item.popup.el = BI.deepClone(o.el)); + isNull(item.popup.el) && (item.popup.el = deepClone(this.options.el)); items.push(item); } else { items.push(node); @@ -79,72 +84,68 @@ BI.CustomTree = BI.inherit(BI.Widget, { }); return items; - }, - + } // 构造树结构, - initTree: function (nodes) { - var self = this, o = this.options; - this.tree = BI.createWidget(o.el, { + initTree(nodes) { + const { el, itemsCreator, value } = this.options; + this.tree = createWidget(el, { element: this, items: this._formatItems(nodes), - itemsCreator: function (op, callback) { - o.itemsCreator.apply(this, [op, function (items) { - var args = Array.prototype.slice.call(arguments, 0); - args[0] = self._formatItems(items); - callback.apply(null, args); + itemsCreator: (op, callback) => { + itemsCreator.apply(this, [op, items => { + const args = Array.prototype.slice.call(arguments, 0); + args[0] = this._formatItems(items); + callback(...args); }]); }, - value: o.value, + value, }); - this.tree.on(BI.Controller.EVENT_CHANGE, function (type, val, obj) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.tree.on(Controller.EVENT_CHANGE, (type, val, obj, ...args) => { + this.fireEvent(Controller.EVENT_CHANGE, type, val, obj, ...args); if (type === BI.Events.CLICK) { - self.fireEvent(BI.CustomTree.EVENT_CHANGE, val, obj); + this.fireEvent(CustomTree.EVENT_CHANGE, val, obj); } }); - }, + } // 生成树方法 - stroke: function (nodes) { - this.populate.apply(this, arguments); - }, + stroke(nodes) { + this.populate(...arguments); + } - populate: function (nodes) { - var args = Array.prototype.slice.call(arguments, 0); + populate(nodes) { + const args = Array.prototype.slice.call(arguments, 0); if (arguments.length > 0) { args[0] = this._formatItems(nodes); } - this.tree.populate.apply(this.tree, args); - }, + this.tree.populate(...args); + } - setValue: function (v) { + setValue(v) { this.tree && this.tree.setValue(v); - }, + } - getValue: function () { + getValue() { return this.tree ? this.tree.getValue() : []; - }, + } - getAllButtons: function () { + getAllButtons() { return this.tree ? this.tree.getAllButtons() : []; - }, + } - getAllLeaves: function () { + getAllLeaves() { return this.tree ? this.tree.getAllLeaves() : []; - }, + } - getNodeById: function (id) { + getNodeById(id) { return this.tree && this.tree.getNodeById(id); - }, + } - getNodeByValue: function (id) { + getNodeByValue(id) { return this.tree && this.tree.getNodeByValue(id); - }, + } - empty: function () { + empty() { this.tree.empty(); - }, -}); -BI.CustomTree.EVENT_CHANGE = "EVENT_CHANGE"; - -BI.shortcut("bi.custom_tree", BI.CustomTree); + } +} diff --git a/src/core/index.js b/src/core/index.js index b7cf86b47..ef4944722 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -7,10 +7,10 @@ import * as behavior from "./behavior"; import * as controllers from "./controller"; import * as func from "./func"; import * as structure from "./structure"; -import {StyleLoaderManager} from "./loader/loader.style"; +import { StyleLoaderManager } from "./loader/loader.style"; import "./h"; -import {ShowListener} from "./listener/listener.show"; -import {shortcut} from "./decorator"; +import { ShowListener } from "./listener/listener.show"; +import { shortcut } from "./decorator"; export * from "./2.base"; export * from "./3.ob"; From 7deb6554b04ef6d626f99dd255c7b7ad1368383c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Fri, 6 Jan 2023 16:17:24 +0800 Subject: [PATCH 046/300] =?UTF-8?q?KERNEL-13972=20refactor:=20import?= =?UTF-8?q?=E4=B8=8D=E6=8D=A2=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/collection/collection.js | 3 +-- src/base/grid/grid.js | 3 +-- src/base/tree/customtree.js | 3 +-- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/base/collection/collection.js b/src/base/collection/collection.js index 2b57f9de3..0cd227204 100644 --- a/src/base/collection/collection.js +++ b/src/base/collection/collection.js @@ -5,8 +5,7 @@ * @class BI.CollectionView * @extends BI.Widget */ -import { Widget, shortcut, extend, emptyFn, debounce, _lazyCreateWidget, isFunction, SectionManager, - isNull, each, clamp, toArray, invert, min, max, nextTick } from "../../core"; +import { Widget, shortcut, extend, emptyFn, debounce, _lazyCreateWidget, isFunction, SectionManager, isNull, each, clamp, toArray, invert, min, max, nextTick } from "../../core"; @shortcut() export class CollectionView extends Widget { _defaultConfig() { diff --git a/src/base/grid/grid.js b/src/base/grid/grid.js index 150723808..6e65a52e0 100644 --- a/src/base/grid/grid.js +++ b/src/base/grid/grid.js @@ -5,8 +5,7 @@ * @class BI.GridView * @extends BI.Widget */ -import { Widget, shortcut, extend, emptyFn, debounce, _lazyCreateWidget, - isFunction, each, isNumber, ScalingCellSizeAndPositionManager, clamp, isEmpty, nextTick } from "../../core"; +import { Widget, shortcut, extend, emptyFn, debounce, _lazyCreateWidget, isFunction, each, isNumber, ScalingCellSizeAndPositionManager, clamp, isEmpty, nextTick } from "../../core"; @shortcut() export class GridView extends Widget { _defaultConfig() { diff --git a/src/base/tree/customtree.js b/src/base/tree/customtree.js index 606e789ed..2e231cd4a 100644 --- a/src/base/tree/customtree.js +++ b/src/base/tree/customtree.js @@ -6,8 +6,7 @@ * @class BI.CustomTree * @extends BI.Single */ -import { Widget, shortcut, extend, emptyFn, Tree, each, isNotEmptyArray, deepClone, stripEL, isWidget, - clone, isNotNull, isNull, createWidget, Controller } from "../../core"; +import { Widget, shortcut, extend, emptyFn, Tree, each, isNotEmptyArray, deepClone, stripEL, isWidget, clone, isNotNull, isNull, createWidget, Controller } from "../../core"; @shortcut() export class CustomTree extends Widget { static xtype = "bi.custom_tree"; From 1530f78a1e405b926e652da2eead493792b99e22 Mon Sep 17 00:00:00 2001 From: impact Date: Fri, 6 Jan 2023 16:15:28 +0800 Subject: [PATCH 047/300] =?UTF-8?q?KERNEL-14020=20refactor:=20base/single?= =?UTF-8?q?=E4=B8=AD=E7=9A=84iframe,image,instruction,link,trigger=20ES6?= =?UTF-8?q?=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/single/0.single.js | 66 +++++++-------- src/base/single/button/node/texticonnode.js | 3 +- src/base/single/editor/editor.js | 4 +- src/base/single/iframe/iframe.js | 62 +++++++------- src/base/single/img/img.js | 42 +++++----- src/base/single/index.js | 5 ++ src/base/single/instruction/instruction.js | 89 +++++++++++---------- src/base/single/label/html.label.js | 2 +- src/base/single/label/label.js | 2 +- src/base/single/link/link.js | 44 +++++----- src/base/single/text.pure.js | 2 +- src/base/single/trigger/trigger.js | 23 +++--- 12 files changed, 183 insertions(+), 161 deletions(-) diff --git a/src/base/single/0.single.js b/src/base/single/0.single.js index cd6ec00b0..cdfaaaca4 100644 --- a/src/base/single/0.single.js +++ b/src/base/single/0.single.js @@ -5,12 +5,12 @@ * 2、title的控制 * 3、文字超过边界显示3个点 * 4、cursor默认pointor - * @class BI.Single - * @extends BI.Widget + * @class Single + * @extends Widget * @abstract */ -import { Widget, shortcut } from "../../core"; +import { Widget, shortcut, Actions, extend, isKey, isNotNull, isFunction, isPlainObject, isNull, delay } from "../../core"; import { Tooltips } from "../0.base"; @shortcut() @@ -18,9 +18,9 @@ export class Single extends Widget { static xtype = "bi.single"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); - return BI.extend(conf, { + return extend(conf, { readonly: false, title: null, warningTitle: null, // deprecated @@ -36,12 +36,12 @@ export class Single extends Widget { const title = this.getTitle(); const showToolTip = (tooltipOpt) => { - if (BI.isKey(tooltipOpt.text) && !Tooltips.has(this.getName())) { + if (isKey(tooltipOpt.text) && !Tooltips.has(this.getName())) { Tooltips.show(e, this.getName(), tooltipOpt, this, opt); if (action) { - BI.Actions.runAction(action, "hover", this.options, this); + Actions.runAction(action, "hover", this.options, this); } - BI.Actions.runGlobalAction("hover", this.options, this); + Actions.runGlobalAction("hover", this.options, this); } } @@ -59,7 +59,7 @@ export class Single extends Widget { _hideTooltip() { const tooltip = Tooltips.get(this.getName()); - if (BI.isNotNull(tooltip)) { + if (isNotNull(tooltip)) { tooltip.element.fadeOut(200, () => { Tooltips.remove(this.getName()); }); @@ -68,7 +68,7 @@ export class Single extends Widget { _init() { const { value } = this.options; - this.options.value = BI.isFunction(value) ? this.__watch(value, (context, newValue) => { + this.options.value = isFunction(value) ? this.__watch(value, (context, newValue) => { this.setValue(newValue); }) : value; super._init(arguments); @@ -76,8 +76,8 @@ export class Single extends Widget { _mounted() { const { enableHover, title, warningTitle, belowMouse, container } = this.options; - if (enableHover || BI.isKey(title) || BI.isKey(warningTitle) - || BI.isFunction(title) || BI.isFunction(warningTitle)) { + if (enableHover || isKey(title) || isKey(warningTitle) + || isFunction(title) || isFunction(warningTitle)) { this.enableHover({ belowMouse, container, @@ -86,11 +86,11 @@ export class Single extends Widget { } _clearTimeOut() { - if (BI.isNotNull(this.showTimeout)) { + if (isNotNull(this.showTimeout)) { clearTimeout(this.showTimeout); this.showTimeout = null; } - if (BI.isNotNull(this.hideTimeout)) { + if (isNotNull(this.hideTimeout)) { clearTimeout(this.hideTimeout); this.hideTimeout = null; } @@ -99,12 +99,12 @@ export class Single extends Widget { _getTooltipOptions(title) { const { tipType } = this.options; let tooltipOpt = {}; - if (BI.isPlainObject(title)) { + if (isPlainObject(title)) { tooltipOpt = title; } else { tooltipOpt.level = this.getTipType() || "success"; // 由于以前的用法,存在大量disabled:true搭配warningTitle的情况,所以这里做一个兼容,disabled:true的情况下,依然优先显示warningTitle,避免只设置了warningTitle而没有设置title的情况 - if (BI.isNull(tipType) && !this.isEnabled()) { + if (isNull(tipType) && !this.isEnabled()) { tooltipOpt.text = (this.getWarningTitle() || title); } else { tooltipOpt.text = tooltipOpt.level === "success" ? title : (this.getWarningTitle() || title); @@ -120,17 +120,17 @@ export class Single extends Widget { this.element.unbind("mouseenter.title").on("mouseenter.title", (e) => { this._e = e; this.mouseOver = true; - if (this.getTipType() === "warning" || (BI.isKey(this.getWarningTitle()) && !this.isEnabled())) { + if (this.getTipType() === "warning" || (isKey(this.getWarningTitle()) && !this.isEnabled())) { delayingTooltips = this.getName(); - this.showTimeout = BI.delay(() => { - if (BI.isNotNull(this.showTimeout) && delayingTooltips === this.getName()) { + this.showTimeout = delay(() => { + if (isNotNull(this.showTimeout) && delayingTooltips === this.getName()) { this._showToolTip(this._e || e, opt); } }, 200); } else if (this.getTipType() === "success" || this.isEnabled()) { delayingTooltips = this.getName(); - this.showTimeout = BI.delay(() => { - if (BI.isNotNull(this.showTimeout) && delayingTooltips === this.getName()) { + this.showTimeout = delay(() => { + if (isNotNull(this.showTimeout) && delayingTooltips === this.getName()) { this._showToolTip(this._e || e, opt); } }, 500); @@ -138,22 +138,22 @@ export class Single extends Widget { }); this.element.unbind("mousemove.title").on("mousemove.title", (e) => { this._e = e; - if (BI.isNotNull(this.showTimeout)) { + if (isNotNull(this.showTimeout)) { clearTimeout(this.showTimeout); this.showTimeout = null; } - if (BI.isNull(this.hideTimeout)) { - this.hideTimeout = BI.delay(() => { - if (BI.isNotNull(this.hideTimeout)) { + if (isNull(this.hideTimeout)) { + this.hideTimeout = delay(() => { + if (isNotNull(this.hideTimeout)) { this._hideTooltip(); } }, 500); } - this.showTimeout = BI.delay(() => { + this.showTimeout = delay(() => { // DEC-5321 IE下如果回调已经进入事件队列,clearTimeout将不会起作用 - if (BI.isNotNull(this.showTimeout)) { - if (BI.isNotNull(this.hideTimeout)) { + if (isNotNull(this.showTimeout)) { + if (isNotNull(this.hideTimeout)) { clearTimeout(this.hideTimeout); this.hideTimeout = null; } @@ -188,7 +188,7 @@ export class Single extends Widget { // opt: {container: '', belowMouse: false} setTitle(title, opt) { this.options.title = title; - if (BI.isKey(title) || BI.isFunction(title)) { + if (isKey(title) || isFunction(title)) { this.enableHover(opt); } else { this.disabledHover(); @@ -197,7 +197,7 @@ export class Single extends Widget { setWarningTitle(title, opt) { this.options.warningTitle = title; - if (BI.isKey(title) || BI.isFunction(title)) { + if (isKey(title) || isFunction(title)) { this.enableHover(opt); } else { this.disabledHover(); @@ -218,7 +218,7 @@ export class Single extends Widget { getTitle() { const title = this.options.title; - if (BI.isFunction(title)) { + if (isFunction(title)) { return title(); } @@ -227,7 +227,7 @@ export class Single extends Widget { getWarningTitle() { const title = this.options.warningTitle; - if (BI.isFunction(title)) { + if (isFunction(title)) { return title(); } @@ -246,7 +246,7 @@ export class Single extends Widget { } _destroyed() { - if (BI.isNotNull(this.showTimeout)) { + if (isNotNull(this.showTimeout)) { clearTimeout(this.showTimeout); this.showTimeout = null; } diff --git a/src/base/single/button/node/texticonnode.js b/src/base/single/button/node/texticonnode.js index e4ca824a1..9a3af8e81 100644 --- a/src/base/single/button/node/texticonnode.js +++ b/src/base/single/button/node/texticonnode.js @@ -7,7 +7,8 @@ import { extend, shortcut } from "../../../../core"; * @extends NodeButton */ @shortcut() -export default class TextIconNode extends NodeButton { +export class TextIconNode extends NodeButton { + static EVENT_CHANGE = "EVENT_CHANGE"; static xtype = "bi.text_icon_node"; diff --git a/src/base/single/editor/editor.js b/src/base/single/editor/editor.js index 0cf075a39..790ed59d8 100644 --- a/src/base/single/editor/editor.js +++ b/src/base/single/editor/editor.js @@ -206,7 +206,7 @@ export class Editor extends Single { _checkToolTip() { const { errorText } = this.options; if (isFunction(errorText)) { - errorText = errorText(this.editor.getValue()); + this.options.errorText = errorText(this.editor.getValue()); } if (isKey(errorText)) { if (!this.isEnabled() || this.isValid() || Bubbles.has(this.getName())) { @@ -298,7 +298,7 @@ export class Editor extends Single { _setErrorVisible(b) { const { errorText, autoTrim, simple } = this.options; if (isFunction(errorText)) { - errorText = errorText(autoTrim ? trim(this.editor.getValue()) : this.editor.getValue()); + this.options.errorText = errorText(autoTrim ? trim(this.editor.getValue()) : this.editor.getValue()); } if (!this.disabledError && isKey(errorText)) { Bubbles[b ? "show" : "hide"](this.getName(), errorText, this, { diff --git a/src/base/single/iframe/iframe.js b/src/base/single/iframe/iframe.js index e2df49e25..15f4d0d2a 100644 --- a/src/base/single/iframe/iframe.js +++ b/src/base/single/iframe/iframe.js @@ -1,14 +1,19 @@ /** - * @class BI.Iframe - * @extends BI.Single + * @class Iframe + * @extends Single * @abstract * Created by GameJian on 2016/3/2. */ -BI.Iframe = BI.inherit(BI.Single, { - _defaultConfig: function (config) { - var conf = BI.Iframe.superclass._defaultConfig.apply(this, arguments); +import { shortcut, extend } from "../../../core"; +import { Single } from "../0.single"; - return BI.extend(conf, { +@shortcut() +export class Iframe extends Single { + static xtype = "bi.iframe"; + + _defaultConfig(config) { + const conf = super._defaultConfig(...arguments); + return extend(conf, { tagName: "iframe", baseCls: (conf.baseCls || "") + " bi-iframe", src: "", @@ -17,42 +22,39 @@ BI.Iframe = BI.inherit(BI.Single, { width: "100%", height: "100%", }); - }, + } - render: function () { - var self = this; - this.element.on("load", function () { - self.fireEvent("EVENT_LOADED"); + render() { + this.element.on("load", () => { + this.fireEvent("EVENT_LOADED"); }); - }, + } - _initProps: function () { - BI.Iframe.superclass._initProps.apply(this, arguments); - var o = this.options; - this.options.attributes = BI.extend({ + _initProps() { + super._initProps(...arguments) + const { src, name } = this.options; + this.options.attributes = extend({ frameborder: 0, - src: o.src, - name: o.name, + src, + name, }, this.options.attributes); - }, + } - setSrc: function (src) { + setSrc(src) { this.options.src = src; this.element.attr("src", src); - }, + } - getSrc: function () { + getSrc() { return this.options.src; - }, + } - setName: function (name) { + setName(name) { this.options.name = name; this.element.attr("name", name); - }, + } - getName: function () { + getName() { return this.options.name; - }, -}); - -BI.shortcut("bi.iframe", BI.Iframe); + } +} diff --git a/src/base/single/img/img.js b/src/base/single/img/img.js index ca715fb79..92475ea8c 100644 --- a/src/base/single/img/img.js +++ b/src/base/single/img/img.js @@ -6,11 +6,17 @@ * @extends BI.Single * @abstract */ -BI.Img = BI.inherit(BI.Single, { - _defaultConfig: function (config) { - var conf = BI.Img.superclass._defaultConfig.apply(this, arguments); +import { shortcut, extend } from "../../../core"; +import { Single } from "../0.single"; - return BI.extend(conf, { +@shortcut() +export class Img extends Single { + static xtype = "bi.img"; + + _defaultConfig(config) { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { tagName: "img", baseCls: (conf.baseCls || "") + " bi-img display-block", src: "", @@ -18,24 +24,22 @@ BI.Img = BI.inherit(BI.Single, { width: "100%", height: "100%", }); - }, + } - _initProps: function () { - BI.Img.superclass._initProps.apply(this, arguments); - var o = this.options; - this.options.attributes = BI.extend({ - src: o.src, + _initProps() { + super._initProps(...arguments) + const { src } = this.options; + this.options.attributes = extend({ + src, }, this.options.attributes); - }, - - setSrc: function (src) { + } + + setSrc(src) { this.options.src = src; this.element.attr("src", src); - }, + } - getSrc: function () { + getSrc() { return this.options.src; - }, -}); - -BI.shortcut("bi.img", BI.Img); + } +} diff --git a/src/base/single/index.js b/src/base/single/index.js index 8fe2e22cc..8806e29dd 100644 --- a/src/base/single/index.js +++ b/src/base/single/index.js @@ -4,6 +4,11 @@ export { PureText } from "./text.pure"; export { Icon } from "./icon/icon"; export { Html } from "./html/html"; export { A } from "./a/a"; +export { Iframe } from "./iframe/iframe"; +export { Link } from "./link/link"; +export { Instruction } from "./instruction/instruction"; +export { Img } from "./img/img"; +export { Trigger } from "./trigger/trigger"; export * from "./tip"; export * from "./label"; export * from "./input"; diff --git a/src/base/single/instruction/instruction.js b/src/base/single/instruction/instruction.js index 71a61a6f3..eb0d8dacd 100644 --- a/src/base/single/instruction/instruction.js +++ b/src/base/single/instruction/instruction.js @@ -1,7 +1,12 @@ -BI.Instruction = BI.inherit(BI.Widget, { - _defaultConfig: function () { - var conf = BI.Link.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { +import { shortcut, Widget, extend } from "../../../core"; + +@shortcut() +export class Instruction extends Widget { + static xtype = "bi.instruction"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + return extend(conf, { baseCls: (conf.baseCls || "") + " bi-instruction", height: 20, level: "error", @@ -9,68 +14,66 @@ BI.Instruction = BI.inherit(BI.Widget, { whiteSpace: "nowrap", hgap: 5 }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const { level, textAlign, whiteSpace, height, hgap, rgap, lgap, vgap, text, keyword, value, py } = this.options; return { type: "bi.label", - ref: function (_ref) { - self.text = _ref; + ref: (_ref) => { + this.text = _ref; }, - cls: "instruction-" + o.level, - textAlign: o.textAlign, - whiteSpace: o.whiteSpace, - textHeight: o.height, - height: o.height, - hgap: o.hgap, - rgap: o.rgap, - lgap: o.lgap, - vgap: o.vgap, - text: o.text, - keyword: o.keyword, - value: o.value, - py: o.py + cls: "instruction-" + level, + textAlign, + whiteSpace, + textHeight: height, + height, + hgap, + rgap, + lgap, + vgap, + text, + keyword, + value, + py }; - }, + } - doRedMark: function () { + doRedMark() { this.text.doRedMark.apply(this.text, arguments); - }, + } - unRedMark: function () { + unRedMark() { this.text.unRedMark.apply(this.text, arguments); - }, + } - doHighLight: function () { + doHighLight() { this.text.doHighLight.apply(this.text, arguments); - }, + } - unHighLight: function () { + unHighLight() { this.text.unHighLight.apply(this.text, arguments); - }, + } - setText: function (v) { + setText(v) { this.options.text = v; this.text.setText(v); - }, + } - getText: function () { + getText() { return this.options.text; - }, + } - setStyle: function (css) { + setStyle(css) { this.text.setStyle(css); - }, + } - setValue: function (v) { + setValue(v) { this.text.setValue(v); - }, + } - getValue: function () { + getValue() { this.text.getValue(); } -}); - -BI.shortcut("bi.instruction", BI.Instruction); +} diff --git a/src/base/single/label/html.label.js b/src/base/single/label/html.label.js index 0fa4f0d14..d4a0af70b 100644 --- a/src/base/single/label/html.label.js +++ b/src/base/single/label/html.label.js @@ -2,7 +2,7 @@ * Created by GUY on 2015/6/26. */ import { shortcut } from "../../../core"; -import { AbstractLabel } from "./abstract.label" +import { AbstractLabel } from "./abstract.label"; @shortcut() export class HtmlLabel extends AbstractLabel { diff --git a/src/base/single/label/label.js b/src/base/single/label/label.js index d5924b63b..e745c9965 100644 --- a/src/base/single/label/label.js +++ b/src/base/single/label/label.js @@ -2,7 +2,7 @@ * Created by GUY on 2015/6/26. */ import { shortcut, isFunction, isNotNull } from "../../../core"; -import { AbstractLabel } from "./abstract.label" +import { AbstractLabel } from "./abstract.label"; @shortcut() export class Label extends AbstractLabel { diff --git a/src/base/single/link/link.js b/src/base/single/link/link.js index 176389af5..89fa1a57f 100644 --- a/src/base/single/link/link.js +++ b/src/base/single/link/link.js @@ -3,34 +3,38 @@ * @class BI.Link * @extends BI.Text */ -BI.Link = BI.inherit(BI.Label, { - _defaultConfig: function () { - var conf = BI.Link.superclass._defaultConfig.apply(this, arguments); +import { shortcut, extend } from "../../../core"; +import { Label } from "../label/label"; - return BI.extend(conf, { +@shortcut() +export class Link extends Label { + static xtype = "bi.link"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { baseCls: (conf.baseCls || "") + " bi-link display-block", tagName: "a", href: "", target: "_blank", }); - }, + } - _createJson: function () { - var o = this.options; + _createJson() { + const { textAlign, whiteSpace, textHeight, text, keyword, value, py, href, target } = this.options; return { type: "bi.a", - textAlign: o.textAlign, - whiteSpace: o.whiteSpace, - lineHeight: o.textHeight, - text: o.text, - keyword: o.keyword, - value: o.value, - py: o.py, - href: o.href, - target: o.target, + textAlign, + whiteSpace, + lineHeight: textHeight, + text, + keyword, + value, + py, + href, + target, }; - }, -}); - -BI.shortcut("bi.link", BI.Link); + } +} diff --git a/src/base/single/text.pure.js b/src/base/single/text.pure.js index b6207c693..1de22cca9 100644 --- a/src/base/single/text.pure.js +++ b/src/base/single/text.pure.js @@ -26,7 +26,7 @@ export class PureText extends Widget { _getShowText() { const { text: optionsText, value } = this.options; - const text = isFunction(optionsText) ? optionsText() : optionsText; + let text = isFunction(optionsText) ? optionsText() : optionsText; text = isKey(text) ? text : value; if (!isKey(text)) { return ""; diff --git a/src/base/single/trigger/trigger.js b/src/base/single/trigger/trigger.js index 486ae898f..3755fc8ae 100644 --- a/src/base/single/trigger/trigger.js +++ b/src/base/single/trigger/trigger.js @@ -4,21 +4,24 @@ * @extends BI.Single * @abstract */ -BI.Trigger = BI.inherit(BI.Single, { - _defaultConfig: function () { - var conf = BI.Trigger.superclass._defaultConfig.apply(this, arguments); +import { extend } from "../../../core"; +import { Single } from "../0.single"; - return BI.extend(conf, { +export class Trigger extends Single { + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { _baseCls: (conf._baseCls || "") + " bi-trigger cursor-pointer", height: 24, }); - }, + } - setKey: function () { + setKey() { - }, + } - getKey: function () { + getKey() { - }, -}); + } +} From 1d97dd10cc5371d5c4d4836bda920d65faa0a9f0 Mon Sep 17 00:00:00 2001 From: Treecat Date: Fri, 6 Jan 2023 17:06:19 +0800 Subject: [PATCH 048/300] KERNEL-14022 refact: textitem --- src/base/single/button/listitem/textitem.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/base/single/button/listitem/textitem.js b/src/base/single/button/listitem/textitem.js index 698843370..29546ad02 100644 --- a/src/base/single/button/listitem/textitem.js +++ b/src/base/single/button/listitem/textitem.js @@ -9,7 +9,7 @@ import { extend, shortcut, createWidget } from "../../../../core"; * @class TextItem * @extends BasicButton */ -@shortcut +@shortcut() export class TextItem extends BasicButton { static xtype = "bi.text_item"; static EVENT_CHANGE = "EVENT_CHANGE"; From ad988917c1e9a61c17bb434ba83ca53062b51334 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Sun, 8 Jan 2023 23:25:26 +0800 Subject: [PATCH 049/300] =?UTF-8?q?=E6=97=A0JIRA=E4=BB=BB=E5=8A=A1=20refac?= =?UTF-8?q?tor:=20=E6=89=B9=E9=87=8F=E6=9B=BF=E6=8D=A2=E4=B8=80=E4=B8=8B?= =?UTF-8?q?=E9=94=99=E8=AF=AF=E5=86=99=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/combination/bubble.js | 2 +- src/base/combination/combo.js | 2 +- src/base/combination/expander.js | 2 +- src/base/combination/group.button.js | 2 +- src/base/combination/group.combo.js | 2 +- src/base/combination/group.virtual.js | 2 +- src/base/combination/loader.js | 2 +- src/base/combination/navigation.js | 2 +- src/base/combination/searcher.js | 2 +- src/base/combination/switcher.js | 2 +- src/base/combination/tab.js | 2 +- src/base/combination/tree.button.js | 2 +- src/base/layer/layer.popover.js | 2 +- src/base/layer/layer.popup.js | 2 +- src/base/layer/layer.searcher.js | 2 +- src/base/single/0.single.js | 2 +- src/base/single/a/a.js | 2 +- src/base/single/button/button.basic.js | 2 +- src/base/single/button/button.node.js | 2 +- src/base/single/button/buttons/button.icon.js | 2 +- src/base/single/button/buttons/button.image.js | 2 +- src/base/single/button/buttons/button.text.js | 2 +- src/base/single/button/listitem/blankiconicontextitem.js | 2 +- src/base/single/button/listitem/blankicontexticonitem.js | 2 +- src/base/single/button/listitem/blankicontextitem.js | 2 +- src/base/single/button/listitem/icontexticonitem.js | 2 +- src/base/single/button/listitem/icontextitem.js | 2 +- src/base/single/button/listitem/texticonitem.js | 2 +- src/base/single/button/listitem/textitem.js | 2 +- src/base/single/button/node/icontexticonnode.js | 2 +- src/base/single/button/node/icontextnode.js | 2 +- src/base/single/button/node/texticonnode.js | 2 +- src/base/single/button/node/textnode.js | 2 +- src/base/single/editor/editor.js | 2 +- src/base/single/editor/editor.multifile.js | 2 +- src/base/single/icon/icon.js | 2 +- src/base/single/input/checkbox/checkbox.image.js | 2 +- src/base/single/input/file.js | 2 +- src/base/single/input/input.js | 2 +- src/base/single/input/radio/radio.image.js | 2 +- src/base/single/label/abstract.label.js | 2 +- src/base/single/tip/0.tip.js | 2 +- src/base/single/tip/tip.toast.js | 2 +- src/base/single/tip/tip.tooltip.js | 2 +- src/case/button/icon/icon.change.js | 2 +- src/case/button/icon/icon.trigger.js | 2 +- src/case/button/icon/iconhalf/icon.half.image.js | 2 +- src/case/button/icon/iconhalf/icon.half.js | 2 +- src/case/button/item.multiselect.js | 2 +- src/case/button/item.singleselect.icontext.js | 2 +- src/case/button/item.singleselect.js | 2 +- src/case/button/item.singleselect.radio.js | 2 +- src/case/button/node/node.arrow.js | 2 +- src/case/button/node/node.first.plus.js | 2 +- src/case/button/node/node.icon.arrow.js | 2 +- src/case/button/node/node.last.plus.js | 2 +- src/case/button/node/node.mid.plus.js | 2 +- src/case/button/node/node.multilayer.icon.arrow.js | 2 +- src/case/button/node/node.plus.js | 2 +- src/case/button/node/siwtcher.tree.node.js | 2 +- src/case/button/treeitem/item.first.treeleaf.js | 2 +- src/case/button/treeitem/item.icon.treeleaf.js | 2 +- src/case/button/treeitem/item.last.treeleaf.js | 2 +- src/case/button/treeitem/item.mid.treeleaf.js | 2 +- src/case/button/treeitem/item.multilayer.icon.treeleaf.js | 2 +- src/case/button/treeitem/treeitem.js | 2 +- src/core/behavior/0.behavior.js | 2 +- src/core/loader/loader.style.js | 2 +- 68 files changed, 68 insertions(+), 68 deletions(-) diff --git a/src/base/combination/bubble.js b/src/base/combination/bubble.js index 49bc6d176..143b73fe4 100644 --- a/src/base/combination/bubble.js +++ b/src/base/combination/bubble.js @@ -20,7 +20,7 @@ export class Bubble extends Widget { static EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: (conf.baseCls || "") + " bi-popper", diff --git a/src/base/combination/combo.js b/src/base/combination/combo.js index 6f16862e2..16d3f6468 100644 --- a/src/base/combination/combo.js +++ b/src/base/combination/combo.js @@ -26,7 +26,7 @@ export class Combo extends Bubble { static EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: (conf.baseCls || "") + " bi-combo" + (BI.isIE() ? " hack" : ""), diff --git a/src/base/combination/expander.js b/src/base/combination/expander.js index fe04aec7a..8f7158470 100644 --- a/src/base/combination/expander.js +++ b/src/base/combination/expander.js @@ -24,7 +24,7 @@ export class Expander extends Widget { static EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-expander", trigger: "click", toggle: true, diff --git a/src/base/combination/group.button.js b/src/base/combination/group.button.js index 57c2e47e2..01b54e98c 100644 --- a/src/base/combination/group.button.js +++ b/src/base/combination/group.button.js @@ -12,7 +12,7 @@ export class ButtonGroup extends Widget { static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-button-group", behaviors: {}, items: [], diff --git a/src/base/combination/group.combo.js b/src/base/combination/group.combo.js index e2c0d1f6f..0fc637511 100644 --- a/src/base/combination/group.combo.js +++ b/src/base/combination/group.combo.js @@ -11,7 +11,7 @@ export class ComboGroup extends Widget { static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-combo-group bi-list-item", // 以下这些属性对每一个combo都是公用的 diff --git a/src/base/combination/group.virtual.js b/src/base/combination/group.virtual.js index a9f069ea7..a7e87c92c 100644 --- a/src/base/combination/group.virtual.js +++ b/src/base/combination/group.virtual.js @@ -7,7 +7,7 @@ export class VirtualGroup extends Widget { static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-virtual-group", items: [], layouts: [{ diff --git a/src/base/combination/loader.js b/src/base/combination/loader.js index 744f2bb12..7cabb8f61 100644 --- a/src/base/combination/loader.js +++ b/src/base/combination/loader.js @@ -14,7 +14,7 @@ export class Loader extends Widget { static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-loader", direction: "top", diff --git a/src/base/combination/navigation.js b/src/base/combination/navigation.js index 671459d5c..da12b1174 100644 --- a/src/base/combination/navigation.js +++ b/src/base/combination/navigation.js @@ -10,7 +10,7 @@ export class Navigation extends Widget { static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { direction: "bottom", // top, bottom, left, right, custom logic: { dynamic: false, diff --git a/src/base/combination/searcher.js b/src/base/combination/searcher.js index acf316e76..dcf482527 100644 --- a/src/base/combination/searcher.js +++ b/src/base/combination/searcher.js @@ -21,7 +21,7 @@ export class Searcher extends Widget { static EVENT_AFTER_INIT = "EVENT_AFTER_INIT"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-searcher", lgap: 0, rgap: 0, diff --git a/src/base/combination/switcher.js b/src/base/combination/switcher.js index b19f75404..7df64dff6 100644 --- a/src/base/combination/switcher.js +++ b/src/base/combination/switcher.js @@ -25,7 +25,7 @@ export class Switcher extends Widget { static EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-switcher", direction: BI.Direction.Top, trigger: "click", diff --git a/src/base/combination/tab.js b/src/base/combination/tab.js index f7a7e2038..d9d5a5cc7 100644 --- a/src/base/combination/tab.js +++ b/src/base/combination/tab.js @@ -10,7 +10,7 @@ export class Tab extends Widget { static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-tab", direction: "top", // top, bottom, left, right, custom single: false, // 是不是单页面 diff --git a/src/base/combination/tree.button.js b/src/base/combination/tree.button.js index be25898f9..79e4b4ed5 100644 --- a/src/base/combination/tree.button.js +++ b/src/base/combination/tree.button.js @@ -13,7 +13,7 @@ export class ButtonTree extends ButtonGroup { static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-button-tree", }); } diff --git a/src/base/layer/layer.popover.js b/src/base/layer/layer.popover.js index 5462b227f..3521af648 100644 --- a/src/base/layer/layer.popover.js +++ b/src/base/layer/layer.popover.js @@ -243,7 +243,7 @@ export class BarPopover extends Popover { static xtype = "bi.bar_popover"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { btns: [BI.i18nText("BI-Basic_OK"), BI.i18nText("BI-Basic_Cancel")], }); } diff --git a/src/base/layer/layer.popup.js b/src/base/layer/layer.popup.js index 359ab2df0..6151faec0 100644 --- a/src/base/layer/layer.popup.js +++ b/src/base/layer/layer.popup.js @@ -15,7 +15,7 @@ export class PopupView extends Widget { static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig(props) { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { _baseCls: `bi-popup-view${props.primary ? " bi-primary" : ""}`, // 品牌色 primary: false, diff --git a/src/base/layer/layer.searcher.js b/src/base/layer/layer.searcher.js index 2ef9d1cbb..cf9d961db 100644 --- a/src/base/layer/layer.searcher.js +++ b/src/base/layer/layer.searcher.js @@ -15,7 +15,7 @@ export class SearcherView extends Pane { static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-searcher-view bi-card`, diff --git a/src/base/single/0.single.js b/src/base/single/0.single.js index cd6ec00b0..20661bf53 100644 --- a/src/base/single/0.single.js +++ b/src/base/single/0.single.js @@ -18,7 +18,7 @@ export class Single extends Widget { static xtype = "bi.single"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return BI.extend(conf, { readonly: false, diff --git a/src/base/single/a/a.js b/src/base/single/a/a.js index 45a9c7846..41edbf3fb 100644 --- a/src/base/single/a/a.js +++ b/src/base/single/a/a.js @@ -13,7 +13,7 @@ export class A extends Text { static xtype = "bi.a"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-a display-block`, diff --git a/src/base/single/button/button.basic.js b/src/base/single/button/button.basic.js index ce2d1dfa8..c5d067b68 100644 --- a/src/base/single/button/button.basic.js +++ b/src/base/single/button/button.basic.js @@ -15,7 +15,7 @@ export class BasicButton extends Single { static EVENT_CHANGE = "BasicButton.EVENT_CHANGE"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { _baseCls: `${conf._baseCls || ""} bi-basic-button${conf.invalid ? "" : " cursor-pointer"}${(BI.isIE() && BI.getIEVersion() < 10) ? " hack" : ""}`, diff --git a/src/base/single/button/button.node.js b/src/base/single/button/button.node.js index d48bab2fb..4684d0c72 100644 --- a/src/base/single/button/button.node.js +++ b/src/base/single/button/button.node.js @@ -14,7 +14,7 @@ export class NodeButton extends BasicButton { static xtype = "bi.node_button"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { _baseCls: `${conf._baseCls || ""} bi-node`, diff --git a/src/base/single/button/buttons/button.icon.js b/src/base/single/button/buttons/button.icon.js index 5f3100a9b..edc65fc28 100644 --- a/src/base/single/button/buttons/button.icon.js +++ b/src/base/single/button/buttons/button.icon.js @@ -12,7 +12,7 @@ export class IconButton extends BasicButton { static xtype = "bi.icon_button"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { _baseCls: `${conf._baseCls || ""} bi-icon-button horizon-center`, diff --git a/src/base/single/button/buttons/button.image.js b/src/base/single/button/buttons/button.image.js index e8fcf6ede..9920ea784 100644 --- a/src/base/single/button/buttons/button.image.js +++ b/src/base/single/button/buttons/button.image.js @@ -15,7 +15,7 @@ export class ImageButton extends BasicButton { static xtype = "bi.image_button"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-image-button`, diff --git a/src/base/single/button/buttons/button.text.js b/src/base/single/button/buttons/button.text.js index 107a8ba38..6f3a2d2ea 100644 --- a/src/base/single/button/buttons/button.text.js +++ b/src/base/single/button/buttons/button.text.js @@ -14,7 +14,7 @@ export class TextButton extends BasicButton { static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-text-button`, diff --git a/src/base/single/button/listitem/blankiconicontextitem.js b/src/base/single/button/listitem/blankiconicontextitem.js index d57267110..e0dd3ac0f 100644 --- a/src/base/single/button/listitem/blankiconicontextitem.js +++ b/src/base/single/button/listitem/blankiconicontextitem.js @@ -14,7 +14,7 @@ export class BlankIconIconTextItem extends BasicButton { static xtype = "bi.blank_icon_icon_text_item"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-blank-icon-icon-text-item`, diff --git a/src/base/single/button/listitem/blankicontexticonitem.js b/src/base/single/button/listitem/blankicontexticonitem.js index 1880cdcb3..11ff0a64d 100644 --- a/src/base/single/button/listitem/blankicontexticonitem.js +++ b/src/base/single/button/listitem/blankicontexticonitem.js @@ -15,7 +15,7 @@ export class BlankIconTextIconItem extends BasicButton { static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-blank-icon-text-icon-item`, diff --git a/src/base/single/button/listitem/blankicontextitem.js b/src/base/single/button/listitem/blankicontextitem.js index 30be259d2..c80c8a2e2 100644 --- a/src/base/single/button/listitem/blankicontextitem.js +++ b/src/base/single/button/listitem/blankicontextitem.js @@ -14,7 +14,7 @@ export class BlankIconTextItem extends BasicButton { static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-blank-icon-text-item`, diff --git a/src/base/single/button/listitem/icontexticonitem.js b/src/base/single/button/listitem/icontexticonitem.js index 3d95eac4e..2727191c1 100644 --- a/src/base/single/button/listitem/icontexticonitem.js +++ b/src/base/single/button/listitem/icontexticonitem.js @@ -16,7 +16,7 @@ export class IconTextIconItem extends BasicButton { static xtype = "bi.icon_text_icon_item"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-icon-text-icon-item`, diff --git a/src/base/single/button/listitem/icontextitem.js b/src/base/single/button/listitem/icontextitem.js index b906cc6e7..074cacbca 100644 --- a/src/base/single/button/listitem/icontextitem.js +++ b/src/base/single/button/listitem/icontextitem.js @@ -14,7 +14,7 @@ export class IconTextItem extends BasicButton { static xtype = "bi.icon_text_item"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-icon-text-item`, diff --git a/src/base/single/button/listitem/texticonitem.js b/src/base/single/button/listitem/texticonitem.js index c17811c92..4c8b53d08 100644 --- a/src/base/single/button/listitem/texticonitem.js +++ b/src/base/single/button/listitem/texticonitem.js @@ -15,7 +15,7 @@ export class TextIconItem extends BasicButton { static EVENT_CHANGE = "EVENT_CHANGE" _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-text-icon-item`, diff --git a/src/base/single/button/listitem/textitem.js b/src/base/single/button/listitem/textitem.js index 29546ad02..62ca182ae 100644 --- a/src/base/single/button/listitem/textitem.js +++ b/src/base/single/button/listitem/textitem.js @@ -15,7 +15,7 @@ export class TextItem extends BasicButton { static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-text-item`, diff --git a/src/base/single/button/node/icontexticonnode.js b/src/base/single/button/node/icontexticonnode.js index 77a737b48..c80903d78 100644 --- a/src/base/single/button/node/icontexticonnode.js +++ b/src/base/single/button/node/icontexticonnode.js @@ -13,7 +13,7 @@ export class IconTextIconNode extends NodeButton { static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-icon-text-icon-node`, diff --git a/src/base/single/button/node/icontextnode.js b/src/base/single/button/node/icontextnode.js index 54c2b60bf..b9281df80 100644 --- a/src/base/single/button/node/icontextnode.js +++ b/src/base/single/button/node/icontextnode.js @@ -13,7 +13,7 @@ export class IconTextNode extends NodeButton { static xtype = "bi.icon_text_node"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-icon-text-node`, diff --git a/src/base/single/button/node/texticonnode.js b/src/base/single/button/node/texticonnode.js index e4ca824a1..48836cfff 100644 --- a/src/base/single/button/node/texticonnode.js +++ b/src/base/single/button/node/texticonnode.js @@ -12,7 +12,7 @@ export default class TextIconNode extends NodeButton { static xtype = "bi.text_icon_node"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-text-icon-node`, diff --git a/src/base/single/button/node/textnode.js b/src/base/single/button/node/textnode.js index c7b56766d..2907b4c9d 100644 --- a/src/base/single/button/node/textnode.js +++ b/src/base/single/button/node/textnode.js @@ -16,7 +16,7 @@ export class TextNode extends NodeButton { _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-text-node`, diff --git a/src/base/single/editor/editor.js b/src/base/single/editor/editor.js index 0cf075a39..59007cd79 100644 --- a/src/base/single/editor/editor.js +++ b/src/base/single/editor/editor.js @@ -33,7 +33,7 @@ export class Editor extends Single { static EVENT_EMPTY = "EVENT_EMPTY"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: "bi-editor bi-focus-shadow", diff --git a/src/base/single/editor/editor.multifile.js b/src/base/single/editor/editor.multifile.js index 0954dcbbb..2f143c048 100644 --- a/src/base/single/editor/editor.multifile.js +++ b/src/base/single/editor/editor.multifile.js @@ -20,7 +20,7 @@ export class MultifileEditor extends Widget { static EVENT_UPLOADED = "EVENT_UPLOADED"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: (conf.baseCls || "") + " bi-multifile-editor", diff --git a/src/base/single/icon/icon.js b/src/base/single/icon/icon.js index 8dddd52b9..63b573a41 100644 --- a/src/base/single/icon/icon.js +++ b/src/base/single/icon/icon.js @@ -11,7 +11,7 @@ export class Icon extends Single { static xtype = "bi.icon"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { tagName: "i", diff --git a/src/base/single/input/checkbox/checkbox.image.js b/src/base/single/input/checkbox/checkbox.image.js index 04a6c5589..3b7e445e7 100644 --- a/src/base/single/input/checkbox/checkbox.image.js +++ b/src/base/single/input/checkbox/checkbox.image.js @@ -13,7 +13,7 @@ export class ImageCheckbox extends IconButton { static EVENT_CHANGE = IconButton.EVENT_CHANGE; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: (conf.baseCls || "") + " bi-image-checkbox check-box-icon", diff --git a/src/base/single/input/file.js b/src/base/single/input/file.js index 8564efda7..9f0e0e708 100644 --- a/src/base/single/input/file.js +++ b/src/base/single/input/file.js @@ -459,7 +459,7 @@ export class File extends Widget { static EVENT_UPLOADED = "EVENT_UPLOADED"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: (conf.baseCls || "") + " bi-file display-block", diff --git a/src/base/single/input/input.js b/src/base/single/input/input.js index bd784b350..59f3a7686 100644 --- a/src/base/single/input/input.js +++ b/src/base/single/input/input.js @@ -34,7 +34,7 @@ export class Input extends Single { static EVENT_RESTRICT = "EVENT_RESTRICT"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: (conf.baseCls || "") + " bi-input display-block overflow-dot", diff --git a/src/base/single/input/radio/radio.image.js b/src/base/single/input/radio/radio.image.js index 513b1feff..72921b79c 100644 --- a/src/base/single/input/radio/radio.image.js +++ b/src/base/single/input/radio/radio.image.js @@ -13,7 +13,7 @@ export class ImageRadio extends IconButton { static EVENT_CHANGE = IconButton.EVENT_CHANGE; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: (conf.baseCls || "") + " bi-radio radio-icon", diff --git a/src/base/single/label/abstract.label.js b/src/base/single/label/abstract.label.js index b794e7fc4..28332de3e 100644 --- a/src/base/single/label/abstract.label.js +++ b/src/base/single/label/abstract.label.js @@ -7,7 +7,7 @@ import { Single } from "../0.single"; export class AbstractLabel extends Single { _defaultConfig(props) { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { textAlign: "center", diff --git a/src/base/single/tip/0.tip.js b/src/base/single/tip/0.tip.js index f94b581ab..22f5e46da 100644 --- a/src/base/single/tip/0.tip.js +++ b/src/base/single/tip/0.tip.js @@ -11,7 +11,7 @@ import { Single } from "../0.single"; import { extend } from "../../../core"; export class Tip extends Single { _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { _baseCls: `${conf._baseCls || ""} bi-tip`, diff --git a/src/base/single/tip/tip.toast.js b/src/base/single/tip/tip.toast.js index e42347d44..e9467e34a 100644 --- a/src/base/single/tip/tip.toast.js +++ b/src/base/single/tip/tip.toast.js @@ -21,7 +21,7 @@ export class Toast extends Tip { static xtype = "bi.toast"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-toast", text: "", level: "success", // success或warning diff --git a/src/base/single/tip/tip.tooltip.js b/src/base/single/tip/tip.tooltip.js index 9c573e9fd..46926195e 100644 --- a/src/base/single/tip/tip.tooltip.js +++ b/src/base/single/tip/tip.tooltip.js @@ -17,7 +17,7 @@ export class Tooltip extends Tip { static xtype = "bi.tooltip"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-tooltip", text: "", level: "success", // success或warning diff --git a/src/case/button/icon/icon.change.js b/src/case/button/icon/icon.change.js index f477373e5..16ebd501d 100644 --- a/src/case/button/icon/icon.change.js +++ b/src/case/button/icon/icon.change.js @@ -17,7 +17,7 @@ export class IconChangeButton extends Single { _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: "bi-icon-change-button", diff --git a/src/case/button/icon/icon.trigger.js b/src/case/button/icon/icon.trigger.js index a9afa3d8a..a7606d59b 100644 --- a/src/case/button/icon/icon.trigger.js +++ b/src/case/button/icon/icon.trigger.js @@ -14,7 +14,7 @@ export class TriggerIconButton extends IconButton { static EVENT_CHANGE = IconButton.EVENT_CHANGE; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-trigger-icon-button overflow-hidden`, diff --git a/src/case/button/icon/iconhalf/icon.half.image.js b/src/case/button/icon/iconhalf/icon.half.image.js index e165b4d23..24d2d0cea 100644 --- a/src/case/button/icon/iconhalf/icon.half.image.js +++ b/src/case/button/icon/iconhalf/icon.half.image.js @@ -13,7 +13,7 @@ export class HalfIconButton extends IconButton { static EVENT_CHANGE = IconButton.EVENT_CHANGE _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { extraCls: "bi-half-icon-button check-half-select-icon", diff --git a/src/case/button/icon/iconhalf/icon.half.js b/src/case/button/icon/iconhalf/icon.half.js index 7a72e5823..a0db816ed 100644 --- a/src/case/button/icon/iconhalf/icon.half.js +++ b/src/case/button/icon/iconhalf/icon.half.js @@ -12,7 +12,7 @@ export class HalfButton extends BasicButton { static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { selected: false, diff --git a/src/case/button/item.multiselect.js b/src/case/button/item.multiselect.js index dd5548f4a..bd82f2dcc 100644 --- a/src/case/button/item.multiselect.js +++ b/src/case/button/item.multiselect.js @@ -13,7 +13,7 @@ export class MultiSelectItem extends BasicButton { _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-multi-select-item", attributes: { tabIndex: 1, diff --git a/src/case/button/item.singleselect.icontext.js b/src/case/button/item.singleselect.icontext.js index c32fc6b5a..58e329ff4 100644 --- a/src/case/button/item.singleselect.icontext.js +++ b/src/case/button/item.singleselect.icontext.js @@ -12,7 +12,7 @@ export class SingleSelectIconTextItem extends Single { static xtype = "bi.single_select_icon_text_item"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-single-select-icon-text-item bi-list-item-active", attributes: { tabIndex: 1, diff --git a/src/case/button/item.singleselect.js b/src/case/button/item.singleselect.js index e06f1c4a9..a3fd34b01 100644 --- a/src/case/button/item.singleselect.js +++ b/src/case/button/item.singleselect.js @@ -7,7 +7,7 @@ export class SingleSelectItem extends BasicButton { static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-single-select-item bi-list-item-active", attributes: { tabIndex: 1, diff --git a/src/case/button/item.singleselect.radio.js b/src/case/button/item.singleselect.radio.js index 8a314165d..0fd83a4b6 100644 --- a/src/case/button/item.singleselect.radio.js +++ b/src/case/button/item.singleselect.radio.js @@ -12,7 +12,7 @@ export class SingleSelectRadioItem extends BasicButton { static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-single-select-radio-item", attributes: { tabIndex: 1, diff --git a/src/case/button/node/node.arrow.js b/src/case/button/node/node.arrow.js index aac112417..dc1834c88 100644 --- a/src/case/button/node/node.arrow.js +++ b/src/case/button/node/node.arrow.js @@ -9,7 +9,7 @@ export class ArrowNode extends NodeButton { static xtype = "bi.arrow_group_node"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-arrow-group-node bi-list-item`, diff --git a/src/case/button/node/node.first.plus.js b/src/case/button/node/node.first.plus.js index 5202c77ee..8e895f801 100644 --- a/src/case/button/node/node.first.plus.js +++ b/src/case/button/node/node.first.plus.js @@ -13,7 +13,7 @@ export class FirstPlusGroupNode extends NodeButton { static xtype = "bi.first_plus_group_node"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-first-plus-group-node bi-list-item`, diff --git a/src/case/button/node/node.icon.arrow.js b/src/case/button/node/node.icon.arrow.js index c779795ec..866568b95 100644 --- a/src/case/button/node/node.icon.arrow.js +++ b/src/case/button/node/node.icon.arrow.js @@ -13,7 +13,7 @@ export class IconArrowNode extends NodeButton { static xtype = "bi.icon_arrow_node"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-icon-arrow-node bi-list-item`, diff --git a/src/case/button/node/node.last.plus.js b/src/case/button/node/node.last.plus.js index 2f273f1d8..95e745f4e 100644 --- a/src/case/button/node/node.last.plus.js +++ b/src/case/button/node/node.last.plus.js @@ -12,7 +12,7 @@ export class LastPlusGroupNode extends NodeButton { static xtype = "bi.last_plus_group_node"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-last-plus-group-node bi-list-item`, diff --git a/src/case/button/node/node.mid.plus.js b/src/case/button/node/node.mid.plus.js index 116a73a48..e1276d6ab 100644 --- a/src/case/button/node/node.mid.plus.js +++ b/src/case/button/node/node.mid.plus.js @@ -12,7 +12,7 @@ export class MidPlusGroupNode extends NodeButton { static xtype = "bi.mid_plus_group_node"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-mid-plus-group-node bi-list-item`, diff --git a/src/case/button/node/node.multilayer.icon.arrow.js b/src/case/button/node/node.multilayer.icon.arrow.js index 958e88b79..995bc0327 100644 --- a/src/case/button/node/node.multilayer.icon.arrow.js +++ b/src/case/button/node/node.multilayer.icon.arrow.js @@ -6,7 +6,7 @@ export class MultiLayerIconArrowNode extends NodeButton { static xtype = "bi.multilayer_icon_arrow_node"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { extraCls: "bi-multilayer-icon-arrow-node bi-list-item", diff --git a/src/case/button/node/node.plus.js b/src/case/button/node/node.plus.js index b04624456..4a4e1b042 100644 --- a/src/case/button/node/node.plus.js +++ b/src/case/button/node/node.plus.js @@ -12,7 +12,7 @@ export class PlusGroupNode extends NodeButton { static xtype = "bi.plus_group_node"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-plus-group-node bi-list-item`, diff --git a/src/case/button/node/siwtcher.tree.node.js b/src/case/button/node/siwtcher.tree.node.js index fe89b6569..502deb48f 100644 --- a/src/case/button/node/siwtcher.tree.node.js +++ b/src/case/button/node/siwtcher.tree.node.js @@ -7,7 +7,7 @@ export class TreeNodeSwitcher extends NodeButton { static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-tree-node-switcher", iconWidth: 24, iconHeight: 24, diff --git a/src/case/button/treeitem/item.first.treeleaf.js b/src/case/button/treeitem/item.first.treeleaf.js index f379f65c0..b69340b14 100644 --- a/src/case/button/treeitem/item.first.treeleaf.js +++ b/src/case/button/treeitem/item.first.treeleaf.js @@ -6,7 +6,7 @@ export class FirstTreeLeafItem extends BasicButton { static xtype = "bi.first_tree_leaf_item"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-first-tree-leaf-item bi-list-item-active", logic: { dynamic: false, diff --git a/src/case/button/treeitem/item.icon.treeleaf.js b/src/case/button/treeitem/item.icon.treeleaf.js index 56b94723b..dee13e086 100644 --- a/src/case/button/treeitem/item.icon.treeleaf.js +++ b/src/case/button/treeitem/item.icon.treeleaf.js @@ -6,7 +6,7 @@ export class IconTreeLeafItem extends BasicButton { static xtype = "bi.icon_tree_leaf_item"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-icon-tree-leaf-item bi-list-item-active", logic: { dynamic: false, diff --git a/src/case/button/treeitem/item.last.treeleaf.js b/src/case/button/treeitem/item.last.treeleaf.js index e8317f892..6b89cfbf6 100644 --- a/src/case/button/treeitem/item.last.treeleaf.js +++ b/src/case/button/treeitem/item.last.treeleaf.js @@ -6,7 +6,7 @@ export class LastTreeLeafItem extends BasicButton { static xtype = "bi.last_tree_leaf_item"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-last-tree-leaf-item bi-list-item-active", logic: { dynamic: false, diff --git a/src/case/button/treeitem/item.mid.treeleaf.js b/src/case/button/treeitem/item.mid.treeleaf.js index dfc00d4db..60d76c414 100644 --- a/src/case/button/treeitem/item.mid.treeleaf.js +++ b/src/case/button/treeitem/item.mid.treeleaf.js @@ -6,7 +6,7 @@ export class MidTreeLeafItem extends BasicButton { static xtype = "bi.mid_tree_leaf_item"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-mid-tree-leaf-item bi-list-item-active", logic: { dynamic: false, diff --git a/src/case/button/treeitem/item.multilayer.icon.treeleaf.js b/src/case/button/treeitem/item.multilayer.icon.treeleaf.js index b39108611..75d67b090 100644 --- a/src/case/button/treeitem/item.multilayer.icon.treeleaf.js +++ b/src/case/button/treeitem/item.multilayer.icon.treeleaf.js @@ -10,7 +10,7 @@ export class MultiLayerIconTreeLeafItem extends BasicButton { static xtype = "bi.multilayer_icon_tree_leaf_item"; _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-multilayer-icon-tree-leaf-item bi-list-item-active", layer: 0, height: 24, diff --git a/src/case/button/treeitem/treeitem.js b/src/case/button/treeitem/treeitem.js index c6235facd..85777dd5c 100644 --- a/src/case/button/treeitem/treeitem.js +++ b/src/case/button/treeitem/treeitem.js @@ -6,7 +6,7 @@ export class BasicTreeItem extends NodeButton { static xtype = "bi.tree_item"; _defaultConfig() { - const conf = super._defaultConfig(arguments); + const conf = super._defaultConfig(...arguments); return extend(conf, { baseCls: `${conf.baseCls || ""} bi-tree-item bi-list-item-active`, diff --git a/src/core/behavior/0.behavior.js b/src/core/behavior/0.behavior.js index 22496e242..37dfb3375 100644 --- a/src/core/behavior/0.behavior.js +++ b/src/core/behavior/0.behavior.js @@ -7,7 +7,7 @@ import { extend } from "../2.base"; export class Behavior extends OB { _defaultConfig() { - return extend(super._defaultConfig(arguments), { + return extend(super._defaultConfig(...arguments), { rule: () => true, }); } diff --git a/src/core/loader/loader.style.js b/src/core/loader/loader.style.js index f89aea175..c775ff49a 100644 --- a/src/core/loader/loader.style.js +++ b/src/core/loader/loader.style.js @@ -8,7 +8,7 @@ import { OB } from "../3.ob"; export class StyleLoaderManager extends OB { _defaultConfig() { - return extend(super._defaultConfig(arguments), {}); + return extend(super._defaultConfig(...arguments), {}); } _init() { From 2d645fa7e72d397695ac2373a82f59c113f9804e Mon Sep 17 00:00:00 2001 From: zsmj Date: Mon, 9 Jan 2023 11:33:40 +0800 Subject: [PATCH 050/300] =?UTF-8?q?KERNEL-14041=20feat:=20core/platform?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=A4=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 3 +- src/core/platform/web/config.js | 559 +++---- src/core/platform/web/detectElementResize.js | 590 +------ src/core/platform/web/dom.js | 1472 +++++++++--------- src/core/platform/web/function.js | 285 ++-- src/core/platform/web/index.js | 4 + src/core/platform/web/load.js | 107 +- 7 files changed, 1272 insertions(+), 1748 deletions(-) create mode 100644 src/core/platform/web/index.js diff --git a/package.json b/package.json index 6f67e4229..1e9064583 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "@babel/polyfill": "7.6.0", "@fui/babel-preset-fineui": "^2.0.0", "@fui/eslint-plugin": "^1.0.19", + "@juggle/resize-observer": "^3.4.0", "@types/node": "15.6.1", "@typescript-eslint/eslint-plugin": "2.33.0", "@typescript-eslint/parser": "2.33.0", @@ -91,4 +92,4 @@ "@types/yargs": "17.0.13", "yargs": "17.6.2" } -} \ No newline at end of file +} diff --git a/src/core/platform/web/config.js b/src/core/platform/web/config.js index 66440ccf8..e4812bd7b 100644 --- a/src/core/platform/web/config.js +++ b/src/core/platform/web/config.js @@ -1,286 +1,315 @@ +import { Plugin } from "../../6.plugin"; + // 工程配置 -!(function () { - // 注册布局 - // adapt类布局优先级规则 - // 1、支持flex的浏览器下使用flex布局 - // 2、不支持flex的浏览器下使用inline布局 - // 3、当列宽既需要自动列宽又需要自适应列宽时,inline布局也处理不了了。当横向出滚动条时使用table布局,不出滚动条时使用float布局 - var _isSupportFlex, _isSupportGrid; - var isSupportFlex = function () { - if (_isSupportFlex == null) { - _isSupportFlex = !!(BI.isSupportCss3 && BI.isSupportCss3("flex")); - } - return _isSupportFlex; - }; - var isSupportGrid = function () { - if (_isSupportGrid == null) { - _isSupportGrid = !!(BI.isSupportCss3 && BI.isSupportCss3("grid")); - } - return _isSupportGrid; - }; - // 判断浏览器是否支持sticky 属性 - var isSupportSticky = (function () { - var vendorList = ["", "-webkit-", "-ms-", "-moz-", "-o-"], - vendorListLength = vendorList.length, - stickyElement = document.createElement("div"); - for (var i = 0; i < vendorListLength; i++) { - stickyElement.style.position = vendorList[i] + "sticky"; - if (stickyElement.style.position !== "") { - return true; - } - } - return false; - })(); - BI.Plugin.configWidget("bi.horizontal", function (ob) { - var supportFlex = isSupportFlex(); - // // 在横向自适应场景下我们需要使用table的自适应撑出滚动条的特性(flex处理不了这种情况) - // // 主要出现在center_adapt或者horizontal_adapt的场景,或者主动设置horizontalAlign的场景 - // if (ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch) { - // return BI.extend({}, ob, {type: "bi.table_adapt"}); - // } - if (supportFlex) { - return BI.extend({}, ob, { type: "bi.flex_horizontal" }); - } - return BI.extend({ - scrollx: true - }, ob, { type: "bi.inline" }); - }); - BI.Plugin.configWidget("bi.vertical", function (ob) { - if (ob.horizontalAlign === BI.HorizontalAlign.Left || ob.horizontalAlign === BI.HorizontalAlign.Right) { - if (isSupportFlex()) { - return BI.extend({}, ob, { type: "bi.flex_vertical" }); - } - return BI.extend({}, ob, { - horizontalAlign: BI.HorizontalAlign.Stretch, - type: "bi.vertical", - items: BI.map(ob.items, function (i, item) { - return { - type: "bi.inline", - horizontalAlign: ob.horizontalAlign, - items: [item] - }; - }) - }); - } - if (ob.verticalAlign === BI.VerticalAlign.Stretch) { - if (isSupportFlex()) { - return BI.extend({ - horizontalAlign: BI.HorizontalAlign.Stretch, - }, ob, { type: "bi.flex_vertical" }); - } - } - return ob; - }); - BI.Plugin.configWidget("bi.inline", function (ob) { - // 当列宽既需要自动列宽又需要自适应列宽时,inline布局也处理不了了,降级table处理吧 - var hasAutoAndFillColumnSize = false; - if (ob.columnSize && ob.columnSize.length > 0) { - if ((ob.columnSize.indexOf("") >= 0 || ob.columnSize.indexOf("auto") >= 0) && ob.columnSize.indexOf("fill") >= 0) { - hasAutoAndFillColumnSize = true; - } - } else { - var hasAuto = false, hasFill = false; - BI.each(ob.items, function (i, item) { - if (item.width === "fill") { - hasFill = true; - } else if (BI.isNull(item.width) || item.width === "" || item.width === "auto") { - hasAuto = true; - } - }); - hasAutoAndFillColumnSize = hasAuto && hasFill; - } +// 注册布局 +// adapt类布局优先级规则 +// 1、支持flex的浏览器下使用flex布局 +// 2、不支持flex的浏览器下使用inline布局 +// 3、当列宽既需要自动列宽又需要自适应列宽时,inline布局也处理不了了。当横向出滚动条时使用table布局,不出滚动条时使用float布局 +let _isSupportFlex, _isSupportGrid; - if (hasAutoAndFillColumnSize) { - // 宽度是不是受限 - if ((ob.scrollable !== true && ob.scrollx !== true) || ob.horizontalAlign === BI.HorizontalAlign.Stretch) { - return BI.extend({ - verticalAlign: BI.VerticalAlign.Top - }, ob, { type: "bi.horizontal_float_fill" }); - } - return BI.extend({ - horizontalAlign: BI.HorizontalAlign.Stretch - }, ob, { type: "bi.table_adapt" }); - } - if (BI.Providers.getProvider("bi.provider.system").getResponsiveMode()) { - return BI.extend({}, ob, { type: "bi.responsive_inline" }); - } - return ob; - }); - BI.Plugin.configWidget("bi.center_adapt", function (ob) { - var supportFlex = isSupportFlex(); - // var isAdapt = !ob.horizontalAlign || ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch; - // if (!isAdapt || justOneItem) { - if (supportFlex) { - return BI.extend({}, ob, { type: "bi.flex_center_adapt" }); - } - return BI.extend({}, ob, { type: "bi.inline_center_adapt" }); - // } - // return ob; - }); - BI.Plugin.configWidget("bi.vertical_adapt", function (ob) { - var supportFlex = isSupportFlex(); - // var isAdapt = ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch; - // if (!isAdapt || justOneItem) { - if (supportFlex) { - return BI.extend({}, ob, { type: "bi.flex_vertical_center_adapt" }); - } - return BI.extend({}, ob, { type: "bi.inline_vertical_adapt" }); - // } - // return ob; - }); - BI.Plugin.configWidget("bi.horizontal_adapt", function (ob) { - var justOneItem = (ob.items && ob.items.length <= 1); - var isAdapt = !ob.horizontalAlign || ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch; - var verticalAlignTop = !ob.verticalAlign || ob.verticalAlign === BI.VerticalAlign.TOP; - if (verticalAlignTop && justOneItem) { - return BI.extend({}, ob, { type: "bi.horizontal_auto" }); - } - var supportFlex = isSupportFlex(); - // 在横向自适应场景下我们需要使用table的自适应撑出滚动条的特性(flex处理不了这种情况) - // 主要出现在center_adapt或者horizontal_adapt的场景,或者主动设置horizontalAlign的场景 - if (isAdapt) { - return BI.extend({ - horizontalAlign: BI.HorizontalAlign.Center - }, ob, { type: "bi.table_adapt" }); - } - if (supportFlex) { - return BI.extend({ - horizontalAlign: BI.HorizontalAlign.Center, - scrollx: false - }, ob, { type: "bi.flex_horizontal" }); - } - return BI.extend({ - horizontalAlign: BI.HorizontalAlign.Center - }, ob, { type: "bi.table_adapt" }); - }); - BI.Plugin.configWidget("bi.horizontal_float", function (ob) { - if (isSupportFlex()) { - return BI.extend({}, ob, { type: "bi.flex_horizontal_adapt" }); - } - if (ob.items && ob.items.length <= 1) { - return BI.extend({}, ob, { type: "bi.inline_horizontal_adapt" }); - } - return ob; - }); +function isSupportFlex() { + if (!_isSupportFlex) { + _isSupportFlex = !!(BI.isSupportCss3 && BI.isSupportCss3("flex")); + } + + return _isSupportFlex; +} + +function isSupportGrid() { + if (!_isSupportGrid) { + _isSupportGrid = !!(BI.isSupportCss3 && BI.isSupportCss3("grid")); + } + + return _isSupportGrid; +} - BI.Plugin.configWidget("bi.horizontal_fill", function (ob) { +// 判断浏览器是否支持sticky 属性 +const isSupportSticky = (function () { + const vendorList = ["", "-webkit-", "-ms-", "-moz-", "-o-"], + vendorListLength = vendorList.length, + stickyElement = document.createElement("div"); + for (let i = 0; i < vendorListLength; i++) { + stickyElement.style.position = `${vendorList[i]}sticky`; + if (stickyElement.style.position !== "") { + return true; + } + } + + return false; +}()); + + +const configWidget = Plugin.configWidget; + +configWidget("bi.horizontal", ob => { + const supportFlex = isSupportFlex(); + // // 在横向自适应场景下我们需要使用table的自适应撑出滚动条的特性(flex处理不了这种情况) + // // 主要出现在center_adapt或者horizontal_adapt的场景,或者主动设置horizontalAlign的场景 + // if (ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch) { + // return BI.extend({}, ob, {type: "bi.table_adapt"}); + // } + if (supportFlex) { + return BI.extend({}, ob, { type: "bi.flex_horizontal" }); + } + + return BI.extend({ + scrollx: true, + }, ob, { type: "bi.inline" }); +}); +configWidget("bi.vertical", ob => { + if (ob.horizontalAlign === BI.HorizontalAlign.Left || ob.horizontalAlign === BI.HorizontalAlign.Right) { if (isSupportFlex()) { - return BI.extend({ - horizontalAlign: BI.HorizontalAlign.Stretch, - verticalAlign: BI.VerticalAlign.Stretch, - scrollx: false - }, ob, { type: "bi.flex_horizontal" }); - } - if ((ob.horizontalAlign && ob.horizontalAlign !== BI.HorizontalAlign.Stretch) || (ob.scrollable === true || ob.scrollx === true)) { - // 宽度不受限,要用table布局 - return BI.extend({ - horizontalAlign: BI.HorizontalAlign.Stretch, - verticalAlign: BI.VerticalAlign.Stretch - }, ob, { type: "bi.table_adapt" }); + return BI.extend({}, ob, { type: "bi.flex_vertical" }); } - return BI.extend({}, ob, { type: "bi.horizontal_float_fill" }); - }); - BI.Plugin.configWidget("bi.vertical_fill", function (ob) { + + return BI.extend({}, ob, { + horizontalAlign: BI.HorizontalAlign.Stretch, + type: "bi.vertical", + items: BI.map(ob.items, (i, item) => { + return { + type: "bi.inline", + horizontalAlign: ob.horizontalAlign, + items: [item], + }; + }), + }); + } + if (ob.verticalAlign === BI.VerticalAlign.Stretch) { if (isSupportFlex()) { return BI.extend({ horizontalAlign: BI.HorizontalAlign.Stretch, - verticalAlign: BI.VerticalAlign.Stretch, - scrolly: false }, ob, { type: "bi.flex_vertical" }); } - if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) { - // 有滚动条,降级到table布局处理 - return BI.extend({}, ob, { - type: "bi.td", - items: BI.map(ob.items, function (i, item) { - return [item]; - }) - }); - } - var hasAuto = false; - if (ob.rowSize && ob.rowSize.length > 0) { - if (ob.rowSize.indexOf("") >= 0 || ob.rowSize.indexOf("auto") >= 0) { + } + + return ob; +}); +configWidget("bi.inline", ob => { + // 当列宽既需要自动列宽又需要自适应列宽时,inline布局也处理不了了,降级table处理吧 + let hasAutoAndFillColumnSize = false; + if (ob.columnSize && ob.columnSize.length > 0) { + if ((ob.columnSize.indexOf("") >= 0 || ob.columnSize.indexOf("auto") >= 0) && ob.columnSize.indexOf("fill") >= 0) { + hasAutoAndFillColumnSize = true; + } + } else { + let hasAuto = false, hasFill = false; + BI.each(ob.items, (i, item) => { + if (item.width === "fill") { + hasFill = true; + } else if (BI.isNull(item.width) || item.width === "" || item.width === "auto") { hasAuto = true; } - } else { - BI.each(ob.items, function (i, item) { - if (BI.isNull(item.height) || item.height === "") { - hasAuto = true; - } - }); - } - if (hasAuto) { - // 有自动高的时候 - return BI.extend({}, ob, { type: "bi.vtape_auto" }); - } - return BI.extend({}, ob, { type: "bi.vtape" }); - }); - BI.Plugin.configWidget("bi.horizontal_sticky", function (ob) { - if (!isSupportSticky) { - return BI.extend({ scrollx: true }, ob, { type: "bi.horizontal_fill" }); - } - }); - BI.Plugin.configWidget("bi.vertical_sticky", function (ob) { - if (!isSupportSticky) { - return BI.extend({ scrolly: true }, ob, { type: "bi.vertical_fill" }); - } - }); + }); + hasAutoAndFillColumnSize = hasAuto && hasFill; + } - BI.Plugin.configWidget("bi.left_right_vertical_adapt", function (ob) { - if (isSupportFlex()) { - // IE下其实也是可以使用flex布局的,只要排除掉出现滚动条的情况 - // if (!BI.isIE() || (ob.scrollable !== true && ob.scrolly !== true)) { - return BI.extend({}, ob, { type: "bi.flex_left_right_vertical_adapt" }); - // } + if (hasAutoAndFillColumnSize) { + // 宽度是不是受限 + if ((ob.scrollable !== true && ob.scrollx !== true) || ob.horizontalAlign === BI.HorizontalAlign.Stretch) { + return BI.extend({ + verticalAlign: BI.VerticalAlign.Top, + }, ob, { type: "bi.horizontal_float_fill" }); } - return ob; - }); - BI.Plugin.configWidget("bi.flex_horizontal", function (ob) { - if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) { - if (ob.hgap > 0 || ob.lgap > 0 || ob.rgap > 0) { - if (BI.Providers.getProvider("bi.provider.system").getResponsiveMode()) { - return BI.extend({}, ob, { type: "bi.responsive_flex_scrollable_horizontal" }); - } - return BI.extend({}, ob, { type: "bi.flex_scrollable_horizontal" }); + + return BI.extend({ + horizontalAlign: BI.HorizontalAlign.Stretch, + }, ob, { type: "bi.table_adapt" }); + } + if (BI.Providers.getProvider("bi.provider.system").getResponsiveMode()) { + return BI.extend({}, ob, { type: "bi.responsive_inline" }); + } + + return ob; +}); +configWidget("bi.center_adapt", ob => { + const supportFlex = isSupportFlex(); + // var isAdapt = !ob.horizontalAlign || ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch; + // if (!isAdapt || justOneItem) { + if (supportFlex) { + return BI.extend({}, ob, { type: "bi.flex_center_adapt" }); + } + + return BI.extend({}, ob, { type: "bi.inline_center_adapt" }); + // } + // return ob; +}); +configWidget("bi.vertical_adapt", ob => { + const supportFlex = isSupportFlex(); + // var isAdapt = ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch; + // if (!isAdapt || justOneItem) { + if (supportFlex) { + return BI.extend({}, ob, { type: "bi.flex_vertical_center_adapt" }); + } + + return BI.extend({}, ob, { type: "bi.inline_vertical_adapt" }); + // } + // return ob; +}); + +configWidget("bi.horizontal_adapt", ob => { + const justOneItem = (ob.items && ob.items.length <= 1); + const isAdapt = !ob.horizontalAlign || ob.horizontalAlign === BI.HorizontalAlign.Center || ob.horizontalAlign === BI.HorizontalAlign.Stretch; + const verticalAlignTop = !ob.verticalAlign || ob.verticalAlign === BI.VerticalAlign.TOP; + if (verticalAlignTop && justOneItem) { + return BI.extend({}, ob, { type: "bi.horizontal_auto" }); + } + const supportFlex = isSupportFlex(); + // 在横向自适应场景下我们需要使用table的自适应撑出滚动条的特性(flex处理不了这种情况) + // 主要出现在center_adapt或者horizontal_adapt的场景,或者主动设置horizontalAlign的场景 + if (isAdapt) { + return BI.extend({ + horizontalAlign: BI.HorizontalAlign.Center, + }, ob, { type: "bi.table_adapt" }); + } + if (supportFlex) { + return BI.extend({ + horizontalAlign: BI.HorizontalAlign.Center, + scrollx: false, + }, ob, { type: "bi.flex_horizontal" }); + } + + return BI.extend({ + horizontalAlign: BI.HorizontalAlign.Center, + }, ob, { type: "bi.table_adapt" }); +}); + +configWidget("bi.horizontal_float", ob => { + if (isSupportFlex()) { + return BI.extend({}, ob, { type: "bi.flex_horizontal_adapt" }); + } + if (ob.items && ob.items.length <= 1) { + return BI.extend({}, ob, { type: "bi.inline_horizontal_adapt" }); + } + + return ob; +}); + +configWidget("bi.horizontal_fill", ob => { + if (isSupportFlex()) { + return BI.extend({ + horizontalAlign: BI.HorizontalAlign.Stretch, + verticalAlign: BI.VerticalAlign.Stretch, + scrollx: false, + }, ob, { type: "bi.flex_horizontal" }); + } + if ((ob.horizontalAlign && ob.horizontalAlign !== BI.HorizontalAlign.Stretch) || (ob.scrollable === true || ob.scrollx === true)) { + // 宽度不受限,要用table布局 + return BI.extend({ + horizontalAlign: BI.HorizontalAlign.Stretch, + verticalAlign: BI.VerticalAlign.Stretch, + }, ob, { type: "bi.table_adapt" }); + } + + return BI.extend({}, ob, { type: "bi.horizontal_float_fill" }); +}); +configWidget("bi.vertical_fill", ob => { + if (isSupportFlex()) { + return BI.extend({ + horizontalAlign: BI.HorizontalAlign.Stretch, + verticalAlign: BI.VerticalAlign.Stretch, + scrolly: false, + }, ob, { type: "bi.flex_vertical" }); + } + if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) { + // 有滚动条,降级到table布局处理 + return BI.extend({}, ob, { + type: "bi.td", + items: BI.map(ob.items, (i, item) => [item]), + }); + } + let hasAuto = false; + if (ob.rowSize && ob.rowSize.length > 0) { + if (ob.rowSize.indexOf("") >= 0 || ob.rowSize.indexOf("auto") >= 0) { + hasAuto = true; + } + } else { + BI.each(ob.items, (i, item) => { + if (BI.isNull(item.height) || item.height === "") { + hasAuto = true; } - } - if (BI.Providers.getProvider("bi.provider.system").getResponsiveMode()) { - return BI.extend({}, ob, { type: "bi.responsive_flex_horizontal" }); - } - }); - BI.Plugin.configWidget("bi.flex_vertical", function (ob) { - if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) { - if (ob.hgap > 0 || ob.lgap > 0 || ob.rgap > 0) { - return BI.extend({}, ob, { type: "bi.flex_scrollable_vertical" }); + }); + } + if (hasAuto) { + // 有自动高的时候 + return BI.extend({}, ob, { type: "bi.vtape_auto" }); + } + + return BI.extend({}, ob, { type: "bi.vtape" }); +}); +configWidget("bi.horizontal_sticky", ob => { + if (!isSupportSticky) { + return BI.extend({ scrollx: true }, ob, { type: "bi.horizontal_fill" }); + } +}); +configWidget("bi.vertical_sticky", ob => { + if (!isSupportSticky) { + return BI.extend({ scrolly: true }, ob, { type: "bi.vertical_fill" }); + } +}); + +configWidget("bi.left_right_vertical_adapt", ob => { + if (isSupportFlex()) { + // IE下其实也是可以使用flex布局的,只要排除掉出现滚动条的情况 + // if (!BI.isIE() || (ob.scrollable !== true && ob.scrolly !== true)) { + return BI.extend({}, ob, { type: "bi.flex_left_right_vertical_adapt" }); + // } + } + + return ob; +}); +configWidget("bi.flex_horizontal", ob => { + if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) { + if (ob.hgap > 0 || ob.lgap > 0 || ob.rgap > 0) { + if (BI.Providers.getProvider("bi.provider.system").getResponsiveMode()) { + return BI.extend({}, ob, { type: "bi.responsive_flex_scrollable_horizontal" }); } - } - }); - BI.Plugin.configWidget("bi.table", function (ob) { - if (!isSupportGrid()) { - return BI.extend({}, ob, { type: "bi.td" }); - } - return ob; - }); + return BI.extend({}, ob, { type: "bi.flex_scrollable_horizontal" }); + } + } + if (BI.Providers.getProvider("bi.provider.system").getResponsiveMode()) { + return BI.extend({}, ob, { type: "bi.responsive_flex_horizontal" }); + } +}); +configWidget("bi.flex_vertical", ob => { + if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) { + if (ob.hgap > 0 || ob.lgap > 0 || ob.rgap > 0) { + return BI.extend({}, ob, { type: "bi.flex_scrollable_vertical" }); + } + } +}); - BI.Plugin.configWidget("bi.radio", function (ob) { - if (BI.isIE() && BI.getIEVersion() <= 9) { - return BI.extend({}, ob, { type: "bi.image_radio" }); - } - return ob; - }); +configWidget("bi.table", ob => { + if (!isSupportGrid()) { + return BI.extend({}, ob, { type: "bi.td" }); + } - BI.Plugin.configWidget("bi.checkbox", function (ob) { - if (BI.isIE() && BI.getIEVersion() <= 9) { - return BI.extend({}, ob, { type: "bi.image_checkbox" }); - } + return ob; +}); + +configWidget("bi.radio", ob => { + if (BI.isIE() && BI.getIEVersion() <= 9) { + return BI.extend({}, ob, { type: "bi.image_radio" }); + } + + return ob; +}); + +configWidget("bi.checkbox", ob => { + if (BI.isIE() && BI.getIEVersion() <= 9) { + return BI.extend({}, ob, { type: "bi.image_checkbox" }); + } + + return ob; +}); + +configWidget("bi.half_icon_button", ob => { + if (BI.isIE() && BI.getIEVersion() < 9) { return ob; - }); + } + + return BI.extend({}, ob, { type: "bi.half_button" }); +}); + - BI.Plugin.configWidget("bi.half_icon_button", function (ob) { - if (BI.isIE() && BI.getIEVersion() < 9) { - return ob; - } - return BI.extend({}, ob, { type: "bi.half_button" }); - }); -}()); diff --git a/src/core/platform/web/detectElementResize.js b/src/core/platform/web/detectElementResize.js index 502ebb0ee..7be166fd9 100644 --- a/src/core/platform/web/detectElementResize.js +++ b/src/core/platform/web/detectElementResize.js @@ -1,571 +1,15 @@ -/** - * Detect Element Resize. - * A minimal library which polyfills the ResizeObserver API and is entirely based on the latest Draft Specification. - * https://github.com/juggle/resize-observer - * version: 3.4.0 - **/ -var ResizeObserverPolyfill = (function (exports) { - 'use strict'; +import { ResizeObserver as ResizeObserverPolyfill } from "@juggle/resize-observer"; - var resizeObservers = []; +const ResizeObserver = window.ResizeObserver || ResizeObserverPolyfill; - var hasActiveObservations = function () { - return resizeObservers.some(function (ro) { - return ro.activeTargets.length > 0; - }); - }; - - var hasSkippedObservations = function () { - return resizeObservers.some(function (ro) { - return ro.skippedTargets.length > 0; - }); - }; - - var msg = 'ResizeObserver loop completed with undelivered notifications.'; - var deliverResizeLoopError = function () { - var event; - if (typeof ErrorEvent === 'function') { - event = new ErrorEvent('error', { - message: msg - }); - } else { - event = document.createEvent('Event'); - event.initEvent('error', false, false); - event.message = msg; - } - window.dispatchEvent(event); - }; - - var ResizeObserverBoxOptions; - (function (ResizeObserverBoxOptions) { - ResizeObserverBoxOptions["BORDER_BOX"] = "border-box"; - ResizeObserverBoxOptions["CONTENT_BOX"] = "content-box"; - ResizeObserverBoxOptions["DEVICE_PIXEL_CONTENT_BOX"] = "device-pixel-content-box"; - })(ResizeObserverBoxOptions || (ResizeObserverBoxOptions = {})); - - var freeze = function (obj) { - return Object.freeze(obj); - }; - - var ResizeObserverSize = (function () { - function ResizeObserverSize(inlineSize, blockSize) { - this.inlineSize = inlineSize; - this.blockSize = blockSize; - freeze(this); - } - - return ResizeObserverSize; - }()); - - var DOMRectReadOnly = (function () { - function DOMRectReadOnly(x, y, width, height) { - this.x = x; - this.y = y; - this.width = width; - this.height = height; - this.top = this.y; - this.left = this.x; - this.bottom = this.top + this.height; - this.right = this.left + this.width; - return freeze(this); - } - - DOMRectReadOnly.prototype.toJSON = function () { - var _a = this, x = _a.x, y = _a.y, top = _a.top, right = _a.right, bottom = _a.bottom, left = _a.left, - width = _a.width, height = _a.height; - return { x: x, y: y, top: top, right: right, bottom: bottom, left: left, width: width, height: height }; - }; - DOMRectReadOnly.fromRect = function (rectangle) { - return new DOMRectReadOnly(rectangle.x, rectangle.y, rectangle.width, rectangle.height); - }; - return DOMRectReadOnly; - }()); - - var isSVG = function (target) { - return target instanceof SVGElement && 'getBBox' in target; - }; - var isHidden = function (target) { - if (isSVG(target)) { - var _a = target.getBBox(), width = _a.width, height = _a.height; - return !width && !height; - } - var _b = target, offsetWidth = _b.offsetWidth, offsetHeight = _b.offsetHeight; - return !(offsetWidth || offsetHeight || target.getClientRects().length); - }; - var isElement = function (obj) { - var _a; - if (obj instanceof Element) { - return true; - } - var scope = (_a = obj === null || obj === void 0 ? void 0 : obj.ownerDocument) === null || _a === void 0 ? void 0 : _a.defaultView; - return !!(scope && obj instanceof scope.Element); - }; - var isReplacedElement = function (target) { - switch (target.tagName) { - case 'INPUT': - if (target.type !== 'image') { - break; - } - case 'VIDEO': - case 'AUDIO': - case 'EMBED': - case 'OBJECT': - case 'CANVAS': - case 'IFRAME': - case 'IMG': - return true; - } - return false; - }; - - var global = typeof window !== 'undefined' ? window : {}; - - var cache = new WeakMap(); - var scrollRegexp = /auto|scroll/; - var verticalRegexp = /^tb|vertical/; - var IE = (/msie|trident/i).test(global.navigator && global.navigator.userAgent); - var parseDimension = function (pixel) { - return parseFloat(pixel || '0'); - }; - var size = function (inlineSize, blockSize, switchSizes) { - if (inlineSize === void 0) { - inlineSize = 0; - } - if (blockSize === void 0) { - blockSize = 0; - } - if (switchSizes === void 0) { - switchSizes = false; - } - return new ResizeObserverSize((switchSizes ? blockSize : inlineSize) || 0, (switchSizes ? inlineSize : blockSize) || 0); - }; - var zeroBoxes = freeze({ - devicePixelContentBoxSize: size(), - borderBoxSize: size(), - contentBoxSize: size(), - contentRect: new DOMRectReadOnly(0, 0, 0, 0) - }); - var calculateBoxSizes = function (target, forceRecalculation) { - if (forceRecalculation === void 0) { - forceRecalculation = false; - } - if (cache.has(target) && !forceRecalculation) { - return cache.get(target); - } - if (isHidden(target)) { - cache.set(target, zeroBoxes); - return zeroBoxes; - } - var cs = getComputedStyle(target); - var svg = isSVG(target) && target.ownerSVGElement && target.getBBox(); - var removePadding = !IE && cs.boxSizing === 'border-box'; - var switchSizes = verticalRegexp.test(cs.writingMode || ''); - var canScrollVertically = !svg && scrollRegexp.test(cs.overflowY || ''); - var canScrollHorizontally = !svg && scrollRegexp.test(cs.overflowX || ''); - var paddingTop = svg ? 0 : parseDimension(cs.paddingTop); - var paddingRight = svg ? 0 : parseDimension(cs.paddingRight); - var paddingBottom = svg ? 0 : parseDimension(cs.paddingBottom); - var paddingLeft = svg ? 0 : parseDimension(cs.paddingLeft); - var borderTop = svg ? 0 : parseDimension(cs.borderTopWidth); - var borderRight = svg ? 0 : parseDimension(cs.borderRightWidth); - var borderBottom = svg ? 0 : parseDimension(cs.borderBottomWidth); - var borderLeft = svg ? 0 : parseDimension(cs.borderLeftWidth); - var horizontalPadding = paddingLeft + paddingRight; - var verticalPadding = paddingTop + paddingBottom; - var horizontalBorderArea = borderLeft + borderRight; - var verticalBorderArea = borderTop + borderBottom; - var horizontalScrollbarThickness = !canScrollHorizontally ? 0 : target.offsetHeight - verticalBorderArea - target.clientHeight; - var verticalScrollbarThickness = !canScrollVertically ? 0 : target.offsetWidth - horizontalBorderArea - target.clientWidth; - var widthReduction = removePadding ? horizontalPadding + horizontalBorderArea : 0; - var heightReduction = removePadding ? verticalPadding + verticalBorderArea : 0; - var contentWidth = svg ? svg.width : parseDimension(cs.width) - widthReduction - verticalScrollbarThickness; - var contentHeight = svg ? svg.height : parseDimension(cs.height) - heightReduction - horizontalScrollbarThickness; - var borderBoxWidth = contentWidth + horizontalPadding + verticalScrollbarThickness + horizontalBorderArea; - var borderBoxHeight = contentHeight + verticalPadding + horizontalScrollbarThickness + verticalBorderArea; - var boxes = freeze({ - devicePixelContentBoxSize: size(Math.round(contentWidth * devicePixelRatio), Math.round(contentHeight * devicePixelRatio), switchSizes), - borderBoxSize: size(borderBoxWidth, borderBoxHeight, switchSizes), - contentBoxSize: size(contentWidth, contentHeight, switchSizes), - contentRect: new DOMRectReadOnly(paddingLeft, paddingTop, contentWidth, contentHeight) - }); - cache.set(target, boxes); - return boxes; - }; - var calculateBoxSize = function (target, observedBox, forceRecalculation) { - var _a = calculateBoxSizes(target, forceRecalculation), borderBoxSize = _a.borderBoxSize, - contentBoxSize = _a.contentBoxSize, devicePixelContentBoxSize = _a.devicePixelContentBoxSize; - switch (observedBox) { - case ResizeObserverBoxOptions.DEVICE_PIXEL_CONTENT_BOX: - return devicePixelContentBoxSize; - case ResizeObserverBoxOptions.BORDER_BOX: - return borderBoxSize; - default: - return contentBoxSize; - } - }; - - var ResizeObserverEntry = (function () { - function ResizeObserverEntry(target) { - var boxes = calculateBoxSizes(target); - this.target = target; - this.contentRect = boxes.contentRect; - this.borderBoxSize = freeze([boxes.borderBoxSize]); - this.contentBoxSize = freeze([boxes.contentBoxSize]); - this.devicePixelContentBoxSize = freeze([boxes.devicePixelContentBoxSize]); - } - - return ResizeObserverEntry; - }()); - - var calculateDepthForNode = function (node) { - if (isHidden(node)) { - return Infinity; - } - var depth = 0; - var parent = node.parentNode; - while (parent) { - depth += 1; - parent = parent.parentNode; - } - return depth; - }; - - var broadcastActiveObservations = function () { - var shallowestDepth = Infinity; - var callbacks = []; - resizeObservers.forEach(function processObserver(ro) { - if (ro.activeTargets.length === 0) { - return; - } - var entries = []; - ro.activeTargets.forEach(function processTarget(ot) { - var entry = new ResizeObserverEntry(ot.target); - var targetDepth = calculateDepthForNode(ot.target); - entries.push(entry); - ot.lastReportedSize = calculateBoxSize(ot.target, ot.observedBox); - if (targetDepth < shallowestDepth) { - shallowestDepth = targetDepth; - } - }); - callbacks.push(function resizeObserverCallback() { - ro.callback.call(ro.observer, entries, ro.observer); - }); - ro.activeTargets.splice(0, ro.activeTargets.length); - }); - for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) { - var callback = callbacks_1[_i]; - callback(); - } - return shallowestDepth; - }; - - var gatherActiveObservationsAtDepth = function (depth) { - resizeObservers.forEach(function processObserver(ro) { - ro.activeTargets.splice(0, ro.activeTargets.length); - ro.skippedTargets.splice(0, ro.skippedTargets.length); - ro.observationTargets.forEach(function processTarget(ot) { - if (ot.isActive()) { - if (calculateDepthForNode(ot.target) > depth) { - ro.activeTargets.push(ot); - } else { - ro.skippedTargets.push(ot); - } - } - }); - }); - }; - - var process = function () { - var depth = 0; - gatherActiveObservationsAtDepth(depth); - while (hasActiveObservations()) { - depth = broadcastActiveObservations(); - gatherActiveObservationsAtDepth(depth); - } - if (hasSkippedObservations()) { - deliverResizeLoopError(); - } - return depth > 0; - }; - - var trigger; - var callbacks = []; - var notify = function () { - return callbacks.splice(0).forEach(function (cb) { - return cb(); - }); - }; - var queueMicroTask = function (callback) { - if (!trigger) { - var toggle_1 = 0; - var el_1 = document.createTextNode(''); - var config = { characterData: true }; - new MutationObserver(function () { - return notify(); - }).observe(el_1, config); - trigger = function () { - el_1.textContent = "".concat(toggle_1 ? toggle_1-- : toggle_1++); - }; - } - callbacks.push(callback); - trigger(); - }; - - var queueResizeObserver = function (cb) { - queueMicroTask(function ResizeObserver() { - requestAnimationFrame(cb); - }); - }; - - var watching = 0; - var isWatching = function () { - return !!watching; - }; - var CATCH_PERIOD = 250; - var observerConfig = { attributes: true, characterData: true, childList: true, subtree: true }; - var events = [ - 'resize', - 'load', - 'transitionend', - 'animationend', - 'animationstart', - 'animationiteration', - 'keyup', - 'keydown', - 'mouseup', - 'mousedown', - 'mouseover', - 'mouseout', - 'blur', - 'focus' - ]; - var time = function (timeout) { - if (timeout === void 0) { - timeout = 0; - } - return Date.now() + timeout; - }; - var scheduled = false; - var Scheduler = (function () { - function Scheduler() { - var _this = this; - this.stopped = true; - this.listener = function () { - return _this.schedule(); - }; - } - - Scheduler.prototype.run = function (timeout) { - var _this = this; - if (timeout === void 0) { - timeout = CATCH_PERIOD; - } - if (scheduled) { - return; - } - scheduled = true; - var until = time(timeout); - queueResizeObserver(function () { - var elementsHaveResized = false; - try { - elementsHaveResized = process(); - } finally { - scheduled = false; - timeout = until - time(); - if (!isWatching()) { - return; - } - if (elementsHaveResized) { - _this.run(1000); - } else if (timeout > 0) { - _this.run(timeout); - } else { - _this.start(); - } - } - }); - }; - Scheduler.prototype.schedule = function () { - this.stop(); - this.run(); - }; - Scheduler.prototype.observe = function () { - var _this = this; - var cb = function () { - return _this.observer && _this.observer.observe(document.body, observerConfig); - }; - document.body ? cb() : global.addEventListener('DOMContentLoaded', cb); - }; - Scheduler.prototype.start = function () { - var _this = this; - if (this.stopped) { - this.stopped = false; - this.observer = new MutationObserver(this.listener); - this.observe(); - events.forEach(function (name) { - return global.addEventListener(name, _this.listener, true); - }); - } - }; - Scheduler.prototype.stop = function () { - var _this = this; - if (!this.stopped) { - this.observer && this.observer.disconnect(); - events.forEach(function (name) { - return global.removeEventListener(name, _this.listener, true); - }); - this.stopped = true; - } - }; - return Scheduler; - }()); - var scheduler = new Scheduler(); - var updateCount = function (n) { - !watching && n > 0 && scheduler.start(); - watching += n; - !watching && scheduler.stop(); - }; - - var skipNotifyOnElement = function (target) { - return !isSVG(target) - && !isReplacedElement(target) - && getComputedStyle(target).display === 'inline'; - }; - var ResizeObservation = (function () { - function ResizeObservation(target, observedBox) { - this.target = target; - this.observedBox = observedBox || ResizeObserverBoxOptions.CONTENT_BOX; - this.lastReportedSize = { - inlineSize: -1, - blockSize: -1 - }; - } - - ResizeObservation.prototype.isActive = function () { - var size = calculateBoxSize(this.target, this.observedBox, true); - if (skipNotifyOnElement(this.target)) { - this.lastReportedSize = size; - } - if (this.lastReportedSize.inlineSize !== size.inlineSize - || this.lastReportedSize.blockSize !== size.blockSize) { - return true; - } - return false; - }; - return ResizeObservation; - }()); - - var ResizeObserverDetail = (function () { - function ResizeObserverDetail(resizeObserver, callback) { - this.activeTargets = []; - this.skippedTargets = []; - this.observationTargets = []; - this.observer = resizeObserver; - this.callback = callback; - } - - return ResizeObserverDetail; - }()); - - var observerMap = new WeakMap(); - var getObservationIndex = function (observationTargets, target) { - for (var i = 0; i < observationTargets.length; i += 1) { - if (observationTargets[i].target === target) { - return i; - } - } - return -1; - }; - var ResizeObserverController = (function () { - function ResizeObserverController() { - } - - ResizeObserverController.connect = function (resizeObserver, callback) { - var detail = new ResizeObserverDetail(resizeObserver, callback); - observerMap.set(resizeObserver, detail); - }; - ResizeObserverController.observe = function (resizeObserver, target, options) { - var detail = observerMap.get(resizeObserver); - var firstObservation = detail.observationTargets.length === 0; - if (getObservationIndex(detail.observationTargets, target) < 0) { - firstObservation && resizeObservers.push(detail); - detail.observationTargets.push(new ResizeObservation(target, options && options.box)); - updateCount(1); - scheduler.schedule(); - } - }; - ResizeObserverController.unobserve = function (resizeObserver, target) { - var detail = observerMap.get(resizeObserver); - var index = getObservationIndex(detail.observationTargets, target); - var lastObservation = detail.observationTargets.length === 1; - if (index >= 0) { - lastObservation && resizeObservers.splice(resizeObservers.indexOf(detail), 1); - detail.observationTargets.splice(index, 1); - updateCount(-1); - } - }; - ResizeObserverController.disconnect = function (resizeObserver) { - var _this = this; - var detail = observerMap.get(resizeObserver); - detail.observationTargets.slice().forEach(function (ot) { - return _this.unobserve(resizeObserver, ot.target); - }); - detail.activeTargets.splice(0, detail.activeTargets.length); - }; - return ResizeObserverController; - }()); - - var ResizeObserver = (function () { - function ResizeObserver(callback) { - if (arguments.length === 0) { - throw new TypeError("Failed to construct 'ResizeObserver': 1 argument required, but only 0 present."); - } - if (typeof callback !== 'function') { - throw new TypeError("Failed to construct 'ResizeObserver': The callback provided as parameter 1 is not a function."); - } - ResizeObserverController.connect(this, callback); - } - - ResizeObserver.prototype.observe = function (target, options) { - if (arguments.length === 0) { - throw new TypeError("Failed to execute 'observe' on 'ResizeObserver': 1 argument required, but only 0 present."); - } - if (!isElement(target)) { - throw new TypeError("Failed to execute 'observe' on 'ResizeObserver': parameter 1 is not of type 'Element"); - } - ResizeObserverController.observe(this, target, options); - }; - ResizeObserver.prototype.unobserve = function (target) { - if (arguments.length === 0) { - throw new TypeError("Failed to execute 'unobserve' on 'ResizeObserver': 1 argument required, but only 0 present."); - } - if (!isElement(target)) { - throw new TypeError("Failed to execute 'unobserve' on 'ResizeObserver': parameter 1 is not of type 'Element"); - } - ResizeObserverController.unobserve(this, target); - }; - ResizeObserver.prototype.disconnect = function () { - ResizeObserverController.disconnect(this); - }; - ResizeObserver.toString = function () { - return 'function ResizeObserver () { [polyfill code] }'; - }; - return ResizeObserver; - }()); - - return ResizeObserver; -})(); - -var ResizeObserver = window.ResizeObserver || ResizeObserverPolyfill; - -var addResizeListener = function (element, fn) { +function addResizeListener(element, fn) { if (ResizeObserver) { if (!element.__resizeObserver__) { - var resizeObserver = new ResizeObserver(function () { - element.__resizeListeners__.forEach(function (listener) { + const resizeObserver = new ResizeObserver((() => { + element.__resizeListeners__.forEach(listener => { BI.$(element).is(":visible") && listener(); }); - }); + })); resizeObserver.observe(element); element.__resizeObserver__ = resizeObserver; } @@ -574,16 +18,18 @@ var addResizeListener = function (element, fn) { } element.__resizeListeners__.push(fn); } -}; -var removeResizeListener = function (element, fn) { +} + +function removeResizeListener(element, fn) { if (ResizeObserver) { if (BI.isNull(fn)) { element.__resizeListeners__ = []; element.__resizeObserver__ && element.__resizeObserver__.unobserve(element); element.__resizeObserver__ = null; + return; } - var index = element.__resizeListeners__.indexOf(fn); + const index = element.__resizeListeners__.indexOf(fn); if (index >= 0) { element.__resizeListeners__.splice(index, 1); if (!element.__resizeListeners__.length) { @@ -592,19 +38,17 @@ var removeResizeListener = function (element, fn) { } } } -}; +} export const ResizeDetector = { - addResizeListener: function (widget, fn) { + addResizeListener(widget, fn) { addResizeListener(widget.element[0], fn); + return function () { removeResizeListener(widget.element[0], fn); }; - }, removeResizeListener: function (widget, fn) { + }, + removeResizeListener(widget, fn) { removeResizeListener(widget.element[0], fn); - } + }, }; - -Object.assign(BI, { - ResizeDetector -}); diff --git a/src/core/platform/web/dom.js b/src/core/platform/web/dom.js index cc9ed0f8d..5835df64f 100644 --- a/src/core/platform/web/dom.js +++ b/src/core/platform/web/dom.js @@ -1,758 +1,784 @@ /** * 对DOM操作的通用函数 - * @type {{}} */ -!(function () { - BI.DOM = BI.DOM || {}; - - BI.extend(BI.DOM, { - ready: function (fn) { - BI.Widget._renderEngine.createElement(document).ready(fn); - } +import { each, isEmpty, isNull } from "../../2.base"; + +export function ready(fn) { + BI.Widget._renderEngine.createElement(document).ready(fn); +} + +export function patchProps(fromElement, toElement) { + const elemData = BI.jQuery._data(fromElement[0]); + const events = elemData.events; + each(events, (eventKey, event) => { + each(event, (i, handler) => { + toElement.on(eventKey + (handler.namespace ? (`.${handler.namespace}`) : ""), handler); + }); }); + const fromChildren = fromElement.children(), toChildren = toElement.children(); + if (fromChildren.length !== toChildren.length) { + throw new Error("不匹配"); + } + each(fromChildren, (i, child) => { + patchProps(BI.jQuery(child), BI.jQuery(toChildren[i])); + }); + each(fromElement.data("__widgets"), (i, widget) => { + widget.element = toElement; + }); +} - BI.extend(BI.DOM, { - - patchProps: function (fromElement, toElement) { - var elemData = BI.jQuery._data(fromElement[0]); - var events = elemData.events; - BI.each(events, function (eventKey, event) { - BI.each(event, function (i, handler) { - toElement.on(eventKey + (handler.namespace ? ("." + handler.namespace) : ""), handler); - }); - }); - var fromChildren = fromElement.children(), toChildren = toElement.children(); - if (fromChildren.length !== toChildren.length) { - throw new Error("不匹配"); - } - BI.each(fromChildren, function (i, child) { - BI.DOM.patchProps(BI.jQuery(child), BI.jQuery(toChildren[i])); - }); - BI.each(fromElement.data("__widgets"), function (i, widget) { - widget.element = toElement; - }); - }, - /** - * 把dom数组或元素悬挂起来,使其不对html产生影响 - * @param dom - */ - hang: function (doms) { - if (BI.isEmpty(doms)) { - return; - } - var frag = BI.Widget._renderEngine.createFragment(); - BI.each(doms, function (i, dom) { - dom instanceof BI.Widget && (dom = dom.element); - dom instanceof BI.$ && dom[0] && frag.appendChild(dom[0]); - }); - return frag; - }, - - isExist: function (obj) { - return BI.Widget._renderEngine.createElement("body").find(obj.element).length > 0; - }, - - // 预加载图片 - preloadImages: function (srcArray, onload) { - var count = 0, images = []; - - function complete() { - count++; - if (count >= srcArray.length) { - onload(); - } - } - - BI.each(srcArray, function (i, src) { - images[i] = new Image(); - images[i].src = src; - images[i].onload = function () { - complete(); - }; - images[i].onerror = function () { - complete(); - }; - }); - }, - - getTextSizeWidth: function (text, fontSize) { - var span = BI.Widget._renderEngine.createElement("").addClass("text-width-span").appendTo("body"); - - if (fontSize == null) { - fontSize = 12; - } - fontSize = fontSize + "px"; - - span.css("font-size", fontSize).text(text); +/** + * 把dom数组或元素悬挂起来,使其不对html产生影响 + * @param dom + */ +export function hang(doms) { + if (isEmpty(doms)) { + return; + } + const frag = BI.Widget._renderEngine.createFragment(); + each(doms, (i, dom) => { + dom instanceof BI.Widget && (dom = dom.element); + dom instanceof BI.$ && dom[0] && frag.appendChild(dom[0]); + }); - var width = span.width(); - span.remove(); + return frag; +} - return width; - }, +export function isExist(obj) { + return BI.Widget._renderEngine.createElement("body").find(obj.element).length > 0; +} - getTextSizeHeight: function (text, fontSize) { - var span = BI.Widget._renderEngine.createElement("").addClass("text-width-span").appendTo("body"); +// 预加载图片 +export function preloadImages(srcArray, onload) { + let count = 0; + const images = []; - if (fontSize == null) { - fontSize = 12; - } - fontSize = fontSize + "px"; - - span.css("font-size", fontSize).text(text); - - var height = span.height(); - span.remove(); - - return height; - }, - - // 获取滚动条的宽度,页面display: none时候获取到的为0 - getScrollWidth: function () { - if (BI.isNull(this._scrollWidth) || this._scrollWidth === 0) { - var ul = BI.Widget._renderEngine.createElement("
").width(50).height(50).css({ - position: "absolute", - top: "-9999px", - overflow: "scroll" - }).appendTo("body"); - this._scrollWidth = ul[0].offsetWidth - ul[0].clientWidth; - ul.destroy(); - } - return this._scrollWidth; - }, - - getImage: function (param, fillStyle, backgroundColor) { - var canvas = document.createElement("canvas"); - var ratio = 2; - BI.Widget._renderEngine.createElement("body").append(canvas); - - var ctx = canvas.getContext("2d"); - ctx.font = "12px Helvetica Neue,Arial,PingFang SC,Hiragino Sans GB,Microsoft YaHei,微软雅黑,Heiti,黑体,sans-serif"; - var w = ctx.measureText(param).width + 4; - canvas.width = w * ratio; - canvas.height = 16 * ratio; - ctx.font = 12 * ratio + "px Helvetica Neue,Arial,PingFang SC,Hiragino Sans GB,Microsoft YaHei,微软雅黑,Heiti,黑体,sans-serif"; - ctx.fillStyle = fillStyle || "#3685f2"; - ctx.textBaseline = "middle"; - // ctx.fillStyle = "#EAF2FD"; - ctx.fillText(param, 2 * ratio, 9 * ratio); - BI.Widget._renderEngine.createElement(canvas).destroy(); - var backColor = backgroundColor || "rgba(54, 133, 242, 0.1)"; - // IE可以放大缩小所以要固定最大最小宽高 - return { - width: w, - height: 16, - src: canvas.toDataURL("image/png"), - style: "background-color: " + backColor + ";vertical-align: middle; margin: 0 1px; width:" + w + "px;height: 16px; max-width:" + w + "px;max-height: 16px; min-width:" + w + "px;min-height: 16px", - param: param - }; + function complete() { + count++; + if (count >= srcArray.length) { + onload(); } + } + + each(srcArray, (i, src) => { + images[i] = new Image(); + images[i].src = src; + images[i].onload = function () { + complete(); + }; + images[i].onerror = function () { + complete(); + }; }); - - BI.extend(BI.DOM, { - - getLeftPosition: function (combo, popup, extraWidth, container) { - var el = combo.element; - var popupEl = popup.element; - var elRect = el[0].getBoundingClientRect(); - var popupElRect = popupEl[0].getBoundingClientRect(); - var containerRect = container ? container.getBoundingClientRect() : { left: 0 }; - - return { - left: elRect.left - containerRect.left - popupElRect.width - (extraWidth || 0) - }; - }, - - getInnerLeftPosition: function (combo, popup, extraWidth) { - return { - left: combo.element.offset().left + (extraWidth || 0) - }; - }, - - getRightPosition: function (combo, popup, extraWidth, container) { - var el = combo.element; - var elRect = el[0].getBoundingClientRect(); - var containerRect = container ? container.getBoundingClientRect() : { left: 0 }; - - return { - left: elRect.left + elRect.width - containerRect.left + (extraWidth || 0) - }; - }, - - getInnerRightPosition: function (combo, popup, extraWidth) { - var el = combo.element, viewBounds = popup.element.bounds(); - return { - left: el.offset().left + el.outerWidth() - viewBounds.width - (extraWidth || 0) - }; - }, - - getTopPosition: function (combo, popup, extraHeight, container) { - var el = combo.element; - var popupEl = popup.element; - var elRect = el[0].getBoundingClientRect(); - var popupElRect = popupEl[0].getBoundingClientRect(); - var containerRect = container ? container.getBoundingClientRect() : { top: 0 }; - - return { - top: elRect.top - containerRect.top - popupElRect.height - (extraHeight || 0) - }; - }, - - getBottomPosition: function (combo, popup, extraHeight, container) { - var el = combo.element; - var elRect = el[0].getBoundingClientRect(); - var containerRect = container ? container.getBoundingClientRect() : { top: 0 }; - - return { - top: elRect.top - containerRect.top + elRect.height + (extraHeight || 0) - }; - }, - - isLeftSpaceEnough: function (combo, popup, extraWidth) { - return BI.DOM.getLeftPosition(combo, popup, extraWidth).left >= 0; - }, - - isInnerLeftSpaceEnough: function (combo, popup, extraWidth) { - var viewBounds = popup.element.bounds(), - windowBounds = BI.Widget._renderEngine.createElement("body").bounds(); - return BI.DOM.getInnerLeftPosition(combo, popup, extraWidth).left + viewBounds.width <= windowBounds.width; - }, - - isRightSpaceEnough: function (combo, popup, extraWidth) { - var viewBounds = popup.element[0].getBoundingClientRect(), - viewportBounds = document.documentElement.getBoundingClientRect(); - return BI.DOM.getRightPosition(combo, popup, extraWidth).left + viewBounds.width <= viewportBounds.width; - }, - - isInnerRightSpaceEnough: function (combo, popup, extraWidth) { - return BI.DOM.getInnerRightPosition(combo, popup, extraWidth).left >= 0; - }, - - isTopSpaceEnough: function (combo, popup, extraHeight) { - return BI.DOM.getTopPosition(combo, popup, extraHeight).top >= 0; - }, - - isBottomSpaceEnough: function (combo, popup, extraHeight) { - var viewBounds = popup.element[0].getBoundingClientRect(), - viewportBounds = document.documentElement.getBoundingClientRect(); - return BI.DOM.getBottomPosition(combo, popup, extraHeight).top + viewBounds.height <= viewportBounds.height; - }, - - isRightSpaceLarger: function (combo) { - var comboBounds = combo.element[0].getBoundingClientRect(), - viewportBounds = document.documentElement.getBoundingClientRect(); - return viewportBounds.width - comboBounds.right >= comboBounds.left; - }, - - isBottomSpaceLarger: function (combo) { - var comboBounds = combo.element[0].getBoundingClientRect(), - viewportBounds = document.documentElement.getBoundingClientRect(); - return viewportBounds.height - comboBounds.bottom >= comboBounds.top; - }, - - _getLeftAlignPosition: function (combo, popup, extraWidth, container) { - var comboRect = combo.element[0].getBoundingClientRect(), - popupRect = popup.element[0].getBoundingClientRect(), - viewportRect = document.documentElement.getBoundingClientRect(), - containerRect = container ? container.getBoundingClientRect() : { left: 0 }; - var left = comboRect.left - containerRect.left + extraWidth; - - if (comboRect.left + popupRect.width > viewportRect.width) { - left = viewportRect.width - popupRect.width - containerRect.left; - } - return left; - }, - - getLeftAlignPosition: function (combo, popup, extraWidth, container) { - var left = this._getLeftAlignPosition(combo, popup, extraWidth, container); - var dir = ""; - // 如果放不下,优先使用RightAlign, 如果RightAlign也放不下, 再使用left=0 - var containerRect = container ? container.getBoundingClientRect() : { left: 0 }; - if (left + containerRect.left < 0) { - left = this._getRightAlignPosition(combo, popup, extraWidth); - dir = "left"; - } - if (left + containerRect.left < 0) { - left = 0 - containerRect.left; - } - return { - left: left, - dir: dir || "right" - }; - }, - - getLeftAdaptPosition: function (combo, popup, extraWidth, container) { - if (BI.DOM.isLeftSpaceEnough(combo, popup, extraWidth, container)) { - return BI.DOM.getLeftPosition(combo, popup, extraWidth, container); - } - return { - left: 0 - }; - }, - - _getRightAlignPosition: function (combo, popup, extraWidth, container) { - var comboBounds = combo.element[0].getBoundingClientRect(), - viewBounds = popup.element[0].getBoundingClientRect(), - containerRect = container ? container.getBoundingClientRect() : { left: 0 }; - return comboBounds.left + comboBounds.width - viewBounds.width - extraWidth - containerRect.left; - }, - - getRightAlignPosition: function (combo, popup, extraWidth, container) { - var left = this._getRightAlignPosition(combo, popup, extraWidth, container); - var dir = ""; - // 如果放不下,优先使用LeftAlign, 如果LeftAlign也放不下, 再使用left=0 - if (left < 0) { - left = this._getLeftAlignPosition(combo, popup, extraWidth, container); - dir = "right"; - } - if (left < 0) { - left = 0; - } - return { - left: left, - dir: dir || "left" - }; - }, - - getRightAdaptPosition: function (combo, popup, extraWidth, container) { - if (BI.DOM.isRightSpaceEnough(combo, popup, extraWidth, container)) { - return BI.DOM.getRightPosition(combo, popup, extraWidth, container); - } - return { - left: document.documentElement.getBoundingClientRect().width - popup.element[0].getBoundingClientRect().width - container.getBoundingClientRect().left - }; - }, - - getTopAlignPosition: function (combo, popup, extraHeight, needAdaptHeight, container) { - var comboBounds = combo.element[0].getBoundingClientRect(), - popupBounds = popup.element[0].getBoundingClientRect(), - viewportBounds = document.documentElement.getBoundingClientRect(), - containerBounds = container ? container.getBoundingClientRect() : { top: 0 }; - var top, adaptHeight, dir; - if (BI.DOM.isBottomSpaceEnough(combo, popup, -1 * comboBounds.height + extraHeight)) { - top = comboBounds.top - containerBounds.top + extraHeight; - } else if (needAdaptHeight) { - top = comboBounds.top - containerBounds.top + extraHeight; - adaptHeight = viewportBounds.height - comboBounds.top; - } else if (BI.DOM.isTopSpaceEnough(combo, popup, -1 * comboBounds.height + extraHeight)) { - // 下方空间不足且不允许调整高度的情况下,优先使用上对齐 - top = comboBounds.top + comboBounds.height - popupBounds.height - containerBounds.top - extraHeight; - dir = "top"; - } else { - top = viewportBounds.height - popupBounds.height; - if (top < extraHeight) { - adaptHeight = viewportBounds.height - extraHeight; - } - } - if (top < extraHeight) { - top = extraHeight; - } - return adaptHeight ? { - top: top, - adaptHeight: adaptHeight, - dir: dir || "bottom" - } : { - top: top, - dir: dir || "bottom" - }; - }, - - getTopAdaptPosition: function (combo, popup, extraHeight, needAdaptHeight, positionRelativeElement) { - var comboBounds = combo.element[0].getBoundingClientRect(), - popupBounds = popup.element[0].getBoundingClientRect(), - positionRelativeElementRect = positionRelativeElement.getBoundingClientRect(), - viewportBounds = document.documentElement.getBoundingClientRect(); - if (BI.DOM.isTopSpaceEnough(combo, popup, extraHeight)) { - return BI.DOM.getTopPosition(combo, popup, extraHeight); - } - if (needAdaptHeight) { - return { - top: 0 - positionRelativeElementRect.top, - adaptHeight: comboBounds.top - extraHeight - }; - } - if (popupBounds.height + extraHeight > viewportBounds.height) { - return { - top: 0 - positionRelativeElementRect.top, - adaptHeight: viewportBounds.height - extraHeight - }; - } - return { - top: 0 - positionRelativeElementRect.top - }; - }, - - getBottomAlignPosition: function (combo, popup, extraHeight, needAdaptHeight, container) { - var comboBounds = combo.element[0].getBoundingClientRect(), - popupBounds = popup.element[0].getBoundingClientRect(), - windowBounds = BI.Widget._renderEngine.createElement("body").bounds(), - containerBounds = container ? container.getBoundingClientRect() : { top: 0 }; - var top, adaptHeight, dir; - if (BI.DOM.isTopSpaceEnough(combo, popup, -1 * comboBounds.height + extraHeight)) { - top = comboBounds.top + comboBounds.height - containerBounds.top - popupBounds.height; - } else if (needAdaptHeight) { - top = 0 - containerBounds.top; - adaptHeight = comboBounds.top + comboBounds.height - extraHeight; - } else if (BI.DOM.isBottomSpaceEnough(combo, popup, -1 * comboBounds.height + extraHeight)) { - // 上方空间不足且不允许调整高度的情况下,优先使用下对齐 - top = comboBounds.top - containerBounds.top + extraHeight; - dir = "bottom"; - } else { - top = 0; - if (popupBounds.height + extraHeight > windowBounds.height) { - adaptHeight = windowBounds.height - extraHeight; - } - } - if (top + containerBounds.top < 0) { - top = 0; - } - return adaptHeight ? { - top: top, - adaptHeight: adaptHeight, - dir: dir || "top" - } : { - top: top, - dir: dir || "top" - }; - }, - - getBottomAdaptPosition: function (combo, popup, extraHeight, needAdaptHeight, positionRelativeElement) { - var comboBounds = combo.element[0].getBoundingClientRect(), - popupBounds = popup.element[0].getBoundingClientRect(), - viewportBounds = document.documentElement.getBoundingClientRect(), - positionRelativeElementRect = positionRelativeElement.getBoundingClientRect(); - if (BI.DOM.isBottomSpaceEnough(combo, popup, extraHeight)) { - return BI.DOM.getBottomPosition(combo, popup, extraHeight, positionRelativeElement); - } - if (needAdaptHeight) { - return { - top: comboBounds.top + comboBounds.height + extraHeight - positionRelativeElementRect.top, - adaptHeight: viewportBounds.height - comboBounds.top - comboBounds.height - extraHeight - }; - } - if (popupBounds.height + extraHeight > viewportBounds.height) { - return { - top: extraHeight - positionRelativeElementRect.top, - adaptHeight: viewportBounds.height - extraHeight - }; - } - return { - top: viewportBounds.height - popupBounds.height - extraHeight - positionRelativeElementRect.top - }; - }, - - getCenterAdaptPosition: function (combo, popup, positionRelativeElement) { - var comboRect = combo.element[0].getBoundingClientRect(), - popupRect = popup.element[0].getBoundingClientRect(), - positionRelativeElementRect = positionRelativeElement.getBoundingClientRect(), - viewportBounds = document.documentElement.getBoundingClientRect(); - var left; - if (comboRect.left + comboRect.width / 2 + popupRect.width / 2 > viewportBounds.width) { - left = viewportBounds.width - popupRect.width - positionRelativeElementRect.left; - } else { - left = comboRect.left + (comboRect.width - popupRect.width) / 2 - positionRelativeElementRect.left; - } - if (left + positionRelativeElementRect.left < 0) { - left = 0; - } - return { - left: left - }; - }, - - getMiddleAdaptPosition: function (combo, popup, positionRelativeElement) { - var comboRect = combo.element[0].getBoundingClientRect(), - popupRect = popup.element[0].getBoundingClientRect(), - positionRelativeElementRect = positionRelativeElement.getBoundingClientRect(), - viewportBounds = document.documentElement.getBoundingClientRect(); - - var top; - if (comboRect.top + comboRect.height / 2 + popupRect.height / 2 > viewportBounds.height) { - top = viewportBounds.height - popupRect.height - positionRelativeElementRect.top; - } else { - top = comboRect.top + (comboRect.height - popupRect.height) / 2 - positionRelativeElementRect.top; - } - if (top + positionRelativeElementRect.top < 0) { - top = 0; - } - return { - top: top - }; - }, - - getComboPositionByDirections: function (combo, popup, extraWidth, extraHeight, needAdaptHeight, directions, container) { - extraWidth || (extraWidth = 0); - extraHeight || (extraHeight = 0); - var i, direct; - var leftRight = [], topBottom = [], innerLeftRight = []; - var isNeedAdaptHeight = false, tbFirst = false, lrFirst = false; - var left, top, pos, firstDir = directions[0]; - for (i = 0; i < directions.length; i++) { - direct = directions[i]; - switch (direct) { - case "left": - leftRight.push(direct); - break; - case "right": - leftRight.push(direct); - break; - case "top": - topBottom.push(direct); - break; - case "bottom": - topBottom.push(direct); - break; - case "innerLeft": - innerLeftRight.push(direct); - break; - case "innerRight": - innerLeftRight.push(direct); - break; - } - } - for (i = 0; i < directions.length; i++) { - direct = directions[i]; - switch (direct) { - case "left": - if (!isNeedAdaptHeight) { - var tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? 0 : extraHeight; - if (BI.DOM.isLeftSpaceEnough(combo, popup, tW)) { - left = BI.DOM.getLeftPosition(combo, popup, tW, container).left; - if (topBottom[0] === "bottom") { - pos = BI.DOM.getTopAlignPosition(combo, popup, tH, needAdaptHeight, container); - } else { - pos = BI.DOM.getBottomAlignPosition(combo, popup, tH, needAdaptHeight, container); - } - pos.dir = "left," + pos.dir; - if (tbFirst) { - pos.change = "left"; - } - pos.left = left; - return pos; - } - } - lrFirst = true; - break; - case "right": - if (!isNeedAdaptHeight) { - var tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? extraWidth : extraHeight; - if (BI.DOM.isRightSpaceEnough(combo, popup, tW)) { - left = BI.DOM.getRightPosition(combo, popup, tW, container).left; - if (topBottom[0] === "bottom") { - pos = BI.DOM.getTopAlignPosition(combo, popup, tH, needAdaptHeight, container); - } else { - pos = BI.DOM.getBottomAlignPosition(combo, popup, tH, needAdaptHeight, container); - } - pos.dir = "right," + pos.dir; - if (tbFirst) { - pos.change = "right"; - } - pos.left = left; - return pos; - } - } - lrFirst = true; - break; - case "top": - var tW = lrFirst ? extraHeight : extraWidth, tH = lrFirst ? extraWidth : extraHeight; - if (BI.DOM.isTopSpaceEnough(combo, popup, tH)) { - top = BI.DOM.getTopPosition(combo, popup, tH, container).top; - if (leftRight[0] === "right") { - pos = BI.DOM.getLeftAlignPosition(combo, popup, tW, container); - } else { - pos = BI.DOM.getRightAlignPosition(combo, popup, tW, container); - } - pos.dir = "top," + pos.dir; - if (lrFirst) { - pos.change = "top"; - } - pos.top = top; - return pos; - } - if (needAdaptHeight) { - isNeedAdaptHeight = true; - } - tbFirst = true; - break; - case "bottom": - var tW = lrFirst ? extraHeight : extraWidth, tH = lrFirst ? extraWidth : extraHeight; - if (BI.DOM.isBottomSpaceEnough(combo, popup, tH)) { - top = BI.DOM.getBottomPosition(combo, popup, tH, container).top; - if (leftRight[0] === "right") { - pos = BI.DOM.getLeftAlignPosition(combo, popup, tW, container); - } else { - pos = BI.DOM.getRightAlignPosition(combo, popup, tW, container); - } - pos.dir = "bottom," + pos.dir; - if (lrFirst) { - pos.change = "bottom"; - } - pos.top = top; - return pos; +} + +export function getTextSizeWidth(text, fontSize = 12) { + const span = BI.Widget._renderEngine.createElement("").addClass("text-width-span").appendTo("body"); + + fontSize = `${fontSize}px`; + + span.css("font-size", fontSize).text(text); + + const width = span.width(); + span.remove(); + + return width; +} + +export function getTextSizeHeight(text, fontSize = 12) { + const span = BI.Widget._renderEngine.createElement("").addClass("text-width-span").appendTo("body"); + + fontSize = `${fontSize}px`; + + span.css("font-size", fontSize).text(text); + + const height = span.height(); + span.remove(); + + return height; +} + +// 获取滚动条的宽度,页面display: none时候获取到的为0 +let _scrollWidth = null; + +export function getScrollWidth() { + if (isNull(_scrollWidth) || _scrollWidth === 0) { + const ul = BI.Widget._renderEngine.createElement("
").width(50).height(50) + .css({ + position: "absolute", + top: "-9999px", + overflow: "scroll", + }) + .appendTo("body"); + _scrollWidth = ul[0].offsetWidth - ul[0].clientWidth; + ul.destroy(); + } + + return _scrollWidth; +} + +export function getImage(param, fillStyle, backgroundColor) { + const canvas = document.createElement("canvas"); + const ratio = 2; + BI.Widget._renderEngine.createElement("body").append(canvas); + + const ctx = canvas.getContext("2d"); + ctx.font = "12px Helvetica Neue,Arial,PingFang SC,Hiragino Sans GB,Microsoft YaHei,微软雅黑,Heiti,黑体,sans-serif"; + const w = ctx.measureText(param).width + 4; + canvas.width = w * ratio; + canvas.height = 16 * ratio; + ctx.font = `${12 * ratio}px Helvetica Neue,Arial,PingFang SC,Hiragino Sans GB,Microsoft YaHei,微软雅黑,Heiti,黑体,sans-serif`; + ctx.fillStyle = fillStyle || "#3685f2"; + ctx.textBaseline = "middle"; + // ctx.fillStyle = "#EAF2FD"; + ctx.fillText(param, 2 * ratio, 9 * ratio); + BI.Widget._renderEngine.createElement(canvas).destroy(); + const backColor = backgroundColor || "rgba(54, 133, 242, 0.1)"; + + // IE可以放大缩小所以要固定最大最小宽高 + return { + width: w, + height: 16, + src: canvas.toDataURL("image/png"), + style: `background-color: ${backColor};vertical-align: middle; margin: 0 1px; width:${w}px;height: 16px; max-width:${w}px;max-height: 16px; min-width:${w}px;min-height: 16px`, + param, + }; +} + +export function getLeftPosition(combo, popup, extraWidth, container) { + const el = combo.element; + const popupEl = popup.element; + const elRect = el[0].getBoundingClientRect(); + const popupElRect = popupEl[0].getBoundingClientRect(); + const containerRect = container ? container.getBoundingClientRect() : { left: 0 }; + + return { + left: elRect.left - containerRect.left - popupElRect.width - (extraWidth || 0), + }; +} + +export function getInnerLeftPosition(combo, popup, extraWidth) { + return { + left: combo.element.offset().left + (extraWidth || 0), + }; +} + +export function getRightPosition(combo, popup, extraWidth, container) { + const el = combo.element; + const elRect = el[0].getBoundingClientRect(); + const containerRect = container ? container.getBoundingClientRect() : { left: 0 }; + + return { + left: elRect.left + elRect.width - containerRect.left + (extraWidth || 0), + }; +} + +export function getInnerRightPosition(combo, popup, extraWidth) { + const el = combo.element, viewBounds = popup.element.bounds(); + + return { + left: el.offset().left + el.outerWidth() - viewBounds.width - (extraWidth || 0), + }; +} + +export function getTopPosition(combo, popup, extraHeight, container) { + const el = combo.element; + const popupEl = popup.element; + const elRect = el[0].getBoundingClientRect(); + const popupElRect = popupEl[0].getBoundingClientRect(); + const containerRect = container ? container.getBoundingClientRect() : { top: 0 }; + + return { + top: elRect.top - containerRect.top - popupElRect.height - (extraHeight || 0), + }; +} + +export function getBottomPosition(combo, popup, extraHeight, container) { + const el = combo.element; + const elRect = el[0].getBoundingClientRect(); + const containerRect = container ? container.getBoundingClientRect() : { top: 0 }; + + return { + top: elRect.top - containerRect.top + elRect.height + (extraHeight || 0), + }; +} + +export function isLeftSpaceEnough(combo, popup, extraWidth) { + return getLeftPosition(combo, popup, extraWidth).left >= 0; +} + +export function isInnerLeftSpaceEnough(combo, popup, extraWidth) { + const viewBounds = popup.element.bounds(), + windowBounds = BI.Widget._renderEngine.createElement("body").bounds(); + + return getInnerLeftPosition(combo, popup, extraWidth).left + viewBounds.width <= windowBounds.width; +} + +export function isRightSpaceEnough(combo, popup, extraWidth) { + const viewBounds = popup.element[0].getBoundingClientRect(), + viewportBounds = document.documentElement.getBoundingClientRect(); + + return getRightPosition(combo, popup, extraWidth).left + viewBounds.width <= viewportBounds.width; +} + +export function isInnerRightSpaceEnough(combo, popup, extraWidth) { + return getInnerRightPosition(combo, popup, extraWidth).left >= 0; +} + +export function isTopSpaceEnough(combo, popup, extraHeight) { + return getTopPosition(combo, popup, extraHeight).top >= 0; +} + +export function isBottomSpaceEnough(combo, popup, extraHeight) { + const viewBounds = popup.element[0].getBoundingClientRect(), + viewportBounds = document.documentElement.getBoundingClientRect(); + + return getBottomPosition(combo, popup, extraHeight).top + viewBounds.height <= viewportBounds.height; +} + +export function isRightSpaceLarger(combo) { + const comboBounds = combo.element[0].getBoundingClientRect(), + viewportBounds = document.documentElement.getBoundingClientRect(); + + return viewportBounds.width - comboBounds.right >= comboBounds.left; +} + +export function isBottomSpaceLarger(combo) { + const comboBounds = combo.element[0].getBoundingClientRect(), + viewportBounds = document.documentElement.getBoundingClientRect(); + + return viewportBounds.height - comboBounds.bottom >= comboBounds.top; +} + +export function _getLeftAlignPosition(combo, popup, extraWidth, container) { + const comboRect = combo.element[0].getBoundingClientRect(), + popupRect = popup.element[0].getBoundingClientRect(), + viewportRect = document.documentElement.getBoundingClientRect(), + containerRect = container ? container.getBoundingClientRect() : { left: 0 }; + let left = comboRect.left - containerRect.left + extraWidth; + + if (comboRect.left + popupRect.width > viewportRect.width) { + left = viewportRect.width - popupRect.width - containerRect.left; + } + + return left; +} + +export function getLeftAlignPosition(combo, popup, extraWidth, container) { + let left = this._getLeftAlignPosition(combo, popup, extraWidth, container); + let dir = ""; + // 如果放不下,优先使用RightAlign, 如果RightAlign也放不下, 再使用left=0 + const containerRect = container ? container.getBoundingClientRect() : { left: 0 }; + if (left + containerRect.left < 0) { + left = this._getRightAlignPosition(combo, popup, extraWidth); + dir = "left"; + } + if (left + containerRect.left < 0) { + left = 0 - containerRect.left; + } + + return { + left, + dir: dir || "right", + }; +} + +export function getLeftAdaptPosition(combo, popup, extraWidth, container) { + if (isLeftSpaceEnough(combo, popup, extraWidth, container)) { + return getLeftPosition(combo, popup, extraWidth, container); + } + + return { + left: 0, + }; +} + +export function _getRightAlignPosition(combo, popup, extraWidth, container) { + const comboBounds = combo.element[0].getBoundingClientRect(), + viewBounds = popup.element[0].getBoundingClientRect(), + containerRect = container ? container.getBoundingClientRect() : { left: 0 }; + + return comboBounds.left + comboBounds.width - viewBounds.width - extraWidth - containerRect.left; +} + +export function getRightAlignPosition(combo, popup, extraWidth, container) { + let left = this._getRightAlignPosition(combo, popup, extraWidth, container); + let dir = ""; + // 如果放不下,优先使用LeftAlign, 如果LeftAlign也放不下, 再使用left=0 + if (left < 0) { + left = this._getLeftAlignPosition(combo, popup, extraWidth, container); + dir = "right"; + } + if (left < 0) { + left = 0; + } + + return { + left, + dir: dir || "left", + }; +} + +export function getRightAdaptPosition(combo, popup, extraWidth, container) { + if (isRightSpaceEnough(combo, popup, extraWidth, container)) { + return getRightPosition(combo, popup, extraWidth, container); + } + + return { + left: document.documentElement.getBoundingClientRect().width - popup.element[0].getBoundingClientRect().width - container.getBoundingClientRect().left, + }; +} + +export function getTopAlignPosition(combo, popup, extraHeight, needAdaptHeight, container) { + const comboBounds = combo.element[0].getBoundingClientRect(), + popupBounds = popup.element[0].getBoundingClientRect(), + viewportBounds = document.documentElement.getBoundingClientRect(), + containerBounds = container ? container.getBoundingClientRect() : { top: 0 }; + let top, adaptHeight, dir; + if (isBottomSpaceEnough(combo, popup, -1 * comboBounds.height + extraHeight)) { + top = comboBounds.top - containerBounds.top + extraHeight; + } else if (needAdaptHeight) { + top = comboBounds.top - containerBounds.top + extraHeight; + adaptHeight = viewportBounds.height - comboBounds.top; + } else if (isTopSpaceEnough(combo, popup, -1 * comboBounds.height + extraHeight)) { + // 下方空间不足且不允许调整高度的情况下,优先使用上对齐 + top = comboBounds.top + comboBounds.height - popupBounds.height - containerBounds.top - extraHeight; + dir = "top"; + } else { + top = viewportBounds.height - popupBounds.height; + if (top < extraHeight) { + adaptHeight = viewportBounds.height - extraHeight; + } + } + if (top < extraHeight) { + top = extraHeight; + } + + return adaptHeight ? { + top, + adaptHeight, + dir: dir || "bottom", + } : { + top, + dir: dir || "bottom", + }; +} + +export function getTopAdaptPosition(combo, popup, extraHeight, needAdaptHeight, positionRelativeElement) { + const comboBounds = combo.element[0].getBoundingClientRect(), + popupBounds = popup.element[0].getBoundingClientRect(), + positionRelativeElementRect = positionRelativeElement.getBoundingClientRect(), + viewportBounds = document.documentElement.getBoundingClientRect(); + if (isTopSpaceEnough(combo, popup, extraHeight)) { + return getTopPosition(combo, popup, extraHeight); + } + if (needAdaptHeight) { + return { + top: 0 - positionRelativeElementRect.top, + adaptHeight: comboBounds.top - extraHeight, + }; + } + if (popupBounds.height + extraHeight > viewportBounds.height) { + return { + top: 0 - positionRelativeElementRect.top, + adaptHeight: viewportBounds.height - extraHeight, + }; + } + + return { + top: 0 - positionRelativeElementRect.top, + }; +} + +export function getBottomAlignPosition(combo, popup, extraHeight, needAdaptHeight, container) { + const comboBounds = combo.element[0].getBoundingClientRect(), + popupBounds = popup.element[0].getBoundingClientRect(), + windowBounds = BI.Widget._renderEngine.createElement("body").bounds(), + containerBounds = container ? container.getBoundingClientRect() : { top: 0 }; + let top, adaptHeight, dir; + if (isTopSpaceEnough(combo, popup, -1 * comboBounds.height + extraHeight)) { + top = comboBounds.top + comboBounds.height - containerBounds.top - popupBounds.height; + } else if (needAdaptHeight) { + top = 0 - containerBounds.top; + adaptHeight = comboBounds.top + comboBounds.height - extraHeight; + } else if (isBottomSpaceEnough(combo, popup, -1 * comboBounds.height + extraHeight)) { + // 上方空间不足且不允许调整高度的情况下,优先使用下对齐 + top = comboBounds.top - containerBounds.top + extraHeight; + dir = "bottom"; + } else { + top = 0; + if (popupBounds.height + extraHeight > windowBounds.height) { + adaptHeight = windowBounds.height - extraHeight; + } + } + if (top + containerBounds.top < 0) { + top = 0; + } + + return adaptHeight ? { + top, + adaptHeight, + dir: dir || "top", + } : { + top, + dir: dir || "top", + }; +} + +export function getBottomAdaptPosition(combo, popup, extraHeight, needAdaptHeight, positionRelativeElement) { + const comboBounds = combo.element[0].getBoundingClientRect(), + popupBounds = popup.element[0].getBoundingClientRect(), + viewportBounds = document.documentElement.getBoundingClientRect(), + positionRelativeElementRect = positionRelativeElement.getBoundingClientRect(); + if (isBottomSpaceEnough(combo, popup, extraHeight)) { + return getBottomPosition(combo, popup, extraHeight, positionRelativeElement); + } + if (needAdaptHeight) { + return { + top: comboBounds.top + comboBounds.height + extraHeight - positionRelativeElementRect.top, + adaptHeight: viewportBounds.height - comboBounds.top - comboBounds.height - extraHeight, + }; + } + if (popupBounds.height + extraHeight > viewportBounds.height) { + return { + top: extraHeight - positionRelativeElementRect.top, + adaptHeight: viewportBounds.height - extraHeight, + }; + } + + return { + top: viewportBounds.height - popupBounds.height - extraHeight - positionRelativeElementRect.top, + }; +} + +export function getCenterAdaptPosition(combo, popup, positionRelativeElement) { + const comboRect = combo.element[0].getBoundingClientRect(), + popupRect = popup.element[0].getBoundingClientRect(), + positionRelativeElementRect = positionRelativeElement.getBoundingClientRect(), + viewportBounds = document.documentElement.getBoundingClientRect(); + let left; + if (comboRect.left + comboRect.width / 2 + popupRect.width / 2 > viewportBounds.width) { + left = viewportBounds.width - popupRect.width - positionRelativeElementRect.left; + } else { + left = comboRect.left + (comboRect.width - popupRect.width) / 2 - positionRelativeElementRect.left; + } + if (left + positionRelativeElementRect.left < 0) { + left = 0; + } + + return { + left, + }; +} + +export function getMiddleAdaptPosition(combo, popup, positionRelativeElement) { + const comboRect = combo.element[0].getBoundingClientRect(), + popupRect = popup.element[0].getBoundingClientRect(), + positionRelativeElementRect = positionRelativeElement.getBoundingClientRect(), + viewportBounds = document.documentElement.getBoundingClientRect(); + + let top; + if (comboRect.top + comboRect.height / 2 + popupRect.height / 2 > viewportBounds.height) { + top = viewportBounds.height - popupRect.height - positionRelativeElementRect.top; + } else { + top = comboRect.top + (comboRect.height - popupRect.height) / 2 - positionRelativeElementRect.top; + } + if (top + positionRelativeElementRect.top < 0) { + top = 0; + } + + return { + top, + }; +} + +export function getComboPositionByDirections(combo, popup, extraWidth, extraHeight, needAdaptHeight, directions, container) { + extraWidth || (extraWidth = 0); + extraHeight || (extraHeight = 0); + let i, direct; + const leftRight = [], topBottom = [], innerLeftRight = []; + let isNeedAdaptHeight = false, tbFirst = false, lrFirst = false; + let left, top, pos, firstDir = directions[0]; + for (i = 0; i < directions.length; i++) { + direct = directions[i]; + switch (direct) { + case "left": + leftRight.push(direct); + break; + case "right": + leftRight.push(direct); + break; + case "top": + topBottom.push(direct); + break; + case "bottom": + topBottom.push(direct); + break; + case "innerLeft": + innerLeftRight.push(direct); + break; + case "innerRight": + innerLeftRight.push(direct); + break; + default: + break; + } + } + for (i = 0; i < directions.length; i++) { + direct = directions[i]; + switch (direct) { + case "left": + if (!isNeedAdaptHeight) { + var tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? 0 : extraHeight; + if (isLeftSpaceEnough(combo, popup, tW)) { + left = getLeftPosition(combo, popup, tW, container).left; + if (topBottom[0] === "bottom") { + pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight, container); + } else { + pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight, container); } - if (needAdaptHeight) { - isNeedAdaptHeight = true; + pos.dir = `left,${pos.dir}`; + if (tbFirst) { + pos.change = "left"; } - tbFirst = true; - break; - case "innerLeft": - if (!isNeedAdaptHeight) { - var tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? 0 : extraHeight; - if (BI.DOM.isInnerLeftSpaceEnough(combo, popup, tW)) { - left = BI.DOM.getInnerLeftPosition(combo, popup, tW).left; - if (topBottom[0] === "bottom") { - pos = BI.DOM.getTopAlignPosition(combo, popup, tH, needAdaptHeight); - } else { - pos = BI.DOM.getBottomAlignPosition(combo, popup, tH, needAdaptHeight); - } - pos.dir = "innerLeft," + pos.dir; - if (tbFirst) { - pos.change = "innerLeft"; - } - pos.left = left; - return pos; - } + pos.left = left; + + return pos; + } + } + lrFirst = true; + break; + case "right": + if (!isNeedAdaptHeight) { + var tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? extraWidth : extraHeight; + if (isRightSpaceEnough(combo, popup, tW)) { + left = getRightPosition(combo, popup, tW, container).left; + if (topBottom[0] === "bottom") { + pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight, container); + } else { + pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight, container); } - lrFirst = true; - break; - case "innerRight": - if (!isNeedAdaptHeight) { - var tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? extraWidth : extraHeight; - if (BI.DOM.isInnerRightSpaceEnough(combo, popup, tW)) { - left = BI.DOM.getInnerRightPosition(combo, popup, tW).left; - if (topBottom[0] === "bottom") { - pos = BI.DOM.getTopAlignPosition(combo, popup, tH, needAdaptHeight); - } else { - pos = BI.DOM.getBottomAlignPosition(combo, popup, tH, needAdaptHeight); - } - pos.dir = "innerLeft," + pos.dir; - if (tbFirst) { - pos.change = "innerRight"; - } - pos.left = left; - return pos; - } + pos.dir = `right,${pos.dir}`; + if (tbFirst) { + pos.change = "right"; } - break; + pos.left = left; + return pos; + } } - } - - // 此处为四个方向放不下时挑空间最大的方向去放置, 也就是说我设置了弹出方向为"bottom,left", - // 最后发现实际弹出方向可能是"top,left",那么此时外界获取popup的方向应该是"top,left" - switch (directions[0]) { - case "left": - case "right": - if (BI.DOM.isRightSpaceLarger(combo)) { - left = BI.DOM.getRightAdaptPosition(combo, popup, extraWidth, container).left; - firstDir = "right"; + lrFirst = true; + break; + case "top": + var tW = lrFirst ? extraHeight : extraWidth, tH = lrFirst ? extraWidth : extraHeight; + if (isTopSpaceEnough(combo, popup, tH)) { + top = getTopPosition(combo, popup, tH, container).top; + if (leftRight[0] === "right") { + pos = getLeftAlignPosition(combo, popup, tW, container); } else { - left = BI.DOM.getLeftAdaptPosition(combo, popup, extraWidth, container).left; - firstDir = "left"; + pos = getRightAlignPosition(combo, popup, tW, container); } - if (topBottom[0] === "bottom") { - pos = BI.DOM.getTopAlignPosition(combo, popup, extraHeight, needAdaptHeight); - pos.left = left; - pos.dir = firstDir + "," + pos.dir; - return pos; + pos.dir = `top,${pos.dir}`; + if (lrFirst) { + pos.change = "top"; } - pos = BI.DOM.getBottomAlignPosition(combo, popup, extraHeight, needAdaptHeight); - pos.left = left; - pos.dir = firstDir + "," + pos.dir; + pos.top = top; + return pos; - default : - if (BI.DOM.isBottomSpaceLarger(combo)) { - top = BI.DOM.getBottomAdaptPosition(combo, popup, extraHeight, needAdaptHeight, container).top; - firstDir = "bottom"; + } + if (needAdaptHeight) { + isNeedAdaptHeight = true; + } + tbFirst = true; + break; + case "bottom": + var tW = lrFirst ? extraHeight : extraWidth, tH = lrFirst ? extraWidth : extraHeight; + if (isBottomSpaceEnough(combo, popup, tH)) { + top = getBottomPosition(combo, popup, tH, container).top; + if (leftRight[0] === "right") { + pos = getLeftAlignPosition(combo, popup, tW, container); } else { - top = BI.DOM.getTopAdaptPosition(combo, popup, extraHeight, needAdaptHeight, container).top; - firstDir = "top"; + pos = getRightAlignPosition(combo, popup, tW, container); } - if (leftRight[0] === "right") { - pos = BI.DOM.getLeftAlignPosition(combo, popup, extraWidth, container); - pos.top = top; - pos.dir = firstDir + "," + pos.dir; - return pos; + pos.dir = `bottom,${pos.dir}`; + if (lrFirst) { + pos.change = "bottom"; } - pos = BI.DOM.getRightAlignPosition(combo, popup, extraWidth, container); pos.top = top; - pos.dir = firstDir + "," + pos.dir; + return pos; - } - }, - - - getComboPosition: function (combo, popup, extraWidth, extraHeight, needAdaptHeight, directions, offsetStyle, positionRelativeElement) { - extraWidth || (extraWidth = 0); - extraHeight || (extraHeight = 0); - var viewportBounds = document.documentElement.getBoundingClientRect(); - var maxHeight = Math.min(popup.attr("maxHeight") || viewportBounds.height, viewportBounds.height); - popup.resetHeight && popup.resetHeight(maxHeight); - var position = BI.DOM.getComboPositionByDirections(combo, popup, extraWidth, extraHeight, needAdaptHeight, directions || ["bottom", "top", "right", "left"], positionRelativeElement); - switch (offsetStyle) { - case "center": - if (position.change) { - var p = BI.DOM.getMiddleAdaptPosition(combo, popup, positionRelativeElement); - position.top = p.top; - } else { - var p = BI.DOM.getCenterAdaptPosition(combo, popup, positionRelativeElement); - position.left = p.left; + } + if (needAdaptHeight) { + isNeedAdaptHeight = true; + } + tbFirst = true; + break; + case "innerLeft": + if (!isNeedAdaptHeight) { + var tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? 0 : extraHeight; + if (isInnerLeftSpaceEnough(combo, popup, tW)) { + left = getInnerLeftPosition(combo, popup, tW).left; + if (topBottom[0] === "bottom") { + pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight); + } else { + pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight); + } + pos.dir = `innerLeft,${pos.dir}`; + if (tbFirst) { + pos.change = "innerLeft"; + } + pos.left = left; + + return pos; } - break; - case "middle": - if (position.change) { - var p = BI.DOM.getCenterAdaptPosition(combo, popup, positionRelativeElement); - position.left = p.left; - } else { - var p = BI.DOM.getMiddleAdaptPosition(combo, popup, positionRelativeElement); - position.top = p.top; + } + lrFirst = true; + break; + case "innerRight": + if (!isNeedAdaptHeight) { + var tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? extraWidth : extraHeight; + if (isInnerRightSpaceEnough(combo, popup, tW)) { + left = getInnerRightPosition(combo, popup, tW).left; + if (topBottom[0] === "bottom") { + pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight); + } else { + pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight); + } + pos.dir = `innerLeft,${pos.dir}`; + if (tbFirst) { + pos.change = "innerRight"; + } + pos.left = left; + + return pos; } - break; + } + break; + default: + break; + } + } + + // 此处为四个方向放不下时挑空间最大的方向去放置, 也就是说我设置了弹出方向为"bottom,left", + // 最后发现实际弹出方向可能是"top,left",那么此时外界获取popup的方向应该是"top,left" + switch (directions[0]) { + case "left": + case "right": + if (isRightSpaceLarger(combo)) { + left = getRightAdaptPosition(combo, popup, extraWidth, container).left; + firstDir = "right"; + } else { + left = getLeftAdaptPosition(combo, popup, extraWidth, container).left; + firstDir = "left"; } - if (needAdaptHeight === true) { - popup.resetHeight && popup.resetHeight(Math.min(viewportBounds.height - position.top - (positionRelativeElement ? positionRelativeElement.getBoundingClientRect().top : 0), maxHeight)); + if (topBottom[0] === "bottom") { + pos = getTopAlignPosition(combo, popup, extraHeight, needAdaptHeight); + pos.left = left; + pos.dir = `${firstDir},${pos.dir}`; + + return pos; } - return position; - }, - - /** - * 获取position:fixed相对定位的元素 - */ - getPositionRelativeContainingBlock: function (element) { - if (['html', 'body', '#document'].indexOf((element.nodeName || '').toLowerCase()) >= 0) { - // $FlowFixMe[incompatible-return]: assume body is always available - return element.ownerDocument.body; + pos = getBottomAlignPosition(combo, popup, extraHeight, needAdaptHeight); + pos.left = left; + pos.dir = `${firstDir},${pos.dir}`; + + return pos; + default : + if (isBottomSpaceLarger(combo)) { + top = getBottomAdaptPosition(combo, popup, extraHeight, needAdaptHeight, container).top; + firstDir = "bottom"; + } else { + top = getTopAdaptPosition(combo, popup, extraHeight, needAdaptHeight, container).top; + firstDir = "top"; + } + if (leftRight[0] === "right") { + pos = getLeftAlignPosition(combo, popup, extraWidth, container); + pos.top = top; + pos.dir = `${firstDir},${pos.dir}`; + + return pos; + } + pos = getRightAlignPosition(combo, popup, extraWidth, container); + pos.top = top; + pos.dir = `${firstDir},${pos.dir}`; + + return pos; + } +} + + +export function getComboPosition(combo, popup, extraWidth, extraHeight, needAdaptHeight, directions, offsetStyle, positionRelativeElement) { + extraWidth || (extraWidth = 0); + extraHeight || (extraHeight = 0); + const viewportBounds = document.documentElement.getBoundingClientRect(); + const maxHeight = Math.min(popup.attr("maxHeight") || viewportBounds.height, viewportBounds.height); + popup.resetHeight && popup.resetHeight(maxHeight); + const position = getComboPositionByDirections(combo, popup, extraWidth, extraHeight, needAdaptHeight, directions || ["bottom", "top", "right", "left"], positionRelativeElement); + switch (offsetStyle) { + case "center": + if (position.change) { + var p = getMiddleAdaptPosition(combo, popup, positionRelativeElement); + position.top = p.top; + } else { + var p = getCenterAdaptPosition(combo, popup, positionRelativeElement); + position.left = p.left; + } + break; + case "middle": + if (position.change) { + var p = getCenterAdaptPosition(combo, popup, positionRelativeElement); + position.left = p.left; + } else { + var p = getMiddleAdaptPosition(combo, popup, positionRelativeElement); + position.top = p.top; } + break; + default: + break; + } + if (needAdaptHeight === true) { + popup.resetHeight && popup.resetHeight(Math.min(viewportBounds.height - position.top - (positionRelativeElement ? positionRelativeElement.getBoundingClientRect().top : 0), maxHeight)); + } - function isExcept(node) { - var _computedStyle = getComputedStyle(node); - var transform = _computedStyle.transform; - var perspective = _computedStyle.perspective; - var filter = _computedStyle.filter; - var willChange = _computedStyle["will-change"]; + return position; +} - return [transform, perspective, filter].some(value => value !== 'none') || (willChange === "transform"); - } +/** + * 获取position:fixed相对定位的元素 + */ +export function getPositionRelativeContainingBlock(element) { + if (["html", "body", "#document"].indexOf((element.nodeName || "").toLowerCase()) >= 0) { + // $FlowFixMe[incompatible-return]: assume body is always available + return element.ownerDocument.body; + } - if (isExcept(element)) { - return element; - } + function isExcept(node) { + const _computedStyle = getComputedStyle(node); + const transform = _computedStyle.transform; + const perspective = _computedStyle.perspective; + const filter = _computedStyle.filter; + const willChange = _computedStyle["will-change"]; - return BI.DOM.getPositionRelativeContainingBlock(element.parentNode); - }, - - /** - * 获取position:fixed相对定位的元素的clientRect - */ - getPositionRelativeContainingBlockRect: function (element) { - var positionRelativeElement = BI.DOM.getPositionRelativeContainingBlock(element); - var rect = positionRelativeElement.getBoundingClientRect(); - - return { - ...rect.toJSON(), - scaleX: rect.width / positionRelativeElement.offsetWidth, - scaleY: rect.height / positionRelativeElement.offsetHeight - }; - }, - }); -})(); + return [transform, perspective, filter].some(value => value !== "none") || (willChange === "transform"); + } + + if (isExcept(element)) { + return element; + } + + return getPositionRelativeContainingBlock(element.parentNode); +} + +/** + * 获取position:fixed相对定位的元素的clientRect + */ +export function getPositionRelativeContainingBlockRect(element) { + const positionRelativeElement = getPositionRelativeContainingBlock(element); + const rect = positionRelativeElement.getBoundingClientRect(); + + return { + ...rect.toJSON(), + scaleX: rect.width / positionRelativeElement.offsetWidth, + scaleY: rect.height / positionRelativeElement.offsetHeight, + }; +} diff --git a/src/core/platform/web/function.js b/src/core/platform/web/function.js index f05ef923d..2044e4160 100644 --- a/src/core/platform/web/function.js +++ b/src/core/platform/web/function.js @@ -1,151 +1,170 @@ // 浏览器相关方法 -BI._.extend(BI, { - isIE: function () { - if(!_global.navigator) { - return false; - } - if (this.__isIE == null) { - this.__isIE = /(msie|trident)/i.test(navigator.userAgent.toLowerCase()); - } - return this.__isIE; - }, +import { isString } from "../../2.base"; - getIEVersion: function () { - if(!_global.navigator) { - return 0; - } - if (this.__IEVersion != null) { - return this.__IEVersion; - } - var version = 0; - var agent = navigator.userAgent.toLowerCase(); - var v1 = agent.match(/(?:msie\s([\w.]+))/); - var v2 = agent.match(/(?:trident.*rv:([\w.]+))/); - if (v1 && v2 && v1[1] && v2[1]) { - version = Math.max(v1[1] * 1, v2[1] * 1); - } else if (v1 && v1[1]) { - version = v1[1] * 1; - } else if (v2 && v2[1]) { - version = v2[1] * 1; - } else { - version = 0; - } - return this.__IEVersion = version; - }, +let __isIE; - isIE9Below: function () { - if (!BI.isIE()) { - return false; - } - return this.getIEVersion() < 9; - }, +export function isIE() { + if (!_global.navigator) { + return false; + } + if (!__isIE) { + __isIE = /(msie|trident)/i.test(navigator.userAgent.toLowerCase()); + } - isEdge: function () { - if(!_global.navigator) { - return false; - } - return /edg/i.test(navigator.userAgent.toLowerCase()); - }, + return __isIE; +} - isChrome: function () { - if(!_global.navigator) { - return false; - } - return /chrome/i.test(navigator.userAgent.toLowerCase()); - }, +let __IEVersion; - isFireFox: function () { - if(!_global.navigator) { - return false; - } - return /firefox/i.test(navigator.userAgent.toLowerCase()); - }, +export function getIEVersion() { + if (!_global.navigator) { + return 0; + } + if (__IEVersion) { + return __IEVersion; + } + let version = 0; + const agent = navigator.userAgent.toLowerCase(); + const v1 = agent.match(/(?:msie\s([\w.]+))/); + const v2 = agent.match(/(?:trident.*rv:([\w.]+))/); + if (v1 && v2 && v1[1] && v2[1]) { + version = Math.max(v1[1] * 1, v2[1] * 1); + } else if (v1 && v1[1]) { + version = v1[1] * 1; + } else if (v2 && v2[1]) { + version = v2[1] * 1; + } else { + version = 0; + } + __IEVersion = version; - isOpera: function () { - if(!_global.navigator) { - return false; - } - return /opera/i.test(navigator.userAgent.toLowerCase()); - }, + return __IEVersion; +} - isSafari: function () { - if(!_global.navigator) { - return false; - } - return /safari/i.test(navigator.userAgent.toLowerCase()) && !/chrome/i.test(navigator.userAgent.toLowerCase()); - }, +export function isIE9Below() { + if (!isIE()) { + return false; + } - isKhtml: function () { - if(!_global.navigator) { - return false; - } - return /Konqueror|Safari|KHTML/i.test(navigator.userAgent); - }, + return getIEVersion() < 9; +} - isMac: function () { - if(!_global.navigator) { - return false; - } - return /macintosh|mac os x/i.test(navigator.userAgent); - }, +export function isEdge() { + if (!_global.navigator) { + return false; + } - isWindows: function () { - if(!_global.navigator) { - return false; - } - return /windows|win32/i.test(navigator.userAgent); - }, + return /edg/i.test(navigator.userAgent.toLowerCase()); +} - isSupportCss3: function (style) { - if(!_global.document) { - return false; - } - var prefix = ["webkit", "Moz", "ms", "o"], - i, len, - humpString = [], - htmlStyle = document.documentElement.style, - _toHumb = function (string) { - if (!BI.isString(string)) { - return ""; - } - - return string.replace(/-(\w)/g, function ($0, $1) { - return $1.toUpperCase(); - }); - }; - - for ( i = 0; i < prefix.length; i++) { - humpString.push(_toHumb(prefix[i] + "-" + style)); - } - humpString.push(_toHumb(style)); +export function isChrome() { + if (!_global.navigator) { + return false; + } - for (i = 0, len = humpString.length; i < len; i++) { - if (humpString[i] in htmlStyle) { - return true; - } - } + return /chrome/i.test(navigator.userAgent.toLowerCase()); +} + +export function isFireFox() { + if (!_global.navigator) { + return false; + } + + return /firefox/i.test(navigator.userAgent.toLowerCase()); +} + +export function isOpera() { + if (!_global.navigator) { + return false; + } + + return /opera/i.test(navigator.userAgent.toLowerCase()); +} + +export function isSafari() { + if (!_global.navigator) { + return false; + } + + return /safari/i.test(navigator.userAgent.toLowerCase()) && !/chrome/i.test(navigator.userAgent.toLowerCase()); +} + +export function isKhtml() { + if (!_global.navigator) { + return false; + } + + return /Konqueror|Safari|KHTML/i.test(navigator.userAgent); +} + +export function isMac() { + if (!_global.navigator) { + return false; + } + + return /macintosh|mac os x/i.test(navigator.userAgent); +} + +export function isWindows() { + if (!_global.navigator) { return false; - }, + } + + return /windows|win32/i.test(navigator.userAgent); +} + +export function isSupportCss3(style) { + if (!_global.document) { + return false; + } + const prefix = ["webkit", "Moz", "ms", "o"]; + const humpString = []; + const htmlStyle = document.documentElement.style; + let i; + let len; - getSafariVersion: function () { - if (!_global.navigator) { - return 0; + function _toHumb(string) { + if (!isString(string)) { + return ""; } - var agent = navigator.userAgent.toLowerCase(); - var version = agent.match(/version\/([\d.]+)/); - if (version && version[1]) { - return version[1] * 1; + + return string.replace(/-(\w)/g, ($0, $1) => $1.toUpperCase()); + }; + + for (i = 0; i < prefix.length; i++) { + humpString.push(_toHumb(`${prefix[i]}-${style}`)); + } + humpString.push(_toHumb(style)); + + for (i = 0, len = humpString.length; i < len; i++) { + if (humpString[i] in htmlStyle) { + return true; } + } + + return false; +} + +export function getSafariVersion() { + if (!_global.navigator) { return 0; - }, - - getMinimumFontSize: function () { - // not work for firefox - const el = document.createElement('div'); - el.style.fontSize = "1px"; - document.body.appendChild(el); - const size = getComputedStyle(el).fontSize; - el.remove(); - return parseInt(size); - } -}); + } + const agent = navigator.userAgent.toLowerCase(); + const version = agent.match(/version\/([\d.]+)/); + if (version && version[1]) { + return version[1] * 1; + } + + return 0; +} + +export function getMinimumFontSize() { + // not work for firefox + const el = document.createElement("div"); + el.style.fontSize = "1px"; + document.body.appendChild(el); + const size = getComputedStyle(el).fontSize; + el.remove(); + + return parseInt(size, 10); +} diff --git a/src/core/platform/web/index.js b/src/core/platform/web/index.js new file mode 100644 index 000000000..6dcaf06ba --- /dev/null +++ b/src/core/platform/web/index.js @@ -0,0 +1,4 @@ +export * as DOM from "./dom"; +export * from "./detectElementResize"; +export * from "./function"; +export * from "./load"; diff --git a/src/core/platform/web/load.js b/src/core/platform/web/load.js index f367b8cf6..7ab3a490a 100644 --- a/src/core/platform/web/load.js +++ b/src/core/platform/web/load.js @@ -1,55 +1,56 @@ -BI._.extend(BI, { - $import: function () { - var _LOADED = {}; // alex:保存加载过的 - function loadReady (src, must) { - var $scripts = BI.$("head script, body script"); - BI.$.each($scripts, function (i, item) { - if (item.src.indexOf(src) != -1) { - _LOADED[src] = true; - } - }); - var $links = BI.$("head link"); - BI.$.each($links, function (i, item) { - if (item.href.indexOf(src) != -1 && must) { - _LOADED[src] = false; - BI.$(item).remove(); - } - }); +const _LOADED = {}; // alex:保存加载过的 +function loadReady(src, must) { + const $scripts = BI.$("head script, body script"); + BI.$.each($scripts, (i, item) => { + if (item.src.indexOf(src) !== -1) { + _LOADED[src] = true; } + }); + const $links = BI.$("head link"); + BI.$.each($links, (i, item) => { + if (item.href.indexOf(src) !== -1 && must) { + _LOADED[src] = false; + BI.$(item).remove(); + } + }); +} - // must=true 强行加载 - return function (src, ext, must) { - loadReady(src, must); - // alex:如果已经加载过了的,直接return - if (_LOADED[src] === true) { - return; - } - if (ext === "css") { - var link = document.createElement("link"); - link.rel = "stylesheet"; - link.type = "text/css"; - link.href = src; - var head = document.getElementsByTagName("head")[0]; - head.appendChild(link); - _LOADED[src] = true; - } else { - // alex:这里用同步调用的方式,必须等待ajax完成 - BI.$.ajax({ - url: src, - dataType: "script", // alex:指定dataType为script,jquery会帮忙做globalEval的事情 - async: false, - cache: true, - complete: function (res, status) { - /* - * alex:发现jquery会很智能地判断一下返回的数据类型是不是script,然后做一个globalEval - * 所以当status为success时就不需要再把其中的内容加到script里面去了 - */ - if (status == "success") { - _LOADED[src] = true; - } - } - }); - } - }; - }() -}); \ No newline at end of file +/** + * + * @param src + * @param ext + * @param must 强行加载 + */ +export function $import(src, ext, must) { + loadReady(src, must); + // alex:如果已经加载过了的,直接return + if (_LOADED[src] === true) { + return; + } + if (ext === "css") { + const link = document.createElement("link"); + link.rel = "stylesheet"; + link.type = "text/css"; + link.href = src; + const head = document.getElementsByTagName("head")[0]; + head.appendChild(link); + _LOADED[src] = true; + } else { + // alex:这里用同步调用的方式,必须等待ajax完成 + BI.$.ajax({ + url: src, + dataType: "script", // alex:指定dataType为script,jquery会帮忙做globalEval的事情 + async: false, + cache: true, + complete(res, status) { + /* + * alex:发现jquery会很智能地判断一下返回的数据类型是不是script,然后做一个globalEval + * 所以当status为success时就不需要再把其中的内容加到script里面去了 + */ + if (status === "success") { + _LOADED[src] = true; + } + }, + }); + } +} From 720ae1260b223edb517be44968299d4a1fda670b Mon Sep 17 00:00:00 2001 From: zsmj Date: Mon, 9 Jan 2023 13:54:01 +0800 Subject: [PATCH 051/300] =?UTF-8?q?KERNEL-14041=20feat:=20core/platform?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=A4=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/func/function.js | 4 +- src/core/index.js | 3 + src/core/platform/web/index.js | 3 + src/core/platform/web/jquery/event.js | 6 +- src/core/platform/web/jquery/fn.js | 465 +++++++++++++------------- src/core/platform/web/jquery/index.js | 4 + 6 files changed, 250 insertions(+), 235 deletions(-) create mode 100644 src/core/platform/web/jquery/index.js diff --git a/src/core/func/function.js b/src/core/func/function.js index ecbd78f2d..5977e24d7 100644 --- a/src/core/func/function.js +++ b/src/core/func/function.js @@ -2,8 +2,8 @@ * 基本的函数 * Created by GUY on 2015/6/24. */ -import {every, isKey, isArray, toUpperCase, each, stripEL, isNotNull, isNull, isObject} from "../2.base"; -import {makeFirstPY} from "../utils/chinesePY"; +import { every, isKey, isArray, toUpperCase, each, stripEL, isNotNull, isNull, isObject } from "../2.base"; +import { makeFirstPY } from "../utils/chinesePY"; /** * 创建唯一的名字 diff --git a/src/core/index.js b/src/core/index.js index 34ab918cd..eca5e3e99 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -16,6 +16,7 @@ import * as constant from "./constant"; import * as logic from "./logic"; import { Element } from "./element"; import * as utils from "./utils"; +import * as platform from "./platform/web"; export * from "./decorator"; export * from "./2.base"; @@ -31,6 +32,7 @@ export * from "./h"; export * from "./constant"; export * from "./logic"; export * from "./utils"; +export * from "./platform/web"; export { StyleLoaderManager, @@ -60,4 +62,5 @@ Object.assign(BI, { useInWorker, ...h, ...utils, + ...platform, }); diff --git a/src/core/platform/web/index.js b/src/core/platform/web/index.js index 6dcaf06ba..db216134b 100644 --- a/src/core/platform/web/index.js +++ b/src/core/platform/web/index.js @@ -2,3 +2,6 @@ export * as DOM from "./dom"; export * from "./detectElementResize"; export * from "./function"; export * from "./load"; + +import "./jquery/index"; +import "./config"; diff --git a/src/core/platform/web/jquery/event.js b/src/core/platform/web/jquery/event.js index b7a9500f3..ea3ec568f 100644 --- a/src/core/platform/web/jquery/event.js +++ b/src/core/platform/web/jquery/event.js @@ -3,8 +3,8 @@ */ BI.$.extend(BI.$.Event.prototype, { // event.stopEvent - stopEvent: function () { + stopEvent() { this.stopPropagation(); this.preventDefault(); - } -}); \ No newline at end of file + }, +}); diff --git a/src/core/platform/web/jquery/fn.js b/src/core/platform/web/jquery/fn.js index 33584d838..16041a83e 100644 --- a/src/core/platform/web/jquery/fn.js +++ b/src/core/platform/web/jquery/fn.js @@ -1,247 +1,252 @@ -if (BI.jQuery) { - (function ($) { - // richer:容器在其各个边缘留出的空间 - if (!$.fn.insets) { - $.fn.insets = function () { - var p = this.padding(), - b = this.border(); - return { - top: p.top, - bottom: p.bottom + b.bottom + b.top, - left: p.left, - right: p.right + b.right + b.left - }; - }; - } - - // richer:获取 && 设置jQuery元素的边界 - if (!$.fn.bounds) { - $.fn.bounds = function (value) { - var tmp = {hasIgnoredBounds: true}; - - if (value) { - if (!isNaN(value.x)) { - tmp.left = value.x; - } - if (!isNaN(value.y)) { - tmp.top = value.y; - } - if (value.width != null) { - tmp.width = (value.width - (this.outerWidth(true) - this.width())); - tmp.width = (tmp.width >= 0) ? tmp.width : value.width; - // fix chrome - // tmp.width = (tmp.width >= 0) ? tmp.width : 0; - } - if (value.height != null) { - tmp.height = value.height - (this.outerHeight(true) - this.height()); - tmp.height = (tmp.height >= 0) ? tmp.height : value.height; - // fix chrome - // tmp.height = (tmp.height >= 0) ? tmp.height : value.0; - } - this.css(tmp); - return this; - } - - // richer:注意此方法只对可见元素有效 - tmp = this.position(); - return { - x: tmp.left, - y: tmp.top, - // richer:这里计算外部宽度和高度的时候,都不包括边框 - width: this.outerWidth(), - height: this.outerHeight() - }; - - }; - } - })(BI.jQuery); - - BI.extend(BI.jQuery.fn, { - - destroy: function () { - this.remove(); - if (BI.isIE() === true) { - this[0].outerHTML = ""; +import { isIE, isIE9Below } from "../function"; +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"; + +BI.jQuery.fn.extend({ + + insets() { + const p = this.padding(), + b = this.border(); + + return { + top: p.top, + bottom: p.bottom + b.bottom + b.top, + left: p.left, + right: p.right + b.right + b.left, + }; + }, + + bounds(value) { + let tmp = { hasIgnoredBounds: true }; + + if (value) { + if (!isNaN(value.x)) { + tmp.left = value.x; } - }, - /** - * 高亮显示 - * @param text 必需 - * @param keyword - * @param py - * @returns {*} - * @private - * 原理: - * 1、得到text的拼音py, 分别看是否匹配关键字keyword, 得到匹配索引tidx和pidx - * 2、比较tidx和pidx, 取大于-1且较小的索引,标红[索引,索引 + keyword.length - 1]的文本 - * 3、text和py各自取tidx/pidx + keyword.length索引开始的子串作为新的text和py, 重复1, 直到text和py有一个为"" - */ - __textKeywordMarked__: function (text, keyword, py) { - if (BI.isNull(text)) { - text = ""; + if (!isNaN(value.y)) { + tmp.top = value.y; } - if (!BI.isKey(keyword) || (text + "").length > 100) { - if (BI.isIE9Below()) { - return this.html(BI.htmlEncode(text)); - } - // textContent性能更好,并且原生防xss - this[0].textContent = text; - return this; + if (value.width != null) { + tmp.width = (value.width - (this.outerWidth(true) - this.width())); + tmp.width = (tmp.width >= 0) ? tmp.width : value.width; + // fix chrome + // tmp.width = (tmp.width >= 0) ? tmp.width : 0; } - keyword = keyword + ""; - keyword = BI.toUpperCase(keyword); - var textLeft = text + ""; - py = (py || BI.makeFirstPY(text, { - splitChar: "\u200b" - })) + ""; - py = BI.toUpperCase(py); - this.empty(); - // BI-48487 性能: makeFirstPY出来的py中包含多音字是必要的,但虽然此方法中做了限制。但是对于一个长度为60,包含14个多音字的字符串 - // 获取的的py长度将达到1966080, 远超过text的长度,到后面都是在做"".substring的无用功,所以此循环应保证py和textLeft长度不为0 - while (py.length > 0 && textLeft.length > 0) { - var tidx = BI.toUpperCase(textLeft).indexOf(keyword); - var pidx = py.indexOf(keyword); - if (pidx >= 0) { - pidx = (pidx - Math.floor(pidx / (textLeft.length + 1))) % textLeft.length; - } + if (value.height != null) { + tmp.height = value.height - (this.outerHeight(true) - this.height()); + tmp.height = (tmp.height >= 0) ? tmp.height : value.height; + // fix chrome + // tmp.height = (tmp.height >= 0) ? tmp.height : value.0; + } + this.css(tmp); - // BI-56945 场景: 对'啊a'标红, a为keyword, 此时tidx为1, pidx为0, 此时使用tidx显然'啊'就无法标红了 - if (tidx >= 0 && (pidx > tidx || pidx === -1)) { - // 标红的text未encode - this.append(BI.htmlEncode(textLeft.substr(0, tidx))); - this.append(BI.$("").addClass("bi-keyword-red-mark") - .html(BI.htmlEncode(textLeft.substr(tidx, keyword.length)))); - - textLeft = textLeft.substr(tidx + keyword.length); - if (BI.isNotEmptyString(py)) { - // 每一组拼音都应该前进,而不是只是当前的 - py = BI.map(py.split("\u200b"), function (idx, ps) { - return ps.slice(tidx + keyword.length); - }).join("\u200b"); - } - } else if (pidx >= 0) { - // BI-56386 这边两个pid / text.length是为了防止截取的首字符串不是完整的,但光这样做还不够,即时错位了,也不能说明就不符合条件 - // 标红的text未encode - this.append(BI.htmlEncode(textLeft.substr(0, pidx))); - this.append(BI.$("").addClass("bi-keyword-red-mark") - .html(BI.htmlEncode(textLeft.substr(pidx, keyword.length)))); - if (BI.isNotEmptyString(py)) { - // 每一组拼音都应该前进,而不是只是当前的 - py = BI.map(py.split("\u200b"), function (idx, ps) { - return ps.slice(pidx + keyword.length); - }).join("\u200b"); - } - textLeft = textLeft.substr(pidx + keyword.length); - } else { - // 标红的text未encode - this.append(BI.htmlEncode(textLeft)); - break; - } + return this; + } + + // richer:注意此方法只对可见元素有效 + tmp = this.position(); + + return { + x: tmp.left, + y: tmp.top, + // richer:这里计算外部宽度和高度的时候,都不包括边框 + width: this.outerWidth(), + height: this.outerHeight(), + }; + }, + + destroy() { + this.remove(); + if (isIE() === true) { + this[0].outerHTML = ""; + } + }, + + /** + * 高亮显示 + * @param text 必需 + * @param keyword + * @param py + * @returns {*} + * @private + * 原理: + * 1、得到text的拼音py, 分别看是否匹配关键字keyword, 得到匹配索引tidx和pidx + * 2、比较tidx和pidx, 取大于-1且较小的索引,标红[索引,索引 + keyword.length - 1]的文本 + * 3、text和py各自取tidx/pidx + keyword.length索引开始的子串作为新的text和py, 重复1, 直到text和py有一个为"" + */ + __textKeywordMarked__(text, keyword, py) { + if (isNull(text)) { + text = ""; + } + if (!isKey(keyword) || (`${text}`).length > 100) { + if (isIE9Below()) { + return this.html(htmlEncode(text)); } + // textContent性能更好,并且原生防xss + this[0].textContent = text; return this; - }, - - getDomHeight: function (parent) { - var clone = BI.$(this).clone(); - clone.appendTo(BI.$(parent || "body")); - var height = clone.height(); - clone.remove(); - return height; - }, - - // 是否有竖直滚动条 - hasVerticalScroll: function () { - return this.height() > 0 && this[0].clientWidth < this[0].offsetWidth; - }, - - // 是否有水平滚动条 - hasHorizonScroll: function () { - return this.width() > 0 && this[0].clientHeight < this[0].offsetHeight; - }, - - // 获取计算后的样式 - getStyle: function (name) { - var node = this[0]; - var computedStyle = void 0; - - // W3C Standard - if (_global.getComputedStyle) { - // In certain cases such as within an iframe in FF3, this returns null. - computedStyle = _global.getComputedStyle(node, null); - if (computedStyle) { - return computedStyle.getPropertyValue(BI.hyphenate(name)); - } + } + keyword = `${keyword}`; + keyword = toUpperCase(keyword); + let textLeft = `${text}`; + py = `${py || makeFirstPY(text, { + splitChar: "\u200b", + })}`; + py = toUpperCase(py); + this.empty(); + // BI-48487 性能: makeFirstPY出来的py中包含多音字是必要的,但虽然此方法中做了限制。但是对于一个长度为60,包含14个多音字的字符串 + // 获取的的py长度将达到1966080, 远超过text的长度,到后面都是在做"".substring的无用功,所以此循环应保证py和textLeft长度不为0 + while (py.length > 0 && textLeft.length > 0) { + const tidx = toUpperCase(textLeft).indexOf(keyword); + let pidx = py.indexOf(keyword); + if (pidx >= 0) { + pidx = (pidx - Math.floor(pidx / (textLeft.length + 1))) % textLeft.length; } - // Safari - if (document.defaultView && document.defaultView.getComputedStyle) { - computedStyle = document.defaultView.getComputedStyle(node, null); - // A Safari bug causes this to return null for `display: none` elements. - if (computedStyle) { - return computedStyle.getPropertyValue(BI.hyphenate(name)); + + // BI-56945 场景: 对'啊a'标红, a为keyword, 此时tidx为1, pidx为0, 此时使用tidx显然'啊'就无法标红了 + if (tidx >= 0 && (pidx > tidx || pidx === -1)) { + // 标红的text未encode + this.append(htmlEncode(textLeft.substr(0, tidx))); + this.append(BI.$("").addClass("bi-keyword-red-mark") + .html(htmlEncode(textLeft.substr(tidx, keyword.length)))); + + textLeft = textLeft.substr(tidx + keyword.length); + if (isNotEmptyString(py)) { + // 每一组拼音都应该前进,而不是只是当前的 + py = map(py.split("\u200b"), (idx, ps) => ps.slice(tidx + keyword.length)).join("\u200b"); } - if (name === "display") { - return "none"; + } else if (pidx >= 0) { + // BI-56386 这边两个pid / text.length是为了防止截取的首字符串不是完整的,但光这样做还不够,即时错位了,也不能说明就不符合条件 + // 标红的text未encode + this.append(htmlEncode(textLeft.substr(0, pidx))); + this.append(BI.$("").addClass("bi-keyword-red-mark") + .html(htmlEncode(textLeft.substr(pidx, keyword.length)))); + if (isNotEmptyString(py)) { + // 每一组拼音都应该前进,而不是只是当前的 + py = map(py.split("\u200b"), (idx, ps) => ps.slice(pidx + keyword.length)).join("\u200b"); } + textLeft = textLeft.substr(pidx + keyword.length); + } else { + // 标红的text未encode + this.append(htmlEncode(textLeft)); + break; } - // Internet Explorer - if (node.currentStyle) { - if (name === "float") { - return node.currentStyle.cssFloat || node.currentStyle.styleFloat; - } - return node.currentStyle[BI.camelize(name)]; + } + + return this; + }, + + getDomHeight(parent) { + const clone = BI.$(this).clone(); + clone.appendTo(BI.$(parent || "body")); + const height = clone.height(); + clone.remove(); + + return height; + }, + + // 是否有竖直滚动条 + hasVerticalScroll() { + return this.height() > 0 && this[0].clientWidth < this[0].offsetWidth; + }, + + // 是否有水平滚动条 + hasHorizonScroll() { + return this.width() > 0 && this[0].clientHeight < this[0].offsetHeight; + }, + + // 获取计算后的样式 + getStyle(name) { + const node = this[0]; + let computedStyle = void 0; + + // W3C Standard + if (_global.getComputedStyle) { + // In certain cases such as within an iframe in FF3, this returns null. + computedStyle = _global.getComputedStyle(node, null); + if (computedStyle) { + return computedStyle.getPropertyValue(hyphenate(name)); + } + } + // Safari + if (document.defaultView && document.defaultView.getComputedStyle) { + computedStyle = document.defaultView.getComputedStyle(node, null); + // A Safari bug causes this to return null for `display: none` elements. + if (computedStyle) { + return computedStyle.getPropertyValue(hyphenate(name)); + } + if (name === "display") { + return "none"; + } + } + // Internet Explorer + if (node.currentStyle) { + if (name === "float") { + return node.currentStyle.cssFloat || node.currentStyle.styleFloat; } - return node.style && node.style[BI.camelize(name)]; - }, - - __isMouseInBounds__: function (e) { - var offset2Body = this.get(0).getBoundingClientRect ? this.get(0).getBoundingClientRect() : this.offset(); - var width = offset2Body.width || this.outerWidth(); - var height = offset2Body.height || this.outerHeight(); - // offset2Body.left的值可能会有小数,导致某点出现false - return !(e.pageX < Math.floor(offset2Body.left) || e.pageX > offset2Body.left + width - || e.pageY < Math.floor(offset2Body.top) || e.pageY > offset2Body.top + height); - }, - - __hasZIndexMask__: function (zindex) { - return zindex && this.zIndexMask[zindex] != null; - }, - - __buildZIndexMask__: function (zindex, domArray) { - this.zIndexMask = this.zIndexMask || {};// 存储z-index的mask - this.indexMask = this.indexMask || [];// 存储mask - var mask = BI.createWidget({ - type: "bi.center_adapt", - cls: "bi-z-index-mask", - items: domArray - }); - - mask.element.css({"z-index": zindex}); - BI.createWidget({ - type: "bi.absolute", - element: this, - items: [{ + + return node.currentStyle[camelize(name)]; + } + + return node.style && node.style[camelize(name)]; + }, + + __isMouseInBounds__(e) { + const offset2Body = this.get(0).getBoundingClientRect ? this.get(0).getBoundingClientRect() : this.offset(); + const width = offset2Body.width || this.outerWidth(); + const height = offset2Body.height || this.outerHeight(); + + // offset2Body.left的值可能会有小数,导致某点出现false + return !(e.pageX < Math.floor(offset2Body.left) || e.pageX > offset2Body.left + width + || e.pageY < Math.floor(offset2Body.top) || e.pageY > offset2Body.top + height); + }, + + __hasZIndexMask__(zindex) { + return zindex && this.zIndexMask[zindex] != null; + }, + + __buildZIndexMask__(zindex, domArray) { + this.zIndexMask = this.zIndexMask || {};// 存储z-index的mask + this.indexMask = this.indexMask || [];// 存储mask + const mask = createWidget({ + type: "bi.center_adapt", + cls: "bi-z-index-mask", + items: domArray, + }); + + mask.element.css({ "z-index": zindex }); + createWidget({ + type: "bi.absolute", + element: this, + items: [ + { el: mask, left: 0, right: 0, top: 0, - bottom: 0 - }] - }); - this.indexMask.push(mask); - zindex && (this.zIndexMask[zindex] = mask); - return mask.element; - }, - - __releaseZIndexMask__: function (zindex) { - if (zindex && this.zIndexMask[zindex]) { - BI.remove(this.indexMask, this.zIndexMask[zindex]); - this.zIndexMask[zindex].destroy(); - return; - } - this.indexMask = this.indexMask || []; - var indexMask = this.indexMask.pop(); - indexMask && indexMask.destroy(); + bottom: 0, + } + ], + }); + this.indexMask.push(mask); + zindex && (this.zIndexMask[zindex] = mask); + + return mask.element; + }, + + __releaseZIndexMask__(zindex) { + if (zindex && this.zIndexMask[zindex]) { + remove(this.indexMask, this.zIndexMask[zindex]); + this.zIndexMask[zindex].destroy(); + + return; } - }); -} + this.indexMask = this.indexMask || []; + const indexMask = this.indexMask.pop(); + indexMask && indexMask.destroy(); + }, +}); + diff --git a/src/core/platform/web/jquery/index.js b/src/core/platform/web/jquery/index.js new file mode 100644 index 000000000..4c523e052 --- /dev/null +++ b/src/core/platform/web/jquery/index.js @@ -0,0 +1,4 @@ +import "./_jquery"; +import "./event"; +import "./fn"; +import "./jquery.mousewheel"; From 5376192e59249eb7a512bcb0d701c6ac1c3f6678 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Mon, 9 Jan 2023 17:41:17 +0800 Subject: [PATCH 052/300] =?UTF-8?q?KERNEL-14035=20refactor:=20layout?= =?UTF-8?q?=E7=9B=B8=E5=85=B3es6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/index.js | 3 + src/core/wrapper/index.js | 2 + src/core/wrapper/layout.js | 736 +++++++++--------- .../wrapper/layout/adapt/absolute.center.js | 51 +- .../layout/adapt/absolute.horizontal.js | 50 +- .../adapt/absolute.leftrightvertical.js | 160 ++-- .../wrapper/layout/adapt/absolute.vertical.js | 48 +- src/core/wrapper/layout/adapt/adapt.center.js | 51 +- .../wrapper/layout/adapt/adapt.horizontal.js | 11 +- .../layout/adapt/adapt.leftrightvertical.js | 177 +++-- src/core/wrapper/layout/adapt/adapt.table.js | 103 +-- .../wrapper/layout/adapt/adapt.vertical.js | 47 +- .../wrapper/layout/adapt/auto.horizontal.js | 50 +- src/core/wrapper/layout/adapt/index.js | 13 + .../wrapper/layout/adapt/inline.center.js | 47 +- .../wrapper/layout/adapt/inline.horizontal.js | 47 +- .../wrapper/layout/adapt/inline.vertical.js | 47 +- src/core/wrapper/layout/index.js | 17 + src/core/wrapper/layout/layout.absolute.js | 138 ++-- src/core/wrapper/layout/layout.adaptive.js | 69 +- src/core/wrapper/layout/layout.border.js | 102 +-- src/core/wrapper/layout/layout.card.js | 215 ++--- src/core/wrapper/layout/layout.default.js | 48 +- src/core/wrapper/layout/layout.division.js | 126 +-- src/core/wrapper/layout/layout.flow.js | 181 +++-- src/core/wrapper/layout/layout.grid.js | 106 +-- src/core/wrapper/layout/layout.horizontal.js | 14 +- src/core/wrapper/layout/layout.inline.js | 91 ++- src/core/wrapper/layout/layout.lattice.js | 55 +- src/core/wrapper/layout/layout.table.js | 95 +-- src/core/wrapper/layout/layout.tape.js | 244 +++--- src/core/wrapper/layout/layout.td.js | 134 ++-- src/core/wrapper/layout/layout.vertical.js | 63 +- src/core/wrapper/layout/layout.window.js | 163 ++-- 34 files changed, 1901 insertions(+), 1603 deletions(-) create mode 100644 src/core/wrapper/index.js create mode 100644 src/core/wrapper/layout/adapt/index.js create mode 100644 src/core/wrapper/layout/index.js diff --git a/src/core/index.js b/src/core/index.js index 34ab918cd..284098aa7 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -16,6 +16,7 @@ import * as constant from "./constant"; import * as logic from "./logic"; import { Element } from "./element"; import * as utils from "./utils"; +import * as wrapper from "./wrapper"; export * from "./decorator"; export * from "./2.base"; @@ -31,6 +32,7 @@ export * from "./h"; export * from "./constant"; export * from "./logic"; export * from "./utils"; +export * from "./wrapper"; export { StyleLoaderManager, @@ -60,4 +62,5 @@ Object.assign(BI, { useInWorker, ...h, ...utils, + ...wrapper, }); diff --git a/src/core/wrapper/index.js b/src/core/wrapper/index.js new file mode 100644 index 000000000..c32c3e3bf --- /dev/null +++ b/src/core/wrapper/index.js @@ -0,0 +1,2 @@ +export { Layout } from "./layout"; +export * from "./layout/index"; diff --git a/src/core/wrapper/layout.js b/src/core/wrapper/layout.js index d2926385d..6649f55bb 100644 --- a/src/core/wrapper/layout.js +++ b/src/core/wrapper/layout.js @@ -1,15 +1,22 @@ +import { isNull, isFunction, each, stripEL, keys, isArray, contains, isKey, isOdd, isWidget, isNotNull, has } from "../2.base"; +import { Widget } from "../4.widget"; +import { _lazyCreateWidget, Providers } from "../5.inject"; +import { shortcut } from "../decorator"; +import { pixFormat, Events } from "../constant"; + /** * 布局容器类 - * @class BI.Layout - * @extends BI.Widget * * @cfg {JSON} options 配置属性 * @cfg {Boolean} [options.scrollable=false] 子组件超出容器边界之后是否会出现滚动条 * @cfg {Boolean} [options.scrollx=false] 子组件超出容器边界之后是否会出现横向滚动条 * @cfg {Boolean} [options.scrolly=false] 子组件超出容器边界之后是否会出现纵向滚动条 */ -BI.Layout = BI.inherit(BI.Widget, { - props: function () { +@shortcut() +export class Layout extends Widget { + static xtype = "bi.layout"; + + props() { return { scrollable: null, // true, false, null scrollx: false, // true, false @@ -18,93 +25,97 @@ BI.Layout = BI.inherit(BI.Widget, { innerHgap: 0, innerVgap: 0, }; - }, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; this._init4Margin(); this._init4Scroll(); - if (BI.isFunction(o.columnSize)) { - var columnSizeFn = o.columnSize; - o.columnSize = this.__watch(columnSizeFn, function (context, newValue) { + if (isFunction(o.columnSize)) { + const columnSizeFn = o.columnSize; + o.columnSize = this.__watch(columnSizeFn, (context, newValue) => { o.columnSize = newValue; - self.resize(); + this.resize(); }); } - if (BI.isFunction(o.rowSize)) { - var rowSizeFn = o.rowSize; - o.rowSize = this.__watch(rowSizeFn, function (context, newValue) { + if (isFunction(o.rowSize)) { + const rowSizeFn = o.rowSize; + o.rowSize = this.__watch(rowSizeFn, (context, newValue) => { o.rowSize = newValue; - self.resize(); + this.resize(); }); } - }, + } - _init4Margin: function () { + _init4Margin() { if (this.options.top) { - this.element.css("top", BI.pixFormat(this.options.top)); + this.element.css("top", pixFormat(this.options.top)); } if (this.options.left) { - this.element.css("left", BI.pixFormat(this.options.left)); + this.element.css("left", pixFormat(this.options.left)); } if (this.options.bottom) { - this.element.css("bottom", BI.pixFormat(this.options.bottom)); + this.element.css("bottom", pixFormat(this.options.bottom)); } if (this.options.right) { - this.element.css("right", BI.pixFormat(this.options.right)); + this.element.css("right", pixFormat(this.options.right)); } - }, + } - _init4Scroll: function () { + _init4Scroll() { switch (this.options.scrollable) { - case true: - case "xy": - this.element.css("overflow", "auto"); - return; - case false: - this.element.css("overflow", "hidden"); - return; - case "x": - this.element.css({ - "overflow-x": "auto", - "overflow-y": "hidden" - }); - return; - case "y": - this.element.css({ - "overflow-x": "hidden", - "overflow-y": "auto" - }); - return; - default : - break; + case true: + case "xy": + this.element.css("overflow", "auto"); + + return; + case false: + this.element.css("overflow", "hidden"); + + return; + case "x": + this.element.css({ + "overflow-x": "auto", + "overflow-y": "hidden", + }); + + return; + case "y": + this.element.css({ + "overflow-x": "hidden", + "overflow-y": "auto", + }); + + return; + default : + break; } if (this.options.scrollx) { this.element.css({ "overflow-x": "auto", - "overflow-y": "hidden" + "overflow-y": "hidden", }); + return; } if (this.options.scrolly) { this.element.css({ "overflow-x": "hidden", - "overflow-y": "auto" + "overflow-y": "auto", }); } - }, + } - appendFragment: function (frag) { + appendFragment(frag) { this.element.append(frag); - }, - - _mountChildren: function () { - var self = this; - var frag = BI.Widget._renderEngine.createFragment(); - var hasChild = false; - for (var key in this._children) { - var child = this._children[key]; - if (child.element !== self.element) { + } + + _mountChildren() { + const frag = Widget._renderEngine.createFragment(); + let hasChild = false; + for (const key in this._children) { + const child = this._children[key]; + if (child.element !== this.element) { frag.appendChild(child.element[0]); hasChild = true; } @@ -112,24 +123,24 @@ BI.Layout = BI.inherit(BI.Widget, { if (hasChild === true) { this.appendFragment(frag); } - }, + } - _getChildName: function (index) { - return "" + index; - }, + _getChildName(index) { + return `${index}`; + } - _addElement: function (i, item, context, widget) { - var self = this, w; + _addElement(i, item, context, widget) { + let w; if (widget) { return widget; } if (!this.hasWidget(this._getChildName(i))) { - w = BI._lazyCreateWidget(item, context); - w.on(BI.Events.DESTROY, function () { - BI.each(self._children, function (name, child) { + w = _lazyCreateWidget(item, context); + w.on(Events.DESTROY, () => { + each(this._children, (name, child) => { if (child === w) { - delete self._children[name]; - self.removeItemAt(name | 0); + delete this._children[name]; + this.removeItemAt(name | 0); } }); }); @@ -137,73 +148,74 @@ BI.Layout = BI.inherit(BI.Widget, { } else { w = this.getWidgetByName(this._getChildName(i)); } + return w; - }, + } - _newElement: function (i, item, context) { - var self = this; - var w = BI._lazyCreateWidget(item, context); - w.on(BI.Events.DESTROY, function () { - BI.each(self._children, function (name, child) { + _newElement(i, item, context) { + const w = _lazyCreateWidget(item, context); + w.on(Events.DESTROY, () => { + each(this._children, (name, child) => { if (child === w) { - delete self._children[name]; - self.removeItemAt(name | 0); + delete this._children[name]; + this.removeItemAt(name | 0); } }); }); + return this._addElement(i, item, context, w); - }, + } - _getOptions: function (item) { - if (item instanceof BI.Widget) { + _getOptions(item) { + if (item instanceof Widget) { item = item.options; } - item = BI.stripEL(item); - if (item instanceof BI.Widget) { + item = stripEL(item); + if (item instanceof Widget) { item = item.options; } + return item; - }, - - _compare: function (item1, item2) { - var self = this; - return eq(item1, item2); + } + _compare(item1, item2) { // 不比较函数 - function eq (a, b, aStack, bStack) { + const eq = (a, b, aStack, bStack) => { if (a === b) { return a !== 0 || 1 / a === 1 / b; } - if (a == null || b == null) { + if (isNull(a) || isNull(b)) { return a === b; } - var className = Object.prototype.toString.call(a); + const className = Object.prototype.toString.call(a); switch (className) { - case "[object RegExp]": - case "[object String]": - return "" + a === "" + b; - case "[object Number]": - if (+a !== +a) { - return +b !== +b; - } - return +a === 0 ? 1 / +a === 1 / b : +a === +b; - case "[object Date]": - case "[object Boolean]": - return +a === +b; + case "[object RegExp]": + case "[object String]": + return `${a}` === `${b}`; + case "[object Number]": + if (+a !== +a) { + return +b !== +b; + } + + return +a === 0 ? 1 / +a === 1 / b : +a === +b; + case "[object Date]": + case "[object Boolean]": + return +a === +b; + default: } - var areArrays = className === "[object Array]"; + const areArrays = className === "[object Array]"; if (!areArrays) { - if (BI.isFunction(a) && BI.isFunction(b)) { + if (isFunction(a) && isFunction(b)) { return true; } - a = self._getOptions(a); - b = self._getOptions(b); + a = this._getOptions(a); + b = this._getOptions(b); } aStack = aStack || []; bStack = bStack || []; - var length = aStack.length; + let length = aStack.length; while (length--) { if (aStack[length] === a) { return bStack[length] === b; @@ -224,115 +236,126 @@ BI.Layout = BI.inherit(BI.Widget, { } } } else { - var keys = BI._.keys(a), key; - length = keys.length; - if (BI._.keys(b).length !== length) { + const aKeys = keys(a); + let key; + length = aKeys.length; + if (keys(b).length !== length) { return false; } while (length--) { - key = keys[length]; - if (!(BI._.has(b, key) && eq(a[key], b[key], aStack, bStack))) { + key = aKeys[length]; + if (!(has(b, key) && eq(a[key], b[key], aStack, bStack))) { return false; } } } aStack.pop(); bStack.pop(); + return true; - } - }, + }; + + return eq(item1, item2); + } - _getWrapper: function () { + _getWrapper() { return this.element; - }, + } // 不依赖于this.options.items进行更新 - _updateItemAt: function (oldIndex, newIndex, item) { - var del = this._children[this._getChildName(oldIndex)]; - var w = this._newElement(newIndex, item); + _updateItemAt(oldIndex, newIndex, item) { + const del = this._children[this._getChildName(oldIndex)]; + const w = this._newElement(newIndex, item); // 需要有个地方临时存一下新建的组件,否则如果直接使用newIndex的话,newIndex位置的元素可能会被用到 - this._children[this._getChildName(newIndex) + "-temp"] = w; - var nextSibling = del.element.next(); + this._children[`${this._getChildName(newIndex)}-temp`] = w; + const nextSibling = del.element.next(); if (nextSibling.length > 0) { - BI.Widget._renderEngine.createElement(nextSibling).before(w.element); + Widget._renderEngine.createElement(nextSibling).before(w.element); } else { w.element.appendTo(this._getWrapper()); } del._destroy(); w._mount(); + return true; - }, + } - _addItemAt: function (index, item) { - for (var i = this.options.items.length; i > index; i--) { + _addItemAt(index, item) { + for (let i = this.options.items.length; i > index; i--) { this._children[this._getChildName(i)] = this._children[this._getChildName(i - 1)]; } delete this._children[this._getChildName(index)]; this.options.items.splice(index, 0, item); - }, + } - _removeItemAt: function (index) { - for (var i = index; i < this.options.items.length - 1; i++) { + _removeItemAt(index) { + for (let i = index; i < this.options.items.length - 1; i++) { this._children[this._getChildName(i)] = this._children[this._getChildName(i + 1)]; } delete this._children[this._getChildName(this.options.items.length - 1)]; this.options.items.splice(index, 1); - }, + } - _clearGap: function (w) { + _clearGap(w) { w.element.css({ "margin-top": "", "margin-bottom": "", "margin-left": "", - "margin-right": "" + "margin-right": "", }); - }, + } - _optimiseGap: function (gap) { - return (gap > 0 && gap < 1) ? (gap * 100).toFixed(1) + "%" : BI.pixFormat(gap); - }, + _optimiseGap(gap) { + return (gap > 0 && gap < 1) ? `${(gap * 100).toFixed(1)}%` : pixFormat(gap); + } - _optimiseItemLgap: function (item) { - if (BI.Providers.getProvider("bi.provider.system").getLayoutOptimize()) { + _optimiseItemLgap(item) { + if (Providers.getProvider("bi.provider.system").getLayoutOptimize()) { return ((!item.type && item.el) ? ((item._lgap || 0) + (item.lgap || 0)) : item._lgap) || 0; } + return (item._lgap || 0) + (item.lgap || 0); - }, - _optimiseItemRgap: function (item) { - if (BI.Providers.getProvider("bi.provider.system").getLayoutOptimize()) { + } + _optimiseItemRgap(item) { + if (Providers.getProvider("bi.provider.system").getLayoutOptimize()) { return ((!item.type && item.el) ? ((item._rgap || 0) + (item.rgap || 0)) : item._rgap) || 0; } + return (item._rgap || 0) + (item.rgap || 0); - }, - _optimiseItemTgap: function (item) { - if (BI.Providers.getProvider("bi.provider.system").getLayoutOptimize()) { + } + _optimiseItemTgap(item) { + if (Providers.getProvider("bi.provider.system").getLayoutOptimize()) { return ((!item.type && item.el) ? ((item._tgap || 0) + (item.tgap || 0)) : item._tgap) || 0; } + return (item._tgap || 0) + (item.tgap || 0); - }, - _optimiseItemBgap: function (item) { - if (BI.Providers.getProvider("bi.provider.system").getLayoutOptimize()) { + } + _optimiseItemBgap(item) { + if (Providers.getProvider("bi.provider.system").getLayoutOptimize()) { return ((!item.type && item.el) ? ((item._bgap || 0) + (item.bgap || 0)) : item._bgap) || 0; } + return (item._bgap || 0) + (item.bgap || 0); - }, - _optimiseItemHgap: function (item) { - if (BI.Providers.getProvider("bi.provider.system").getLayoutOptimize()) { + } + _optimiseItemHgap(item) { + if (Providers.getProvider("bi.provider.system").getLayoutOptimize()) { return ((!item.type && item.el) ? ((item._hgap || 0) + (item.hgap || 0)) : item._hgap) || 0; } + return (item._hgap || 0) + (item.hgap || 0); - }, - _optimiseItemVgap: function (item) { - if (BI.Providers.getProvider("bi.provider.system").getLayoutOptimize()) { + } + _optimiseItemVgap(item) { + if (Providers.getProvider("bi.provider.system").getLayoutOptimize()) { return ((!item.type && item.el) ? ((item._vgap || 0) + (item.vgap || 0)) : item._vgap) || 0; } + return (item._vgap || 0) + (item.vgap || 0); - }, + } - _handleGap: function (w, item, hIndex, vIndex) { - var o = this.options; - var innerLgap, innerRgap, innerTgap, innerBgap; - if (BI.isNull(vIndex)) { + _handleGap(w, item, hIndex, vIndex) { + const o = this.options; + let innerLgap, innerRgap, innerTgap, innerBgap; + if (isNull(vIndex)) { innerTgap = innerBgap = o.innerVgap; innerLgap = hIndex === 0 ? o.innerHgap : 0; innerRgap = hIndex === o.items.length - 1 ? o.innerHgap : 0; @@ -342,83 +365,83 @@ BI.Layout = BI.inherit(BI.Widget, { innerBgap = vIndex === o.items.length - 1 ? o.innerVgap : 0; } if (o.vgap + o.tgap + innerTgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item) !== 0) { - var top = ((BI.isNull(vIndex) || vIndex === 0) ? o.vgap : 0) + o.tgap + innerTgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item); + const top = ((isNull(vIndex) || vIndex === 0) ? o.vgap : 0) + o.tgap + innerTgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item); w.element.css({ - "margin-top": this._optimiseGap(top) + "margin-top": this._optimiseGap(top), }); } if (o.hgap + o.lgap + innerLgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item) !== 0) { - var left = ((BI.isNull(hIndex) || hIndex === 0) ? o.hgap : 0) + o.lgap + innerLgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item); + const left = ((isNull(hIndex) || hIndex === 0) ? o.hgap : 0) + o.lgap + innerLgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item); w.element.css({ - "margin-left": this._optimiseGap(left) + "margin-left": this._optimiseGap(left), }); } if (o.hgap + o.rgap + innerRgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item) !== 0) { - var right = o.hgap + o.rgap + innerRgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item); + const right = o.hgap + o.rgap + innerRgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item); w.element.css({ - "margin-right": this._optimiseGap(right) + "margin-right": this._optimiseGap(right), }); } if (o.vgap + o.bgap + innerBgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item) !== 0) { - var bottom = o.vgap + o.bgap + innerBgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item); + const bottom = o.vgap + o.bgap + innerBgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item); w.element.css({ - "margin-bottom": this._optimiseGap(bottom) + "margin-bottom": this._optimiseGap(bottom), }); } - }, + } // 横向换纵向 - _handleReverseGap: function (w, item, index) { - var o = this.options; - var innerLgap, innerRgap, innerTgap, innerBgap; - innerLgap = innerRgap = o.innerHgap; - innerTgap = index === 0 ? o.innerVgap : 0; - innerBgap = index === o.items.length - 1 ? o.innerVgap : 0; + _handleReverseGap(w, item, index) { + const o = this.options; + const innerLgap = o.innerHgap; + const innerRgap = o.innerHgap; + const innerTgap = index === 0 ? o.innerVgap : 0; + const innerBgap = index === o.items.length - 1 ? o.innerVgap : 0; if (o.vgap + o.tgap + innerTgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item) !== 0) { - var top = (index === 0 ? o.vgap : 0) + (index === 0 ? o.tgap : 0) + innerTgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item); + const top = (index === 0 ? o.vgap : 0) + (index === 0 ? o.tgap : 0) + innerTgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item); w.element.css({ - "margin-top": this._optimiseGap(top) + "margin-top": this._optimiseGap(top), }); } if (o.hgap + o.lgap + innerLgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item) !== 0) { - var left = o.hgap + o.lgap + innerLgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item); + const left = o.hgap + o.lgap + innerLgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item); w.element.css({ - "margin-left": this._optimiseGap(left) + "margin-left": this._optimiseGap(left), }); } if (o.hgap + o.rgap + innerRgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item) !== 0) { - var right = o.hgap + o.rgap + innerRgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item); + const right = o.hgap + o.rgap + innerRgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item); w.element.css({ - "margin-right": this._optimiseGap(right) + "margin-right": this._optimiseGap(right), }); } // 这里的代码是关键 if (o.vgap + o.hgap + o.bgap + innerBgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item) !== 0) { - var bottom = (index === o.items.length - 1 ? o.vgap : o.hgap) + (index === o.items.length - 1 ? o.bgap : 0) + innerBgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item); + const bottom = (index === o.items.length - 1 ? o.vgap : o.hgap) + (index === o.items.length - 1 ? o.bgap : 0) + innerBgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item); w.element.css({ - "margin-bottom": this._optimiseGap(bottom) + "margin-bottom": this._optimiseGap(bottom), }); } - }, + } /** * 添加一个子组件到容器中 - * @param {JSON/BI.Widget} item 子组件 + * @param {JSON/Widget} item 子组件 */ - addItem: function (item) { + addItem(item) { return this.addItemAt(this.options.items.length, item); - }, + } - prependItem: function (item) { + prependItem(item) { return this.addItemAt(0, item); - }, + } - addItemAt: function (index, item) { + addItemAt(index, item) { if (index < 0 || index > this.options.items.length) { return; } this._addItemAt(index, item); - var w = this._addElement(index, item); + const w = this._addElement(index, item); // addItemAt 还是用之前的找上个兄弟节点向后插入的方式 if (index > 0) { this._children[this._getChildName(index - 1)].element.after(w.element); @@ -426,16 +449,17 @@ BI.Layout = BI.inherit(BI.Widget, { w.element.prependTo(this._getWrapper()); } w._mount(); + return w; - }, - - removeItemAt: function (indexes) { - indexes = BI.isArray(indexes) ? indexes : [indexes]; - var deleted = []; - var newItems = [], newChildren = {}; - for (var i = 0, len = this.options.items.length; i < len; i++) { - var child = this._children[this._getChildName(i)]; - if (BI.contains(indexes, i)) { + } + + removeItemAt(indexes) { + indexes = isArray(indexes) ? indexes : [indexes]; + const deleted = []; + const newItems = [], newChildren = {}; + for (let i = 0, len = this.options.items.length; i < len; i++) { + const child = this._children[this._getChildName(i)]; + if (contains(indexes, i)) { child && deleted.push(child); } else { newChildren[this._getChildName(newItems.length)] = child; @@ -444,45 +468,46 @@ BI.Layout = BI.inherit(BI.Widget, { } this.options.items = newItems; this._children = newChildren; - BI.each(deleted, function (i, c) { + each(deleted, (i, c) => { c._destroy(); }); - }, + } - shouldUpdateItem: function (index, item) { - var child = this._children[this._getChildName(index)]; + shouldUpdateItem(index, item) { + const child = this._children[this._getChildName(index)]; if (!child || !child.shouldUpdate) { return null; } + return child.shouldUpdate(this._getOptions(item)); - }, - - addItems: function (items, context) { - var self = this, o = this.options; - var fragment = BI.Widget._renderEngine.createFragment(); - var added = []; - BI.each(items, function (i, item) { - var w = self._addElement(o.items.length, item, context); - self._children[self._getChildName(o.items.length)] = w; + } + + addItems(items, context) { + const o = this.options; + const fragment = Widget._renderEngine.createFragment(); + const added = []; + each(items, (i, item) => { + const w = this._addElement(o.items.length, item, context); + this._children[this._getChildName(o.items.length)] = w; o.items.push(item); added.push(w); fragment.appendChild(w.element[0]); }); if (this._isMounted) { this._getWrapper().append(fragment); - BI.each(added, function (i, w) { + each(added, (i, w) => { w._mount(); }); } - }, + } - prependItems: function (items, context) { + prependItems(items, context) { items = items || []; - var fragment = BI.Widget._renderEngine.createFragment(); - var added = []; - for (var i = items.length - 1; i >= 0; i--) { + const fragment = Widget._renderEngine.createFragment(); + const added = []; + for (let i = items.length - 1; i >= 0; i--) { this._addItemAt(0, items[i]); - var w = this._addElement(0, items[i], context); + const w = this._addElement(0, items[i], context); this._children[this._getChildName(0)] = w; this.options.items.unshift(items[i]); added.push(w); @@ -490,47 +515,48 @@ BI.Layout = BI.inherit(BI.Widget, { } if (this._isMounted) { this._getWrapper().prepend(fragment); - BI.each(added, function (i, w) { + each(added, (i, w) => { w._mount(); }); } - }, + } - getValue: function () { - var self = this, value = [], child; - BI.each(this.options.items, function (i) { - if (child = self._children[self._getChildName(i)]) { - var v = child.getValue(); - v = BI.isArray(v) ? v : [v]; + getValue() { + let value = [], child; + each(this.options.items, i => { + child = this._children[this._getChildName(i)]; + if (child) { + let v = child.getValue(); + v = isArray(v) ? v : [v]; value = value.concat(v); } }); + return value; - }, + } - setValue: function (v) { - var self = this, child; - BI.each(this.options.items, function (i) { - if (child = self._children[self._getChildName(i)]) { - child.setValue(v); - } + setValue(v) { + let child; + each(this.options.items, i => { + child = this._children[this._getChildName(i)]; + child && child.setValue(v); }); - }, + } - setText: function (v) { - var self = this, child; - BI.each(this.options.items, function (i) { - if (child = self._children[self._getChildName(i)]) { - child.setText(v); - } + setText(v) { + let child; + each(this.options.items, i => { + child = this._children[this._getChildName(i)]; + child && child.setText(v); }); - }, + } - patchItem: function (oldVnode, vnode, oldIndex, newIndex) { - var shouldUpdate = this.shouldUpdateItem(oldIndex, vnode); - var child = this._children[this._getChildName(oldIndex)]; + patchItem(oldVnode, vnode, oldIndex, newIndex) { + const shouldUpdate = this.shouldUpdateItem(oldIndex, vnode); + const child = this._children[this._getChildName(oldIndex)]; if (shouldUpdate) { - this._children[this._getChildName(newIndex) + "-temp"] = child; + this._children[`${this._getChildName(newIndex)}-temp`] = child; + return child._update(this._getOptions(vnode), shouldUpdate); } if (shouldUpdate === null && !this._compare(oldVnode, vnode)) { @@ -539,69 +565,68 @@ BI.Layout = BI.inherit(BI.Widget, { // } return this._updateItemAt(oldIndex, newIndex, vnode); } - }, - - updateChildren: function (oldCh, newCh, context) { - var self = this; - var oldStartIdx = 0, newStartIdx = 0; - var oldEndIdx = oldCh.length - 1; - var oldStartVnode = oldCh[0]; - var oldEndVnode = oldCh[oldEndIdx]; - var newEndIdx = newCh.length - 1; - var newStartVnode = newCh[0]; - var newEndVnode = newCh[newEndIdx]; - var before; - var updated; - var children = {}; - BI.each(oldCh, function (i, child) { - child = self._getOptions(child); - var key = child.key == null ? i : child.key; - if (BI.isKey(key)) { - children[key] = self._children[self._getChildName(i)]; + } + + updateChildren(oldCh, newCh, context) { + let oldStartIdx = 0, newStartIdx = 0; + let oldEndIdx = oldCh.length - 1; + let oldStartVnode = oldCh[0]; + let oldEndVnode = oldCh[oldEndIdx]; + let newEndIdx = newCh.length - 1; + let newStartVnode = newCh[0]; + let newEndVnode = newCh[newEndIdx]; + let before; + let updated; + const children = {}; + each(oldCh, (i, child) => { + child = this._getOptions(child); + const key = isNull(child.key) ? i : child.key; + if (isKey(key)) { + children[key] = this._children[this._getChildName(i)]; } }); while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { - if (BI.isNull(oldStartVnode)) { + if (isNull(oldStartVnode)) { oldStartVnode = oldCh[++oldStartIdx]; - } else if (BI.isNull(oldEndVnode)) { + } else if (isNull(oldEndVnode)) { oldEndVnode = oldCh[--oldEndIdx]; } else if (sameVnode(oldStartVnode, newStartVnode, oldStartIdx, newStartIdx)) { - var willUpdate = this.patchItem(oldStartVnode, newStartVnode, oldStartIdx, newStartIdx); + const willUpdate = this.patchItem(oldStartVnode, newStartVnode, oldStartIdx, newStartIdx); updated = willUpdate || updated; - children[oldStartVnode.key == null ? oldStartIdx : oldStartVnode.key] = willUpdate ? this._children[this._getChildName(newStartIdx) + "-temp"] : this._children[this._getChildName(oldStartIdx)]; + children[isNull(oldStartVnode.key) ? oldStartIdx : oldStartVnode.key] = willUpdate ? this._children[`${this._getChildName(newStartIdx)}-temp`] : this._children[this._getChildName(oldStartIdx)]; oldStartVnode = oldCh[++oldStartIdx]; newStartVnode = newCh[++newStartIdx]; } else if (sameVnode(oldEndVnode, newEndVnode, oldEndIdx, newEndIdx)) { - var willUpdate = this.patchItem(oldEndVnode, newEndVnode, oldEndIdx, newEndIdx); + const willUpdate = this.patchItem(oldEndVnode, newEndVnode, oldEndIdx, newEndIdx); updated = willUpdate || updated; - children[oldEndVnode.key == null ? oldEndIdx : oldEndVnode.key] = willUpdate ? this._children[this._getChildName(newEndIdx) + "-temp"] : this._children[this._getChildName(oldEndIdx)]; + children[isNull(oldEndVnode.key) ? oldEndIdx : oldEndVnode.key] = willUpdate ? this._children[`${this._getChildName(newEndIdx)}-temp`] : this._children[this._getChildName(oldEndIdx)]; oldEndVnode = oldCh[--oldEndIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldStartVnode, newEndVnode)) { - var willUpdate = this.patchItem(oldStartVnode, newEndVnode, oldStartIdx, newStartIdx); + const willUpdate = this.patchItem(oldStartVnode, newEndVnode, oldStartIdx, newStartIdx); updated = willUpdate || updated; - children[oldStartVnode.key == null ? oldStartIdx : oldStartVnode.key] = willUpdate ? this._children[this._getChildName(newStartIdx) + "-temp"] : this._children[this._getChildName(oldStartIdx)]; + children[isNull(oldStartVnode.key) ? oldStartIdx : oldStartVnode.key] = willUpdate ? this._children[`${this._getChildName(newStartIdx)}-temp`] : this._children[this._getChildName(oldStartIdx)]; insertBefore(oldStartVnode, oldEndVnode, true); oldStartVnode = oldCh[++oldStartIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldEndVnode, newStartVnode)) { - var willUpdate = this.patchItem(oldEndVnode, newStartVnode, oldEndIdx, newEndIdx); + const willUpdate = this.patchItem(oldEndVnode, newStartVnode, oldEndIdx, newEndIdx); updated = willUpdate || updated; - children[oldEndVnode.key == null ? oldEndIdx : oldEndVnode.key] = willUpdate ? this._children[this._getChildName(newEndIdx) + "-temp"] : this._children[this._getChildName(oldEndIdx)]; + children[isNull(oldEndVnode) ? oldEndIdx : oldEndVnode.key] = willUpdate ? this._children[`${this._getChildName(newEndIdx)}-temp`] : this._children[this._getChildName(oldEndIdx)]; insertBefore(oldEndVnode, oldStartVnode); oldEndVnode = oldCh[--oldEndIdx]; newStartVnode = newCh[++newStartIdx]; } else { - var sameOldVnode = findOldVnode(oldCh, newStartVnode, oldStartIdx, oldEndIdx); - if (BI.isNull(sameOldVnode[0])) { // 不存在就把新的放到左边 - var node = addNode(newStartVnode, newStartIdx, context); + const sameOldVnode = findOldVnode(oldCh, newStartVnode, oldStartIdx, oldEndIdx); + if (isNull(sameOldVnode[0])) { // 不存在就把新的放到左边 + const node = addNode(newStartVnode, newStartIdx, context); insertBefore(node, oldStartVnode); - } else { // 如果新节点在旧节点区间中存在就复用一下 - var sameOldIndex = sameOldVnode[1]; - var willUpdate = self.patchItem(sameOldVnode[0], newStartVnode, sameOldIndex, newStartIdx); + } else { // 如果新节点在旧节点区间中存在就复用一下 + const sameOldIndex = sameOldVnode[1]; + const willUpdate = this.patchItem(sameOldVnode[0], newStartVnode, sameOldIndex, newStartIdx); updated = willUpdate || updated; - children[sameOldVnode[0].key == null ? newStartIdx : sameOldVnode[0].key] = willUpdate ? this._children[this._getChildName(newStartIdx) + "-temp"] : self._children[self._getChildName(sameOldIndex)]; + children[isNull(sameOldVnode[0].key) ? newStartIdx : sameOldVnode[0].key] = willUpdate ? this._children[`${this._getChildName(newStartIdx)}-temp`] : this._children[this._getChildName(sameOldIndex)]; oldCh[sameOldIndex] = undefined; insertBefore(sameOldVnode[0], oldStartVnode); } @@ -609,63 +634,65 @@ BI.Layout = BI.inherit(BI.Widget, { } } if (oldStartIdx > oldEndIdx) { - before = BI.isNull(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1]; + before = isNull(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1]; addVnodes(before, newCh, newStartIdx, newEndIdx, context); } else if (newStartIdx > newEndIdx) { removeVnodes(oldCh, oldStartIdx, oldEndIdx); } this._children = {}; - BI.each(newCh, function (i, child) { - var node = self._getOptions(child); - var key = node.key == null ? i : node.key; - children[key]._setParent && children[key]._setParent(self); + each(newCh, (i, child) => { + const node = this._getOptions(child); + const key = isNull(node.key) ? i : node.key; + children[key]._setParent && children[key]._setParent(this); children[key]._mount(); - self._children[self._getChildName(i)] = children[key]; + this._children[this._getChildName(i)] = children[key]; }); - function sameVnode (vnode1, vnode2, oldIndex, newIndex) { - vnode1 = self._getOptions(vnode1); - vnode2 = self._getOptions(vnode2); - if (BI.isKey(vnode1.key)) { + const sameVnode = (vnode1, vnode2, oldIndex, newIndex) => { + vnode1 = this._getOptions(vnode1); + vnode2 = this._getOptions(vnode2); + if (isKey(vnode1.key)) { return vnode1.key === vnode2.key; } if (oldIndex >= 0) { return oldIndex === newIndex; } - } + }; - function addNode (vnode, index, context) { - var opt = self._getOptions(vnode); - var key = opt.key == null ? index : opt.key; - return children[key] = self._newElement(index, vnode, context); - } + const addNode = (vnode, index, context) => { + const opt = this._getOptions(vnode); + const key = isNull(opt.key) ? index : opt.key; + children[key] = this._newElement(index, vnode, context); + + return children[key]; + }; - function addVnodes (before, vnodes, startIdx, endIdx, context) { + const addVnodes = (before, vnodes, startIdx, endIdx, context) => { for (; startIdx <= endIdx; ++startIdx) { - var node = addNode(vnodes[startIdx], startIdx, context); + const node = addNode(vnodes[startIdx], startIdx, context); insertBefore(node, before, false, startIdx); } - } + }; - function removeVnodes (vnodes, startIdx, endIdx) { + const removeVnodes = (vnodes, startIdx, endIdx) => { for (; startIdx <= endIdx; ++startIdx) { - var ch = vnodes[startIdx]; - if (BI.isNotNull(ch)) { - var node = self._getOptions(ch); - var key = node.key == null ? startIdx : node.key; + const ch = vnodes[startIdx]; + if (isNotNull(ch)) { + const node = this._getOptions(ch); + const key = isNull(node.key) ? startIdx : node.key; children[key]._destroy(); } } - } + }; - function insertBefore (insert, before, isNext, index) { - insert = self._getOptions(insert); - before = before && self._getOptions(before); - var insertKey = BI.isKey(insert.key) ? insert.key : index; + const insertBefore = (insert, before, isNext, index) => { + insert = this._getOptions(insert); + before = before && this._getOptions(before); + const insertKey = isKey(insert.key) ? insert.key : index; if (before && children[before.key]) { - var beforeKey = BI.isKey(before.key) ? before.key : index; - var next; + const beforeKey = isKey(before.key) ? before.key : index; + let next; if (isNext) { next = children[beforeKey].element.next(); } else { @@ -674,30 +701,31 @@ BI.Layout = BI.inherit(BI.Widget, { if (next.length > 0) { next.before(children[insertKey].element); } else { - self._getWrapper().append(children[insertKey].element); + this._getWrapper().append(children[insertKey].element); } } else { - self._getWrapper().append(children[insertKey].element); + this._getWrapper().append(children[insertKey].element); } - } + }; - function findOldVnode (vnodes, vNode, beginIdx, endIdx) { - var i, found, findIndex; + const findOldVnode = (vnodes, vNode, beginIdx, endIdx) => { + let i, found, findIndex; for (i = beginIdx; i <= endIdx; ++i) { if (vnodes[i] && sameVnode(vnodes[i], vNode)) { found = vnodes[i]; findIndex = i; } } + return [found, findIndex]; - } + }; return updated; - }, + } - forceUpdate: function (opt) { + forceUpdate(opt) { if (this._isMounted) { - BI.each(this._children, function (i, c) { + each(this._children, (i, c) => { c.destroy(); }); this._children = {}; @@ -706,29 +734,27 @@ BI.Layout = BI.inherit(BI.Widget, { this.options.items = opt.items; this.stroke(opt.items); this._mount(); - }, + } - update: function (opt) { - var o = this.options; - var items = opt.items || []; - var context = opt.context; - var oldItems = o.items; + update(opt) { + const o = this.options; + const items = opt.items || []; + const context = opt.context; + const oldItems = o.items; this.options.items = items; + return this.updateChildren(oldItems, items, context); - }, + } - stroke: function (items, options) { + stroke(items, options) { options = options || {}; - var self = this; - BI.each(items, function (i, item) { - if (item) { - self._addElement(i, item, options.context); - } + each(items, (i, item) => { + item && this._addElement(i, item, options.context); }); - }, + } - getRowColumnCls: function (rowIndex, colIndex, lastRowIndex, lastColIndex) { - var cls = ""; + getRowColumnCls(rowIndex, colIndex, lastRowIndex, lastColIndex) { + let cls = ""; if (rowIndex === 0) { cls += " first-row"; } else if (rowIndex === lastRowIndex) { @@ -739,17 +765,17 @@ BI.Layout = BI.inherit(BI.Widget, { } else if (colIndex === lastColIndex) { cls += " last-col"; } - BI.isOdd(rowIndex + 1) ? (cls += " odd-row") : (cls += " even-row"); - BI.isOdd(colIndex + 1) ? (cls += " odd-col") : (cls += " even-col"); + isOdd(rowIndex + 1) ? (cls += " odd-row") : (cls += " even-row"); + isOdd(colIndex + 1) ? (cls += " odd-col") : (cls += " even-col"); cls += " center-element"; return cls; - }, + } - removeWidget: function (nameOrWidget) { - var removeIndex, self = this; - if (BI.isWidget(nameOrWidget)) { - BI.each(this._children, function (name, child) { + removeWidget(nameOrWidget) { + let removeIndex; + if (isWidget(nameOrWidget)) { + each(this._children, (name, child) => { if (child === nameOrWidget) { removeIndex = name; } @@ -760,34 +786,34 @@ BI.Layout = BI.inherit(BI.Widget, { if (removeIndex) { this._removeItemAt(removeIndex | 0); } - }, + } - empty: function () { - BI.Layout.superclass.empty.apply(this, arguments); + empty() { + super.empty(...arguments); this.options.items = []; - }, + } - destroy: function () { - BI.Layout.superclass.destroy.apply(this, arguments); + destroy() { + super.destroy(...arguments); this.options.items = []; - }, + } - populate: function (items, options) { + populate(items, options) { items = items || []; options = options || {}; if (this._isMounted) { this.update({ - items: items, - context: options.context + items, + context: options.context, }); + return; } this.options.items = items; this.stroke(items, options); - }, + } - resize: function () { + resize() { this.stroke(this.options.items); } -}); -BI.shortcut("bi.layout", BI.Layout); +} diff --git a/src/core/wrapper/layout/adapt/absolute.center.js b/src/core/wrapper/layout/adapt/absolute.center.js index 14a122f00..126a9ec23 100644 --- a/src/core/wrapper/layout/adapt/absolute.center.js +++ b/src/core/wrapper/layout/adapt/absolute.center.js @@ -1,47 +1,54 @@ +import { shortcut } from "../../../decorator"; +import { Layout } from "../../layout"; +import { extend, isFunction } from "../../../2.base"; + /** * absolute实现的居中布局 - * @class BI.AbsoluteCenterLayout - * @extends BI.Layout + * @class AbsoluteCenterLayout + * @extends Layout */ -BI.AbsoluteCenterLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.AbsoluteCenterLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class AbsoluteCenterLayout extends Layout { + static xtype ="bi.absolute_center_adapt"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-abs-c-a", hgap: 0, lgap: 0, rgap: 0, vgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, + } - render: function () { - BI.AbsoluteCenterLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + render() { + super.render(...arguments); + const o = this.options; + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - _addElement: function (i, item) { - var o = this.options; - var w = BI.AbsoluteCenterLayout.superclass._addElement.apply(this, arguments); + _addElement(i, item) { + const o = this.options; + const w = super._addElement(...arguments); w.element.css({ position: "absolute", left: this._optimiseGap(o.hgap + o.lgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item)), right: this._optimiseGap(o.hgap + o.rgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item)), top: this._optimiseGap(o.vgap + o.tgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item)), bottom: this._optimiseGap(o.vgap + o.bgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item)), - margin: "auto" + margin: "auto", }); + return w; - }, + } - populate: function (items) { - BI.AbsoluteCenterLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.absolute_center_adapt", BI.AbsoluteCenterLayout); +} diff --git a/src/core/wrapper/layout/adapt/absolute.horizontal.js b/src/core/wrapper/layout/adapt/absolute.horizontal.js index 81bd4d05c..cedcfa334 100644 --- a/src/core/wrapper/layout/adapt/absolute.horizontal.js +++ b/src/core/wrapper/layout/adapt/absolute.horizontal.js @@ -1,26 +1,35 @@ +import { shortcut } from "../../../decorator"; +import { Layout } from "../../layout"; +import { extend } from "../../../2.base"; +import { HorizontalAlign } from "../../../constant"; + /** - * absolute实现的居中布局 - * @class BI.AbsoluteHorizontalLayout - * @extends BI.Layout + * absolute实现的水平布局 + * @class AbsoluteHorizontalLayout + * @extends Layout */ -BI.AbsoluteHorizontalLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.AbsoluteHorizontalLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class AbsoluteHorizontalLayout extends Layout { + static xtype = "bi.absolute_horizontal_adapt"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-abs-h-a", - horizontalAlign: BI.HorizontalAlign.Center, + horizontalAlign: HorizontalAlign.Center, rowSize: [], hgap: 0, lgap: 0, rgap: 0, vgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, + } - render: function () { - var self = this, o = this.options; - BI.AbsoluteHorizontalLayout.superclass.render.apply(this, arguments); + render() { + const o = this.options; + super.render(...arguments); + return { type: "bi.vtape", horizontalAlign: o.horizontalAlign, @@ -29,8 +38,8 @@ BI.AbsoluteHorizontalLayout = BI.inherit(BI.Layout, { scrollx: o.scrollx, scrolly: o.scrolly, scrollable: o.scrollable, - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, hgap: o.hgap, vgap: o.vgap, @@ -41,14 +50,13 @@ BI.AbsoluteHorizontalLayout = BI.inherit(BI.Layout, { innerHgap: o.innerHgap, innerVgap: o.innerVgap, }; - }, + } - resize: function () { + resize() { this.layout.resize(); - }, + } - populate: function (items) { - this.layout.populate.apply(this, arguments); + populate(...args) { + this.layout.populate(...args); } -}); -BI.shortcut("bi.absolute_horizontal_adapt", BI.AbsoluteHorizontalLayout); +} diff --git a/src/core/wrapper/layout/adapt/absolute.leftrightvertical.js b/src/core/wrapper/layout/adapt/absolute.leftrightvertical.js index 25d5aab94..c8e2bc533 100644 --- a/src/core/wrapper/layout/adapt/absolute.leftrightvertical.js +++ b/src/core/wrapper/layout/adapt/absolute.leftrightvertical.js @@ -1,8 +1,16 @@ -BI.AbsoluteLeftRightVerticalAdaptLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.AbsoluteLeftRightVerticalAdaptLayout.superclass.props.apply(this, arguments), { +import { shortcut } from "../../../decorator"; +import { Layout } from "../../layout"; +import { extend, isArray, each, map, stripEL } from "../../../2.base"; +import { VerticalAlign } from "../../../constant"; + +@shortcut() +export class AbsoluteLeftRightVerticalAdaptLayout extends Layout { + static xtype = "bi.absolute_left_right_vertical_adapt"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-abs-lr-v-a", - verticalAlign: BI.VerticalAlign.Middle, + verticalAlign: VerticalAlign.Middle, items: {}, llgap: 0, lrgap: 0, @@ -15,32 +23,34 @@ BI.AbsoluteLeftRightVerticalAdaptLayout = BI.inherit(BI.Layout, { rhgap: 0, rtgap: 0, rbgap: 0, - rvgap: 0 + rvgap: 0, }); - }, - render: function () { - var o = this.options, self = this; - BI.AbsoluteLeftRightVerticalAdaptLayout.superclass.render.apply(this, arguments); + } + + render() { + const o = this.options; + super.render(...arguments); + return { type: "bi.htape", innerHgap: o.innerHgap, innerVgap: o.innerVgap, - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, verticalAlign: o.verticalAlign, items: this._formatItems(o.items), scrollx: o.scrollx, scrolly: o.scrolly, - scrollable: o.scrollable + scrollable: o.scrollable, }; - }, + } - _formatItems: function (items) { - var self = this, o = this.options; - var left, right; - if (BI.isArray(items)) { - BI.each(items, function (i, item) { + _formatItems(items) { + const o = this.options; + let left, right; + if (isArray(items)) { + each(items, (i, item) => { if (item.left) { left = item.left; } @@ -49,85 +59,92 @@ BI.AbsoluteLeftRightVerticalAdaptLayout = BI.inherit(BI.Layout, { } }); } - var leftItems = left || items.left || []; - var rightItems = right || items.right || []; - leftItems = BI.map(leftItems, function (i, item) { - var json = { - el: BI.stripEL(item), - width: item.width + let leftItems = left || items.left || []; + let rightItems = right || items.right || []; + leftItems = map(leftItems, (i, item) => { + const json = { + el: stripEL(item), + width: item.width, }; - if (o.lvgap + o.ltgap + self._optimiseItemTgap(item) + self._optimiseItemVgap(item) !== 0) { - json.tgap = o.lvgap + o.ltgap + self._optimiseItemTgap(item) + self._optimiseItemVgap(item); + if (o.lvgap + o.ltgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item) !== 0) { + json.tgap = o.lvgap + o.ltgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item); } - if (o.lhgap + o.llgap + self._optimiseItemLgap(item) + self._optimiseItemHgap(item) !== 0) { - json.lgap = (i === 0 ? o.lhgap : 0) + o.llgap + self._optimiseItemLgap(item) + self._optimiseItemHgap(item); + if (o.lhgap + o.llgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item) !== 0) { + json.lgap = (i === 0 ? o.lhgap : 0) + o.llgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item); } - if (o.lhgap + o.lrgap + self._optimiseItemRgap(item) + self._optimiseItemHgap(item) !== 0) { - json.rgap = o.lhgap + o.lrgap + self._optimiseItemRgap(item) + self._optimiseItemHgap(item); + if (o.lhgap + o.lrgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item) !== 0) { + json.rgap = o.lhgap + o.lrgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item); } - if (o.lvgap + o.lbgap + self._optimiseItemBgap(item) + self._optimiseItemVgap(item) !== 0) { - json.bgap = o.lvgap + o.lbgap + self._optimiseItemBgap(item) + self._optimiseItemVgap(item); + if (o.lvgap + o.lbgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item) !== 0) { + json.bgap = o.lvgap + o.lbgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item); } + return json; }); - rightItems = BI.map(rightItems, function (i, item) { - var json = { - el: BI.stripEL(item), - width: item.width + rightItems = map(rightItems, (i, item) => { + const json = { + el: stripEL(item), + width: item.width, }; - if (o.rvgap + o.rtgap + self._optimiseItemTgap(item) + self._optimiseItemVgap(item) !== 0) { - json.tgap = o.rvgap + o.rtgap + self._optimiseItemTgap(item) + self._optimiseItemVgap(item); + if (o.rvgap + o.rtgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item) !== 0) { + json.tgap = o.rvgap + o.rtgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item); } - if (o.rhgap + o.rlgap + self._optimiseItemLgap(item) + self._optimiseItemHgap(item) !== 0) { - json.lgap = (i === 0 ? o.rhgap : 0) + o.rlgap + self._optimiseItemLgap(item) + self._optimiseItemHgap(item); + if (o.rhgap + o.rlgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item) !== 0) { + json.lgap = (i === 0 ? o.rhgap : 0) + o.rlgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item); } - if (o.rhgap + o.rrgap + self._optimiseItemRgap(item) + self._optimiseItemHgap(item) !== 0) { - json.rgap = o.rhgap + o.rrgap + self._optimiseItemRgap(item) + self._optimiseItemHgap(item); + if (o.rhgap + o.rrgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item) !== 0) { + json.rgap = o.rhgap + o.rrgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item); } - if (o.rvgap + o.rbgap + self._optimiseItemBgap(item) + self._optimiseItemVgap(item) !== 0) { - json.bgap = o.rvgap + o.rbgap + self._optimiseItemBgap(item) + self._optimiseItemVgap(item); + if (o.rvgap + o.rbgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item) !== 0) { + json.bgap = o.rvgap + o.rbgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item); } + return json; }); + return leftItems.concat({}, rightItems); - }, + } - resize: function () { + resize() { this.layout.stroke(this._formatItems(this.options.items)); - }, + } - addItem: function () { + addItem() { // do nothing throw new Error("不能添加子组件"); - }, + } - populate: function (items) { + populate(items) { this.layout.populate(this._formatItems(items)); } -}); -BI.shortcut("bi.absolute_left_right_vertical_adapt", BI.AbsoluteLeftRightVerticalAdaptLayout); +} + +@shortcut() +export class AbsoluteRightVerticalAdaptLayout extends Layout { + static xtype = "bi.absolute_right_vertical_adapt"; -BI.AbsoluteRightVerticalAdaptLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.AbsoluteRightVerticalAdaptLayout.superclass.props.apply(this, arguments), { + props () { + return extend(super.props(...arguments), { baseCls: "bi-abs-r-v-a", - verticalAlign: BI.VerticalAlign.Middle, + verticalAlign: VerticalAlign.Middle, items: [], lgap: 0, rgap: 0, hgap: 0, tgap: 0, bgap: 0, - vgap: 0 + vgap: 0, }); - }, - render: function () { - var o = this.options, self = this; - BI.AbsoluteRightVerticalAdaptLayout.superclass.render.apply(this, arguments); + } + + render () { + const o = this.options; + super.render(...arguments); + return { type: "bi.htape", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, verticalAlign: o.verticalAlign, items: [{}].concat(o.items), @@ -139,21 +156,20 @@ BI.AbsoluteRightVerticalAdaptLayout = BI.inherit(BI.Layout, { vgap: o.vgap, scrollx: o.scrollx, scrolly: o.scrolly, - scrollable: o.scrollable + scrollable: o.scrollable, }; - }, + } - resize: function () { + resize () { this.layout.stroke([{}].concat(this.options.items)); - }, + } - addItem: function () { + addItem () { // do nothing throw new Error("不能添加子组件"); - }, + } - populate: function (items) { + populate (items) { this.layout.populate([{}].concat(items)); } -}); -BI.shortcut("bi.absolute_right_vertical_adapt", BI.AbsoluteRightVerticalAdaptLayout); +} diff --git a/src/core/wrapper/layout/adapt/absolute.vertical.js b/src/core/wrapper/layout/adapt/absolute.vertical.js index 94a6e39fe..ea3f750a2 100644 --- a/src/core/wrapper/layout/adapt/absolute.vertical.js +++ b/src/core/wrapper/layout/adapt/absolute.vertical.js @@ -1,26 +1,35 @@ +import { shortcut } from "../../../decorator"; +import { Layout } from "../../layout"; +import { extend } from "../../../2.base"; +import { VerticalAlign } from "../../../constant"; + /** * absolute实现的居中布局 - * @class BI.AbsoluteVerticalLayout - * @extends BI.Layout + * @class AbsoluteVerticalLayout + * @extends Layout */ -BI.AbsoluteVerticalLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.AbsoluteVerticalLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class AbsoluteVerticalLayout extends Layout { + static xtype = "bi.absolute_vertical_adapt"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-abs-v-a", - verticalAlign: BI.VerticalAlign.Middle, + verticalAlign: VerticalAlign.Middle, columnSize: [], hgap: 0, lgap: 0, rgap: 0, vgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, + } - render: function () { - var self = this, o = this.options; - BI.AbsoluteVerticalLayout.superclass.render.apply(this, arguments); + render() { + const o = this.options; + super.render(...arguments); + return { type: "bi.htape", verticalAlign: o.verticalAlign, @@ -29,8 +38,8 @@ BI.AbsoluteVerticalLayout = BI.inherit(BI.Layout, { scrollx: o.scrollx, scrolly: o.scrolly, scrollable: o.scrollable, - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, hgap: o.hgap, vgap: o.vgap, @@ -41,14 +50,13 @@ BI.AbsoluteVerticalLayout = BI.inherit(BI.Layout, { innerHgap: o.innerHgap, innerVgap: o.innerVgap, }; - }, + } - resize: function () { + resize() { this.layout.resize(); - }, + } - populate: function (items) { - this.layout.populate.apply(this, arguments); + populate(...args) { + this.layout.populate(...args); } -}); -BI.shortcut("bi.absolute_vertical_adapt", BI.AbsoluteVerticalLayout); +} diff --git a/src/core/wrapper/layout/adapt/adapt.center.js b/src/core/wrapper/layout/adapt/adapt.center.js index fb088c5a9..446633caf 100644 --- a/src/core/wrapper/layout/adapt/adapt.center.js +++ b/src/core/wrapper/layout/adapt/adapt.center.js @@ -1,13 +1,21 @@ +import { shortcut } from "../../../decorator"; +import { Layout } from "../../layout"; +import { extend } from "../../../2.base"; +import { HorizontalAlign, VerticalAlign } from "../../../constant"; + /** * 自适应水平和垂直方向都居中容器 - * @class BI.CenterAdaptLayout - * @extends BI.Layout + * @class CenterAdaptLayout + * @extends Layout */ -BI.CenterAdaptLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.CenterAdaptLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class CenterAdaptLayout extends Layout { + static xtype = "bi.center_adapt"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-c-a", - horizontalAlign: BI.HorizontalAlign.Center, + horizontalAlign: HorizontalAlign.Center, columnSize: [], scrollx: false, hgap: 0, @@ -15,23 +23,25 @@ BI.CenterAdaptLayout = BI.inherit(BI.Layout, { lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, - render: function () { - var o = this.options, self = this; - BI.CenterAdaptLayout.superclass.render.apply(this, arguments); + } + + render() { + const o = this.options; + super.render(...arguments); + return { type: "bi.horizontal", - verticalAlign: BI.VerticalAlign.Middle, + verticalAlign: VerticalAlign.Middle, horizontalAlign: o.horizontalAlign, columnSize: o.columnSize, scrollx: o.scrollx, scrolly: o.scrolly, scrollable: o.scrollable, items: o.items, - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, hgap: o.hgap, vgap: o.vgap, @@ -42,14 +52,13 @@ BI.CenterAdaptLayout = BI.inherit(BI.Layout, { innerHgap: o.innerHgap, innerVgap: o.innerVgap, }; - }, + } - resize: function () { + resize() { this.layout.resize(); - }, + } - populate: function (items) { - this.layout.populate.apply(this, arguments); + populate(...args) { + this.layout.populate(...args); } -}); -BI.shortcut("bi.center_adapt", BI.CenterAdaptLayout); +} diff --git a/src/core/wrapper/layout/adapt/adapt.horizontal.js b/src/core/wrapper/layout/adapt/adapt.horizontal.js index 4d6fbae2a..4e44c6c19 100644 --- a/src/core/wrapper/layout/adapt/adapt.horizontal.js +++ b/src/core/wrapper/layout/adapt/adapt.horizontal.js @@ -1,8 +1,9 @@ +import { shortcut } from "../../../decorator"; + /** * 水平方向居中容器 - * @class BI.HorizontalAdaptLayout - * @extends BI.Layout */ -BI.HorizontalAdaptLayout = function () { -}; -BI.shortcut("bi.horizontal_adapt", BI.HorizontalAdaptLayout); +@shortcut() +export class HorizontalAdaptLayout { + static xtype = "bi.horizontal_adapt"; +} diff --git a/src/core/wrapper/layout/adapt/adapt.leftrightvertical.js b/src/core/wrapper/layout/adapt/adapt.leftrightvertical.js index cafc1dafb..5fd5e9a65 100644 --- a/src/core/wrapper/layout/adapt/adapt.leftrightvertical.js +++ b/src/core/wrapper/layout/adapt/adapt.leftrightvertical.js @@ -1,15 +1,23 @@ +import { shortcut } from "../../../decorator"; +import { Layout } from "../../layout"; +import { extend, isArray, each } from "../../../2.base"; +import { HorizontalAlign } from "../../../constant"; + /** * 左右分离,垂直方向居中容器 * items:{ left: [{el:{type:"bi.button"}}], right:[{el:{type:"bi.button"}}] } - * @class BI.LeftRightVerticalAdaptLayout - * @extends BI.Layout + * @class LeftRightVerticalAdaptLayout + * @extends Layout */ -BI.LeftRightVerticalAdaptLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.LeftRightVerticalAdaptLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class LeftRightVerticalAdaptLayout extends Layout { + static xtype = "bi.left_right_vertical_adapt"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-lr-v-a", items: {}, llgap: 0, @@ -23,14 +31,15 @@ BI.LeftRightVerticalAdaptLayout = BI.inherit(BI.Layout, { rhgap: 0, rtgap: 0, rbgap: 0, - rvgap: 0 + rvgap: 0, }); - }, - render: function () { - var o = this.options, self = this; - BI.LeftRightVerticalAdaptLayout.superclass.render.apply(this, arguments); - var leftRight = this._getLeftRight(o.items); - var layoutArray = []; + } + + render() { + const o = this.options; + super.render(...arguments); + const leftRight = this._getLeftRight(o.items); + const layoutArray = []; if (leftRight.left || "left" in o.items) { layoutArray.push({ type: "bi.left", @@ -39,8 +48,8 @@ BI.LeftRightVerticalAdaptLayout = BI.inherit(BI.Layout, { items: [{ el: { type: "bi.vertical_adapt", - ref: function (_ref) { - self.left = _ref; + ref: _ref => { + this.left = _ref; }, height: "100%", items: leftRight.left || o.items.left, @@ -49,9 +58,9 @@ BI.LeftRightVerticalAdaptLayout = BI.inherit(BI.Layout, { rgap: o.lrgap, tgap: o.ltgap, bgap: o.lbgap, - vgap: o.lvgap - } - }] + vgap: o.lvgap, + }, + }], }); } if (leftRight.right || "right" in o.items) { @@ -62,8 +71,8 @@ BI.LeftRightVerticalAdaptLayout = BI.inherit(BI.Layout, { items: [{ el: { type: "bi.vertical_adapt", - ref: function (_ref) { - self.right = _ref; + ref: _ref => { + this.right = _ref; }, height: "100%", items: leftRight.right || o.items.right, @@ -72,18 +81,19 @@ BI.LeftRightVerticalAdaptLayout = BI.inherit(BI.Layout, { rgap: o.rrgap, tgap: o.rtgap, bgap: o.rbgap, - vgap: o.rvgap - } - }] + vgap: o.rvgap, + }, + }], }); } + return layoutArray; - }, + } - _getLeftRight: function (items) { - var left, right; - if (BI.isArray(items)) { - BI.each(items, function (i, item) { + _getLeftRight(items) { + let left, right; + if (isArray(items)) { + each(items, (i, item) => { if (item.left) { left = item.left; } @@ -92,35 +102,37 @@ BI.LeftRightVerticalAdaptLayout = BI.inherit(BI.Layout, { } }); } + return { - left: left, - right: right + left, + right, }; - }, + } - resize: function () { - var leftRight = this._getLeftRight(this.options.items); + resize() { + const leftRight = this._getLeftRight(this.options.items); this.left.stroke(leftRight.left || this.options.items.left); this.right.stroke(leftRight.right || this.options.items.right); - }, + } - addItem: function () { + addItem() { // do nothing throw new Error("不能添加子组件"); - }, + } - populate: function (items) { - var leftRight = this._getLeftRight(items); + populate(items) { + const leftRight = this._getLeftRight(items); this.left.populate(leftRight.left || items.left); this.right.populate(leftRight.right || items.right); } -}); -BI.shortcut("bi.left_right_vertical_adapt", BI.LeftRightVerticalAdaptLayout); +} +@shortcut() +export class LeftVerticalAdaptLayout extends Layout { + static xtype = "bi.left_vertical_adapt"; -BI.LeftVerticalAdaptLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.LeftRightVerticalAdaptLayout.superclass.props.apply(this, arguments), { + props() { + return extend(super.props(...arguments), { baseCls: "bi-l-v-a", items: [], columnSize: [], @@ -129,16 +141,18 @@ BI.LeftVerticalAdaptLayout = BI.inherit(BI.Layout, { hgap: 0, tgap: 0, bgap: 0, - vgap: 0 + vgap: 0, }); - }, - render: function () { - var o = this.options, self = this; - BI.LeftVerticalAdaptLayout.superclass.render.apply(this, arguments); + } + + render() { + const o = this.options; + super.render(...arguments); + return { type: "bi.vertical_adapt", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, items: o.items, columnSize: o.columnSize, @@ -152,28 +166,30 @@ BI.LeftVerticalAdaptLayout = BI.inherit(BI.Layout, { innerVgap: o.innerVgap, scrollx: o.scrollx, scrolly: o.scrolly, - scrollable: o.scrollable + scrollable: o.scrollable, }; - }, + } - resize: function () { + resize() { this.layout.resize(); - }, + } - addItem: function () { + addItem() { // do nothing throw new Error("不能添加子组件"); - }, + } - populate: function (items) { - this.layout.populate.apply(this, arguments); + populate(items) { + this.layout.populate(...arguments); } -}); -BI.shortcut("bi.left_vertical_adapt", BI.LeftVerticalAdaptLayout); +} -BI.RightVerticalAdaptLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.RightVerticalAdaptLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class RightVerticalAdaptLayout extends Layout { + static xtype = "bi.right_vertical_adapt"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-r-v-a", items: [], columnSize: [], @@ -182,18 +198,20 @@ BI.RightVerticalAdaptLayout = BI.inherit(BI.Layout, { hgap: 0, tgap: 0, bgap: 0, - vgap: 0 + vgap: 0, }); - }, - render: function () { - var o = this.options, self = this; - BI.RightVerticalAdaptLayout.superclass.render.apply(this, arguments); + } + + render() { + const o = this.options; + super.render(...arguments); + return { type: "bi.vertical_adapt", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, - horizontalAlign: BI.HorizontalAlign.Right, + horizontalAlign: HorizontalAlign.Right, items: o.items, columnSize: o.columnSize, hgap: o.hgap, @@ -206,21 +224,20 @@ BI.RightVerticalAdaptLayout = BI.inherit(BI.Layout, { innerVgap: o.innerVgap, scrollx: o.scrollx, scrolly: o.scrolly, - scrollable: o.scrollable + scrollable: o.scrollable, }; - }, + } - resize: function () { + resize() { this.layout.resize(); - }, + } - addItem: function () { + addItem() { // do nothing throw new Error("不能添加子组件"); - }, + } - populate: function (items) { - this.layout.populate(items); + populate(...args) { + this.layout.populate(...args); } -}); -BI.shortcut("bi.right_vertical_adapt", BI.RightVerticalAdaptLayout); +} diff --git a/src/core/wrapper/layout/adapt/adapt.table.js b/src/core/wrapper/layout/adapt/adapt.table.js index 5691840af..4526edde6 100644 --- a/src/core/wrapper/layout/adapt/adapt.table.js +++ b/src/core/wrapper/layout/adapt/adapt.table.js @@ -1,78 +1,91 @@ +import { shortcut } from "../../../decorator"; +import { Layout } from "../../layout"; +import { extend, isFunction, some, isNull } from "../../../2.base"; +import { Widget } from "../../../4.widget"; +import { _lazyCreateWidget } from "../../../5.inject"; +import { HorizontalAlign, VerticalAlign } from "../../../constant"; + /** * 使用display:table和display:table-cell实现的horizontal布局 - * @class BI.TableAdaptLayout - * @extends BI.Layout + * @class TableAdaptLayout + * @extends Layout */ -BI.TableAdaptLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.TableAdaptLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class TableAdaptLayout extends Layout { + static xtype = "bi.table_adapt"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-t-a", columnSize: [], - verticalAlign: BI.VerticalAlign.Top, - horizontalAlign: BI.HorizontalAlign.Left, + verticalAlign: VerticalAlign.Top, + horizontalAlign: HorizontalAlign.Left, hgap: 0, vgap: 0, lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, - render: function () { - BI.TableAdaptLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - this.$table = BI.Widget._renderEngine.createElement("
").css({ + } + + render() { + super.render(...arguments); + const o = this.options; + this.$table = Widget._renderEngine.createElement("
").css({ position: "relative", display: "table", - width: (o.horizontalAlign === BI.HorizontalAlign.Center || o.horizontalAlign === BI.HorizontalAlign.Stretch || this._hasFill()) ? "100%" : "auto", - height: (o.verticalAlign !== BI.VerticalAlign.Top) ? "100%" : "auto", - "white-space": "nowrap" + width: (o.horizontalAlign === HorizontalAlign.Center || o.horizontalAlign === HorizontalAlign.Stretch || this._hasFill()) ? "100%" : "auto", + height: (o.verticalAlign !== VerticalAlign.Top) ? "100%" : "auto", + "white-space": "nowrap", }); - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - _hasFill: function () { - var o = this.options; + _hasFill() { + const o = this.options; if (o.columnSize.length > 0) { return o.columnSize.indexOf("fill") >= 0; } - return BI.some(o.items, function (i, item) { + + return some(o.items, (i, item) => { if (item.width === "fill") { return true; } }); - }, + } - _addElement: function (i, item) { - var o = this.options; - var td, width = ""; - var columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; + _addElement(i, item) { + const o = this.options; + let td, width = ""; + let w; + const columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; if (columnSize > 0) { width = this._optimiseGap(columnSize + (i === 0 ? o.hgap : 0) + o.hgap + o.lgap + o.rgap); } - if ((BI.isNull(columnSize) || columnSize === "") && this._hasFill()) { + if ((isNull(columnSize) || columnSize === "") && this._hasFill()) { width = 2; } if (!this.hasWidget(this._getChildName(i))) { - var w = BI._lazyCreateWidget(item); - w.element.css({position: "relative", top: "0", left: "0", margin: "0px auto"}); - td = BI._lazyCreateWidget({ + w = _lazyCreateWidget(item); + w.element.css({ position: "relative", top: "0", left: "0", margin: "0px auto" }); + td = _lazyCreateWidget({ type: "bi.default", - width: width, - items: [w] + width, + items: [w], }); this.addWidget(this._getChildName(i), td); } else { td = this.getWidgetByName(this._getChildName(i)); td.element.width(width); } - if (o.verticalAlign === BI.VerticalAlign.Stretch) { - var top = o.vgap + o.tgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item), + if (o.verticalAlign === VerticalAlign.Stretch) { + const top = o.vgap + o.tgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item), bottom = o.vgap + o.bgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item); - w.element.css("height", "calc(100% - " + this._optimiseGap(top + bottom) + ")"); + w.element.css("height", `calc(100% - ${this._optimiseGap(top + bottom)})`); } // 对于表现为td的元素设置最大宽度,有几点需要注意 // 1、由于直接对td设置最大宽度是在规范中未定义的, 所以要使用类似td:firstChild来迂回实现 @@ -81,7 +94,7 @@ BI.TableAdaptLayout = BI.inherit(BI.Layout, { if (columnSize > 0) { td.element.css({ "max-width": width, - "min-width": width + "min-width": width, }); } if (i === 0) { @@ -91,20 +104,20 @@ BI.TableAdaptLayout = BI.inherit(BI.Layout, { position: "relative", display: "table-cell", "vertical-align": o.verticalAlign, - height: "100%" + height: "100%", }); this._handleGap(w, item, i); + return td; - }, + } - appendFragment: function (frag) { + appendFragment(frag) { this.$table.append(frag); this.element.append(this.$table); - }, + } - populate: function (items) { - BI.TableAdaptLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.table_adapt", BI.TableAdaptLayout); +} diff --git a/src/core/wrapper/layout/adapt/adapt.vertical.js b/src/core/wrapper/layout/adapt/adapt.vertical.js index 31c227595..0a0f6c012 100644 --- a/src/core/wrapper/layout/adapt/adapt.vertical.js +++ b/src/core/wrapper/layout/adapt/adapt.vertical.js @@ -1,13 +1,20 @@ +import { shortcut } from "../../../decorator"; +import { Layout } from "../../layout"; +import { HorizontalAlign, VerticalAlign } from "../../../constant"; + /** * 垂直方向居中容器 - * @class BI.VerticalAdaptLayout - * @extends BI.Layout + * @class VerticalAdaptLayout + * @extends Layout */ -BI.VerticalAdaptLayout = BI.inherit(BI.Layout, { - props: { +@shortcut() +export class VerticalAdaptLayout extends Layout { + static xtype = "bi.vertical_adapt"; + + props = { baseCls: "bi-v-a", - horizontalAlign: BI.HorizontalAlign.Left, - verticalAlign: BI.VerticalAlign.Middle, + horizontalAlign: HorizontalAlign.Left, + verticalAlign: VerticalAlign.Middle, columnSize: [], scrollx: false, hgap: 0, @@ -15,12 +22,13 @@ BI.VerticalAdaptLayout = BI.inherit(BI.Layout, { lgap: 0, rgap: 0, tgap: 0, - bgap: 0 - }, + bgap: 0, + } - render: function () { - var self = this, o = this.options; - BI.VerticalAdaptLayout.superclass.render.apply(this, arguments); + render() { + const o = this.options; + super.render(...arguments); + return { type: "bi.horizontal", horizontalAlign: o.horizontalAlign, @@ -30,8 +38,8 @@ BI.VerticalAdaptLayout = BI.inherit(BI.Layout, { scrollx: o.scrollx, scrolly: o.scrolly, scrollable: o.scrollable, - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, hgap: o.hgap, vgap: o.vgap, @@ -42,14 +50,13 @@ BI.VerticalAdaptLayout = BI.inherit(BI.Layout, { innerHgap: o.innerHgap, innerVgap: o.innerVgap, }; - }, + } - resize: function () { + resize() { this.layout.resize(); - }, + } - populate: function (items) { - this.layout.populate.apply(this, arguments); + populate(...args) { + this.layout.populate(...args); } -}); -BI.shortcut("bi.vertical_adapt", BI.VerticalAdaptLayout); +} diff --git a/src/core/wrapper/layout/adapt/auto.horizontal.js b/src/core/wrapper/layout/adapt/auto.horizontal.js index ed0f5e29c..f55acaeea 100644 --- a/src/core/wrapper/layout/adapt/auto.horizontal.js +++ b/src/core/wrapper/layout/adapt/auto.horizontal.js @@ -1,44 +1,50 @@ +import { shortcut } from "../../../decorator"; +import { Layout } from "../../layout"; +import { extend, isFunction } from "../../../2.base"; + /** * 水平方向居中自适应容器 - * @class BI.HorizontalAutoLayout - * @extends BI.Layout + * @class HorizontalAutoLayout + * @extends Layout */ -BI.HorizontalAutoLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.HorizontalAutoLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class HorizontalAutoLayout extends Layout { + static xtype = "bi.horizontal_auto"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-h-o", hgap: 0, lgap: 0, rgap: 0, vgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, + } - render: function () { - BI.HorizontalAutoLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + render() { + super.render(...arguments); + const o = this.options; + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - _addElement: function (i, item) { - var o = this.options; - var w = BI.HorizontalAutoLayout.superclass._addElement.apply(this, arguments); + _addElement(i, item) { + const w = super._addElement(...arguments); w.element.css({ position: "relative", - margin: "0px auto" + margin: "0px auto", }); this._handleGap(w, item, null, i); + return w; - }, + } - populate: function (items) { - BI.HorizontalAutoLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.horizontal_auto", BI.HorizontalAutoLayout); +} diff --git a/src/core/wrapper/layout/adapt/index.js b/src/core/wrapper/layout/adapt/index.js new file mode 100644 index 000000000..82505c49c --- /dev/null +++ b/src/core/wrapper/layout/adapt/index.js @@ -0,0 +1,13 @@ +export { AbsoluteCenterLayout } from "./absolute.center"; +export { AbsoluteHorizontalLayout } from "./absolute.horizontal"; +export { AbsoluteLeftRightVerticalAdaptLayout, AbsoluteRightVerticalAdaptLayout } from "./absolute.leftrightvertical"; +export { AbsoluteVerticalLayout } from "./absolute.vertical"; +export { CenterAdaptLayout } from "./adapt.center"; +export { HorizontalAdaptLayout } from "./adapt.horizontal"; +export { LeftRightVerticalAdaptLayout, LeftVerticalAdaptLayout, RightVerticalAdaptLayout } from "./adapt.leftrightvertical"; +export { TableAdaptLayout } from "./adapt.table"; +export { VerticalAdaptLayout } from "./adapt.vertical"; +export { HorizontalAutoLayout } from "./auto.horizontal"; +export { InlineCenterAdaptLayout } from "./inline.center"; +export { InlineHorizontalAdaptLayout } from "./inline.horizontal"; +export { InlineVerticalAdaptLayout } from "./inline.vertical"; diff --git a/src/core/wrapper/layout/adapt/inline.center.js b/src/core/wrapper/layout/adapt/inline.center.js index 5d7d073af..ede12b455 100644 --- a/src/core/wrapper/layout/adapt/inline.center.js +++ b/src/core/wrapper/layout/adapt/inline.center.js @@ -1,35 +1,43 @@ +import { shortcut } from "../../../decorator"; +import { Layout } from "../../layout"; +import { extend } from "../../../2.base"; +import { HorizontalAlign, VerticalAlign } from "../../../constant"; + /** * 内联布局 - * @class BI.InlineCenterAdaptLayout - * @extends BI.Layout + * @class InlineCenterAdaptLayout + * @extends Layout * * @cfg {JSON} options 配置属性 * @cfg {Number} [hgap=0] 水平间隙 * @cfg {Number} [vgap=0] 垂直间隙 */ -BI.InlineCenterAdaptLayout = BI.inherit(BI.Layout, { +@shortcut() +export class InlineCenterAdaptLayout extends Layout { + static xtype = "bi.inline_center_adapt"; - props: function () { - return BI.extend(BI.InlineCenterAdaptLayout.superclass.props.apply(this, arguments), { + props() { + return extend(super.props(...arguments), { baseCls: "bi-i-c-a", - horizontalAlign: BI.HorizontalAlign.Center, - verticalAlign: BI.VerticalAlign.Middle, + horizontalAlign: HorizontalAlign.Center, + verticalAlign: VerticalAlign.Middle, columnSize: [], hgap: 0, vgap: 0, lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; + return { type: "bi.inline", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, items: o.items, horizontalAlign: o.horizontalAlign, @@ -44,14 +52,13 @@ BI.InlineCenterAdaptLayout = BI.inherit(BI.Layout, { innerHgap: o.innerHgap, innerVgap: o.innerVgap, }; - }, + } - resize: function () { + resize() { this.layout.resize(); - }, + } - populate: function (items) { - this.layout.populate.apply(this.layout, arguments); + populate(...args) { + this.layout.populate(...args); } -}); -BI.shortcut("bi.inline_center_adapt", BI.InlineCenterAdaptLayout); +} diff --git a/src/core/wrapper/layout/adapt/inline.horizontal.js b/src/core/wrapper/layout/adapt/inline.horizontal.js index 09874f1b5..5f7a6a3a2 100644 --- a/src/core/wrapper/layout/adapt/inline.horizontal.js +++ b/src/core/wrapper/layout/adapt/inline.horizontal.js @@ -1,35 +1,43 @@ +import { shortcut } from "../../../decorator"; +import { Layout } from "../../layout"; +import { extend } from "../../../2.base"; +import { HorizontalAlign, VerticalAlign } from "../../../constant"; + /** * 内联布局 - * @class BI.InlineHorizontalAdaptLayout - * @extends BI.Layout + * @class InlineHorizontalAdaptLayout + * @extends Layout * * @cfg {JSON} options 配置属性 * @cfg {Number} [hgap=0] 水平间隙 * @cfg {Number} [vgap=0] 垂直间隙 */ -BI.InlineHorizontalAdaptLayout = BI.inherit(BI.Layout, { +@shortcut() +export class InlineHorizontalAdaptLayout extends Layout { + static xtype = "bi.inline_horizontal_adapt"; - props: function () { - return BI.extend(BI.InlineHorizontalAdaptLayout.superclass.props.apply(this, arguments), { + props() { + return extend(super.props(...arguments), { baseCls: "bi-i-h-a", - horizontalAlign: BI.HorizontalAlign.Center, - verticalAlign: BI.VerticalAlign.Top, + horizontalAlign: HorizontalAlign.Center, + verticalAlign: VerticalAlign.Top, columnSize: [], hgap: 0, vgap: 0, lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; + return { type: "bi.inline", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, items: o.items, horizontalAlign: o.horizontalAlign, @@ -44,14 +52,13 @@ BI.InlineHorizontalAdaptLayout = BI.inherit(BI.Layout, { innerHgap: o.innerHgap, innerVgap: o.innerVgap, }; - }, + } - resize: function () { + resize() { this.layout.resize(); - }, + } - populate: function (items) { - this.layout.populate.apply(this.layout, arguments); + populate(...args) { + this.layout.populate(...args); } -}); -BI.shortcut("bi.inline_horizontal_adapt", BI.InlineHorizontalAdaptLayout); +} diff --git a/src/core/wrapper/layout/adapt/inline.vertical.js b/src/core/wrapper/layout/adapt/inline.vertical.js index 09d76592e..748074c02 100644 --- a/src/core/wrapper/layout/adapt/inline.vertical.js +++ b/src/core/wrapper/layout/adapt/inline.vertical.js @@ -1,35 +1,43 @@ +import { shortcut } from "../../../decorator"; +import { Layout } from "../../layout"; +import { extend } from "../../../2.base"; +import { HorizontalAlign, VerticalAlign } from "../../../constant"; + /** * 内联布局 - * @class BI.InlineVerticalAdaptLayout - * @extends BI.Layout + * @class InlineVerticalAdaptLayout + * @extends Layout * * @cfg {JSON} options 配置属性 * @cfg {Number} [hgap=0] 水平间隙 * @cfg {Number} [vgap=0] 垂直间隙 */ -BI.InlineVerticalAdaptLayout = BI.inherit(BI.Layout, { +@shortcut() +export class InlineVerticalAdaptLayout extends Layout { + static xtype = "bi.inline_vertical_adapt"; - props: function () { - return BI.extend(BI.InlineVerticalAdaptLayout.superclass.props.apply(this, arguments), { + props() { + return extend(super.props(...arguments), { baseCls: "bi-i-v-a", - horizontalAlign: BI.HorizontalAlign.Left, - verticalAlign: BI.VerticalAlign.Middle, + horizontalAlign: HorizontalAlign.Left, + verticalAlign: VerticalAlign.Middle, columnSize: [], hgap: 0, vgap: 0, lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; + return { type: "bi.inline", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, items: o.items, horizontalAlign: o.horizontalAlign, @@ -44,14 +52,13 @@ BI.InlineVerticalAdaptLayout = BI.inherit(BI.Layout, { innerHgap: o.innerHgap, innerVgap: o.innerVgap, }; - }, + } - resize: function () { + resize() { this.layout.resize(); - }, + } - populate: function (items) { - this.layout.populate.apply(this.layout, arguments); + populate(...args) { + this.layout.populate(...args); } -}); -BI.shortcut("bi.inline_vertical_adapt", BI.InlineVerticalAdaptLayout); +} diff --git a/src/core/wrapper/layout/index.js b/src/core/wrapper/layout/index.js new file mode 100644 index 000000000..03bd1cf74 --- /dev/null +++ b/src/core/wrapper/layout/index.js @@ -0,0 +1,17 @@ +export { AbsoluteLayout } from "./layout.absolute"; +export { AdaptiveLayout } from "./layout.adaptive"; +export { BorderLayout } from "./layout.border"; +export { CardLayout } from "./layout.card"; +export { DefaultLayout } from "./layout.default"; +export { DivisionLayout } from "./layout.division"; +export { FloatLeftLayout, FloatRightLayout } from "./layout.flow"; +export { GridLayout } from "./layout.grid"; +export { HorizontalLayout } from "./layout.horizontal"; +export { InlineLayout } from "./layout.inline"; +export { LatticeLayout } from "./layout.lattice"; +export { TableLayout } from "./layout.table"; +export { HTapeLayout, VTapeLayout } from "./layout.tape"; +export { TdLayout } from "./layout.td"; +export { VerticalLayout } from "./layout.vertical"; +export { WindowLayout } from "./layout.window"; +export * from "./adapt"; diff --git a/src/core/wrapper/layout/layout.absolute.js b/src/core/wrapper/layout/layout.absolute.js index 6333b38a8..7e88bd630 100644 --- a/src/core/wrapper/layout/layout.absolute.js +++ b/src/core/wrapper/layout/layout.absolute.js @@ -1,115 +1,119 @@ +import { shortcut } from "../../decorator"; +import { Layout } from "../layout"; +import { extend, isFunction, map, parseFloat, isKey, pick, isNotNull, isNumber } from "../../2.base"; + /** * 固定子组件上下左右的布局容器 - * @class BI.AbsoluteLayout - * @extends BI.Layout */ -BI.AbsoluteLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.AbsoluteLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class AbsoluteLayout extends Layout { + static xtype = "bi.absolute"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-abs", hgap: null, vgap: null, lgap: null, rgap: null, tgap: null, - bgap: null + bgap: null, }); - }, - render: function () { - BI.AbsoluteLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + } + + render() { + super.render(...arguments); + const o = this.options; + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - _addElement: function (i, item) { - var o = this.options; - var w = BI.AbsoluteLayout.superclass._addElement.apply(this, arguments); - var left = 0, right = 0, top = 0, bottom = 0; - var offsets = BI.pick(item, ["top", "right", "bottom", "left"]); + _addElement(i, item) { + const o = this.options; + const w = super._addElement(...arguments); + let left = 0, right = 0, top = 0, bottom = 0; + let offsets = pick(item, ["top", "right", "bottom", "left"]); - if (BI.isKey(item.inset)) { - var insets = BI.map((item.inset + "").split(" "), function (i, str) { - return BI.parseFloat(str); - }); + if (isKey(item.inset)) { + const insets = map((`${item.inset}`).split(" "), (i, str) => parseFloat(str)); switch (insets.length) { - case 1: - offsets = {top: insets[0], bottom: insets[0], left: insets[0], right: insets[0]} - break; - case 2: - offsets = {top: insets[0], bottom: insets[0], left: insets[1], right: insets[1]} - break; - case 3: - offsets = {top: insets[0], left: insets[1], right: insets[1], bottom: insets[2]} - break - case 4: - default: - offsets = {top: insets[0], right: insets[1], bottom: insets[2], left: insets[3]} - break; + case 1: + offsets = { top: insets[0], bottom: insets[0], left: insets[0], right: insets[0] }; + break; + case 2: + offsets = { top: insets[0], bottom: insets[0], left: insets[1], right: insets[1] }; + break; + case 3: + offsets = { top: insets[0], left: insets[1], right: insets[1], bottom: insets[2] }; + break; + case 4: + default: + offsets = { top: insets[0], right: insets[1], bottom: insets[2], left: insets[3] }; + break; } } - if (BI.isNotNull(offsets.left)) { - w.element.css({left: BI.isNumber(offsets.left) ? this._optimiseGap(offsets.left) : offsets.left}); + if (isNotNull(offsets.left)) { + w.element.css({ left: isNumber(offsets.left) ? this._optimiseGap(offsets.left) : offsets.left }); left += offsets.left; } - if (BI.isNotNull(offsets.right)) { - w.element.css({right: BI.isNumber(offsets.right) ? this._optimiseGap(offsets.right) : offsets.right}); + if (isNotNull(offsets.right)) { + w.element.css({ right: isNumber(offsets.right) ? this._optimiseGap(offsets.right) : offsets.right }); right += offsets.right; } - if (BI.isNotNull(offsets.top)) { - w.element.css({top: BI.isNumber(offsets.top) ? this._optimiseGap(offsets.top) : offsets.top}); + if (isNotNull(offsets.top)) { + w.element.css({ top: isNumber(offsets.top) ? this._optimiseGap(offsets.top) : offsets.top }); top += offsets.top; } - if (BI.isNotNull(offsets.bottom)) { - w.element.css({bottom: BI.isNumber(offsets.bottom) ? this._optimiseGap(offsets.bottom) : offsets.bottom}); + if (isNotNull(offsets.bottom)) { + w.element.css({ bottom: isNumber(offsets.bottom) ? this._optimiseGap(offsets.bottom) : offsets.bottom }); bottom += offsets.bottom; } - if (BI.isNotNull(o.hgap)) { + if (isNotNull(o.hgap)) { left += o.hgap; - w.element.css({left: this._optimiseGap(left)}); + w.element.css({ left: this._optimiseGap(left) }); right += o.hgap; - w.element.css({right: this._optimiseGap(right)}); + w.element.css({ right: this._optimiseGap(right) }); } - if (BI.isNotNull(o.vgap)) { + if (isNotNull(o.vgap)) { top += o.vgap; - w.element.css({top: this._optimiseGap(top)}); + w.element.css({ top: this._optimiseGap(top) }); bottom += o.vgap; - w.element.css({bottom: this._optimiseGap(bottom)}); + w.element.css({ bottom: this._optimiseGap(bottom) }); } - if (BI.isNotNull(o.lgap)) { + if (isNotNull(o.lgap)) { left += o.lgap; - w.element.css({left: this._optimiseGap(left)}); + w.element.css({ left: this._optimiseGap(left) }); } - if (BI.isNotNull(o.rgap)) { + if (isNotNull(o.rgap)) { right += o.rgap; - w.element.css({right: this._optimiseGap(right)}); + w.element.css({ right: this._optimiseGap(right) }); } - if (BI.isNotNull(o.tgap)) { + if (isNotNull(o.tgap)) { top += o.tgap; - w.element.css({top: this._optimiseGap(top)}); + w.element.css({ top: this._optimiseGap(top) }); } - if (BI.isNotNull(o.bgap)) { + if (isNotNull(o.bgap)) { bottom += o.bgap; - w.element.css({bottom: this._optimiseGap(bottom)}); + w.element.css({ bottom: this._optimiseGap(bottom) }); } - if (BI.isNotNull(item.width)) { - w.element.css({width: BI.isNumber(item.width) ? this._optimiseGap(item.width) : item.width}); + if (isNotNull(item.width)) { + w.element.css({ width: isNumber(item.width) ? this._optimiseGap(item.width) : item.width }); } - if (BI.isNotNull(item.height)) { - w.element.css({height: BI.isNumber(item.height) ? this._optimiseGap(item.height) : item.height}); + if (isNotNull(item.height)) { + w.element.css({ height: isNumber(item.height) ? this._optimiseGap(item.height) : item.height }); } - w.element.css({position: "absolute"}); + w.element.css({ position: "absolute" }); + return w; - }, + } - populate: function (items) { - BI.AbsoluteLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.absolute", BI.AbsoluteLayout); +} diff --git a/src/core/wrapper/layout/layout.adaptive.js b/src/core/wrapper/layout/layout.adaptive.js index 20b758ef4..e11e23eb4 100644 --- a/src/core/wrapper/layout/layout.adaptive.js +++ b/src/core/wrapper/layout/layout.adaptive.js @@ -1,63 +1,70 @@ -BI.AdaptiveLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.AdaptiveLayout.superclass.props.apply(this, arguments), { +import { shortcut } from "../../decorator"; +import { Layout } from "../layout"; +import { extend, isNumber, isNotNull, isFunction } from "../../2.base"; + +@shortcut() +export class AdaptiveLayout extends Layout { + static xtype = "bi.adaptive"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-adaptive", hgap: 0, vgap: 0, lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, - render: function () { - BI.AdaptiveLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { + } + + render() { + super.render(...arguments); + const self = this, o = this.options; + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { self.populate(newValue); }) : o.items; this.populate(items); - }, + } - _addElement: function (i, item) { - var o = this.options; - var w = BI.AdaptiveLayout.superclass._addElement.apply(this, arguments); - w.element.css({position: "relative"}); - if (BI.isNotNull(item.left)) { + _addElement(i, item) { + const w = super._addElement(...arguments); + w.element.css({ position: "relative" }); + if (isNotNull(item.left)) { w.element.css({ - left: BI.isNumber(item.left) ? this._optimiseGap(item.left) : item.left + left: isNumber(item.left) ? this._optimiseGap(item.left) : item.left, }); } - if (BI.isNotNull(item.right)) { + if (isNotNull(item.right)) { w.element.css({ - right: BI.isNumber(item.right) ? this._optimiseGap(item.right) : item.right + right: isNumber(item.right) ? this._optimiseGap(item.right) : item.right, }); } - if (BI.isNotNull(item.top)) { + if (isNotNull(item.top)) { w.element.css({ - top: BI.isNumber(item.top) ? this._optimiseGap(item.top) : item.top + top: isNumber(item.top) ? this._optimiseGap(item.top) : item.top, }); } - if (BI.isNotNull(item.bottom)) { + if (isNotNull(item.bottom)) { w.element.css({ - bottom: BI.isNumber(item.bottom) ? this._optimiseGap(item.bottom) : item.bottom + bottom: isNumber(item.bottom) ? this._optimiseGap(item.bottom) : item.bottom, }); } this._handleGap(w, item); - if (BI.isNotNull(item.width)) { - w.element.css({width: BI.isNumber(item.width) ? this._optimiseGap(item.width) : item.width}); + if (isNotNull(item.width)) { + w.element.css({ width: isNumber(item.width) ? this._optimiseGap(item.width) : item.width }); } - if (BI.isNotNull(item.height)) { - w.element.css({height: BI.isNumber(item.height) ? this._optimiseGap(item.height) : item.height}); + if (isNotNull(item.height)) { + w.element.css({ height: isNumber(item.height) ? this._optimiseGap(item.height) : item.height }); } + return w; - }, + } - populate: function (items) { - BI.AbsoluteLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.adaptive", BI.AdaptiveLayout); +} diff --git a/src/core/wrapper/layout/layout.border.js b/src/core/wrapper/layout/layout.border.js index 15d3877af..717bc173a 100644 --- a/src/core/wrapper/layout/layout.border.js +++ b/src/core/wrapper/layout/layout.border.js @@ -1,42 +1,51 @@ +import { shortcut } from "../../decorator"; +import { Layout } from "../layout"; +import { extend, isNotNull, isFunction } from "../../2.base"; +import { _lazyCreateWidget } from "../../5.inject"; + /** * 上下的高度固定/左右的宽度固定,中间的高度/宽度自适应 * - * @class BI.BorderLayout - * @extends BI.Layout + * @class BorderLayout + * @extends Layout */ -BI.BorderLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.BorderLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class BorderLayout extends Layout { + static xtype = "bi.border"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-border-layout", - items: {} + items: {}, }); - }, - render: function () { - BI.BorderLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { + } + + render() { + super.render(...arguments); + const self = this, o = this.options; + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { self.populate(newValue); }) : o.items; this.populate(items); - }, + } - addItem: function (item) { + addItem(item) { // do nothing throw new Error("不能添加子组件"); - }, + } - stroke: function (regions) { - var item; - var top = 0; - var bottom = 0; - var left = 0; - var right = 0; + stroke(regions) { + let item; + let top = 0; + let bottom = 0; + let left = 0; + let right = 0; if ("north" in regions) { - item = regions["north"]; - if (item != null) { + item = regions.north; + if (isNotNull(item)) { if (item.el) { if (!this.hasWidget(this._getChildName("north"))) { - var w = BI._lazyCreateWidget(item); + const w = _lazyCreateWidget(item); this.addWidget(this._getChildName("north"), w); } this.getWidgetByName(this._getChildName("north")).element.height(this._optimiseGap(item.height)) @@ -45,18 +54,18 @@ BI.BorderLayout = BI.inherit(BI.Layout, { top: this._optimiseGap(item.top || 0), left: this._optimiseGap(item.left || 0), right: this._optimiseGap(item.right || 0), - bottom: "initial" + bottom: "initial", }); } top = (item.height || 0) + (item.top || 0) + (item.bottom || 0); } } if ("south" in regions) { - item = regions["south"]; - if (item != null) { + item = regions.south; + if (isNotNull(item)) { if (item.el) { if (!this.hasWidget(this._getChildName("south"))) { - var w = BI._lazyCreateWidget(item); + const w = _lazyCreateWidget(item); this.addWidget(this._getChildName("south"), w); } this.getWidgetByName(this._getChildName("south")).element.height(this._optimiseGap(item.height)) @@ -65,18 +74,18 @@ BI.BorderLayout = BI.inherit(BI.Layout, { bottom: this._optimiseGap(item.bottom || 0), left: this._optimiseGap(item.left || 0), right: this._optimiseGap(item.right || 0), - top: "initial" + top: "initial", }); } bottom = (item.height || 0) + (item.top || 0) + (item.bottom || 0); } } if ("west" in regions) { - item = regions["west"]; - if (item != null) { + item = regions.west; + if (isNotNull(item)) { if (item.el) { if (!this.hasWidget(this._getChildName("west"))) { - var w = BI._lazyCreateWidget(item); + const w = _lazyCreateWidget(item); this.addWidget(this._getChildName("west"), w); } this.getWidgetByName(this._getChildName("west")).element.width(this._optimiseGap(item.width)) @@ -85,18 +94,18 @@ BI.BorderLayout = BI.inherit(BI.Layout, { left: this._optimiseGap(item.left || 0), top: this._optimiseGap(top), bottom: this._optimiseGap(bottom), - right: "initial" + right: "initial", }); } left = (item.width || 0) + (item.left || 0) + (item.right || 0); } } if ("east" in regions) { - item = regions["east"]; - if (item != null) { + item = regions.east; + if (isNotNull(item)) { if (item.el) { if (!this.hasWidget(this._getChildName("east"))) { - var w = BI._lazyCreateWidget(item); + const w = _lazyCreateWidget(item); this.addWidget(this._getChildName("east"), w); } this.getWidgetByName(this._getChildName("east")).element.width(this._optimiseGap(item.width)) @@ -105,17 +114,17 @@ BI.BorderLayout = BI.inherit(BI.Layout, { right: this._optimiseGap(item.right || 0), top: this._optimiseGap(top), bottom: this._optimiseGap(bottom), - left: "initial" + left: "initial", }); } right = (item.width || 0) + (item.left || 0) + (item.right || 0); } } if ("center" in regions) { - item = regions["center"]; - if (item != null) { + item = regions.center; + if (isNotNull(item)) { if (!this.hasWidget(this._getChildName("center"))) { - var w = BI._lazyCreateWidget(item); + const w = _lazyCreateWidget(item); this.addWidget(this._getChildName("center"), w); } this.getWidgetByName(this._getChildName("center")).element @@ -124,19 +133,18 @@ BI.BorderLayout = BI.inherit(BI.Layout, { top: this._optimiseGap(top), bottom: this._optimiseGap(bottom), left: this._optimiseGap(left), - right: this._optimiseGap(right) + right: this._optimiseGap(right), }); } } - }, + } - update: function (opt) { + update(opt) { return this.forceUpdate(opt); - }, + } - populate: function (items) { - BI.BorderLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.border", BI.BorderLayout); +} diff --git a/src/core/wrapper/layout/layout.card.js b/src/core/wrapper/layout/layout.card.js index 97034efba..4b2fbad2a 100644 --- a/src/core/wrapper/layout/layout.card.js +++ b/src/core/wrapper/layout/layout.card.js @@ -1,211 +1,215 @@ +import { shortcut } from "../../decorator"; +import { Layout } from "../layout"; +import { extend, each, isNotNull, isFunction, findIndex, isWidget, some, map, isKey } from "../../2.base"; +import { _lazyCreateWidget } from "../../5.inject"; +import { Events } from "../../constant"; +import { Action } from "../../action"; + /** * 卡片布局,可以做到当前只显示一个组件,其他的都隐藏 - * @class BI.CardLayout - * @extends BI.Layout + * @class CardLayout + * @extends Layout * * @cfg {JSON} options 配置属性 * @cfg {String} options.defaultShowName 默认展示的子组件名 */ -BI.CardLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.CardLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class CardLayout extends Layout { + static xtype = "bi.card"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-card-layout", - items: [] + items: [], }); - }, + } - render: function () { - BI.CardLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + render() { + super.render(...arguments); + const o = this.options; + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - stroke: function (items) { - var self = this, o = this.options; + stroke(items) { + const o = this.options; this.showIndex = void 0; - BI.each(items, function (i, item) { + each(items, (i, item) => { if (item) { - if (!self.hasWidget(item.cardName)) { - var w = BI._lazyCreateWidget(item); - w.on(BI.Events.DESTROY, function () { - var index = BI.findIndex(o.items, function (i, tItem) { - return tItem.cardName == item.cardName; - }); + let w; + if (!this.hasWidget(item.cardName)) { + w = _lazyCreateWidget(item); + w.on(Events.DESTROY, () => { + const index = findIndex(o.items, (i, tItem) => tItem.cardName === item.cardName); if (index > -1) { o.items.splice(index, 1); } }); - self.addWidget(self._getChildName(item.cardName), w); + this.addWidget(this._getChildName(item.cardName), w); } else { - var w = self.getWidgetByName(self._getChildName(item.cardName)); + w = this.getWidgetByName(this._getChildName(item.cardName)); } w.element.css({ position: "relative", top: "0", left: "0", width: "100%", - height: "100%" + height: "100%", }); w.setVisible(false); } }); - }, + } - resize: function () { + resize() { // console.log("Card布局不需要resize"); - }, + } - update: function (opt) { + update(opt) { return this.forceUpdate(opt); - }, + } - empty: function () { - BI.CardLayout.superclass.empty.apply(this, arguments); + empty(...args) { + super.empty(...args); this.options.items = []; - }, + } - populate: function (items) { - BI.CardLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); this.options.defaultShowName && this.showCardByName(this.options.defaultShowName); - }, + } - isCardExisted: function (cardName) { - return BI.some(this.options.items, function (i, item) { - return item.cardName == cardName && item.el; - }); - }, + isCardExisted(cardName) { + return some(this.options.items, (i, item) => item.cardName === cardName && item.el); + } - getCardByName: function (cardName) { + getCardByName(cardName) { if (!this.isCardExisted(cardName)) { throw new Error("cardName不存在", cardName); } + return this._children[this._getChildName(cardName)]; - }, + } - _deleteCardByName: function (cardName) { + _deleteCardByName(cardName) { delete this._children[this._getChildName(cardName)]; - var index = BI.findIndex(this.options.items, function (i, item) { - return item.cardName == cardName; - }); + const index = findIndex(this.options.items, (i, item) => item.cardName === cardName); if (index > -1) { this.options.items.splice(index, 1); } - }, + } - deleteCardByName: function (cardName) { + deleteCardByName(cardName) { if (!this.isCardExisted(cardName)) { throw new Error("cardName不存在", cardName); } - var child = this._children[this._getChildName(cardName)]; + const child = this._children[this._getChildName(cardName)]; this._deleteCardByName(cardName); child && child._destroy(); - }, + } - addCardByName: function (cardName, cardItem) { + addCardByName(cardName, cardItem) { if (this.isCardExisted(cardName)) { throw new Error("cardName 已存在", cardName); } - var widget = BI._lazyCreateWidget(cardItem, this); + const widget = _lazyCreateWidget(cardItem, this); widget.element.css({ position: "relative", top: "0", left: "0", width: "100%", - height: "100%" + height: "100%", }).appendTo(this.element); widget.invisible(); this.addWidget(this._getChildName(cardName), widget); - this.options.items.push({el: cardItem, cardName: cardName}); + this.options.items.push({ el: cardItem, cardName }); + return widget; - }, + } - showCardByName: function (name, action, callback) { - var self = this; + showCardByName(name, action, callback) { // name不存在的时候全部隐藏 - var exist = this.isCardExisted(name); - if (this.showIndex != null) { + const exist = this.isCardExisted(name); + if (isNotNull(this.showIndex)) { this.lastShowIndex = this.showIndex; } this.showIndex = name; - var flag = false; - BI.each(this.options.items, function (i, item) { - var el = self._children[self._getChildName(item.cardName)]; + let flag = false; + each(this.options.items, (i, item) => { + const el = this._children[this._getChildName(item.cardName)]; if (el) { - if (name != item.cardName) { + if (name !== item.cardName) { // 动画效果只有在全部都隐藏的时候才有意义,且只要执行一次动画操作就够了 - !flag && !exist && (BI.Action && action instanceof BI.Action) ? (action.actionBack(el), flag = true) : el.invisible(); + !flag && !exist && (Action && action instanceof Action) ? (action.actionBack(el), flag = true) : el.invisible(); } else { - (BI.Action && action instanceof BI.Action) ? action.actionPerformed(void 0, el, callback) : (el.visible(), callback && callback()); + (Action && action instanceof Action) ? action.actionPerformed(void 0, el, callback) : (el.visible(), callback && callback()); } } }); - }, + } - showLastCard: function () { - var self = this; + showLastCard() { this.showIndex = this.lastShowIndex; - BI.each(this.options.items, function (i, item) { - self._children[self._getChildName(item.cardName)].setVisible(self.showIndex == i); + each(this.options.items, (i, item) => { + this._children[this._getChildName(item.cardName)].setVisible(this.showIndex === i); }); - }, + } - setDefaultShowName: function (name) { + setDefaultShowName(name) { this.options.defaultShowName = name; + return this; - }, + } - getDefaultShowName: function () { + getDefaultShowName() { return this.options.defaultShowName; - }, + } - getAllCardNames: function () { - return BI.map(this.options.items, function (i, item) { - return item.cardName; - }); - }, + getAllCardNames() { + return map(this.options.items, (i, item) => item.cardName); + } - getShowingCard: function () { - if (!BI.isKey(this.showIndex)) { + getShowingCard() { + if (!isKey(this.showIndex)) { return void 0; } + return this.getWidgetByName(this._getChildName(this.showIndex)); - }, + } - deleteAllCard: function () { - var self = this; - BI.each(this.getAllCardNames(), function (i, name) { - self.deleteCardByName(name); + deleteAllCard() { + each(this.getAllCardNames(), (i, name) => { + this.deleteCardByName(name); }); - }, + } - hideAllCard: function () { - var self = this; - BI.each(this.options.items, function (i, item) { - self._children[self._getChildName(item.cardName)].invisible(); + hideAllCard() { + each(this.options.items, (i, item) => { + this._children[this._getChildName(item.cardName)].invisible(); }); - }, + } - isAllCardHide: function () { - var self = this; - var flag = true; - BI.some(this.options.items, function (i, item) { - if (self._children[self._getChildName(item.cardName)].isVisible()) { + isAllCardHide() { + let flag = true; + some(this.options.items, (i, item) => { + if (this._children[this._getChildName(item.cardName)].isVisible()) { flag = false; + return false; } }); + return flag; - }, + } - removeWidget: function (nameOrWidget) { - var removeName, self = this; - if (BI.isWidget(nameOrWidget)) { - BI.each(this._children, function (name, child) { + removeWidget(nameOrWidget) { + let removeName; + if (isWidget(nameOrWidget)) { + each(this._children, (name, child) => { if (child === nameOrWidget) { removeName = name; } @@ -217,5 +221,4 @@ BI.CardLayout = BI.inherit(BI.Layout, { this._deleteCardByName(removeName); } } -}); -BI.shortcut("bi.card", BI.CardLayout); +} diff --git a/src/core/wrapper/layout/layout.default.js b/src/core/wrapper/layout/layout.default.js index 90e4bf569..325be127e 100644 --- a/src/core/wrapper/layout/layout.default.js +++ b/src/core/wrapper/layout/layout.default.js @@ -1,39 +1,47 @@ +import { shortcut } from "../../decorator"; +import { Layout } from "../layout"; +import { extend, isFunction } from "../../2.base"; + /** * 默认的布局方式 * - * @class BI.DefaultLayout - * @extends BI.Layout + * @class DefaultLayout + * @extends Layout */ -BI.DefaultLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.DefaultLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class DefaultLayout extends Layout { + static xtype = "bi.default"; + + props() { + return extend(super.props(...arguments), { hgap: 0, vgap: 0, lgap: 0, rgap: 0, tgap: 0, bgap: 0, - items: [] + items: [], }); - }, - render: function () { - BI.DefaultLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + } + + render() { + super.render(...arguments); + const o = this.options; + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - _addElement: function (i, item) { - var w = BI.DefaultLayout.superclass._addElement.apply(this, arguments); + _addElement(i, item) { + const w = super._addElement(...arguments); this._handleGap(w, item); + return w; - }, + } - populate: function (items) { - BI.DefaultLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.default", BI.DefaultLayout); +} diff --git a/src/core/wrapper/layout/layout.division.js b/src/core/wrapper/layout/layout.division.js index 307166283..92701e7c0 100644 --- a/src/core/wrapper/layout/layout.division.js +++ b/src/core/wrapper/layout/layout.division.js @@ -1,36 +1,46 @@ +import { shortcut } from "../../decorator"; +import { Layout } from "../layout"; +import { extend, isFunction, makeArray, each, isArray } from "../../2.base"; +import { Widget } from "../../4.widget"; +import { _lazyCreateWidget } from "../../5.inject"; + /** * 分隔容器的控件,按照宽度和高度所占比平分整个容器 * - * @class BI.DivisionLayout - * @extends BI.Layout + * @class DivisionLayout + * @extends Layout */ -BI.DivisionLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.DivisionLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class DivisionLayout extends Layout { + static xtype = "bi.division"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-division", columns: null, rows: null, - items: [] + items: [], }); - }, - render: function () { - BI.DivisionLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + } + + render() { + super.render(...arguments); + const o = this.options; + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - addItem: function (item) { + addItem(item) { // do nothing throw new Error("不能添加子组件"); - }, + } - stroke: function (items) { - var o = this.options, self = this; - var rows = o.rows || o.items.length, columns = o.columns || ((o.items[0] && o.items[0].length) | 0); - var map = BI.makeArray(rows), widths = {}, heights = {}; + stroke(items) { + const o = this.options; + const rows = o.rows || o.items.length, columns = o.columns || ((o.items[0] && o.items[0].length) | 0); + const map = makeArray(rows), widths = {}, heights = {}; function firstElement (item, cls) { item.addClass(cls); @@ -45,9 +55,9 @@ BI.DivisionLayout = BI.inherit(BI.Layout, { } function first (item, cls) { - if (item instanceof BI.Widget) { + if (item instanceof Widget) { firstElement(item.element, cls); - } else if (item.el instanceof BI.Widget) { + } else if (item.el instanceof Widget) { firstElement(item.el.element, cls); } else if (item.el) { firstObject(item.el, cls); @@ -56,12 +66,12 @@ BI.DivisionLayout = BI.inherit(BI.Layout, { } } - BI.each(map, function (i) { - map[i] = BI.makeArray(columns); + each(map, i => { + map[i] = makeArray(columns); }); - BI.each(items, function (i, item) { - if (BI.isArray(item)) { - BI.each(item, function (j, el) { + each(items, (i, item) => { + if (isArray(item)) { + each(item, (j, el) => { widths[i] = (widths[i] || 0) + item.width; heights[j] = (heights[j] || 0) + item.height; map[i][j] = el; @@ -73,56 +83,56 @@ BI.DivisionLayout = BI.inherit(BI.Layout, { heights[item.column] = (heights[item.column] || 0) + item.height; map[item.row][item.column] = item; }); - for (var i = 0; i < rows; i++) { - var totalW = 0; - for (var j = 0; j < columns; j++) { + for (let i = 0; i < rows; i++) { + let totalW = 0; + for (let j = 0; j < columns; j++) { + let w; if (!map[i][j]) { - throw new Error("item(" + i + "" + j + ") 必须", map); + throw new Error(`item(${i}${j}) 必须`, map); } - if (!this.hasWidget(this._getChildName(i + "_" + j))) { - var w = BI._lazyCreateWidget(map[i][j]); - this.addWidget(this._getChildName(i + "_" + j), w); + if (!this.hasWidget(this._getChildName(`${i}_${j}`))) { + w = _lazyCreateWidget(map[i][j]); + this.addWidget(this._getChildName(`${i}_${j}`), w); } else { - w = this.getWidgetByName(this._getChildName(i + "_" + j)); + w = this.getWidgetByName(this._getChildName(`${i}_${j}`)); } - var left = totalW * 100 / widths[i]; - w.element.css({position: "absolute", left: left + "%"}); + const left = totalW * 100 / widths[i]; + w.element.css({ position: "absolute", left: `${left}%` }); if (j > 0) { - var lastW = this.getWidgetByName(this._getChildName(i + "_" + (j - 1))); - lastW.element.css({right: (100 - left) + "%"}); + const lastW = this.getWidgetByName(this._getChildName(`${i}_${j - 1}`)); + lastW.element.css({ right: `${100 - left}%` }); } - if (j == o.columns - 1) { - w.element.css({right: "0%"}); + if (j === o.columns - 1) { + w.element.css({ right: "0%" }); } - first(w, self.getRowColumnCls(i, j, rows - 1, columns - 1)); + first(w, this.getRowColumnCls(i, j, rows - 1, columns - 1)); totalW += map[i][j].width; } } - for (var j = 0; j < o.columns; j++) { - var totalH = 0; - for (var i = 0; i < o.rows; i++) { - var w = this.getWidgetByName(this._getChildName(i + "_" + j)); - var top = totalH * 100 / heights[j]; - w.element.css({top: top + "%"}); + for (let j = 0; j < o.columns; j++) { + let totalH = 0; + for (let i = 0; i < o.rows; i++) { + const w = this.getWidgetByName(this._getChildName(`${i}_${j}`)); + const top = totalH * 100 / heights[j]; + w.element.css({ top: `${top}%` }); if (i > 0) { - var lastW = this.getWidgetByName(this._getChildName((i - 1) + "_" + j)); - lastW.element.css({bottom: (100 - top) + "%"}); + const lastW = this.getWidgetByName(this._getChildName(`${i - 1}_${j}`)); + lastW.element.css({ bottom: `${100 - top}%` }); } - if (i == o.rows - 1) { - w.element.css({bottom: "0%"}); + if (i === o.rows - 1) { + w.element.css({ bottom: "0%" }); } totalH += map[i][j].height; } } - }, + } - update: function (opt) { + update(opt) { return this.forceUpdate(opt); - }, + } - populate: function (items) { - BI.DivisionLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.division", BI.DivisionLayout); +} diff --git a/src/core/wrapper/layout/layout.flow.js b/src/core/wrapper/layout/layout.flow.js index 13b9fdb54..0ab22e88d 100644 --- a/src/core/wrapper/layout/layout.flow.js +++ b/src/core/wrapper/layout/layout.flow.js @@ -1,183 +1,196 @@ +import { shortcut } from "../../decorator"; +import { Layout } from "../layout"; +import { extend, isFunction, isNotNull, isNumber } from "../../2.base"; +import { pixFormat } from "../../constant"; + /** * 靠左对齐的自由浮动布局 - * @class BI.FloatLeftLayout - * @extends BI.Layout + * @class FloatLeftLayout + * @extends Layout * * @cfg {JSON} options 配置属性 * @cfg {Number} [hgap=0] 水平间隙 * @cfg {Number} [vgap=0] 垂直间隙 */ -BI.FloatLeftLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FloatLeftLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class FloatLeftLayout extends Layout { + static xtype = "bi.left"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-left clearfix", hgap: 0, vgap: 0, lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, - render: function () { - BI.FloatLeftLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; + } + + render() { + super.render(...arguments); + const o = this.options; if (o.innerHgap !== 0) { this.element.css({ paddingLeft: this._optimiseGap(o.innerHgap), - paddingRight: this._optimiseGap(o.innerHgap) - }) + paddingRight: this._optimiseGap(o.innerHgap), + }); } if (o.innerVgap !== 0) { this.element.css({ paddingTop: this._optimiseGap(o.innerVgap), - paddingBottom: this._optimiseGap(o.innerVgap) - }) + paddingBottom: this._optimiseGap(o.innerVgap), + }); } - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - _addElement: function (i, item) { - var o = this.options; - var w = BI.FloatLeftLayout.superclass._addElement.apply(this, arguments); - w.element.css({position: "relative", float: "left"}); - if (BI.isNotNull(item.left)) { - w.element.css({left: BI.isNumber(item.left) ? this._optimiseGap(item.left) : item.left}); + _addElement(i, item) { + const o = this.options; + const w = super._addElement(...arguments); + w.element.css({ position: "relative", "float": "left" }); + if (isNotNull(item.left)) { + w.element.css({ left: isNumber(item.left) ? this._optimiseGap(item.left) : item.left }); } - if (BI.isNotNull(item.right)) { - w.element.css({right: BI.isNumber(item.right) ? this._optimiseGap(item.right) : item.right}); + if (isNotNull(item.right)) { + w.element.css({ right: isNumber(item.right) ? this._optimiseGap(item.right) : item.right }); } - if (BI.isNotNull(item.top)) { - w.element.css({top: BI.isNumber(item.top) ? this._optimiseGap(item.top) : item.top}); + if (isNotNull(item.top)) { + w.element.css({ top: isNumber(item.top) ? this._optimiseGap(item.top) : item.top }); } - if (BI.isNotNull(item.bottom)) { - w.element.css({bottom: BI.isNumber(item.bottom) ? this._optimiseGap(item.bottom) : item.bottom}); + if (isNotNull(item.bottom)) { + w.element.css({ bottom: isNumber(item.bottom) ? this._optimiseGap(item.bottom) : item.bottom }); } if (o.vgap + o.tgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item) !== 0) { - var top = o.vgap / 2 + o.tgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item); + const top = o.vgap / 2 + o.tgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item); w.element.css({ - "margin-top": this._optimiseGap(top) + "margin-top": this._optimiseGap(top), }); } if (o.hgap + o.lgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item) !== 0) { - var left = o.hgap / 2 + o.lgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item); + const left = o.hgap / 2 + o.lgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item); w.element.css({ - "margin-left": this._optimiseGap(left) + "margin-left": this._optimiseGap(left), }); } if (o.hgap + o.rgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item) !== 0) { - var right = o.hgap / 2 + o.rgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item); + const right = o.hgap / 2 + o.rgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item); w.element.css({ - "margin-right": this._optimiseGap(right) + "margin-right": this._optimiseGap(right), }); } if (o.vgap + o.bgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item) !== 0) { - var bottom = o.vgap / 2 + o.bgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item); + const bottom = o.vgap / 2 + o.bgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item); w.element.css({ - "margin-bottom": this._optimiseGap(bottom) + "margin-bottom": this._optimiseGap(bottom), }); } + return w; - }, + } - populate: function (items) { - BI.FloatLeftLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.left", BI.FloatLeftLayout); +} /** * 靠右对齐的自由浮动布局 - * @class BI.FloatRightLayout - * @extends BI.Layout + * @class FloatRightLayout + * @extends Layout * * @cfg {JSON} options 配置属性 * @cfg {Number} [hgap=0] 水平间隙 * @cfg {Number} [vgap=0] 垂直间隙 */ -BI.FloatRightLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FloatRightLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class FloatRightLayout extends Layout { + static xtype = "bi.right"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-right clearfix", hgap: 0, vgap: 0, lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, - render: function () { - BI.FloatRightLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; + } + + render() { + super.render(...arguments); + const o = this.options; if (o.innerHgap !== 0) { this.element.css({ paddingLeft: this._optimiseGap(o.innerHgap), - paddingRight: this._optimiseGap(o.innerHgap) - }) + paddingRight: this._optimiseGap(o.innerHgap), + }); } if (o.innerVgap !== 0) { this.element.css({ paddingTop: this._optimiseGap(o.innerVgap), - paddingBottom: this._optimiseGap(o.innerVgap) - }) + paddingBottom: this._optimiseGap(o.innerVgap), + }); } - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - _addElement: function (i, item) { - var o = this.options; - var w = BI.FloatRightLayout.superclass._addElement.apply(this, arguments); - w.element.css({position: "relative", float: "right"}); - if (BI.isNotNull(item.left)) { - w.element.css({left: BI.pixFormat(item.left)}); + _addElement(i, item) { + const o = this.options; + const w = super._addElement(...arguments); + w.element.css({ position: "relative", "float": "right" }); + if (isNotNull(item.left)) { + w.element.css({ left: pixFormat(item.left) }); } - if (BI.isNotNull(item.right)) { - w.element.css({right: BI.pixFormat(item.right)}); + if (isNotNull(item.right)) { + w.element.css({ right: pixFormat(item.right) }); } - if (BI.isNotNull(item.top)) { - w.element.css({top: BI.pixFormat(item.top)}); + if (isNotNull(item.top)) { + w.element.css({ top: pixFormat(item.top) }); } - if (BI.isNotNull(item.bottom)) { - w.element.css({bottom: BI.pixFormat(item.bottom)}); + if (isNotNull(item.bottom)) { + w.element.css({ bottom: pixFormat(item.bottom) }); } if (o.vgap + o.tgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item) !== 0) { - var top = o.vgap / 2 + o.tgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item); + const top = o.vgap / 2 + o.tgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item); w.element.css({ - "margin-top": this._optimiseGap(top) + "margin-top": this._optimiseGap(top), }); } if (o.hgap + o.lgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item) !== 0) { - var left = o.hgap / 2 + o.lgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item); + const left = o.hgap / 2 + o.lgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item); w.element.css({ - "margin-left": this._optimiseGap(left) + "margin-left": this._optimiseGap(left), }); } if (o.hgap + o.rgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item) !== 0) { - var right = o.hgap / 2 + o.rgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item); + const right = o.hgap / 2 + o.rgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item); w.element.css({ - "margin-right": this._optimiseGap(right) + "margin-right": this._optimiseGap(right), }); } if (o.vgap + o.bgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item) !== 0) { - var bottom = o.vgap / 2 + o.bgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item); + const bottom = o.vgap / 2 + o.bgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item); w.element.css({ - "margin-bottom": this._optimiseGap(bottom) + "margin-bottom": this._optimiseGap(bottom), }); } + return w; - }, + } - populate: function (items) { - BI.FloatRightLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.right", BI.FloatRightLayout); +} diff --git a/src/core/wrapper/layout/layout.grid.js b/src/core/wrapper/layout/layout.grid.js index 53e4cf00b..9f06311b9 100644 --- a/src/core/wrapper/layout/layout.grid.js +++ b/src/core/wrapper/layout/layout.grid.js @@ -1,38 +1,42 @@ -/** - * 上下的高度固定/左右的宽度固定,中间的高度/宽度自适应 - * - * @class BI.BorderLayout - * @extends BI.Layout - */ -BI.GridLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.GridLayout.superclass.props.apply(this, arguments), { +import { shortcut } from "../../decorator"; +import { Layout } from "../layout"; +import { extend, isFunction, isArray, each } from "../../2.base"; +import { Widget } from "../../4.widget"; +import { _lazyCreateWidget } from "../../5.inject"; + +@shortcut() +export class GridLayout extends Layout { + static xtype = "bi.grid"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-grid", columns: null, rows: null, - items: [] + items: [], }); - }, - render: function () { - BI.GridLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + } + + render() { + super.render(...arguments); + const o = this.options; + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - addItem: function () { + addItem() { // do nothing throw new Error("不能添加子组件"); - }, + } - stroke: function (items) { - var self = this, o = this.options; - var rows = o.rows || o.items.length, columns = o.columns || ((o.items[0] && o.items[0].length) | 0); - var width = 100 / columns, height = 100 / rows; - var els = []; - for (var i = 0; i < rows; i++) { + stroke(items) { + const o = this.options; + const rows = o.rows || o.items.length, columns = o.columns || ((o.items[0] && o.items[0].length) | 0); + const width = 100 / columns, height = 100 / rows; + const els = []; + for (let i = 0; i < rows; i++) { els[i] = []; } @@ -49,9 +53,9 @@ BI.GridLayout = BI.inherit(BI.Layout, { } function first (item, row, col) { - if (item instanceof BI.Widget) { + if (item instanceof Widget) { firstElement(item.element, row, col); - } else if (item.el instanceof BI.Widget) { + } else if (item.el instanceof Widget) { firstElement(item.el.element, row, col); } else if (item.el) { firstObject(item.el, row, col); @@ -60,46 +64,46 @@ BI.GridLayout = BI.inherit(BI.Layout, { } } - BI.each(items, function (i, item) { - if (BI.isArray(item)) { - BI.each(item, function (j, el) { - els[i][j] = BI._lazyCreateWidget(el); + each(items, (i, item) => { + if (isArray(item)) { + each(item, (j, el) => { + els[i][j] = _lazyCreateWidget(el); }); + return; } - els[item.row][item.column] = BI._lazyCreateWidget(item); + els[item.row][item.column] = _lazyCreateWidget(item); }); - for (var i = 0; i < rows; i++) { - for (var j = 0; j < columns; j++) { + for (let i = 0; i < rows; i++) { + for (let j = 0; j < columns; j++) { if (!els[i][j]) { - els[i][j] = BI._lazyCreateWidget({ - type: "bi.layout" + els[i][j] = _lazyCreateWidget({ + type: "bi.layout", }); } - first(els[i][j], self.getRowColumnCls(i, j, rows - 1, columns - 1)); + first(els[i][j], this.getRowColumnCls(i, j, rows - 1, columns - 1)); els[i][j].element.css({ position: "absolute", - top: height * i + "%", - left: width * j + "%", - right: (100 - (width * (j + 1))) + "%", - bottom: (100 - (height * (i + 1))) + "%" + top: `${height * i}%`, + left: `${width * j}%`, + right: `${100 - (width * (j + 1))}%`, + bottom: `${100 - (height * (i + 1))}%`, }); - this.addWidget(this._getChildName(i + "_" + j), els[i][j]); + this.addWidget(this._getChildName(`${i}_${j}`), els[i][j]); } } - }, + } - resize: function () { + resize() { // console.log("grid布局不需要resize") - }, + } - update: function (opt) { + update(opt) { return this.forceUpdate(opt); - }, + } - populate: function (items) { - BI.GridLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.grid", BI.GridLayout); +} diff --git a/src/core/wrapper/layout/layout.horizontal.js b/src/core/wrapper/layout/layout.horizontal.js index 525538e92..32938ef93 100644 --- a/src/core/wrapper/layout/layout.horizontal.js +++ b/src/core/wrapper/layout/layout.horizontal.js @@ -1,8 +1,6 @@ -/** - * 水平布局 - * @class BI.HorizontalLayout - * @extends BI.Layout - */ -BI.HorizontalLayout = function () { -}; -BI.shortcut("bi.horizontal", BI.HorizontalLayout); +import { shortcut } from "../../decorator"; + +@shortcut() +export class HorizontalLayout { + static xtype = "bi.horizontal"; +} diff --git a/src/core/wrapper/layout/layout.inline.js b/src/core/wrapper/layout/layout.inline.js index 661a6bf77..e837af6fc 100644 --- a/src/core/wrapper/layout/layout.inline.js +++ b/src/core/wrapper/layout/layout.inline.js @@ -1,19 +1,26 @@ +import { shortcut } from "../../decorator"; +import { Layout } from "../layout"; +import { extend, isFunction, isNull } from "../../2.base"; +import { pixFormat, HorizontalAlign, VerticalAlign } from "../../constant"; + /** * 内联布局 - * @class BI.InlineLayout - * @extends BI.Layout + * @class InlineLayout + * @extends Layout * * @cfg {JSON} options 配置属性 * @cfg {Number} [hgap=0] 水平间隙 * @cfg {Number} [vgap=0] 垂直间隙 */ -BI.InlineLayout = BI.inherit(BI.Layout, { +@shortcut() +export class InlineLayout extends Layout { + static xtype = "bi.inline"; - props: function () { - return BI.extend(BI.InlineLayout.superclass.props.apply(this, arguments), { + props() { + return extend(super.props(...arguments), { baseCls: "bi-i", - horizontalAlign: BI.HorizontalAlign.Left, - verticalAlign: BI.VerticalAlign.Top, + horizontalAlign: HorizontalAlign.Left, + verticalAlign: VerticalAlign.Top, columnSize: [], hgap: 0, vgap: 0, @@ -21,80 +28,80 @@ BI.InlineLayout = BI.inherit(BI.Layout, { rgap: 0, tgap: 0, bgap: 0, - items: [] + items: [], }); - }, + } - render: function () { - BI.InlineLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; + render() { + super.render(...arguments); + const o = this.options; this.element.css({ - textAlign: o.horizontalAlign + textAlign: o.horizontalAlign, }); - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - _addElement: function (i, item) { - var o = this.options; - var w = BI.InlineLayout.superclass._addElement.apply(this, arguments); - var columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; + _addElement(i, item) { + const o = this.options; + const w = super._addElement(...arguments); + let columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; if (o.columnSize.length > 0) { if (item.width >= 1 && o.columnSize[i] >= 1 && o.columnSize[i] !== item.width) { columnSize = null; } } if (columnSize > 0) { - w.element.width(columnSize < 1 ? ((columnSize * 100).toFixed(1) + "%") : BI.pixFormat(columnSize)); + w.element.width(columnSize < 1 ? (`${(columnSize * 100).toFixed(1)}%`) : pixFormat(columnSize)); } w.element.css({ position: "relative", - "vertical-align": o.verticalAlign + "vertical-align": o.verticalAlign, }); w.element.addClass("i-item"); if (columnSize === "fill" || columnSize === "") { - var length = 0, gap = o.hgap + o.innerHgap; - var fillCount = 0, autoCount = 0; - for (var k = 0, len = o.columnSize.length || o.items.length; k < len; k++) { - var cz = o.columnSize.length > 0 ? o.columnSize[k] : o.items[k].width; + let length = 0, gap = o.hgap + o.innerHgap; + let fillCount = 0, autoCount = 0; + for (let k = 0, len = o.columnSize.length || o.items.length; k < len; k++) { + let cz = o.columnSize.length > 0 ? o.columnSize[k] : o.items[k].width; if (cz === "fill") { fillCount++; cz = 0; - } else if (cz === "" || BI.isNull(cz)) { + } else if (cz === "" || isNull(cz)) { autoCount++; cz = 0; } gap += o.hgap + o.lgap + o.rgap + this._optimiseItemLgap(o.items[k]) + this._optimiseItemRgap(o.items[k]) + this._optimiseItemHgap(o.items[k]); length += cz; } - length = length > 0 && length < 1 ? (length * 100).toFixed(1) + "%" : BI.pixFormat(length); - gap = gap > 0 && gap < 1 ? (gap * 100).toFixed(1) + "%" : BI.pixFormat(gap); + length = length > 0 && length < 1 ? `${(length * 100).toFixed(1)}%` : pixFormat(length); + gap = gap > 0 && gap < 1 ? `${(gap * 100).toFixed(1)}%` : pixFormat(gap); if (columnSize === "fill") { - w.element.css("min-width", "calc((100% - " + length + " - " + gap + ")" + (fillCount > 1 ? "/" + fillCount : "") + ")"); + w.element.css("min-width", `calc((100% - ${length} - ${gap})${fillCount > 1 ? `/${fillCount}` : ""})`); } - if (o.horizontalAlign === BI.HorizontalAlign.Stretch || !(o.scrollable === true || o.scrollx === true)) { + if (o.horizontalAlign === HorizontalAlign.Stretch || !(o.scrollable === true || o.scrollx === true)) { if (columnSize === "fill") { - w.element.css("max-width", "calc((100% - " + length + " - " + gap + ")" + (fillCount > 1 ? "/" + fillCount : "") + ")"); + w.element.css("max-width", `calc((100% - ${length} - ${gap})${fillCount > 1 ? `/${fillCount}` : ""})`); } else { - w.element.css("max-width", "calc((100% - " + length + " - " + gap + ")" + (autoCount > 1 ? "/" + autoCount : "") + ")"); + w.element.css("max-width", `calc((100% - ${length} - ${gap})${autoCount > 1 ? `/${autoCount}` : ""})`); } } } this._handleGap(w, item, i); - if (o.verticalAlign === BI.VerticalAlign.Stretch && BI.isNull(item.height)) { - var top = o.innerVgap + o.vgap + o.tgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item), + if (o.verticalAlign === VerticalAlign.Stretch && isNull(item.height)) { + const top = o.innerVgap + o.vgap + o.tgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item), bottom = o.innerVgap + o.vgap + o.bgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item); - var gap = (top + bottom) > 0 && (top + bottom) < 1 ? ((top + bottom) * 100).toFixed(1) + "%" : BI.pixFormat(top + bottom); - w.element.css("height", "calc(100% - " + gap + ")"); + const gap = (top + bottom) > 0 && (top + bottom) < 1 ? `${((top + bottom) * 100).toFixed(1)}%` : pixFormat(top + bottom); + w.element.css("height", `calc(100% - ${gap})`); } + return w; - }, + } - populate: function (items) { - BI.InlineLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.inline", BI.InlineLayout); +} diff --git a/src/core/wrapper/layout/layout.lattice.js b/src/core/wrapper/layout/layout.lattice.js index 34845aa7b..65d049976 100644 --- a/src/core/wrapper/layout/layout.lattice.js +++ b/src/core/wrapper/layout/layout.lattice.js @@ -1,43 +1,52 @@ +import { shortcut } from "../../decorator"; +import { Layout } from "../layout"; +import { extend, isFunction, sum } from "../../2.base"; + /** * 靠左对齐的自由浮动布局 - * @class BI.LatticeLayout - * @extends BI.Layout + * @class LatticeLayout + * @extends Layout * * @cfg {JSON} options 配置属性 * @cfg {Number} [hgap=0] 水平间隙 * @cfg {Number} [vgap=0] 垂直间隙 */ -BI.LatticeLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.LatticeLayout.superclass.props.apply(this, arguments), { - baseCls: "bi-lattice clearfix" +@shortcut() +export class LatticeLayout extends Layout { + static xtype = "bi.lattice"; + + props() { + return extend(super.props(...arguments), { + baseCls: "bi-lattice clearfix", // columnSize: [0.2, 0.2, 0.6], }); - }, - render: function () { - BI.LatticeLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { + } + + render() { + super.render(...arguments); + const self = this, o = this.options; + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { self.populate(newValue); }) : o.items; this.populate(items); - }, + } - _addElement: function (i, item) { - var o = this.options; - var w = BI.LatticeLayout.superclass._addElement.apply(this, arguments); + _addElement(i, item) { + const o = this.options; + const w = super._addElement(...arguments); + let width; if (o.columnSize && o.columnSize[i]) { - var width = o.columnSize[i] / BI.sum(o.columnSize) * 100 + "%"; + width = `${o.columnSize[i] / sum(o.columnSize) * 100}%`; } else { - var width = 1 / this.options.items.length * 100 + "%"; + width = `${1 / this.options.items.length * 100}%`; } - w.element.css({position: "relative", float: "left", width: width}); + w.element.css({ position: "relative", "float": "left", width }); + return w; - }, + } - populate: function (items) { - BI.LatticeLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.lattice", BI.LatticeLayout); +} diff --git a/src/core/wrapper/layout/layout.table.js b/src/core/wrapper/layout/layout.table.js index 51d6eeb14..ec75bc8f0 100644 --- a/src/core/wrapper/layout/layout.table.js +++ b/src/core/wrapper/layout/layout.table.js @@ -1,36 +1,46 @@ +import { shortcut } from "../../decorator"; +import { Layout } from "../layout"; +import { extend, isFunction, range, isArray, map, reduce, isEmpty, formatEL } from "../../2.base"; +import { Widget } from "../../4.widget"; +import { HorizontalAlign, VerticalAlign } from "../../constant"; + /** * 上下的高度固定/左右的宽度固定,中间的高度/宽度自适应 * - * @class BI.TableLayout - * @extends BI.Layout + * @class TableLayout + * @extends Layout */ -BI.TableLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.TableLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class TableLayout extends Layout { + static xtype = "bi.table"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-t", // scrolly: true, columnSize: [], rowSize: [], - horizontalAlign: BI.HorizontalAlign.Stretch, - verticalAlign: BI.VerticalAlign.Stretch, + horizontalAlign: HorizontalAlign.Stretch, + verticalAlign: VerticalAlign.Stretch, // rowSize: 30, // or [30,30,30] hgap: 0, vgap: 0, items: [], }); - }, - render: function () { - BI.TableLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + } + + render() { + super.render(...arguments); + const o = this.options; + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; - var columnSize = o.columnSize.length > 0 ? o.columnSize : BI.range(items[0].length).fill(""); + const columnSize = o.columnSize.length > 0 ? o.columnSize : range(items[0].length).fill(""); if (columnSize.length > 0) { - var template = []; - for (var i = 0; i < columnSize.length; i++) { + const template = []; + for (let i = 0; i < columnSize.length; i++) { if (columnSize[i] === "") { template.push("auto"); } else if (columnSize[i] === "fill") { @@ -41,9 +51,7 @@ BI.TableLayout = BI.inherit(BI.Layout, { } this.element.css({ "grid-template-columns": template.join(" "), - "grid-template-rows": BI.isArray(o.rowSize) ? BI.map(o.rowSize, function (i, size) { - return self._optimiseGap(size); - }).join(" ") : BI.range(o.items.length).fill(this._optimiseGap(o.rowSize)).join(" "), + "grid-template-rows": isArray(o.rowSize) ? map(o.rowSize, (i, size) => this._optimiseGap(size)).join(" ") : range(o.items.length).fill(this._optimiseGap(o.rowSize)).join(" "), "grid-row-gap": this._optimiseGap(o.vgap), "grid-column-gap": this._optimiseGap(o.hgap), }); @@ -51,15 +59,15 @@ BI.TableLayout = BI.inherit(BI.Layout, { return { type: "bi.default", - ref: function (_ref) { - self.layout = _ref; + ref(_ref) { + this.layout = _ref; }, items: this._formatItems(items), }; - }, + } - _formatItems: function (items) { - var o = this.options, self = this; + _formatItems(items) { + const o = this.options; function firstElement (item, cls) { item.addClass(cls); @@ -74,9 +82,9 @@ BI.TableLayout = BI.inherit(BI.Layout, { } function first (item, cls) { - if (item instanceof BI.Widget) { + if (item instanceof Widget) { return firstElement(item.element, cls); - } else if (item.el instanceof BI.Widget) { + } else if (item.el instanceof Widget) { return firstElement(item.el.element, cls); } else if (item.el) { return firstObject(item.el, cls); @@ -91,30 +99,27 @@ BI.TableLayout = BI.inherit(BI.Layout, { columnSize: ["fill"], horizontalAlign: o.horizontalAlign, verticalAlign: o.verticalAlign, - items: [BI.formatEL(item)], + items: [formatEL(item)], }; } - return BI.reduce(items, function (rowItems, result, rowIndex) { - return result.concat(BI.map(rowItems, function (colIndex, item) { - var cls = self.getRowColumnCls(rowIndex, colIndex, items.length - 1, rowItems.length - 1); - if (BI.isEmpty(item)) { - return first(wrapLayout({ - type: "bi.layout", - }), cls); - } + return reduce(items, (rowItems, result, rowIndex) => result.concat(map(rowItems, (colIndex, item) => { + const cls = this.getRowColumnCls(rowIndex, colIndex, items.length - 1, rowItems.length - 1); + if (isEmpty(item)) { + return first(wrapLayout({ + type: "bi.layout", + }), cls); + } - return first(wrapLayout(item), cls); - })); - }, []); - }, + return first(wrapLayout(item), cls); + })), []); + } - resize: function () { + resize() { // console.log("table布局不需要resize"); - }, + } - populate: function (items) { + populate(items) { this.layout.populate(this._formatItems(items)); - }, -}); -BI.shortcut("bi.table", BI.TableLayout); + } +} diff --git a/src/core/wrapper/layout/layout.tape.js b/src/core/wrapper/layout/layout.tape.js index 9303f5865..9ad981f4e 100644 --- a/src/core/wrapper/layout/layout.tape.js +++ b/src/core/wrapper/layout/layout.tape.js @@ -1,13 +1,22 @@ +import { shortcut } from "../../decorator"; +import { Layout } from "../layout"; +import { extend, isFunction, compact, each, isEmptyObject, isNumber, isNull, any, backAny } from "../../2.base"; +import { _lazyCreateWidget } from "../../5.inject"; +import { HorizontalAlign, VerticalAlign } from "../../constant"; + /** * 水平tape布局 - * @class BI.HTapeLayout - * @extends BI.Layout + * @class HTapeLayout + * @extends Layout */ -BI.HTapeLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.HTapeLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class HTapeLayout extends Layout { + static xtype = "bi.htape"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-h-tape", - verticalAlign: BI.VerticalAlign.Top, + verticalAlign: VerticalAlign.Top, hgap: 0, vgap: 0, lgap: 0, @@ -15,37 +24,39 @@ BI.HTapeLayout = BI.inherit(BI.Layout, { tgap: 0, bgap: 0, columnSize: [], - items: [] + items: [], }); - }, - render: function () { - BI.HTapeLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + } + + render() { + super.render(...arguments); + const o = this.options; + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - addItem: function (item) { + addItem(item) { // do nothing throw new Error("不能添加子组件"); - }, + } - stroke: function (items) { - var self = this, o = this.options; - items = BI.compact(items); - BI.each(items, function (i, item) { - if (BI.isEmptyObject(item)) { + stroke(items) { + const o = this.options; + items = compact(items); + each(items, (i, item) => { + let w; + if (isEmptyObject(item)) { return; } - if (!self.hasWidget(self._getChildName(i))) { - var w = BI._lazyCreateWidget(item); - self.addWidget(self._getChildName(i), w); + if (!this.hasWidget(this._getChildName(i))) { + w = _lazyCreateWidget(item); + this.addWidget(this._getChildName(i), w); } else { - w = self.getWidgetByName(self._getChildName(i)); + w = this.getWidgetByName(this._getChildName(i)); } - var columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; + let columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; if (o.columnSize.length > 0) { if (item.width >= 1 && o.columnSize[i] >= 1 && o.columnSize[i] !== item.width) { columnSize = item.width; @@ -53,90 +64,92 @@ BI.HTapeLayout = BI.inherit(BI.Layout, { } w.element.css({ position: "absolute", - top: self._optimiseGap(self._optimiseItemTgap(item) + self._optimiseItemVgap(item) + o.innerVgap + o.vgap + o.tgap), - bottom: self._optimiseGap(self._optimiseItemBgap(item) + self._optimiseItemVgap(item) + o.innerVgap + o.vgap + o.bgap), - width: BI.isNumber(columnSize) ? self._optimiseGap(columnSize) : "" + top: this._optimiseGap(this._optimiseItemTgap(item) + this._optimiseItemVgap(item) + o.innerVgap + o.vgap + o.tgap), + bottom: this._optimiseGap(this._optimiseItemBgap(item) + this._optimiseItemVgap(item) + o.innerVgap + o.vgap + o.bgap), + width: isNumber(columnSize) ? this._optimiseGap(columnSize) : "", }); - if (o.verticalAlign === BI.VerticalAlign.Middle) { + if (o.verticalAlign === VerticalAlign.Middle) { w.element.css({ marginTop: "auto", - marginBottom: "auto" + marginBottom: "auto", }); - } else if (o.verticalAlign === BI.VerticalAlign.Bottom) { + } else if (o.verticalAlign === VerticalAlign.Bottom) { w.element.css({ - marginTop: "auto" + marginTop: "auto", }); } }); - var left = {}, right = {}; + const left = {}, right = {}; left[0] = o.innerHgap; right[items.length - 1] = o.innerHgap; - BI.any(items, function (i, item) { - if (BI.isEmptyObject(item)) { + any(items, (i, item) => { + if (isEmptyObject(item)) { return true; } - var w = self.getWidgetByName(self._getChildName(i)); - var columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; + const w = this.getWidgetByName(this._getChildName(i)); + let columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; if (o.columnSize.length > 0) { if (item.width >= 1 && o.columnSize[i] >= 1 && o.columnSize[i] !== item.width) { columnSize = item.width; } } - if (BI.isNull(left[i])) { - var preColumnSize = o.columnSize.length > 0 ? o.columnSize[i - 1] : items[i - 1].width; - left[i] = left[i - 1] + preColumnSize + self._optimiseItemLgap(items[i - 1]) + self._optimiseItemRgap(items[i - 1]) + 2 * self._optimiseItemHgap(items[i - 1]) + o.hgap + o.lgap + o.rgap; + if (isNull(left[i])) { + const preColumnSize = o.columnSize.length > 0 ? o.columnSize[i - 1] : items[i - 1].width; + left[i] = left[i - 1] + preColumnSize + this._optimiseItemLgap(items[i - 1]) + this._optimiseItemRgap(items[i - 1]) + 2 * this._optimiseItemHgap(items[i - 1]) + o.hgap + o.lgap + o.rgap; } w.element.css({ - left: self._optimiseGap(left[i] + self._optimiseItemLgap(item) + self._optimiseItemHgap(item) + o.hgap + o.lgap) + left: this._optimiseGap(left[i] + this._optimiseItemLgap(item) + this._optimiseItemHgap(item) + o.hgap + o.lgap), }); - if (BI.isNull(columnSize) || columnSize === "" || columnSize === "fill") { + if (isNull(columnSize) || columnSize === "" || columnSize === "fill") { return true; } }); - BI.backAny(items, function (i, item) { - if (BI.isEmptyObject(item)) { + backAny(items, (i, item) => { + if (isEmptyObject(item)) { return true; } - var w = self.getWidgetByName(self._getChildName(i)); - var columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; - if (BI.isNull(right[i])) { - var nextColumnSize = o.columnSize.length > 0 ? o.columnSize[i + 1] : items[i + 1].width; - right[i] = right[i + 1] + nextColumnSize + self._optimiseItemLgap(items[i + 1]) + self._optimiseItemRgap(items[i + 1]) + 2 * self._optimiseItemHgap(items[i + 1]) + o.hgap + o.lgap + o.rgap; + const w = this.getWidgetByName(this._getChildName(i)); + const columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; + if (isNull(right[i])) { + const nextColumnSize = o.columnSize.length > 0 ? o.columnSize[i + 1] : items[i + 1].width; + right[i] = right[i + 1] + nextColumnSize + this._optimiseItemLgap(items[i + 1]) + this._optimiseItemRgap(items[i + 1]) + 2 * this._optimiseItemHgap(items[i + 1]) + o.hgap + o.lgap + o.rgap; } w.element.css({ - right: self._optimiseGap(right[i] + self._optimiseItemRgap(item) + self._optimiseItemHgap(item) + o.hgap + o.rgap) + right: this._optimiseGap(right[i] + this._optimiseItemRgap(item) + this._optimiseItemHgap(item) + o.hgap + o.rgap), }); - if (BI.isNull(columnSize) || columnSize === "" || columnSize === "fill") { + if (isNull(columnSize) || columnSize === "" || columnSize === "fill") { return true; } }); - }, + } - update: function (opt) { + update(opt) { return this.forceUpdate(opt); - }, + } - populate: function (items) { - BI.HTapeLayout.superclass.populate.apply(this, arguments); + populate(items) { + super.populate(...arguments); this._mount(); } -}); -BI.shortcut("bi.htape", BI.HTapeLayout); +} /** * 垂直tape布局 - * @class BI.VTapeLayout - * @extends BI.Layout + * @class VTapeLayout + * @extends Layout */ -BI.VTapeLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.VTapeLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class VTapeLayout extends Layout { + static xtype = "bi.vtape"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-v-tape", - horizontalAlign: BI.HorizontalAlign.Left, + horizontalAlign: HorizontalAlign.Left, hgap: 0, vgap: 0, lgap: 0, @@ -144,33 +157,35 @@ BI.VTapeLayout = BI.inherit(BI.Layout, { tgap: 0, bgap: 0, rowSize: [], - items: [] + items: [], }); - }, - render: function () { - BI.VTapeLayout.superclass.render.apply(this, arguments); + } + + render() { + super.render(...arguments); this.populate(this.options.items); - }, + } - addItem: function (item) { + addItem(item) { // do nothing throw new Error("不能添加子组件"); - }, + } - stroke: function (items) { - var self = this, o = this.options; - items = BI.compact(items); - BI.each(items, function (i, item) { - if (BI.isEmptyObject(item)) { + stroke(items) { + const o = this.options; + items = compact(items); + each(items, (i, item) => { + let w; + if (isEmptyObject(item)) { return; } - if (!self.hasWidget(self._getChildName(i))) { - var w = BI._lazyCreateWidget(item); - self.addWidget(self._getChildName(i), w); + if (!this.hasWidget(this._getChildName(i))) { + w = _lazyCreateWidget(item); + this.addWidget(this._getChildName(i), w); } else { - w = self.getWidgetByName(self._getChildName(i)); + w = this.getWidgetByName(this._getChildName(i)); } - var rowSize = o.rowSize.length > 0 ? o.rowSize[i] : item.height; + let rowSize = o.rowSize.length > 0 ? o.rowSize[i] : item.height; if (o.rowSize.length > 0) { if (item.height >= 1 && o.rowSize[i] >= 1 && o.rowSize[i] !== item.height) { rowSize = item.height; @@ -178,76 +193,75 @@ BI.VTapeLayout = BI.inherit(BI.Layout, { } w.element.css({ position: "absolute", - left: self._optimiseGap(self._optimiseItemLgap(item) + self._optimiseItemHgap(item) + o.innerHgap + o.hgap + o.lgap), - right: self._optimiseGap(self._optimiseItemRgap(item) + self._optimiseItemHgap(item) + o.innerHgap + o.hgap + o.rgap), - height: BI.isNumber(rowSize) ? self._optimiseGap(rowSize) : "" + left: this._optimiseGap(this._optimiseItemLgap(item) + this._optimiseItemHgap(item) + o.innerHgap + o.hgap + o.lgap), + right: this._optimiseGap(this._optimiseItemRgap(item) + this._optimiseItemHgap(item) + o.innerHgap + o.hgap + o.rgap), + height: isNumber(rowSize) ? this._optimiseGap(rowSize) : "", }); - if (o.horizontalAlign === BI.HorizontalAlign.Center) { + if (o.horizontalAlign === HorizontalAlign.Center) { w.element.css({ marginLeft: "auto", - marginRight: "auto" + marginRight: "auto", }); - } else if (o.horizontalAlign === BI.HorizontalAlign.Right) { + } else if (o.horizontalAlign === HorizontalAlign.Right) { w.element.css({ - marginLeft: "auto" + marginLeft: "auto", }); } }); - var top = {}, bottom = {}; + const top = {}, bottom = {}; top[0] = o.innerVgap; bottom[items.length - 1] = o.innerVgap; - BI.any(items, function (i, item) { - if (BI.isEmptyObject(item)) { + any(items, (i, item) => { + if (isEmptyObject(item)) { return true; } - var w = self.getWidgetByName(self._getChildName(i)); - var rowSize = o.rowSize.length > 0 ? o.rowSize[i] : item.height; + const w = this.getWidgetByName(this._getChildName(i)); + let rowSize = o.rowSize.length > 0 ? o.rowSize[i] : item.height; if (o.rowSize.length > 0) { if (item.height >= 1 && o.rowSize[i] >= 1 && o.rowSize[i] !== item.height) { rowSize = item.height; } } - if (BI.isNull(top[i])) { - var preRowSize = o.rowSize.length > 0 ? o.rowSize[i - 1] : items[i - 1].height; - top[i] = top[i - 1] + preRowSize + self._optimiseItemTgap(items[i - 1]) + self._optimiseItemBgap(items[i - 1]) + 2 * self._optimiseItemVgap(items[i - 1]) + o.vgap + o.tgap + o.bgap; + if (isNull(top[i])) { + const preRowSize = o.rowSize.length > 0 ? o.rowSize[i - 1] : items[i - 1].height; + top[i] = top[i - 1] + preRowSize + this._optimiseItemTgap(items[i - 1]) + this._optimiseItemBgap(items[i - 1]) + 2 * this._optimiseItemVgap(items[i - 1]) + o.vgap + o.tgap + o.bgap; } w.element.css({ - top: self._optimiseGap(top[i] + self._optimiseItemTgap(item) + self._optimiseItemVgap(item) + o.vgap + o.tgap) + top: this._optimiseGap(top[i] + this._optimiseItemTgap(item) + this._optimiseItemVgap(item) + o.vgap + o.tgap), }); - if (BI.isNull(rowSize) || rowSize === "" || rowSize === "fill") { + if (isNull(rowSize) || rowSize === "" || rowSize === "fill") { return true; } }); - BI.backAny(items, function (i, item) { - if (BI.isEmptyObject(item)) { + backAny(items, (i, item) => { + if (isEmptyObject(item)) { return true; } - var w = self.getWidgetByName(self._getChildName(i)); - var rowSize = o.rowSize.length > 0 ? o.rowSize[i] : item.height; - if (BI.isNull(bottom[i])) { - var nextRowSize = o.rowSize.length > 0 ? o.rowSize[i + 1] : items[i + 1].height; - bottom[i] = bottom[i + 1] + nextRowSize + self._optimiseItemTgap(items[i + 1]) + self._optimiseItemBgap(items[i + 1]) + 2 * self._optimiseItemVgap(items[i + 1]) + o.vgap + o.tgap + o.bgap; + const w = this.getWidgetByName(this._getChildName(i)); + const rowSize = o.rowSize.length > 0 ? o.rowSize[i] : item.height; + if (isNull(bottom[i])) { + const nextRowSize = o.rowSize.length > 0 ? o.rowSize[i + 1] : items[i + 1].height; + bottom[i] = bottom[i + 1] + nextRowSize + this._optimiseItemTgap(items[i + 1]) + this._optimiseItemBgap(items[i + 1]) + 2 * this._optimiseItemVgap(items[i + 1]) + o.vgap + o.tgap + o.bgap; } w.element.css({ - bottom: self._optimiseGap(bottom[i] + self._optimiseItemBgap(item) + self._optimiseItemVgap(item) + o.vgap + o.bgap) + bottom: this._optimiseGap(bottom[i] + this._optimiseItemBgap(item) + this._optimiseItemVgap(item) + o.vgap + o.bgap), }); - if (BI.isNull(rowSize) || rowSize === "" || rowSize === "fill") { + if (isNull(rowSize) || rowSize === "" || rowSize === "fill") { return true; } }); - }, + } - update: function (opt) { + update(opt) { return this.forceUpdate(opt); - }, + } - populate: function (items) { - BI.VTapeLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.vtape", BI.VTapeLayout); +} diff --git a/src/core/wrapper/layout/layout.td.js b/src/core/wrapper/layout/layout.td.js index cb3221570..e9228ca2d 100644 --- a/src/core/wrapper/layout/layout.td.js +++ b/src/core/wrapper/layout/layout.td.js @@ -1,45 +1,56 @@ +import { shortcut } from "../../decorator"; +import { Layout } from "../layout"; +import { extend, isFunction, isOdd, some, isNumber, isNull } from "../../2.base"; +import { Widget } from "../../4.widget"; +import { _lazyCreateWidget } from "../../5.inject"; +import { HorizontalAlign, VerticalAlign } from "../../constant"; + /** * td布局 - * @class BI.TdLayout - * @extends BI.Layout + * @class TdLayout + * @extends Layout */ -BI.TdLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.TdLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class TdLayout extends Layout { + static xtype = "bi.td"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-td", columnSize: [], rowSize: [], - verticalAlign: BI.VerticalAlign.Middle, - horizontalAlign: BI.HorizontalAlign.Stretch, + verticalAlign: VerticalAlign.Middle, + horizontalAlign: HorizontalAlign.Stretch, hgap: 0, vgap: 0, tgap: 0, bgap: 0, lgap: 0, rgap: 0, - items: [] + items: [], }); - }, - render: function () { - BI.TdLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - this.$table = BI.Widget._renderEngine.createElement("").attr({cellspacing: 0, cellpadding: 0}).css({ + } + + render() { + super.render(...arguments); + const o = this.options; + this.$table = Widget._renderEngine.createElement("
").attr({ cellspacing: 0, cellpadding: 0 }).css({ position: "relative", - width: (o.horizontalAlign === BI.HorizontalAlign.Center || o.horizontalAlign === BI.HorizontalAlign.Stretch) ? "100%" : "auto", - height: (o.verticalAlign !== BI.VerticalAlign.Top) ? "100%" : "auto", + width: (o.horizontalAlign === HorizontalAlign.Center || o.horizontalAlign === HorizontalAlign.Stretch) ? "100%" : "auto", + height: (o.verticalAlign !== VerticalAlign.Top) ? "100%" : "auto", "border-spacing": "0px", border: "none", - "border-collapse": "separate" + "border-collapse": "separate", }); this.rows = 0; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - _addElement: function (idx, arr) { - var o = this.options; + _addElement(idx, arr) { + const o = this.options; function firstElement (item, row, col) { if (row === 0) { @@ -48,28 +59,28 @@ BI.TdLayout = BI.inherit(BI.Layout, { if (col === 0) { item.addClass("first-col"); } - item.addClass(BI.isOdd(row + 1) ? "odd-row" : "even-row"); - item.addClass(BI.isOdd(col + 1) ? "odd-col" : "even-col"); + item.addClass(isOdd(row + 1) ? "odd-row" : "even-row"); + item.addClass(isOdd(col + 1) ? "odd-col" : "even-col"); item.addClass("center-element"); } function firstObject (item, row, col) { - var cls = ""; + let cls = ""; if (row === 0) { cls += " first-row"; } if (col === 0) { cls += " first-col"; } - BI.isOdd(row + 1) ? (cls += " odd-row") : (cls += " even-row"); - BI.isOdd(col + 1) ? (cls += " odd-col") : (cls += " even-col"); - item.cls = (item.cls || "") + cls + " center-element"; + isOdd(row + 1) ? (cls += " odd-row") : (cls += " even-row"); + isOdd(col + 1) ? (cls += " odd-col") : (cls += " even-col"); + item.cls = `${(item.cls || "") + cls} center-element`; } function first (item, row, col) { - if (item instanceof BI.Widget) { + if (item instanceof Widget) { firstElement(item.element, row, col); - } else if (item.el instanceof BI.Widget) { + } else if (item.el instanceof Widget) { firstElement(item.el.element, row, col); } else if (item.el) { firstObject(item.el, row, col); @@ -78,30 +89,30 @@ BI.TdLayout = BI.inherit(BI.Layout, { } } - var height = BI.isNumber(o.rowSize) ? this._optimiseGap(o.rowSize) : (o.rowSize[idx] === "" ? this._optimiseGap(1) : this._optimiseGap(o.rowSize[idx])); - var tr = BI._lazyCreateWidget({ + const height = isNumber(o.rowSize) ? this._optimiseGap(o.rowSize) : (o.rowSize[idx] === "" ? this._optimiseGap(1) : this._optimiseGap(o.rowSize[idx])); + const tr = _lazyCreateWidget({ type: "bi.default", tagName: "tr", - height: height, + height, css: { "max-height": height, - "min-height": height - } + "min-height": height, + }, }); - for (var i = 0; i < arr.length; i++) { - var w = BI._lazyCreateWidget(arr[i]); - if (o.verticalAlign === BI.VerticalAlign.Stretch) { - var top = o.vgap + o.tgap + this._optimiseItemTgap(arr[i]) + this._optimiseItemVgap(arr[i]), + for (let i = 0; i < arr.length; i++) { + const w = _lazyCreateWidget(arr[i]); + if (o.verticalAlign === VerticalAlign.Stretch) { + const top = o.vgap + o.tgap + this._optimiseItemTgap(arr[i]) + this._optimiseItemVgap(arr[i]), bottom = o.vgap + o.bgap + this._optimiseItemBgap(arr[i]) + this._optimiseItemVgap(arr[i]); - w.element.css("height", "calc(100% - " + this._optimiseGap(top + bottom) + ")"); + w.element.css("height", `calc(100% - ${this._optimiseGap(top + bottom)})`); } - w.element.css({position: "relative", top: "0", left: "0", margin: "0px auto"}); - var item = arr[i]; + w.element.css({ position: "relative", top: "0", left: "0", margin: "0px auto" }); + const item = arr[i]; this._handleGap(w, item, i); first(w, this.rows++, i); - var width = ""; - var columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; + let width = ""; + const columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; if (columnSize > 0) { width = this._optimiseGap(columnSize + (i === 0 ? o.hgap : 0) + o.hgap + o.lgap + o.rgap); } @@ -109,20 +120,21 @@ BI.TdLayout = BI.inherit(BI.Layout, { if (o.columnSize.length > 0) { return o.columnSize.indexOf("fill") >= 0; } - return BI.some(arr, function (i, item) { + + return some(arr, (i, item) => { if (item.width === "fill") { return true; } }); } - if ((BI.isNull(columnSize) || columnSize === "") && hasFill()) { + if ((isNull(columnSize) || columnSize === "") && hasFill()) { width = 2; } - var td = BI._lazyCreateWidget({ + const td = _lazyCreateWidget({ type: "bi.default", - width: width, + width, tagName: "td", - items: [w] + items: [w], }); // 对于表现为td的元素设置最大宽度,有几点需要注意 // 1、由于直接对td设置最大宽度是在规范中未定义的, 所以要使用类似td:firstChild来迂回实现 @@ -131,7 +143,7 @@ BI.TdLayout = BI.inherit(BI.Layout, { if (columnSize > 0) { td.element.css({ "max-width": width, - "min-width": width + "min-width": width, }); } td.element.css({ @@ -139,30 +151,30 @@ BI.TdLayout = BI.inherit(BI.Layout, { "vertical-align": o.verticalAlign, margin: "0", padding: "0", - border: "none" + border: "none", }); tr.addItem(td); } this.addWidget(this._getChildName(idx), tr); + return tr; - }, + } - appendFragment: function (frag) { + appendFragment(frag) { this.$table.append(frag); this.element.append(this.$table); - }, + } - resize: function () { + resize() { // console.log("td布局不需要resize"); - }, + } - update: function (opt) { + update(opt) { return this.forceUpdate(opt); - }, + } - populate: function (items) { - BI.TdLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.td", BI.TdLayout); +} diff --git a/src/core/wrapper/layout/layout.vertical.js b/src/core/wrapper/layout/layout.vertical.js index b181b1d41..ada08e063 100644 --- a/src/core/wrapper/layout/layout.vertical.js +++ b/src/core/wrapper/layout/layout.vertical.js @@ -1,54 +1,63 @@ +import { shortcut } from "../../decorator"; +import { Layout } from "../layout"; +import { extend, isFunction } from "../../2.base"; +import { HorizontalAlign } from "../../constant"; + /** * 垂直布局 - * @class BI.VerticalLayout - * @extends BI.Layout + * @class VerticalLayout + * @extends Layout */ -BI.VerticalLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.VerticalLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class VerticalLayout extends Layout { + static xtype = "bi.vertical"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-v", - horizontalAlign: BI.HorizontalAlign.Stretch, + horizontalAlign: HorizontalAlign.Stretch, hgap: 0, vgap: 0, lgap: 0, rgap: 0, tgap: 0, bgap: 0, - scrolly: true + scrolly: true, }); - }, - render: function () { - BI.VerticalLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + } + + render() { + super.render(...arguments); + const o = this.options; + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - _addElement: function (i, item) { - var o = this.options; - var w = BI.VerticalLayout.superclass._addElement.apply(this, arguments); + _addElement(i, item) { + const o = this.options; + const w = super._addElement(...arguments); w.element.css({ - position: "relative" + position: "relative", }); this._handleGap(w, item, null, i); - if (o.horizontalAlign === BI.HorizontalAlign.Center) { + if (o.horizontalAlign === HorizontalAlign.Center) { w.element.css({ marginLeft: "auto", - marginRight: "auto" + marginRight: "auto", }); - } else if (o.horizontalAlign === BI.HorizontalAlign.Right) { + } else if (o.horizontalAlign === HorizontalAlign.Right) { w.element.css({ - marginLeft: "auto" + marginLeft: "auto", }); } + return w; - }, + } - populate: function (items) { - BI.VerticalLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.vertical", BI.VerticalLayout); +} diff --git a/src/core/wrapper/layout/layout.window.js b/src/core/wrapper/layout/layout.window.js index a6e6c6a26..34dfe422f 100644 --- a/src/core/wrapper/layout/layout.window.js +++ b/src/core/wrapper/layout/layout.window.js @@ -1,11 +1,20 @@ +import { shortcut } from "../../decorator"; +import { Layout } from "../layout"; +import { extend, isFunction, makeArray, isNumber, isNull } from "../../2.base"; +import { Widget } from "../../4.widget"; +import { _lazyCreateWidget } from "../../5.inject"; + /** * - * @class BI.WindowLayout - * @extends BI.Layout + * @class WindowLayout + * @extends Layout */ -BI.WindowLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.WindowLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class WindowLayout extends Layout { + static xtype = "bi.window"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-window", columns: 3, rows: 2, @@ -17,30 +26,31 @@ BI.WindowLayout = BI.inherit(BI.Layout, { bgap: 0, columnSize: [], rowSize: [], - items: [] + items: [], }); - }, - render: function () { - BI.WindowLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + } + + render() { + super.render(...arguments); + const o = this.options; + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - addItem: function (item) { + addItem(item) { // do nothing throw new Error("不能添加子组件"); - }, + } - stroke: function (items) { - var o = this.options, self = this; - if (BI.isNumber(o.rowSize)) { - o.rowSize = BI.makeArray(o.items.length, 1 / o.items.length); + stroke(items) { + const o = this.options; + if (isNumber(o.rowSize)) { + o.rowSize = makeArray(o.items.length, 1 / o.items.length); } - if (BI.isNumber(o.columnSize)) { - o.columnSize = BI.makeArray(o.items[0].length, 1 / o.items[0].length); + if (isNumber(o.columnSize)) { + o.columnSize = makeArray(o.items[0].length, 1 / o.items[0].length); } function firstElement (item, cls) { @@ -56,9 +66,9 @@ BI.WindowLayout = BI.inherit(BI.Layout, { } function first (item, row, col) { - if (item instanceof BI.Widget) { + if (item instanceof Widget) { firstElement(item.element, row, col); - } else if (item.el instanceof BI.Widget) { + } else if (item.el instanceof Widget) { firstElement(item.el.element, row, col); } else if (item.el) { firstObject(item.el, row, col); @@ -67,108 +77,111 @@ BI.WindowLayout = BI.inherit(BI.Layout, { } } - for (var i = 0; i < o.rows; i++) { - for (var j = 0; j < o.columns; j++) { + for (let i = 0; i < o.rows; i++) { + for (let j = 0; j < o.columns; j++) { if (!o.items[i][j]) { throw new Error("构造错误", o.items); } - if (!this.hasWidget(this._getChildName(i + "_" + j))) { - var w = BI._lazyCreateWidget(o.items[i][j]); - w.element.css({position: "absolute"}); - this.addWidget(this._getChildName(i + "_" + j), w); + if (!this.hasWidget(this._getChildName(`${i}_${j}`))) { + const w = _lazyCreateWidget(o.items[i][j]); + w.element.css({ position: "absolute" }); + this.addWidget(this._getChildName(`${i}_${j}`), w); } } } - var left = {}, right = {}, top = {}, bottom = {}; + const left = {}, right = {}, top = {}, bottom = {}; left[0] = 0; top[0] = 0; right[o.columns - 1] = 0; bottom[o.rows - 1] = 0; // 从上到下 - for (var i = 0; i < o.rows; i++) { - for (var j = 0; j < o.columns; j++) { - var wi = this.getWidgetByName(this._getChildName(i + "_" + j)); - if (BI.isNull(top[i])) { + for (let i = 0; i < o.rows; i++) { + for (let j = 0; j < o.columns; j++) { + const wi = this.getWidgetByName(this._getChildName(`${i}_${j}`)); + if (isNull(top[i])) { top[i] = top[i - 1] + (o.rowSize[i - 1] < 1 ? o.rowSize[i - 1] : o.rowSize[i - 1] + o.vgap + o.bgap); } - var t = this._optimiseGap(top[i] + o.vgap + o.tgap), h = ""; - if (BI.isNumber(o.rowSize[i])) { + const t = this._optimiseGap(top[i] + o.vgap + o.tgap); + let h = ""; + if (isNumber(o.rowSize[i])) { h = this._optimiseGap(o.rowSize[i]); } - wi.element.css({top: t, height: h}); - first(wi, self.getRowColumnCls(i, j, o.rows - 1, o.columns - 1)); + wi.element.css({ top: t, height: h }); + first(wi, this.getRowColumnCls(i, j, o.rows - 1, o.columns - 1)); } - if (!BI.isNumber(o.rowSize[i])) { + if (!isNumber(o.rowSize[i])) { break; } } // 从下到上 - for (var i = o.rows - 1; i >= 0; i--) { - for (var j = 0; j < o.columns; j++) { - var wi = this.getWidgetByName(this._getChildName(i + "_" + j)); - if (BI.isNull(bottom[i])) { + for (let i = o.rows - 1; i >= 0; i--) { + for (let j = 0; j < o.columns; j++) { + const wi = this.getWidgetByName(this._getChildName(`${i}_${j}`)); + if (isNull(bottom[i])) { bottom[i] = bottom[i + 1] + (o.rowSize[i + 1] < 1 ? o.rowSize[i + 1] : o.rowSize[i + 1] + o.vgap + o.tgap); } - var b = this._optimiseGap(bottom[i] + o.vgap + o.bgap), h = ""; - if (BI.isNumber(o.rowSize[i])) { + const b = this._optimiseGap(bottom[i] + o.vgap + o.bgap); + let h = ""; + if (isNumber(o.rowSize[i])) { h = this._optimiseGap(o.rowSize[i]); } - wi.element.css({bottom: b, height: h}); - first(wi, self.getRowColumnCls(i, j, o.rows - 1, o.columns - 1)); + wi.element.css({ bottom: b, height: h }); + first(wi, this.getRowColumnCls(i, j, o.rows - 1, o.columns - 1)); } - if (!BI.isNumber(o.rowSize[i])) { + if (!isNumber(o.rowSize[i])) { break; } } // 从左到右 - for (var j = 0; j < o.columns; j++) { - for (var i = 0; i < o.rows; i++) { - var wi = this.getWidgetByName(this._getChildName(i + "_" + j)); - if (BI.isNull(left[j])) { + for (let j = 0; j < o.columns; j++) { + for (let i = 0; i < o.rows; i++) { + const wi = this.getWidgetByName(this._getChildName(`${i}_${j}`)); + if (isNull(left[j])) { left[j] = left[j - 1] + (o.columnSize[j - 1] < 1 ? o.columnSize[j - 1] : o.columnSize[j - 1] + o.hgap + o.rgap); } - var l = this._optimiseGap(left[j] + o.hgap + o.lgap), w = ""; - if (BI.isNumber(o.columnSize[j])) { + const l = this._optimiseGap(left[j] + o.hgap + o.lgap); + let w = ""; + if (isNumber(o.columnSize[j])) { w = this._optimiseGap(o.columnSize[j]); } - wi.element.css({left: l, width: w}); - first(wi, self.getRowColumnCls(i, j, o.rows - 1, o.columns - 1)); + wi.element.css({ left: l, width: w }); + first(wi, this.getRowColumnCls(i, j, o.rows - 1, o.columns - 1)); } - if (!BI.isNumber(o.columnSize[j])) { + if (!isNumber(o.columnSize[j])) { break; } } // 从右到左 - for (var j = o.columns - 1; j >= 0; j--) { - for (var i = 0; i < o.rows; i++) { - var wi = this.getWidgetByName(this._getChildName(i + "_" + j)); - if (BI.isNull(right[j])) { + for (let j = o.columns - 1; j >= 0; j--) { + for (let i = 0; i < o.rows; i++) { + const wi = this.getWidgetByName(this._getChildName(`${i}_${j}`)); + if (isNull(right[j])) { right[j] = right[j + 1] + (o.columnSize[j + 1] < 1 ? o.columnSize[j + 1] : o.columnSize[j + 1] + o.hgap + o.lgap); } - var r = this._optimiseGap(right[j] + o.hgap + o.rgap), w = ""; - if (BI.isNumber(o.columnSize[j])) { + const r = this._optimiseGap(right[j] + o.hgap + o.rgap); + let w = ""; + if (isNumber(o.columnSize[j])) { w = this._optimiseGap(o.columnSize[j]); } - wi.element.css({right: r, width: w}); - first(wi, self.getRowColumnCls(i, j, o.rows - 1, o.columns - 1)); + wi.element.css({ right: r, width: w }); + first(wi, this.getRowColumnCls(i, j, o.rows - 1, o.columns - 1)); } - if (!BI.isNumber(o.columnSize[j])) { + if (!isNumber(o.columnSize[j])) { break; } } - }, + } - resize: function () { + resize() { // console.log("window布局不需要resize"); - }, + } - update: function (opt) { + update(opt) { return this.forceUpdate(opt); - }, + } - populate: function (items) { - BI.WindowLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.window", BI.WindowLayout); +} From 7074a0dcbeca2179560858ffbd025e439864bc1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Tue, 10 Jan 2023 14:00:18 +0800 Subject: [PATCH 053/300] =?UTF-8?q?KERNEL-14045=20refactor:=20calendar?= =?UTF-8?q?=E5=92=8Cpager=E6=96=87=E4=BB=B6es6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/case/calendar/calendar.date.item.js | 70 ++++--- src/case/calendar/calendar.js | 255 ++++++++++++----------- src/case/calendar/calendar.year.js | 198 +++++++++--------- src/case/calendar/index.js | 3 + src/case/index.js | 6 + src/case/pager/index.js | 3 + src/case/pager/pager.all.count.js | 206 ++++++++++--------- src/case/pager/pager.detail.js | 260 ++++++++++++------------ src/case/pager/pager.direction.js | 167 ++++++++------- 9 files changed, 605 insertions(+), 563 deletions(-) create mode 100644 src/case/calendar/index.js create mode 100644 src/case/pager/index.js diff --git a/src/case/calendar/calendar.date.item.js b/src/case/calendar/calendar.date.item.js index 3b2d865a0..eaac1234e 100644 --- a/src/case/calendar/calendar.date.item.js +++ b/src/case/calendar/calendar.date.item.js @@ -1,16 +1,23 @@ /** * 专门为calendar的视觉加的button,作为私有button,不能配置任何属性,也不要用这个玩意 */ -BI.CalendarDateItem = BI.inherit(BI.BasicButton, { - props: function() { + +import { shortcut } from "../../core"; +import { BasicButton } from "../../base/single/button/button.basic"; +@shortcut() +export class CalendarDateItem extends BasicButton { + props() { return { baseCls: "bi-calendar-date-item", height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + 8, - } - }, + }; + } + + static xtype = "bi.calendar_date_item"; - render: function () { - var self = this, o = this.options; + render () { + const { text, value, lgap, rgap, tgap, bgap } = this.options; + return { type: "bi.absolute", items: [{ @@ -18,41 +25,40 @@ BI.CalendarDateItem = BI.inherit(BI.BasicButton, { type: "bi.text_item", cls: "bi-border-radius bi-list-item-select", textAlign: "center", - text: o.text, - value: o.value, - ref: function () { - self.text = this; - } + text, + value, + ref: _ref => { + this.text = _ref; + }, }, - left: o.lgap, - right: o.rgap, - top: o.tgap, - bottom: o.bgap - }] + left: lgap, + right: rgap, + top: tgap, + bottom: bgap, + }], }; - }, + } - doHighLight: function () { - this.text.doHighLight.apply(this.text, arguments); - }, + doHighLight () { + this.text.doHighLight(...arguments); + } - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - }, + unHighLight () { + this.text.unHighLight(...arguments); + } - setValue: function () { + setValue () { if (!this.isReadOnly()) { - this.text.setValue.apply(this.text, arguments); + this.text.setValue(...arguments); } - }, + } - setSelected: function (b) { - BI.CalendarDateItem.superclass.setSelected.apply(this, arguments); + setSelected (b) { + super.setSelected(...arguments); this.text.setSelected(b); - }, + } - getValue: function () { + getValue () { return this.text.getValue(); } -}); -BI.shortcut("bi.calendar_date_item", BI.CalendarDateItem); +} diff --git a/src/case/calendar/calendar.js b/src/case/calendar/calendar.js index 5645fb1f5..fdbd6b984 100644 --- a/src/case/calendar/calendar.js +++ b/src/case/calendar/calendar.js @@ -3,32 +3,36 @@ * @class BI.Calendar * @extends BI.Widget */ -BI.Calendar = BI.inherit(BI.Widget, { - _defaultConfig: function () { - var conf = BI.Calendar.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { +import { shortcut, Widget, getDate, each, range, extend, isLeapYear, Date, StartOfWeek, checkDateVoid, map, createWidget, createItems, LogicFactory, Controller, getShortDayName, getOffsetDate, isNotEmptyString, parseInt } from "../../core"; +@shortcut() +export class Calendar extends Widget { + static xtype = "bi.calendar"; + + _defaultConfig () { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { baseCls: "bi-calendar", logic: { - dynamic: false + dynamic: false, }, min: "1900-01-01", // 最小日期 max: "2099-12-31", // 最大日期 year: 2015, month: 8, - day: 25 + day: 25, }); - }, - - _dateCreator: function (Y, M, D) { - var self = this, o = this.options, log = {}, De = BI.getDate(); - var mins = o.min.match(/\d+/g); - var maxs = o.max.match(/\d+/g); + } + _dateCreator (Y, M, D) { + const { min, max } = this.options, log = {}, De = getDate(); + const mins = min.match(/\d+/g); + const maxs = max.match(/\d+/g); De.setFullYear(Y, M, D); log.ymd = [De.getFullYear(), De.getMonth(), De.getDate()]; - var MD = BI.Date._MD.slice(0); - MD[1] = BI.isLeapYear(log.ymd[0]) ? 29 : 28; + const MD = Date._MD.slice(0); + MD[1] = isLeapYear(log.ymd[0]) ? 29 : 28; // 日期所在月第一天 De.setFullYear(log.ymd[0], log.ymd[1], 1); @@ -36,15 +40,16 @@ BI.Calendar = BI.inherit(BI.Widget, { log.FDay = De.getDay(); // 当前BI.StartOfWeek与周日对齐后的FDay是周几 - var offSetFDay = (7 - BI.StartOfWeek + log.FDay) % 7; + const offSetFDay = (7 - StartOfWeek + log.FDay) % 7; // 当前月页第一天是几号 log.PDay = MD[M === 0 ? 11 : M - 1] - offSetFDay + 1; log.NDay = 1; - var items = []; - BI.each(BI.range(42), function (i) { - var td = {}, YY = log.ymd[0], MM = log.ymd[1] + 1, DD; + const items = []; + each(range(42), i => { + const td = {}; + let YY = log.ymd[0], MM = log.ymd[1] + 1, DD; // 上个月的日期 if (i < offSetFDay) { td.lastMonth = true; @@ -63,89 +68,92 @@ BI.Calendar = BI.inherit(BI.Widget, { MM === 12 && (YY += 1); MM = MM === 12 ? 1 : MM + 1; } - if (BI.checkDateVoid(YY, MM, DD, mins, maxs)[0]) { + if (checkDateVoid(YY, MM, DD, mins, maxs)[0]) { td.disabled = true; } td.text = DD; items.push(td); }); + return items; - }, + } - _init: function () { - BI.Calendar.superclass._init.apply(this, arguments); - var self = this, o = this.options; - var items = BI.map(this._getWeekLabel(), function (i, value) { + _init () { + super._init(...arguments); + const { year, month, day, logic } = this.options; + const items = map(this._getWeekLabel(), (i, value) => { return { type: "bi.label", height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - text: value + text: value, }; }); - var title = BI.createWidget({ + const title = createWidget({ type: "bi.button_group", height: 44, - items: items, + items, layouts: [{ type: "bi.center", hgap: 5, - vgap: 10 - }] + vgap: 10, + }], }); - this.days = BI.createWidget({ + this.days = createWidget({ type: "bi.button_group", - items: BI.createItems(this._getItems(), {}), - value: o.year + "-" + o.month + "-" + o.day, - layouts: [BI.LogicFactory.createLogic("table", BI.extend({}, o.logic, { + items: createItems(this._getItems(), {}), + value: `${year}-${month}-${day}`, + layouts: [LogicFactory.createLogic("table", extend({}, logic, { columns: 7, rows: 6, columnSize: [1 / 7, 1 / 7, 1 / 7, 1 / 7, 1 / 7, 1 / 7, 1 / 7], - rowSize: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + 8 - }))] + rowSize: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + 8, + }))], }); - this.days.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.days.on(Controller.EVENT_CHANGE, () => { + this.fireEvent(Controller.EVENT_CHANGE, arguments); }); - BI.createWidget(BI.extend({ - element: this + createWidget(extend({ + element: this, - }, BI.LogicFactory.createLogic("vertical", BI.extend({}, o.logic, { - items: BI.LogicFactory.createLogicItemsByDirection("top", title, { + }, LogicFactory.createLogic("vertical", extend({}, logic, { + items: LogicFactory.createLogicItemsByDirection("top", title, { el: this.days, - tgap: -5 - }) + tgap: -5, + }), })))); - }, + } - _getWeekLabel: function () { - return BI.map(BI.range(0, 7), function (idx, v) { - return BI.getShortDayName((v + BI.StartOfWeek) % 7); - }); - }, + _getWeekLabel () { + return map(range(0, 7), (idx, v) => getShortDayName((v + StartOfWeek) % 7)); + } - isFrontDate: function () { - var o = this.options, c = this._const; - var Y = o.year, M = o.month, De = BI.getDate(), day = De.getDay(); + isFrontDate () { + const { year, month, min, max } = this.options; + let Y = year; + const M = month, De = getDate(), day = De.getDay(); Y = Y | 0; De.setFullYear(Y, M, 1); - var newDate = BI.getOffsetDate(De, -1 * (day + 1)); - return !!BI.checkDateVoid(newDate.getFullYear(), newDate.getMonth(), newDate.getDate(), o.min, o.max)[0]; - }, + const newDate = getOffsetDate(De, -1 * (day + 1)); + + return !!checkDateVoid(newDate.getFullYear(), newDate.getMonth(), newDate.getDate(), min, max)[0]; + } - isFinalDate: function () { - var o = this.options, c = this._const; - var Y = o.year, M = o.month, De = BI.getDate(), day = De.getDay(); + isFinalDate () { + const { year, month, min, max } = this.options; + let Y = year; + const M = month, De = getDate(), day = De.getDay(); Y = Y | 0; De.setFullYear(Y, M, 1); - var newDate = BI.getOffsetDate(De, 42 - day); - return !!BI.checkDateVoid(newDate.getFullYear(), newDate.getMonth(), newDate.getDate(), o.min, o.max)[0]; - }, + const newDate = getOffsetDate(De, 42 - day); + + return !!checkDateVoid(newDate.getFullYear(), newDate.getMonth(), newDate.getDate(), min, max)[0]; + } - _getItems: function () { - var o = this.options; - var days = this._dateCreator(o.year, o.month - 1, o.day); - var items = []; + _getItems () { + const o = this.options; + const days = this._dateCreator(o.year, o.month - 1, o.day); + const items = []; items.push(days.slice(0, 7)); items.push(days.slice(7, 14)); items.push(days.slice(14, 21)); @@ -153,93 +161,94 @@ BI.Calendar = BI.inherit(BI.Widget, { items.push(days.slice(28, 35)); items.push(days.slice(35, 42)); - return BI.map(items, function (i, item) { - return BI.map(item, function (j, td) { - var month = td.lastMonth ? o.month - 1 : (td.nextMonth ? o.month + 1 : o.month); - var year = o.year; - if (month > 12) { - month = 1; - year++; - } else if (month < 1) { - month = 12; - year--; - } - return BI.extend(td, { - type: "bi.calendar_date_item", - once: false, - forceSelected: true, - value: year + "-" + month + "-" + td.text, - disabled: td.disabled, - cls: td.lastMonth || td.nextMonth ? "bi-tips" : "", - lgap: 2, - rgap: 2, - tgap: 4, - bgap: 4 - // selected: td.currentDay - }); + return map(items, (i, item) => map(item, (j, td) => { + let month = td.lastMonth ? o.month - 1 : (td.nextMonth ? o.month + 1 : o.month); + let year = o.year; + if (month > 12) { + month = 1; + year++; + } else if (month < 1) { + month = 12; + year--; + } + + return extend(td, { + type: "bi.calendar_date_item", + once: false, + forceSelected: true, + value: `${year}-${month}-${td.text}`, + disabled: td.disabled, + cls: td.lastMonth || td.nextMonth ? "bi-tips" : "", + lgap: 2, + rgap: 2, + tgap: 4, + bgap: 4, + // selected: td.currentDay }); - }); - }, + })); + } - _populate: function() { + _populate() { this.days.populate(this._getItems()); - }, + } - setMinDate: function (minDate) { - var o = this.options; - if (BI.isNotEmptyString(o.min)) { + setMinDate (minDate) { + const o = this.options; + if (isNotEmptyString(o.min)) { o.min = minDate; this._populate(); } - }, + } - setMaxDate: function (maxDate) { - var o = this.options; - if (BI.isNotEmptyString(o.max)) { + setMaxDate (maxDate) { + const o = this.options; + if (isNotEmptyString(o.max)) { o.max = maxDate; this._populate(); } - }, + } - setValue: function (ob) { - this.days.setValue([ob.year + "-" + ob.month + "-" + ob.day]); - }, + setValue (ob) { + this.days.setValue([`${ob.year}-${ob.month}-${ob.day}`]); + } - getValue: function () { - var date = this.days.getValue()[0].match(/\d+/g); + getValue () { + const date = this.days.getValue()[0].match(/\d+/g); + return { year: date[0] | 0, month: date[1] | 0, - day: date[2] | 0 + day: date[2] | 0, }; } -}); +} -BI.extend(BI.Calendar, { - getPageByDateJSON: function (json) { - var year = BI.getDate().getFullYear(); - var month = BI.getDate().getMonth(); - var page = (json.year - year) * 12; +extend(Calendar, { + getPageByDateJSON (json) { + const year = getDate().getFullYear(); + const month = getDate().getMonth(); + let page = (json.year - year) * 12; page += json.month - 1 - month; + return page; }, - getDateJSONByPage: function (v) { - var months = BI.getDate().getMonth(); - var page = v; + getDateJSONByPage (v) { + const months = getDate().getMonth(); + let page = v; // 对当前page做偏移,使到当前年初 page = page + months; - var year = BI.parseInt(page / 12); - if(page < 0 && page % 12 !== 0) { + let year = parseInt(page / 12); + if (page < 0 && page % 12 !== 0) { year--; } - var month = page >= 0 ? (page % 12) : ((12 + page % 12) % 12); + const month = page >= 0 ? (page % 12) : ((12 + page % 12) % 12); + return { - year: BI.getDate().getFullYear() + year, - month: month + 1 + year: getDate().getFullYear() + year, + month: month + 1, }; - } + }, }); -BI.shortcut("bi.calendar", BI.Calendar); diff --git a/src/case/calendar/calendar.year.js b/src/case/calendar/calendar.year.js index 95fcaccdb..b225c3e8a 100644 --- a/src/case/calendar/calendar.year.js +++ b/src/case/calendar/calendar.year.js @@ -3,99 +3,104 @@ * @class BI.YearCalendar * @extends BI.Widget */ -BI.YearCalendar = BI.inherit(BI.Widget, { - - _defaultConfig: function () { - var conf = BI.YearCalendar.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { +import { shortcut, Widget, extend, parseDateTime, range, checkDateVoid, print, getDate, each, createWidget, createItems, LogicFactory, Controller, makeArray, map, isNotEmptyString } from "../../core"; +@shortcut() +export class YearCalendar extends Widget { + static xtype = "bi.year_calendar"; + _defaultConfig () { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { baseCls: "bi-year-calendar", behaviors: {}, logic: { - dynamic: false + dynamic: false, }, min: "1900-01-01", // 最小日期 max: "2099-12-31", // 最大日期 - year: null + year: null, }); - }, + } - _yearCreator: function (Y) { - var o = this.options; + _yearCreator (Y) { + const { min, max } = this.options; Y = Y | 0; - var start = BI.YearCalendar.getStartYear(Y); - var items = []; + const start = YearCalendar.getStartYear(Y); + const items = []; // 对于年控件来说,只要传入的minDate和maxDate的year区间包含v就是合法的 - var startDate = BI.parseDateTime(o.min, "%Y-%X-%d"); - var endDate = BI.parseDateTime(o.max, "%Y-%X-%d"); - BI.each(BI.range(BI.YearCalendar.INTERVAL), function (i) { - var td = {}; - if (BI.checkDateVoid(start + i, 1, 1, BI.print(BI.getDate(startDate.getFullYear(), 0, 1), "%Y-%X-%d"), BI.print(BI.getDate(endDate.getFullYear(), 0, 1), "%Y-%X-%d"))[0]) { + const startDate = parseDateTime(min, "%Y-%X-%d"); + const endDate = parseDateTime(max, "%Y-%X-%d"); + each(range(YearCalendar.INTERVAL), i => { + const td = {}; + if (checkDateVoid(start + i, 1, 1, print(getDate(startDate.getFullYear(), 0, 1), "%Y-%X-%d"), print(getDate(endDate.getFullYear(), 0, 1), "%Y-%X-%d"))[0]) { td.disabled = true; } td.text = start + i; items.push(td); }); + return items; - }, - - _init: function () { - BI.YearCalendar.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.currentYear = BI.getDate().getFullYear(); + } + _init () { + super._init(...arguments); + const { behaviors, logic } = this.options; + this.currentYear = getDate().getFullYear(); - this.years = BI.createWidget({ + this.years = createWidget({ type: "bi.button_group", - behaviors: o.behaviors, - items: BI.createItems(this._getItems(), {}), - layouts: [BI.LogicFactory.createLogic("table", BI.extend({}, o.logic, { + behaviors, + items: createItems(this._getItems(), {}), + layouts: [LogicFactory.createLogic("table", extend({}, logic, { columns: 2, rows: 6, columnSize: [1 / 2, 1 / 2], rowSize: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, })), { type: "bi.center_adapt", - vgap: 2 - }] + vgap: 2, + }], }); - this.years.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.years.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic("vertical", BI.extend({}, o.logic, { + createWidget(extend({ + element: this, + }, LogicFactory.createLogic("vertical", extend({}, logic, { scrolly: true, vgap: 5, hgap: 6, - items: BI.LogicFactory.createLogicItemsByDirection("top", this.years) + items: LogicFactory.createLogicItemsByDirection("top", this.years), })))); - }, + } - isFrontYear: function () { - var o = this.options; - var Y = o.year; + isFrontYear () { + const { min, max } = this.options; + let Y = this.options.year; Y = Y | 0; - return !!BI.checkDateVoid(BI.YearCalendar.getStartYear(Y) - 1, 1, 1, o.min, o.max)[0]; - }, + + return !!checkDateVoid(YearCalendar.getStartYear(Y) - 1, 1, 1, min, max)[0]; + } - isFinalYear: function () { - var o = this.options, c = this._const; - var Y = o.year; + isFinalYear () { + const { min, max } = this.options; + let Y = this.options.year; Y = Y | 0; - return !!BI.checkDateVoid(BI.YearCalendar.getEndYear(Y) + 1, 1, 1, o.min, o.max)[0]; - }, + + return !!checkDateVoid(YearCalendar.getEndYear(Y) + 1, 1, 1, min, max)[0]; + } - _getItems: function () { - var o = this.options; - var years = this._yearCreator(o.year || this.currentYear); + _getItems () { + const { year } = this.options; + const years = this._yearCreator(year || this.currentYear); // 纵向排列年 - var len = years.length, tyears = BI.makeArray(len, ""); - var map = [0, 6, 1, 7, 2, 8, 3, 9, 4, 10, 5, 11]; - BI.each(years, function (i, y) { - tyears[i] = years[map[i]]; + const len = years.length, tyears = makeArray(len, ""); + const mapArr = [0, 6, 1, 7, 2, 8, 3, 9, 4, 10, 5, 11]; + each(years, (i, y) => { + tyears[i] = years[mapArr[i]]; }); - var items = []; + const items = []; items.push(tyears.slice(0, 2)); items.push(tyears.slice(2, 4)); items.push(tyears.slice(4, 6)); @@ -103,71 +108,70 @@ BI.YearCalendar = BI.inherit(BI.Widget, { items.push(tyears.slice(8, 10)); items.push(tyears.slice(10, 12)); - return BI.map(items, function (i, item) { - return BI.map(item, function (j, td) { - return BI.extend(td, { - type: "bi.text_item", - cls: "bi-list-item-select bi-border-radius", - textAlign: "center", - whiteSpace: "normal", - once: false, - forceSelected: true, - height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - width: 45, - value: td.text, - disabled: td.disabled - }); - }); - }); - }, + return map(items, (i, item) => map(item, (j, td) => extend(td, { + type: "bi.text_item", + cls: "bi-list-item-select bi-border-radius", + textAlign: "center", + whiteSpace: "normal", + once: false, + forceSelected: true, + height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, + width: 45, + value: td.text, + disabled: td.disabled, + }))); + } - _populate: function () { + _populate () { this.years.populate(this._getItems()); - }, + } - setMinDate: function (minDate) { - var o = this.options; - if (BI.isNotEmptyString(o.min)) { + setMinDate (minDate) { + const o = this.options; + if (isNotEmptyString(o.min)) { o.min = minDate; this._populate(); } - }, + } - setMaxDate: function (maxDate) { - var o = this.options; - if (BI.isNotEmptyString(this.options.max)) { + setMaxDate (maxDate) { + const o = this.options; + if (isNotEmptyString(this.options.max)) { o.max = maxDate; this._populate(); } - }, + } - setValue: function (val) { + setValue (val) { this.years.setValue([val]); - }, + } - getValue: function () { + getValue () { return this.years.getValue()[0]; } -}); +} + // 类方法 -BI.extend(BI.YearCalendar, { +extend(YearCalendar, { INTERVAL: 12, // 获取显示的第一年 - getStartYear: function (year) { - var cur = BI.getDate().getFullYear(); - return year - ((year - cur + 3) % BI.YearCalendar.INTERVAL + 12) % BI.YearCalendar.INTERVAL; + getStartYear (year) { + const cur = getDate().getFullYear(); + + return year - ((year - cur + 3) % YearCalendar.INTERVAL + 12) % YearCalendar.INTERVAL; }, - getEndYear: function (year) { - return BI.YearCalendar.getStartYear(year) + BI.YearCalendar.INTERVAL - 1; + getEndYear (year) { + return YearCalendar.getStartYear(year) + YearCalendar.INTERVAL - 1; }, - getPageByYear: function (year) { - var cur = BI.getDate().getFullYear(); - year = BI.YearCalendar.getStartYear(year); - return (year - cur + 3) / BI.YearCalendar.INTERVAL; - } + getPageByYear (year) { + const cur = getDate().getFullYear(); + year = YearCalendar.getStartYear(year); + + return (year - cur + 3) / YearCalendar.INTERVAL; + }, }); -BI.shortcut("bi.year_calendar", BI.YearCalendar); + diff --git a/src/case/calendar/index.js b/src/case/calendar/index.js new file mode 100644 index 000000000..17c7f5fac --- /dev/null +++ b/src/case/calendar/index.js @@ -0,0 +1,3 @@ +export { CalendarDateItem } from "./calendar.date.item"; +export { Calendar } from "./calendar"; +export { YearCalendar } from "./calendar.year"; diff --git a/src/case/index.js b/src/case/index.js index 5e8b11baf..40247c96e 100644 --- a/src/case/index.js +++ b/src/case/index.js @@ -1,7 +1,13 @@ import * as button from "./button"; +import * as calendarItem from "./calendar"; +import * as pager from "./pager"; Object.assign(BI, { ...button, + ...calendarItem, + ...pager, }); export * from "./button"; +export * from "./calendar"; +export * from "./pager"; diff --git a/src/case/pager/index.js b/src/case/pager/index.js new file mode 100644 index 000000000..ec62a806d --- /dev/null +++ b/src/case/pager/index.js @@ -0,0 +1,3 @@ +export { AllCountPager } from "./pager.all.count"; +export { DetailPager } from "./pager.detail"; +export { DirectionPager } from "./pager.direction"; diff --git a/src/case/pager/pager.all.count.js b/src/case/pager/pager.all.count.js index 8e03d57ca..2b8f0f9b5 100644 --- a/src/case/pager/pager.all.count.js +++ b/src/case/pager/pager.all.count.js @@ -2,10 +2,15 @@ * 有总页数和总行数的分页控件 * Created by Young's on 2016/10/13. */ -BI.AllCountPager = BI.inherit(BI.Widget, { - - _defaultConfig: function () { - return BI.extend(BI.AllCountPager.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, Widget, extend, isPositiveInteger, createWidget, parseInt, HorizontalAlign, isNotEmptyObject } from "../../core"; +// import { TextEditor } from "../../widget/editor/editor.text"; +import { Pager } from "../../base/pager/pager"; +@shortcut() +export class AllCountPager extends Widget { + static xtype = "bi.all_count_pager"; + static EVENT_CHANGE = "EVENT_CHANGE"; + _defaultConfig () { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-all-count-pager", pagerDirection: "vertical", // 翻页按钮方向,可选值:vertical/horizontal height: 24, @@ -16,36 +21,36 @@ BI.AllCountPager = BI.inherit(BI.Widget, { showRowCount: true, showRowInfo: true, }); - }, - _init: function () { - BI.AllCountPager.superclass._init.apply(this, arguments); - var self = this, o = this.options, pagerIconCls = this._getPagerIconCls(); - this.editor = BI.createWidget({ + } + _init () { + super._init(...arguments); + const { pages, curr, hasPrev, hasNext, firstPage, lastPage, height, showRowCount } = this.options, pagerIconCls = this._getPagerIconCls(); + this.editor = createWidget({ type: "bi.small_text_editor", cls: "pager-editor bi-border-radius", - validationChecker: function (v) { - return (o.pages === 0 && v === "0") || BI.isPositiveInteger(v); + validationChecker (v) { + return (pages === 0 && v === "0") || isPositiveInteger(v); }, hgap: 4, vgap: 0, - value: o.curr, + value: curr, errorText: BI.i18nText("BI-Please_Input_Positive_Integer"), width: 40, height: 24, - invisible: o.pages <= 1 + invisible: pages <= 1, }); - this.pager = BI.createWidget({ + this.pager = createWidget({ type: "bi.pager", width: 58, layouts: [{ type: "bi.horizontal", - lgap: 5 + lgap: 5, }], dynamicShow: false, - pages: o.pages, - curr: o.curr, + pages, + curr, groups: 0, first: false, @@ -57,7 +62,7 @@ BI.AllCountPager = BI.inherit(BI.Widget, { warningTitle: BI.i18nText("BI-Current_Is_First_Page"), height: 22, width: 22, - cls: "bi-border bi-border-radius all-pager-prev bi-list-item-select2 " + pagerIconCls.preCls + cls: `bi-border bi-border-radius all-pager-prev bi-list-item-select2 ${pagerIconCls.preCls}`, }, next: { type: "bi.icon_button", @@ -66,42 +71,43 @@ BI.AllCountPager = BI.inherit(BI.Widget, { warningTitle: BI.i18nText("BI-Current_Is_Last_Page"), height: 22, width: 22, - cls: "bi-border bi-border-radius all-pager-next bi-list-item-select2 " + pagerIconCls.nextCls + cls: `bi-border bi-border-radius all-pager-next bi-list-item-select2 ${pagerIconCls.nextCls}`, }, - hasPrev: o.hasPrev, - hasNext: o.hasNext, - firstPage: o.firstPage, - lastPage: o.lastPage, - invisible: o.pages <= 1 + hasPrev, + hasNext, + firstPage, + lastPage, + invisible: pages <= 1, }); - this.editor.on(BI.TextEditor.EVENT_CONFIRM, function () { - self.pager.setValue(BI.parseInt(self.editor.getValue())); - self.fireEvent(BI.AllCountPager.EVENT_CHANGE); + // TODO:需等到TextEditor 完成es6化后才可替换BI.TextEditor + this.editor.on(BI.TextEditor.EVENT_CONFIRM, () => { + this.pager.setValue(parseInt(this.editor.getValue())); + this.fireEvent(AllCountPager.EVENT_CHANGE); }); - this.pager.on(BI.Pager.EVENT_CHANGE, function () { - self.fireEvent(BI.AllCountPager.EVENT_CHANGE); + this.pager.on(Pager.EVENT_CHANGE, () => { + this.fireEvent(AllCountPager.EVENT_CHANGE); }); - this.pager.on(BI.Pager.EVENT_AFTER_POPULATE, function () { - self.editor.setValue(self.pager.getCurrentPage()); + this.pager.on(Pager.EVENT_AFTER_POPULATE, () => { + this.editor.setValue(this.pager.getCurrentPage()); }); - this.allPages = BI.createWidget({ + this.allPages = createWidget({ type: "bi.label", - title: o.pages, - height: o.height, - text: "/" + o.pages, + title: pages, + height, + text: `/${pages}`, lgap: 5, - invisible: o.pages <= 1 + invisible: pages <= 1, }); - BI.createWidget(o.showRowCount ? { + createWidget(showRowCount ? { type: "bi.vertical_adapt", element: this, scrollx: false, columnSize: ["fill", ""], - horizontalAlign: BI.HorizontalAlign.Right, + horizontalAlign: HorizontalAlign.Right, items: [ this._getRowCountObject(), this.editor, this.allPages, this.pager @@ -109,126 +115,124 @@ BI.AllCountPager = BI.inherit(BI.Widget, { } : { type: "bi.vertical_adapt", element: this, - items: [this.editor, this.allPages, this.pager] + items: [this.editor, this.allPages, this.pager], }); - }, - - _getPagerIconCls: function () { - var o = this.options; - switch (o.pagerDirection) { - case "horizontal": - return { - preCls: "row-pre-page-h-font ", - nextCls: "row-next-page-h-font " - }; - case "vertical": - default: - return { - preCls: "column-pre-page-h-font ", - nextCls: "column-next-page-h-font " - }; + } + + _getPagerIconCls () { + const { pagerDirection } = this.options; + switch (pagerDirection) { + case "horizontal": + return { + preCls: "row-pre-page-h-font ", + nextCls: "row-next-page-h-font ", + }; + case "vertical": + default: + return { + preCls: "column-pre-page-h-font ", + nextCls: "column-next-page-h-font ", + }; } - }, + } - _getRowCountObject: function() { - var self = this, o = this.options; + _getRowCountObject() { + const { height, count, rowInfoObject } = this.options; return { type: "bi.left", - height: o.height, + height, scrollable: false, - ref: function (_ref) { - self.rowCountObject = _ref; + ref: _ref => { + this.rowCountObject = _ref; }, items: [{ type: "bi.label", - height: o.height, + height, text: BI.i18nText("BI-Basic_Total"), - ref: function (_ref) { - self.prevText = _ref; - } + ref: _ref => { + this.prevText = _ref; + }, }, { el: { type: "bi.label", - ref: function (_ref) { - self.rowCount = _ref; + ref: _ref => { + this.rowCount = _ref; }, cls: "row-count", - height: o.height, - text: o.count, - title: o.count + height, + text: count, + title: count, }, hgap: 5, }, { type: "bi.label", - height: o.height, + height, text: BI.i18nText("BI-Tiao_Data"), - textAlign: "left" - }, BI.isNotEmptyObject(o.rowInfoObject) ? o.rowInfoObject : null] + textAlign: "left", + }, isNotEmptyObject(rowInfoObject) ? rowInfoObject : null], }; - }, + } - setAllPages: function (v) { - this.allPages.setText("/" + v); + setAllPages (v) { + this.allPages.setText(`/${v}`); this.allPages.setTitle(v); this.options.pages = v; this.pager.setAllPages(v); this.editor.setEnable(v >= 1); this.setPagerVisible(v > 1); - }, + } - setShowRowInfo: function (b) { + setShowRowInfo (b) { this.options.showRowInfo = b; this.rowCountObject.setVisible(b); - }, + } - setValue: function (v) { + setValue (v) { this.pager.setValue(v); - }, + } - setVPage: function (v) { + setVPage (v) { this.pager.setValue(v); - }, + } - setCount: function (count) { + setCount (count) { if (this.options.showRowCount) { this.rowCount.setText(count); this.rowCount.setTitle(count); } - }, + } - setCountPrevText: function (text) { + setCountPrevText (text) { if (this.options.showRowCount) { this.prevText.setText(text); } - }, + } - getCurrentPage: function () { + getCurrentPage () { return this.pager.getCurrentPage(); - }, + } - hasPrev: function () { + hasPrev () { return this.pager.hasPrev(); - }, + } - hasNext: function () { + hasNext () { return this.pager.hasNext(); - }, + } - isShowPager: function () { + isShowPager () { return this.options.showRowInfo || this.options.pages > 1; - }, + } - setPagerVisible: function (b) { + setPagerVisible (b) { this.editor.setVisible(b); this.allPages.setVisible(b); this.pager.setVisible(b); - }, + } - populate: function () { + populate () { this.pager.populate(); this.setPagerVisible(this.options.pages > 1); } -}); -BI.AllCountPager.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.all_count_pager", BI.AllCountPager); \ No newline at end of file +} diff --git a/src/case/pager/pager.detail.js b/src/case/pager/pager.detail.js index 36e8392f6..2516aac1c 100644 --- a/src/case/pager/pager.detail.js +++ b/src/case/pager/pager.detail.js @@ -5,9 +5,15 @@ * @class BI.DetailPager * @extends BI.Widget */ -BI.DetailPager = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.DetailPager.superclass._defaultConfig.apply(this, arguments), { + +import { shortcut, Widget, extend, emptyFn, result, debounce, isKey, createWidget, createItems, Controller, Events, MIN, MAX } from "../../core"; +@shortcut() +export class DetailPager extends Widget { + static xtype = "bi.detail_pager"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_AFTER_POPULATE = "EVENT_AFTER_POPULATE"; + _defaultConfig () { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-detail-pager", behaviors: {}, layouts: [{ @@ -19,11 +25,11 @@ BI.DetailPager = BI.inherit(BI.Widget, { dynamicShowFirstLast: false, // 是否动态显示首页、尾页 dynamicShowPrevNext: false, // 是否动态显示上一页、下一页 pages: false, // 总页数 - curr: function () { + curr () { return 1; }, // 初始化当前页 groups: 0, // 连续显示分页数 - jump: BI.emptyFn, // 分页的回调函数 + jump: emptyFn, // 分页的回调函数 first: false, // 是否显示首页 last: false, // 是否显示尾页 @@ -31,35 +37,34 @@ BI.DetailPager = BI.inherit(BI.Widget, { next: "下一页", firstPage: 1, - lastPage: function () { // 在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 + lastPage () { // 在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 return 1; }, - hasPrev: BI.emptyFn, // pages不可用时有效 - hasNext: BI.emptyFn // pages不可用时有效 + hasPrev: emptyFn, // pages不可用时有效 + hasNext: emptyFn, // pages不可用时有效 }); - }, - _init: function () { - BI.DetailPager.superclass._init.apply(this, arguments); - var self = this; - this.currPage = BI.result(this.options, "curr"); + } + _init () { + super._init(...arguments); + this.currPage = result(this.options, "curr"); // 翻页太灵敏 this._lock = false; - this._debouce = BI.debounce(function () { - self._lock = false; + this._debouce = debounce(() => { + this._lock = false; }, 300); this._populate(); - }, - - _populate: function () { - var self = this, o = this.options, view = [], dict = {}; + } + _populate () { + const o = this.options, view = [], dict = {}; + const { dynamicShow, dynamicShowPrevNext, hasPrev, dynamicShowFirstLast, hasNext, behaviors, layouts, jump } = this.options; this.empty(); - var pages = BI.result(o, "pages"); - var curr = BI.result(this, "currPage"); - var groups = BI.result(o, "groups"); - var first = BI.result(o, "first"); - var last = BI.result(o, "last"); - var prev = BI.result(o, "prev"); - var next = BI.result(o, "next"); + const pages = result(o, "pages"); + const curr = result(this, "currPage"); + let groups = result(o, "groups"); + let first = result(o, "first"); + let last = result(o, "last"); + const prev = result(o, "prev"); + const next = result(o, "next"); if (pages === false) { groups = 0; @@ -73,32 +78,32 @@ BI.DetailPager = BI.inherit(BI.Widget, { dict.index = Math.ceil((curr + ((groups > 1 && groups !== pages) ? 1 : 0)) / (groups === 0 ? 1 : groups)); // 当前页非首页,则输出上一页 - if (((!o.dynamicShow && !o.dynamicShowPrevNext) || curr > 1) && prev !== false) { - if (BI.isKey(prev)) { + if (((!dynamicShow && !dynamicShowPrevNext) || curr > 1) && prev !== false) { + if (isKey(prev)) { view.push({ text: prev, value: "prev", - disabled: pages === false ? o.hasPrev(curr) === false : !(curr > 1 && prev !== false) + disabled: pages === false ? hasPrev(curr) === false : !(curr > 1 && prev !== false), }); } else { - view.push(BI.extend({ - disabled: pages === false ? o.hasPrev(curr) === false : !(curr > 1 && prev !== false) + view.push(extend({ + disabled: pages === false ? hasPrev(curr) === false : !(curr > 1 && prev !== false), }, prev)); } } // 当前组非首组,则输出首页 - if (((!o.dynamicShow && !o.dynamicShowFirstLast) || (dict.index > 1 && groups !== 0)) && first) { + if (((!dynamicShow && !dynamicShowFirstLast) || (dict.index > 1 && groups !== 0)) && first) { view.push({ text: first, value: "first", - disabled: !(dict.index > 1 && groups !== 0) + disabled: !(dict.index > 1 && groups !== 0), }); if (dict.index > 1 && groups !== 0) { view.push({ type: "bi.label", cls: "page-ellipsis", - text: "\u2026" + text: "\u2026", }); } } @@ -107,13 +112,14 @@ BI.DetailPager = BI.inherit(BI.Widget, { dict.poor = Math.floor((groups - 1) / 2); dict.start = dict.index > 1 ? curr - dict.poor : 1; dict.end = dict.index > 1 ? (function () { - var max = curr + (groups - dict.poor - 1); + const max = curr + (groups - dict.poor - 1); + return max > pages ? pages : max; }()) : groups; if (dict.end - dict.start < groups - 1) { // 最后一组状态 dict.start = dict.end - groups + 1; } - var s = dict.start, e = dict.end; + let s = dict.start, e = dict.end; if (first && last && (dict.index > 1 && groups !== 0) && (pages > groups && dict.end < pages && groups !== 0)) { s++; e--; @@ -123,164 +129,166 @@ BI.DetailPager = BI.inherit(BI.Widget, { view.push({ text: s, value: s, - selected: true + selected: true, }); } else { view.push({ text: s, - value: s + value: s, }); } } // 总页数大于连续分页数,且当前组最大页小于总页,输出尾页 - if (((!o.dynamicShow && !o.dynamicShowFirstLast) || (pages > groups && dict.end < pages && groups !== 0)) && last) { + if (((!dynamicShow && !dynamicShowFirstLast) || (pages > groups && dict.end < pages && groups !== 0)) && last) { if (pages > groups && dict.end < pages && groups !== 0) { view.push({ type: "bi.label", cls: "page-ellipsis", - text: "\u2026" + text: "\u2026", }); } view.push({ text: last, value: "last", - disabled: !(pages > groups && dict.end < pages && groups !== 0) + disabled: !(pages > groups && dict.end < pages && groups !== 0), }); } // 当前页不为尾页时,输出下一页 dict.flow = !prev && groups === 0; - if (((!o.dynamicShow && !o.dynamicShowPrevNext) && next) || (curr !== pages && next || dict.flow)) { + if (((!dynamicShow && !dynamicShowPrevNext) && next) || (curr !== pages && next || dict.flow)) { view.push((function () { - if (BI.isKey(next)) { + if (isKey(next)) { if (pages === false) { - return {text: next, value: "next", disabled: o.hasNext(curr) === false}; + return { text: next, value: "next", disabled: hasNext(curr) === false }; } + return (dict.flow && curr === pages) ? - {text: next, value: "next", disabled: true} + { text: next, value: "next", disabled: true } : - {text: next, value: "next", disabled: !(curr !== pages && next || dict.flow)}; + { text: next, value: "next", disabled: !(curr !== pages && next || dict.flow) }; } - return BI.extend({ - disabled: pages === false ? o.hasNext(curr) === false : !(curr !== pages && next || dict.flow) + + return extend({ + disabled: pages === false ? hasNext(curr) === false : !(curr !== pages && next || dict.flow), }, next); - }())); } - this.button_group = BI.createWidget({ + this.button_group = createWidget({ type: "bi.button_group", element: this, - items: BI.createItems(view, { + items: createItems(view, { cls: "page-item bi-border bi-list-item-active", - height: 23 + height: 23, }), - behaviors: o.behaviors, - layouts: o.layouts + behaviors, + layouts, }); - this.button_group.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - if (self._lock === true) { + this.button_group.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { + if (this._lock === true) { return; } - self._lock = true; - self._debouce(); - if (type === BI.Events.CLICK) { - var v = self.button_group.getValue()[0]; + this._lock = true; + this._debouce(); + if (type === Events.CLICK) { + const v = this.button_group.getValue()[0]; switch (v) { - case "first": - self.currPage = 1; - break; - case "last": - self.currPage = pages; - break; - case "prev": - self.currPage--; - break; - case "next": - self.currPage++; - break; - default: - self.currPage = v; - break; + case "first": + this.currPage = 1; + break; + case "last": + this.currPage = pages; + break; + case "prev": + this.currPage--; + break; + case "next": + this.currPage++; + break; + default: + this.currPage = v; + break; } - o.jump.apply(self, [{ - pages: pages, - curr: self.currPage + jump.apply(this, [{ + pages, + curr: this.currPage, }]); - self._populate(); - self.fireEvent(BI.DetailPager.EVENT_CHANGE, obj); + this._populate(); + this.fireEvent(DetailPager.EVENT_CHANGE, obj); } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); }); - this.fireEvent(BI.DetailPager.EVENT_AFTER_POPULATE); - }, + this.fireEvent(DetailPager.EVENT_AFTER_POPULATE); + } - getCurrentPage: function () { + getCurrentPage () { return this.currPage; - }, + } - setAllPages: function (pages) { + setAllPages (pages) { this.options.pages = pages; this._populate(); - }, + } - hasPrev: function (v) { + hasPrev (v) { v || (v = 1); - var o = this.options; - var pages = this.options.pages; - return pages === false ? o.hasPrev(v) : v > 1; - }, + const { hasPrev } = this.options; + const pages = this.options.pages; + + return pages === false ? hasPrev(v) : v > 1; + } - hasNext: function (v) { + hasNext (v) { v || (v = 1); - var o = this.options; - var pages = this.options.pages; - return pages === false ? o.hasNext(v) : v < pages; - }, + const { hasNext } = this.options; + const pages = this.options.pages; + + return pages === false ? hasNext(v) : v < pages; + } - setValue: function (v) { - var o = this.options; + setValue (v) { + const o = this.options; + const { pages } = this.options; v = v || 0; v = v < 1 ? 1 : v; - if (o.pages === false) { - var lastPage = BI.result(o, "lastPage"), firstPage = 1; - this.currPage = v > lastPage ? lastPage : ((firstPage = BI.result(o, "firstPage")), (v < firstPage ? firstPage : v)); + if (pages === false) { + const lastPage = result(o, "lastPage"); + let firstPage = 1; + this.currPage = v > lastPage ? lastPage : ((firstPage = result(o, "firstPage")), (v < firstPage ? firstPage : v)); } else { - v = v > o.pages ? o.pages : v; + v = v > pages ? pages : v; this.currPage = v; } this._populate(); - }, + } - getValue: function () { - var val = this.button_group.getValue()[0]; + getValue () { + const val = this.button_group.getValue()[0]; switch (val) { - case "prev": - return -1; - case "next": - return 1; - case "first": - return BI.MIN; - case "last": - return BI.MAX; - default : - return val; + case "prev": + return -1; + case "next": + return 1; + case "first": + return MIN; + case "last": + return MAX; + default : + return val; } - }, + } - attr: function (key, value) { - BI.DetailPager.superclass.attr.apply(this, arguments); + attr (key, value) { + super.attr(...arguments); if (key === "curr") { - this.currPage = BI.result(this.options, "curr"); + this.currPage = result(this.options, "curr"); } - }, + } - populate: function () { + populate () { this._populate(); } -}); -BI.DetailPager.EVENT_CHANGE = "EVENT_CHANGE"; -BI.DetailPager.EVENT_AFTER_POPULATE = "EVENT_AFTER_POPULATE"; -BI.shortcut("bi.detail_pager", BI.DetailPager); +} diff --git a/src/case/pager/pager.direction.js b/src/case/pager/pager.direction.js index dcc0ab96b..ab375792c 100644 --- a/src/case/pager/pager.direction.js +++ b/src/case/pager/pager.direction.js @@ -5,80 +5,83 @@ * @class BI.DirectionPager * @extends BI.Widget */ -BI.DirectionPager = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.DirectionPager.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, Widget, extend, emptyFn, createWidget } from "../../core"; +import { Pager } from "../../base/pager/pager"; +@shortcut() +export class DirectionPager extends Widget { + static EVENT_CHANGE = "EVENT_CHANGE"; + static xtype = "bi.direction_pager"; + + _defaultConfig () { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-direction-pager", height: 24, horizontal: { pages: false, // 总页数 curr: 1, // 初始化当前页, pages为数字时可用 - hasPrev: BI.emptyFn, - hasNext: BI.emptyFn, + hasPrev: emptyFn, + hasNext: emptyFn, firstPage: 1, - lastPage: BI.emptyFn + lastPage: emptyFn, }, vertical: { pages: false, // 总页数 curr: 1, // 初始化当前页, pages为数字时可用 - hasPrev: BI.emptyFn, - hasNext: BI.emptyFn, + hasPrev: emptyFn, + hasNext: emptyFn, firstPage: 1, - lastPage: BI.emptyFn - } + lastPage: emptyFn, + }, }); - }, - _init: function () { - BI.DirectionPager.superclass._init.apply(this, arguments); - var self = this, o = this.options; - var v = o.vertical, h = o.horizontal; + } + _init () { + super._init(...arguments); this._createVPager(); this._createHPager(); - this.layout = BI.createWidget({ + this.layout = createWidget({ type: "bi.absolute", scrollable: false, element: this, items: [{ el: this.vpager, top: 0, - right: 86 + right: 86, }, { el: this.vlabel, top: 0, - right: 110 + right: 110, }, { el: this.hpager, top: 0, - right: 0 + right: 0, }, { el: this.hlabel, top: 0, - right: 24 - }] + right: 24, + }], }); - }, + } - _createVPager: function () { - var self = this, o = this.options; - var v = o.vertical; - this.vlabel = BI.createWidget({ + _createVPager () { + const v = this.options.vertical; + this.vlabel = createWidget({ type: "bi.label", width: 24, height: 24, value: v.curr, title: v.curr, - invisible: true + invisible: true, }); - this.vpager = BI.createWidget({ + this.vpager = createWidget({ type: "bi.pager", width: 72, layouts: [{ type: "bi.horizontal", scrollx: false, - rgap: 24 + rgap: 24, }], invisible: true, @@ -96,7 +99,7 @@ BI.DirectionPager = BI.inherit(BI.Widget, { warningTitle: BI.i18nText("BI-Current_Is_First_Page"), height: 22, width: 22, - cls: "bi-border bi-border-radius direction-pager-prev column-pre-page-h-font bi-list-item-select2" + cls: "bi-border bi-border-radius direction-pager-prev column-pre-page-h-font bi-list-item-select2", }, next: { type: "bi.icon_button", @@ -105,42 +108,40 @@ BI.DirectionPager = BI.inherit(BI.Widget, { warningTitle: BI.i18nText("BI-Current_Is_Last_Page"), height: 22, width: 22, - cls: "bi-border bi-border-radius direction-pager-next column-next-page-h-font bi-list-item-select2" + cls: "bi-border bi-border-radius direction-pager-next column-next-page-h-font bi-list-item-select2", }, hasPrev: v.hasPrev, hasNext: v.hasNext, firstPage: v.firstPage, - lastPage: v.lastPage + lastPage: v.lastPage, }); - this.vpager.on(BI.Pager.EVENT_CHANGE, function () { - self.fireEvent(BI.DirectionPager.EVENT_CHANGE); + this.vpager.on(Pager.EVENT_CHANGE, () => { + this.fireEvent(DirectionPager.EVENT_CHANGE); }); - this.vpager.on(BI.Pager.EVENT_AFTER_POPULATE, function () { - self.vlabel.setValue(this.getCurrentPage()); - self.vlabel.setTitle(this.getCurrentPage()); + this.vpager.on(Pager.EVENT_AFTER_POPULATE, () => { + this.vlabel.setValue(this.vpager.getCurrentPage()); + this.vlabel.setTitle(this.vpager.getCurrentPage()); }); - }, - - _createHPager: function () { - var self = this, o = this.options; - var h = o.horizontal; - this.hlabel = BI.createWidget({ + } + _createHPager () { + const h = this.options.horizontal; + this.hlabel = createWidget({ type: "bi.label", width: 24, height: 24, value: h.curr, title: h.curr, - invisible: true + invisible: true, }); - this.hpager = BI.createWidget({ + this.hpager = createWidget({ type: "bi.pager", width: 72, layouts: [{ type: "bi.horizontal", scrollx: false, - rgap: 24 + rgap: 24, }], invisible: true, @@ -158,7 +159,7 @@ BI.DirectionPager = BI.inherit(BI.Widget, { warningTitle: BI.i18nText("BI-Current_Is_First_Page"), height: 22, width: 22, - cls: "bi-border bi-border-radius direction-pager-prev row-pre-page-h-font bi-list-item-select2" + cls: "bi-border bi-border-radius direction-pager-prev row-pre-page-h-font bi-list-item-select2", }, next: { type: "bi.icon_button", @@ -167,74 +168,74 @@ BI.DirectionPager = BI.inherit(BI.Widget, { warningTitle: BI.i18nText("BI-Current_Is_Last_Page"), height: 22, width: 22, - cls: "bi-border bi-border-radius direction-pager-next row-next-page-h-font bi-list-item-select2" + cls: "bi-border bi-border-radius direction-pager-next row-next-page-h-font bi-list-item-select2", }, hasPrev: h.hasPrev, hasNext: h.hasNext, firstPage: h.firstPage, - lastPage: h.lastPage + lastPage: h.lastPage, }); - this.hpager.on(BI.Pager.EVENT_CHANGE, function () { - self.fireEvent(BI.DirectionPager.EVENT_CHANGE); + this.hpager.on(Pager.EVENT_CHANGE, () => { + this.fireEvent(DirectionPager.EVENT_CHANGE); }); - this.hpager.on(BI.Pager.EVENT_AFTER_POPULATE, function () { - self.hlabel.setValue(this.getCurrentPage()); - self.hlabel.setTitle(this.getCurrentPage()); + this.hpager.on(Pager.EVENT_AFTER_POPULATE, () => { + this.hlabel.setValue(this.hpager.getCurrentPage()); + this.hlabel.setTitle(this.hpager.getCurrentPage()); }); - }, + } - getVPage: function () { + getVPage () { return this.vpager.getCurrentPage(); - }, + } - getHPage: function () { + getHPage () { return this.hpager.getCurrentPage(); - }, + } - setVPage: function (v) { + setVPage (v) { this.vpager.setValue(v); this.vlabel.setValue(v); this.vlabel.setTitle(v); - }, + } - setHPage: function (v) { + setHPage (v) { this.hpager.setValue(v); this.hlabel.setValue(v); this.hlabel.setTitle(v); - }, + } - hasVNext: function () { + hasVNext () { return this.vpager.hasNext(); - }, + } - hasHNext: function () { + hasHNext () { return this.hpager.hasNext(); - }, + } - hasVPrev: function () { + hasVPrev () { return this.vpager.hasPrev(); - }, + } - hasHPrev: function () { + hasHPrev () { return this.hpager.hasPrev(); - }, + } - setHPagerVisible: function (b) { + setHPagerVisible (b) { this.hpager.setVisible(b); this.hlabel.setVisible(b); - }, + } - setVPagerVisible: function (b) { + setVPagerVisible (b) { this.vpager.setVisible(b); this.vlabel.setVisible(b); - }, + } - populate: function () { + populate () { this.vpager.populate(); this.hpager.populate(); - var vShow = false, hShow = false; + let vShow = false, hShow = false; if (!this.hasHNext() && !this.hasHPrev()) { this.setHPagerVisible(false); } else { @@ -248,8 +249,8 @@ BI.DirectionPager = BI.inherit(BI.Widget, { vShow = true; } this.setVisible(hShow || vShow); - var num = [86, 110, 0, 24]; - var items = this.layout.attr("items"); + const num = [86, 110, 0, 24]; + const items = this.layout.attr("items"); if (vShow === true && hShow === true) { items[0].right = num[0]; @@ -265,12 +266,10 @@ BI.DirectionPager = BI.inherit(BI.Widget, { } this.layout.attr("items", items); this.layout.resize(); - }, + } - clear: function () { + clear () { this.vpager.attr("curr", 1); this.hpager.attr("curr", 1); } -}); -BI.DirectionPager.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.direction_pager", BI.DirectionPager); \ No newline at end of file +} From 95ccea46754dd75d1696a5c0af686833fb4f146d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Tue, 10 Jan 2023 15:09:07 +0800 Subject: [PATCH 054/300] =?UTF-8?q?KERNEL-14045=20refactor:=20=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E5=BC=95=E7=94=A8=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/case/calendar/calendar.date.item.js | 2 +- src/case/pager/pager.all.count.js | 2 +- src/case/pager/pager.direction.js | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/case/calendar/calendar.date.item.js b/src/case/calendar/calendar.date.item.js index eaac1234e..217fad14e 100644 --- a/src/case/calendar/calendar.date.item.js +++ b/src/case/calendar/calendar.date.item.js @@ -3,7 +3,7 @@ */ import { shortcut } from "../../core"; -import { BasicButton } from "../../base/single/button/button.basic"; +import { BasicButton } from "../../base"; @shortcut() export class CalendarDateItem extends BasicButton { props() { diff --git a/src/case/pager/pager.all.count.js b/src/case/pager/pager.all.count.js index 2b8f0f9b5..9475772c5 100644 --- a/src/case/pager/pager.all.count.js +++ b/src/case/pager/pager.all.count.js @@ -4,7 +4,7 @@ */ import { shortcut, Widget, extend, isPositiveInteger, createWidget, parseInt, HorizontalAlign, isNotEmptyObject } from "../../core"; // import { TextEditor } from "../../widget/editor/editor.text"; -import { Pager } from "../../base/pager/pager"; +import { Pager } from "../../base"; @shortcut() export class AllCountPager extends Widget { static xtype = "bi.all_count_pager"; diff --git a/src/case/pager/pager.direction.js b/src/case/pager/pager.direction.js index ab375792c..731b7655b 100644 --- a/src/case/pager/pager.direction.js +++ b/src/case/pager/pager.direction.js @@ -7,7 +7,7 @@ */ import { shortcut, Widget, extend, emptyFn, createWidget } from "../../core"; -import { Pager } from "../../base/pager/pager"; +import { Pager } from "../../base"; @shortcut() export class DirectionPager extends Widget { static EVENT_CHANGE = "EVENT_CHANGE"; From 40b12b865e5bd9c1f0ccbaeb86d2e6df942088be Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Tue, 10 Jan 2023 15:20:42 +0800 Subject: [PATCH 055/300] =?UTF-8?q?=E6=97=A0JIRA=E4=BB=BB=E5=8A=A1=20chore?= =?UTF-8?q?:=20=E7=BB=99src=E9=85=8D=E7=BD=AE=E4=B8=AA=E5=88=AB=E5=90=8D?= =?UTF-8?q?=EF=BC=8C=E4=BE=BF=E4=BA=8E=E8=B7=AF=E5=BE=84=E5=BC=95=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tsconfig.json | 3 +++ webpack/webpack.common.js | 3 +++ 2 files changed, 6 insertions(+) diff --git a/tsconfig.json b/tsconfig.json index a964cc231..02dacc43b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -22,6 +22,9 @@ "noFallthroughCasesInSwitch": true, "emitDeclarationOnly": true, "allowJs": true, + "paths": { + "@/*": ["./src/*"] + } }, "include": [ "typescript/*.ts", diff --git a/webpack/webpack.common.js b/webpack/webpack.common.js index e19801a99..bded912e7 100644 --- a/webpack/webpack.common.js +++ b/webpack/webpack.common.js @@ -33,6 +33,9 @@ module.exports = { resolve: { mainFields: ['module', 'main'], extensions: ['.js', '.ts'], + alias: { + "@": path.resolve(__dirname, '../src'), + }, }, module: { rules: [ From 9f6d614bdd8b82b03477b9eb639386c0eb20b4ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Tue, 10 Jan 2023 15:55:27 +0800 Subject: [PATCH 056/300] =?UTF-8?q?KERNEL-14045=20refactor:=20=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=E5=88=AB=E5=90=8D=E4=BF=AE=E6=94=B9=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/case/calendar/calendar.date.item.js | 4 ++-- src/case/calendar/calendar.js | 2 +- src/case/calendar/calendar.year.js | 2 +- src/case/pager/pager.all.count.js | 2 +- src/case/pager/pager.detail.js | 2 +- src/case/pager/pager.direction.js | 4 ++-- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/case/calendar/calendar.date.item.js b/src/case/calendar/calendar.date.item.js index 217fad14e..3322de754 100644 --- a/src/case/calendar/calendar.date.item.js +++ b/src/case/calendar/calendar.date.item.js @@ -2,8 +2,8 @@ * 专门为calendar的视觉加的button,作为私有button,不能配置任何属性,也不要用这个玩意 */ -import { shortcut } from "../../core"; -import { BasicButton } from "../../base"; +import { shortcut } from "@/core"; +import { BasicButton } from "@/base"; @shortcut() export class CalendarDateItem extends BasicButton { props() { diff --git a/src/case/calendar/calendar.js b/src/case/calendar/calendar.js index fdbd6b984..da9a41442 100644 --- a/src/case/calendar/calendar.js +++ b/src/case/calendar/calendar.js @@ -3,7 +3,7 @@ * @class BI.Calendar * @extends BI.Widget */ -import { shortcut, Widget, getDate, each, range, extend, isLeapYear, Date, StartOfWeek, checkDateVoid, map, createWidget, createItems, LogicFactory, Controller, getShortDayName, getOffsetDate, isNotEmptyString, parseInt } from "../../core"; +import { shortcut, Widget, getDate, each, range, extend, isLeapYear, Date, StartOfWeek, checkDateVoid, map, createWidget, createItems, LogicFactory, Controller, getShortDayName, getOffsetDate, isNotEmptyString, parseInt } from "@/core"; @shortcut() export class Calendar extends Widget { static xtype = "bi.calendar"; diff --git a/src/case/calendar/calendar.year.js b/src/case/calendar/calendar.year.js index b225c3e8a..4c782da5b 100644 --- a/src/case/calendar/calendar.year.js +++ b/src/case/calendar/calendar.year.js @@ -3,7 +3,7 @@ * @class BI.YearCalendar * @extends BI.Widget */ -import { shortcut, Widget, extend, parseDateTime, range, checkDateVoid, print, getDate, each, createWidget, createItems, LogicFactory, Controller, makeArray, map, isNotEmptyString } from "../../core"; +import { shortcut, Widget, extend, parseDateTime, range, checkDateVoid, print, getDate, each, createWidget, createItems, LogicFactory, Controller, makeArray, map, isNotEmptyString } from "@/core"; @shortcut() export class YearCalendar extends Widget { static xtype = "bi.year_calendar"; diff --git a/src/case/pager/pager.all.count.js b/src/case/pager/pager.all.count.js index 9475772c5..4e5a30e18 100644 --- a/src/case/pager/pager.all.count.js +++ b/src/case/pager/pager.all.count.js @@ -2,7 +2,7 @@ * 有总页数和总行数的分页控件 * Created by Young's on 2016/10/13. */ -import { shortcut, Widget, extend, isPositiveInteger, createWidget, parseInt, HorizontalAlign, isNotEmptyObject } from "../../core"; +import { shortcut, Widget, extend, isPositiveInteger, createWidget, parseInt, HorizontalAlign, isNotEmptyObject } from "@/core"; // import { TextEditor } from "../../widget/editor/editor.text"; import { Pager } from "../../base"; @shortcut() diff --git a/src/case/pager/pager.detail.js b/src/case/pager/pager.detail.js index 2516aac1c..37e56edc5 100644 --- a/src/case/pager/pager.detail.js +++ b/src/case/pager/pager.detail.js @@ -6,7 +6,7 @@ * @extends BI.Widget */ -import { shortcut, Widget, extend, emptyFn, result, debounce, isKey, createWidget, createItems, Controller, Events, MIN, MAX } from "../../core"; +import { shortcut, Widget, extend, emptyFn, result, debounce, isKey, createWidget, createItems, Controller, Events, MIN, MAX } from "@/core"; @shortcut() export class DetailPager extends Widget { static xtype = "bi.detail_pager"; diff --git a/src/case/pager/pager.direction.js b/src/case/pager/pager.direction.js index 731b7655b..512b2cc20 100644 --- a/src/case/pager/pager.direction.js +++ b/src/case/pager/pager.direction.js @@ -6,8 +6,8 @@ * @extends BI.Widget */ -import { shortcut, Widget, extend, emptyFn, createWidget } from "../../core"; -import { Pager } from "../../base"; +import { shortcut, Widget, extend, emptyFn, createWidget } from "@/core"; +import { Pager } from "@/base"; @shortcut() export class DirectionPager extends Widget { static EVENT_CHANGE = "EVENT_CHANGE"; From 87bf4511820a8ca32c7dbe80aa4e987d6fcd973d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Tue, 10 Jan 2023 16:06:27 +0800 Subject: [PATCH 057/300] =?UTF-8?q?KERNEL-14045=20refactor:=20=E8=A1=A5?= =?UTF-8?q?=E5=85=85=E5=88=AB=E5=90=8D=E4=BF=AE=E6=94=B9=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/case/pager/pager.all.count.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/case/pager/pager.all.count.js b/src/case/pager/pager.all.count.js index 4e5a30e18..2dfdc0c3c 100644 --- a/src/case/pager/pager.all.count.js +++ b/src/case/pager/pager.all.count.js @@ -3,8 +3,8 @@ * Created by Young's on 2016/10/13. */ import { shortcut, Widget, extend, isPositiveInteger, createWidget, parseInt, HorizontalAlign, isNotEmptyObject } from "@/core"; -// import { TextEditor } from "../../widget/editor/editor.text"; -import { Pager } from "../../base"; +// import { TextEditor } from "@/widget/editor/editor.text"; +import { Pager } from "@/base"; @shortcut() export class AllCountPager extends Widget { static xtype = "bi.all_count_pager"; From 9f397fcee1936fb310b6d391dc72b77a18345c03 Mon Sep 17 00:00:00 2001 From: Treecat Date: Tue, 10 Jan 2023 17:12:47 +0800 Subject: [PATCH 058/300] =?UTF-8?q?=E6=97=A0jira=20feat:=20es6=E5=8C=96?= =?UTF-8?q?=E8=84=9A=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.js | 106 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 es6.js diff --git a/es6.js b/es6.js new file mode 100644 index 000000000..665270440 --- /dev/null +++ b/es6.js @@ -0,0 +1,106 @@ +const fs = require("fs"); + +const srcName = process.argv[2]; + +const sourceCode = fs.readFileSync(srcName).toString(); + +const clzName = /BI\.(.*?)\s\=\sBI\.inherit\(/.exec(sourceCode)[1]; + +const superName = /inherit\(BI\.(.*?),/.exec(sourceCode)[1]; + +// const xtype = /BI.shortcut\(\"(.*?)\"/.exec(sourceCode)[1]; + +const collection = { + static: {} +}; + +const BI = { + inherit(_, options) { + collection.methods = Object.keys(options).map((key) => options[key]); + return collection.static; + }, + shortcut(xtype) { + collection.xtype = xtype; + } +}; + +eval(sourceCode); + +let M = ""; +let E = ""; +let I = ""; + +const coreImport = { + shortcut: true +}; + +if (superName === "Widget") { + coreImport.Widget = true; +} + +// 静态方法 +Object.keys(collection.static).forEach((key) => { + E += `\tstatic ${key} = "${collection.static[key]}"\n`; +}); + +// 对函数进行替换 +collection.methods.forEach((el) => { + let f = el.toString().replace(/^function/, el.name) + "\n"; + + + // 换 BI.Button.superclass + f = f.replace(`BI.${clzName}.superclass`, "super"); + // 换 super._defaultConfig + f = f.replace( + `super\._defaultConfig\.apply\(this\,\sarguments\)`, + "super._defaultConfig(arguments)" + ); + // 换 super.xxx.apply + f = f.replace(/super\.(.*?)\.apply\(this\,\sarguments\)/, (a) => { + const f = /super\.(.*?)\.apply\(this\,\sarguments\)/.exec(a); + return `super.${f[1]}(...arguments)`; + }); + + const target = [ + "isNull", + "toPix", + "isKey", + "isObject", + "map", + "extend", + "isFunction", + "isEmptyArray", + "isArray" + ]; + + target.forEach((t) => { + const arr = f.split(`BI.${t}`); + // nodejs 低版本没有 replaceAll + if (arr.length > 1) { + coreImport[t] = true; + f = arr.join(t); + } + + }); + + M += f; +}); + +Object.keys(coreImport).forEach((el) => { + I += `${el},`; +}); + +const outputCode = ` +import {${I}} from "@/core" + +@shortcut() +export class ${clzName} extends ${superName} { +\tstatic xtype = "${collection.xtype}" + +${E} + +${M} +} +`; + +fs.writeFileSync(srcName + ".js", outputCode); From bda879d580613b74ed998f34d07e89332bc257ef Mon Sep 17 00:00:00 2001 From: Treecat Date: Tue, 10 Jan 2023 20:41:28 +0800 Subject: [PATCH 059/300] =?UTF-8?q?=E6=97=A0jira=20fix:es6=E8=84=9A?= =?UTF-8?q?=E6=9C=AC=E4=BF=AE=E5=A4=8D=E4=B8=80=E4=BA=9B=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.js | 52 ++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 36 insertions(+), 16 deletions(-) diff --git a/es6.js b/es6.js index 665270440..d2be104d0 100644 --- a/es6.js +++ b/es6.js @@ -11,17 +11,26 @@ const superName = /inherit\(BI\.(.*?),/.exec(sourceCode)[1]; // const xtype = /BI.shortcut\(\"(.*?)\"/.exec(sourceCode)[1]; const collection = { - static: {} + "static": {}, + attr: {}, }; const BI = { inherit(_, options) { - collection.methods = Object.keys(options).map((key) => options[key]); + collection.methods = Object.keys(options) + .filter(key => typeof options[key] === "function") + .map(key => options[key]); + Object.keys(options) + .filter(key => typeof options[key] !== "function") + .forEach(key => { + collection.attr[key] = options[key]; + }); + return collection.static; }, shortcut(xtype) { collection.xtype = xtype; - } + }, }; eval(sourceCode); @@ -29,24 +38,28 @@ eval(sourceCode); let M = ""; let E = ""; let I = ""; +let A = ""; const coreImport = { - shortcut: true + shortcut: true, }; if (superName === "Widget") { coreImport.Widget = true; } +Object.keys(collection.attr).forEach(key => { + A = `${key} = ${JSON.stringify(collection.attr[key])};`; +}); + // 静态方法 -Object.keys(collection.static).forEach((key) => { +Object.keys(collection.static).forEach(key => { E += `\tstatic ${key} = "${collection.static[key]}"\n`; }); // 对函数进行替换 -collection.methods.forEach((el) => { - let f = el.toString().replace(/^function/, el.name) + "\n"; - +collection.methods.forEach(el => { + let f = `${el.toString().replace(/^function/, el.name)}\n`; // 换 BI.Button.superclass f = f.replace(`BI.${clzName}.superclass`, "super"); @@ -56,8 +69,9 @@ collection.methods.forEach((el) => { "super._defaultConfig(arguments)" ); // 换 super.xxx.apply - f = f.replace(/super\.(.*?)\.apply\(this\,\sarguments\)/, (a) => { + f = f.replace(/super\.(.*?)\.apply\(this\,\sarguments\)/, a => { const f = /super\.(.*?)\.apply\(this\,\sarguments\)/.exec(a); + return `super.${f[1]}(...arguments)`; }); @@ -70,23 +84,26 @@ collection.methods.forEach((el) => { "extend", "isFunction", "isEmptyArray", - "isArray" + "isArray", + "Controller", + clzName, + "createWidget", + "Events", ]; - target.forEach((t) => { + target.forEach(t => { const arr = f.split(`BI.${t}`); // nodejs 低版本没有 replaceAll if (arr.length > 1) { - coreImport[t] = true; + if (t !== clzName) coreImport[t] = true; f = arr.join(t); } - }); - M += f; + M += `${f}\n`; }); -Object.keys(coreImport).forEach((el) => { +Object.keys(coreImport).forEach(el => { I += `${el},`; }); @@ -97,10 +114,13 @@ import {${I}} from "@/core" export class ${clzName} extends ${superName} { \tstatic xtype = "${collection.xtype}" +${A} + ${E} ${M} } `; -fs.writeFileSync(srcName + ".js", outputCode); +// fs.writeFileSync(`${srcName}.js.raw`, sourceCode); +fs.writeFileSync(srcName, outputCode); From 2aefcaac8b8a6d9ad2787dd2e4215d0184f514ae Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Tue, 10 Jan 2023 20:47:52 +0800 Subject: [PATCH 060/300] =?UTF-8?q?KERNEL-14035=20refactor:=20=E5=89=A9?= =?UTF-8?q?=E4=BD=99=E7=9A=84layout?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/0.base.js | 4 +- src/core/wrapper/layout/fill/auto.vtape.js | 100 +++++----- .../wrapper/layout/fill/fill.horizontal.js | 9 +- src/core/wrapper/layout/fill/fill.vertical.js | 9 +- .../layout/fill/float.fill.horizontal.js | 147 ++++++++------- src/core/wrapper/layout/fill/index.js | 4 + src/core/wrapper/layout/flex/flex.center.js | 49 +++-- .../layout/flex/flex.horizontal.center.js | 55 +++--- .../wrapper/layout/flex/flex.horizontal.js | 72 ++++--- .../flex/flex.leftrightvertical.center.js | 96 +++++----- .../layout/flex/flex.vertical.center.js | 55 +++--- src/core/wrapper/layout/flex/flex.vertical.js | 68 ++++--- src/core/wrapper/layout/flex/index.js | 7 + .../flex/wrapper/flex.wrapper.center.js | 49 +++-- .../wrapper/flex.wrapper.horizontal.center.js | 55 +++--- .../flex/wrapper/flex.wrapper.horizontal.js | 83 ++++---- .../wrapper/flex.wrapper.vertical.center.js | 55 +++--- .../flex/wrapper/flex.wrapper.vertical.js | 83 ++++---- src/core/wrapper/layout/flex/wrapper/index.js | 5 + .../layout/float/float.absolute.center.js | 46 +++-- .../layout/float/float.absolute.horizontal.js | 66 ++++--- .../float/float.absolute.leftrightvertical.js | 178 ++++++++++-------- .../layout/float/float.absolute.vertical.js | 66 ++++--- .../wrapper/layout/float/float.horizontal.js | 68 ++++--- src/core/wrapper/layout/float/index.js | 5 + src/core/wrapper/layout/index.js | 6 + src/core/wrapper/layout/middle/index.js | 4 + .../wrapper/layout/middle/middle.center.js | 76 ++++---- .../layout/middle/middle.float.center.js | 83 ++++---- .../layout/middle/middle.horizontal.js | 77 ++++---- .../wrapper/layout/middle/middle.vertical.js | 68 ++++--- src/core/wrapper/layout/responsive/index.js | 3 + .../responsive/responsive.flex.horizontal.js | 68 +++---- .../responsive.flex.wrapper.horizontal.js | 72 +++---- .../layout/responsive/responsive.inline..js | 50 ----- .../layout/responsive/responsive.inline.js | 58 ++++++ src/core/wrapper/layout/sticky/index.js | 2 + .../layout/sticky/sticky.horizontal.js | 42 +++-- .../wrapper/layout/sticky/sticky.vertical.js | 42 +++-- 39 files changed, 1190 insertions(+), 895 deletions(-) create mode 100644 src/core/wrapper/layout/fill/index.js create mode 100644 src/core/wrapper/layout/flex/index.js create mode 100644 src/core/wrapper/layout/flex/wrapper/index.js create mode 100644 src/core/wrapper/layout/float/index.js create mode 100644 src/core/wrapper/layout/middle/index.js create mode 100644 src/core/wrapper/layout/responsive/index.js delete mode 100644 src/core/wrapper/layout/responsive/responsive.inline..js create mode 100644 src/core/wrapper/layout/responsive/responsive.inline.js create mode 100644 src/core/wrapper/layout/sticky/index.js diff --git a/src/base/0.base.js b/src/base/0.base.js index e4daef1cf..a2cffed9b 100644 --- a/src/base/0.base.js +++ b/src/base/0.base.js @@ -7,7 +7,7 @@ import { PopoverController, ResizeController, TooltipsController, - StyleLoaderManager, + StyleLoaderManager } from "../core"; const Resizers = new ResizeController(); @@ -20,7 +20,7 @@ const Drawers = new DrawerController(); const Broadcasts = new BroadcastController(); const StyleLoaders = new StyleLoaderManager(); -export { +export { Resizers, Layers, Maskers, diff --git a/src/core/wrapper/layout/fill/auto.vtape.js b/src/core/wrapper/layout/fill/auto.vtape.js index efc784f5d..aa6c2eb9b 100644 --- a/src/core/wrapper/layout/fill/auto.vtape.js +++ b/src/core/wrapper/layout/fill/auto.vtape.js @@ -1,9 +1,17 @@ -BI.AutoVerticalTapeLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.AutoVerticalTapeLayout.superclass.props.apply(this, arguments), { +import { shortcut } from "@/core/decorator"; +import { extend, any, isEmptyObject, isNull, backAny } from "@/core/2.base"; +import { HorizontalAlign, VerticalAlign } from "@/core/constant"; +import { Layout } from "../../layout"; + +@shortcut() +export class AutoVerticalTapeLayout extends Layout { + static xtype = "bi.vtape_auto"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-auto-htape", - horizontalAlign: BI.HorizontalAlign.Stretch, - verticalAlign: BI.VerticalAlign.Stretch, + horizontalAlign: HorizontalAlign.Stretch, + verticalAlign: VerticalAlign.Stretch, hgap: 0, vgap: 0, lgap: 0, @@ -11,16 +19,17 @@ BI.AutoVerticalTapeLayout = BI.inherit(BI.Layout, { tgap: 0, bgap: 0, rowSize: [], - items: [] + items: [], }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; + return { type: "bi.vtape", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, items: o.items, horizontalAlign: o.horizontalAlign, @@ -35,65 +44,65 @@ BI.AutoVerticalTapeLayout = BI.inherit(BI.Layout, { innerHgap: o.innerHgap, innerVgap: o.innerVgap, }; - }, + } - _handleResize: function () { - var self = this, o = this.options; - var items = o.items; - var top = {}, bottom = {}; + _handleResize() { + const o = this.options; + const items = o.items; + const top = {}, bottom = {}; top[0] = o.innerVgap; bottom[items.length - 1] = o.innerVgap; - BI.any(items, function (i, item) { - if (BI.isEmptyObject(item)) { + any(items, (i, item) => { + if (isEmptyObject(item)) { return true; } - var w = self.layout.getWidgetByName(self._getChildName(i)); - var rowSize = o.rowSize.length > 0 ? o.rowSize[i] : item.height; + const w = this.layout.getWidgetByName(this._getChildName(i)); + let rowSize = o.rowSize.length > 0 ? o.rowSize[i] : item.height; if (o.rowSize.length > 0) { if (item.height >= 1 && o.rowSize[i] >= 1 && o.rowSize[i] !== item.height) { rowSize = item.height; } } - if (BI.isNull(top[i])) { - var preRowSize = o.rowSize.length > 0 ? o.rowSize[i - 1] : items[i - 1].height; + if (isNull(top[i])) { + let preRowSize = o.rowSize.length > 0 ? o.rowSize[i - 1] : items[i - 1].height; if (preRowSize === "") { - preRowSize = self.layout.getWidgetByName(self._getChildName(i - 1)).element.height(); + preRowSize = this.layout.getWidgetByName(this._getChildName(i - 1)).element.height(); } - top[i] = top[i - 1] + preRowSize + self._optimiseItemTgap(items[i - 1]) + self._optimiseItemBgap(items[i - 1]) + 2 * self._optimiseItemVgap(items[i - 1]) + o.vgap + o.tgap + o.bgap; + top[i] = top[i - 1] + preRowSize + this._optimiseItemTgap(items[i - 1]) + this._optimiseItemBgap(items[i - 1]) + 2 * this._optimiseItemVgap(items[i - 1]) + o.vgap + o.tgap + o.bgap; } w.element.css({ - top: self._optimiseGap(top[i] + self._optimiseItemTgap(item) + self._optimiseItemVgap(item) + o.vgap + o.tgap) + top: this._optimiseGap(top[i] + this._optimiseItemTgap(item) + this._optimiseItemVgap(item) + o.vgap + o.tgap), }); if (rowSize === "fill") { return true; } }); - BI.backAny(items, function (i, item) { - if (BI.isEmptyObject(item)) { + backAny(items, (i, item) => { + if (isEmptyObject(item)) { return true; } - var w = self.layout.getWidgetByName(self._getChildName(i)); - var rowSize = o.rowSize.length > 0 ? o.rowSize[i] : item.height; - if (BI.isNull(bottom[i])) { - var nextRowSize = o.rowSize.length > 0 ? o.rowSize[i + 1] : items[i + 1].height; + const w = this.layout.getWidgetByName(this._getChildName(i)); + const rowSize = o.rowSize.length > 0 ? o.rowSize[i] : item.height; + if (isNull(bottom[i])) { + let nextRowSize = o.rowSize.length > 0 ? o.rowSize[i + 1] : items[i + 1].height; if (nextRowSize === "") { - nextRowSize = self.layout.getWidgetByName(self._getChildName(i + 1)).element.height(); + nextRowSize = this.layout.getWidgetByName(this._getChildName(i + 1)).element.height(); } - bottom[i] = bottom[i + 1] + nextRowSize + self._optimiseItemTgap(items[i + 1]) + self._optimiseItemBgap(items[i + 1]) + 2 * self._optimiseItemVgap(items[i + 1]) + o.vgap + o.tgap + o.bgap; + bottom[i] = bottom[i + 1] + nextRowSize + this._optimiseItemTgap(items[i + 1]) + this._optimiseItemBgap(items[i + 1]) + 2 * this._optimiseItemVgap(items[i + 1]) + o.vgap + o.tgap + o.bgap; } w.element.css({ - bottom: self._optimiseGap(bottom[i] + self._optimiseItemBgap(item) + self._optimiseItemVgap(item) + o.vgap + o.bgap), + bottom: this._optimiseGap(bottom[i] + this._optimiseItemBgap(item) + this._optimiseItemVgap(item) + o.vgap + o.bgap), }); if (rowSize === "fill") { return true; } }); - }, + } - mounted: function () { + mounted() { if (window.ResizeObserver) { this.resizeObserver = new window.ResizeObserver(this._handleResize.bind(this)); this.resizeObserver.observe(this.element[0]); @@ -103,23 +112,22 @@ BI.AutoVerticalTapeLayout = BI.inherit(BI.Layout, { this.mutationObserver.observe(this.element[0], { attributes: true, childList: true, - subtree: true + subtree: true, }); } this._handleResize(); - }, + } - destroyed: function () { + destroyed() { this.resizeObserver && this.resizeObserver.unobserve(this.element[0]); this.mutationObserver && this.mutationObserver.disconnect(); - }, + } - resize: function () { + resize() { this.layout.resize(); - }, + } - populate: function (items) { - this.layout.populate.apply(this.layout, arguments); + populate(...args) { + this.layout.populate(...args); } -}); -BI.shortcut("bi.vtape_auto", BI.AutoVerticalTapeLayout); +} diff --git a/src/core/wrapper/layout/fill/fill.horizontal.js b/src/core/wrapper/layout/fill/fill.horizontal.js index 72ce8d393..88cc76e7d 100644 --- a/src/core/wrapper/layout/fill/fill.horizontal.js +++ b/src/core/wrapper/layout/fill/fill.horizontal.js @@ -1,6 +1,9 @@ +import { shortcut } from "@/core/decorator"; + /** * 横向填满布局 */ -BI.HorizontalFillLayout = function () { -}; -BI.shortcut("bi.horizontal_fill", BI.HorizontalFillLayout); +@shortcut() +export class HorizontalFillLayout { + static xtype = "bi.horizontal_fill"; +} diff --git a/src/core/wrapper/layout/fill/fill.vertical.js b/src/core/wrapper/layout/fill/fill.vertical.js index 9acd9c307..66fbafa7d 100644 --- a/src/core/wrapper/layout/fill/fill.vertical.js +++ b/src/core/wrapper/layout/fill/fill.vertical.js @@ -1,6 +1,9 @@ +import { shortcut } from "@/core/decorator"; + /** * 纵向填满布局 */ -BI.VerticalFillLayout = function () { -}; -BI.shortcut("bi.vertical_fill", BI.VerticalFillLayout); +@shortcut() +export class VerticalFillLayout { + static xtype = "bi.vertical_fill"; +} diff --git a/src/core/wrapper/layout/fill/float.fill.horizontal.js b/src/core/wrapper/layout/fill/float.fill.horizontal.js index 512ffb627..cd3475ad8 100644 --- a/src/core/wrapper/layout/fill/float.fill.horizontal.js +++ b/src/core/wrapper/layout/fill/float.fill.horizontal.js @@ -1,9 +1,18 @@ -BI.FloatHorizontalFillLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FloatHorizontalFillLayout.superclass.props.apply(this, arguments), { +import { shortcut } from "@/core/decorator"; +import { extend, any, isEmptyObject, isNull, backAny, isFunction, compact, each } from "@/core/2.base"; +import { _lazyCreateWidget } from "@/core/5.inject"; +import { HorizontalAlign, VerticalAlign } from "@/core/constant"; +import { Layout } from "../../layout"; + +@shortcut() +export class FloatHorizontalFillLayout extends Layout { + static xtype = "bi.horizontal_float_fill"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-h-float-fill clearfix", - horizontalAlign: BI.HorizontalAlign.Stretch, - verticalAlign: BI.VerticalAlign.Stretch, + horizontalAlign: HorizontalAlign.Stretch, + verticalAlign: VerticalAlign.Stretch, hgap: 0, vgap: 0, lgap: 0, @@ -11,134 +20,136 @@ BI.FloatHorizontalFillLayout = BI.inherit(BI.Layout, { tgap: 0, bgap: 0, columnSize: [], - items: [] + items: [], }); - }, - render: function () { - BI.FloatHorizontalFillLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + } + + render() { + super.render(...arguments); + const o = this.options; + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - addItem: function (item) { + addItem(item) { // do nothing throw new Error("不能添加子组件"); - }, + } - stroke: function (items) { - var self = this, o = this.options; - items = BI.compact(items); - var rank = 0; + stroke(items) { + const o = this.options; + items = compact(items); + let rank = 0; - function createWidget (i, item, desc) { - if (o.verticalAlign !== BI.VerticalAlign.Stretch) { - var w = BI._lazyCreateWidget({ + const createWidget = (i, item, desc) => { + let w; + if (o.verticalAlign !== VerticalAlign.Stretch) { + w = _lazyCreateWidget({ type: "bi.vertical_adapt", - horizontalAlign: BI.HorizontalAlign.Stretch, + horizontalAlign: HorizontalAlign.Stretch, verticalAlign: o.verticalAlign, columnSize: ["fill"], - items: [item] + items: [item], }); } else { - var w = BI._lazyCreateWidget(item); + w = _lazyCreateWidget(item); } - if (o.vgap + o.tgap + self._optimiseItemTgap(item) + self._optimiseItemVgap(item) !== 0) { + if (o.vgap + o.tgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item) !== 0) { w.element.css({ - "margin-top": self._optimiseGap(o.vgap + o.tgap + self._optimiseItemTgap(item) + self._optimiseItemVgap(item)) + "margin-top": this._optimiseGap(o.vgap + o.tgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item)), }); } if (desc) { - if (o.hgap + o.rgap + self._optimiseItemRgap(item) + self._optimiseItemHgap(item) !== 0) { + if (o.hgap + o.rgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item) !== 0) { w.element.css({ - "margin-right": self._optimiseGap((i === o.items.length - 1 ? o.hgap : 0) + o.rgap + self._optimiseItemRgap(item) + self._optimiseItemHgap(item)) + "margin-right": this._optimiseGap((i === o.items.length - 1 ? o.hgap : 0) + o.rgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item)), }); } - if (o.hgap + o.lgap + self._optimiseItemLgap(item) + self._optimiseItemHgap(item) !== 0) { + if (o.hgap + o.lgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item) !== 0) { w.element.css({ - "margin-left": self._optimiseGap(o.hgap + o.lgap + self._optimiseItemLgap(item) + self._optimiseItemHgap(item)) + "margin-left": this._optimiseGap(o.hgap + o.lgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item)), }); } } else { - if (o.hgap + o.lgap + self._optimiseItemLgap(item) + self._optimiseItemHgap(item) !== 0) { + if (o.hgap + o.lgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item) !== 0) { w.element.css({ - "margin-left": self._optimiseGap((i === 0 ? o.hgap : 0) + o.lgap + self._optimiseItemLgap(item) + self._optimiseItemHgap(item)) + "margin-left": this._optimiseGap((i === 0 ? o.hgap : 0) + o.lgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item)), }); } - if (o.hgap + o.rgap + self._optimiseItemRgap(item) + self._optimiseItemHgap(item) !== 0) { + if (o.hgap + o.rgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item) !== 0) { w.element.css({ - "margin-right": self._optimiseGap(o.hgap + o.rgap + self._optimiseItemRgap(item) + self._optimiseItemHgap(item)) + "margin-right": this._optimiseGap(o.hgap + o.rgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item)), }); } } - if (o.vgap + o.bgap + self._optimiseItemBgap(item) + self._optimiseItemVgap(item) !== 0) { + if (o.vgap + o.bgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item) !== 0) { w.element.css({ - "margin-bottom": self._optimiseGap(o.vgap + o.bgap + self._optimiseItemBgap(item) + self._optimiseItemVgap(item)) + "margin-bottom": this._optimiseGap(o.vgap + o.bgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item)), }); } - var top = o.vgap + o.tgap + self._optimiseItemTgap(item) + self._optimiseItemVgap(item), - bottom = o.vgap + o.bgap + self._optimiseItemBgap(item) + self._optimiseItemVgap(item); - if (o.verticalAlign === BI.VerticalAlign.Stretch && BI.isNull(item.height)) { + const top = o.vgap + o.tgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item), + bottom = o.vgap + o.bgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item); + if (o.verticalAlign === VerticalAlign.Stretch && isNull(item.height)) { w.element.css({ - height: "calc(100% - " + self._optimiseGap(top + bottom) + ")" + height: `calc(100% - ${this._optimiseGap(top + bottom)})`, }); } w.element.css({ - position: "relative" + position: "relative", }); + return w; - } + }; - BI.any(items, function (i, item) { - if (BI.isEmptyObject(item)) { + any(items, (i, item) => { + if (isEmptyObject(item)) { return true; } - var columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; + const columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; if (columnSize === "fill") { return true; } - var w = createWidget(i, item); - self.addWidget(self._getChildName(rank++), w); + const w = createWidget(i, item); + this.addWidget(this._getChildName(rank++), w); w.element.css({ - float: "left" + "float": "left", }); }); - BI.backAny(items, function (i, item) { - if (BI.isEmptyObject(item)) { + backAny(items, (i, item) => { + if (isEmptyObject(item)) { return true; } - var columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; + const columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; if (columnSize === "fill") { return true; } - var w = createWidget(i, item, true); - self.addWidget(self._getChildName(rank++), w); + const w = createWidget(i, item, true); + this.addWidget(this._getChildName(rank++), w); w.element.css({ - float: "right" + "float": "right", }); }); - BI.each(items, function (i, item) { - var columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; + each(items, (i, item) => { + const columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; if (columnSize === "fill") { - var w = createWidget(i, item); - self.addWidget(self._getChildName(rank++), w); + const w = createWidget(i, item); + this.addWidget(this._getChildName(rank++), w); } }); - }, + } - resize: function () { + resize() { // console.log("填充布局不需要resize"); - }, + } - update: function (opt) { + update(opt) { return this.forceUpdate(opt); - }, + } - populate: function (items) { - BI.FloatHorizontalFillLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.horizontal_float_fill", BI.FloatHorizontalFillLayout); +} diff --git a/src/core/wrapper/layout/fill/index.js b/src/core/wrapper/layout/fill/index.js new file mode 100644 index 000000000..aefc020d1 --- /dev/null +++ b/src/core/wrapper/layout/fill/index.js @@ -0,0 +1,4 @@ +export { AutoVerticalTapeLayout } from "./auto.vtape"; +export { HorizontalFillLayout } from "./fill.horizontal"; +export { VerticalFillLayout } from "./fill.vertical"; +export { FloatHorizontalFillLayout } from "./float.fill.horizontal"; diff --git a/src/core/wrapper/layout/flex/flex.center.js b/src/core/wrapper/layout/flex/flex.center.js index 8944b3add..caec5842e 100644 --- a/src/core/wrapper/layout/flex/flex.center.js +++ b/src/core/wrapper/layout/flex/flex.center.js @@ -1,30 +1,40 @@ +import { shortcut } from "@/core/decorator"; +import { extend } from "@/core/2.base"; +import { HorizontalAlign, VerticalAlign } from "@/core/constant"; +import { Layout } from "../../layout"; + /** *自适应水平和垂直方向都居中容器 * Created by GUY on 2016/12/2. * - * @class BI.FlexCenterLayout - * @extends BI.Layout + * @class FlexCenterLayout + * @extends Layout */ -BI.FlexCenterLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FlexCenterLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class FlexCenterLayout extends Layout { + static xtype = "bi.flex_center_adapt"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-f-c", - verticalAlign: BI.VerticalAlign.Middle, - horizontalAlign: BI.HorizontalAlign.Center, + verticalAlign: VerticalAlign.Middle, + horizontalAlign: HorizontalAlign.Center, hgap: 0, vgap: 0, lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, - render: function () { - var self = this, o = this.options; + } + + render() { + const o = this.options; + return { type: "bi.flex_horizontal", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, horizontalAlign: o.horizontalAlign, verticalAlign: o.verticalAlign, @@ -39,16 +49,15 @@ BI.FlexCenterLayout = BI.inherit(BI.Layout, { bgap: o.bgap, innerHgap: o.innerHgap, innerVgap: o.innerVgap, - items: o.items + items: o.items, }; - }, + } - resize: function () { + resize() { this.layout.resize(); - }, + } - populate: function (items) { + populate(items) { this.layout.populate(items); } -}); -BI.shortcut("bi.flex_center_adapt", BI.FlexCenterLayout); +} diff --git a/src/core/wrapper/layout/flex/flex.horizontal.center.js b/src/core/wrapper/layout/flex/flex.horizontal.center.js index 220f1f394..ffc0d6aac 100644 --- a/src/core/wrapper/layout/flex/flex.horizontal.center.js +++ b/src/core/wrapper/layout/flex/flex.horizontal.center.js @@ -1,15 +1,23 @@ +import { shortcut } from "@/core/decorator"; +import { extend } from "@/core/2.base"; +import { HorizontalAlign, VerticalAlign } from "@/core/constant"; +import { Layout } from "../../layout"; + /** * Created by GUY on 2016/12/2. * - * @class BI.FlexHorizontalCenter - * @extends BI.Layout + * @class FlexHorizontalCenter + * @extends Layout */ -BI.FlexHorizontalCenter = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FlexHorizontalCenter.superclass.props.apply(this, arguments), { +@shortcut() +export class FlexHorizontalCenter extends Layout { + static xtype = "bi.flex_horizontal_adapt"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-f-h-c", - horizontalAlign: BI.HorizontalAlign.Center, - verticalAlign: BI.VerticalAlign.Top, + horizontalAlign: HorizontalAlign.Center, + verticalAlign: VerticalAlign.Top, rowSize: [], scrolly: false, hgap: 0, @@ -17,15 +25,17 @@ BI.FlexHorizontalCenter = BI.inherit(BI.Layout, { lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, - render: function () { - var self = this, o = this.options; + } + + render() { + const o = this.options; + return { type: "bi.flex_vertical", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, horizontalAlign: o.horizontalAlign, verticalAlign: o.verticalAlign, @@ -40,17 +50,20 @@ BI.FlexHorizontalCenter = BI.inherit(BI.Layout, { bgap: o.bgap, innerHgap: o.innerHgap, innerVgap: o.innerVgap, - items: o.items + items: o.items, }; - }, + } - resize: function () { + resize() { this.layout.resize(); - }, + } - populate: function (items) { + populate(items) { this.layout.populate(items); } -}); -BI.shortcut("bi.flex_horizontal_adapt", BI.FlexHorizontalCenter); -BI.shortcut("bi.flex_horizontal_center_adapt", BI.FlexHorizontalCenter); +} + +@shortcut() +export class FlexHorizontalCenterAdapt extends FlexHorizontalCenter { + static xtype = "bi.flex_horizontal_center_adapt"; +} diff --git a/src/core/wrapper/layout/flex/flex.horizontal.js b/src/core/wrapper/layout/flex/flex.horizontal.js index 75326335b..7489d30a7 100644 --- a/src/core/wrapper/layout/flex/flex.horizontal.js +++ b/src/core/wrapper/layout/flex/flex.horizontal.js @@ -1,16 +1,24 @@ +import { shortcut } from "@/core/decorator"; +import { extend, isFunction, some } from "@/core/2.base"; +import { HorizontalAlign, VerticalAlign } from "@/core/constant"; +import { Layout } from "../../layout"; + /** *自适应水平和垂直方向都居中容器 * Created by GUY on 2016/12/2. * - * @class BI.FlexHorizontalLayout - * @extends BI.Layout + * @class FlexHorizontalLayout + * @extends Layout */ -BI.FlexHorizontalLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FlexHorizontalLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class FlexHorizontalLayout extends Layout { + static xtype = "bi.flex_horizontal"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-f-h", - verticalAlign: BI.VerticalAlign.Top, - horizontalAlign: BI.HorizontalAlign.Left, // 如果只有一个子元素且想让该子元素横向撑满,设置成Stretch + verticalAlign: VerticalAlign.Top, + horizontalAlign: HorizontalAlign.Left, // 如果只有一个子元素且想让该子元素横向撑满,设置成Stretch columnSize: [], scrollx: true, hgap: 0, @@ -18,52 +26,54 @@ BI.FlexHorizontalLayout = BI.inherit(BI.Layout, { lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, - render: function () { - BI.FlexHorizontalLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - this.element.addClass("v-" + o.verticalAlign).addClass("h-" + o.horizontalAlign); + } + + render() { + super.render(...arguments); + const o = this.options; + this.element.addClass(`v-${o.verticalAlign}`).addClass(`h-${o.horizontalAlign}`); if (o.scrollable === true || o.scrollx === true) { this.element.addClass("f-scroll-x"); } if (o.scrollable === true || o.scrolly === true) { this.element.addClass("f-scroll-y"); } - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - _hasFill: function () { - var o = this.options; + _hasFill() { + const o = this.options; if (o.columnSize.length > 0) { return o.columnSize.indexOf("fill") >= 0 || o.columnSize.indexOf("auto") >= 0; } - return BI.some(o.items, function (i, item) { + + return some(o.items, (i, item) => { if (item.width === "fill" || item.width === "auto") { return true; } }); - }, + } - _addElement: function (i, item) { - var o = this.options; - var w = BI.FlexHorizontalLayout.superclass._addElement.apply(this, arguments); - var columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; + _addElement(i, item) { + const o = this.options; + const w = super._addElement(...arguments); + let columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; if (o.columnSize.length > 0) { if (item.width >= 1 && o.columnSize[i] >= 1 && o.columnSize[i] !== item.width) { columnSize = null; } } w.element.css({ - position: "relative" + position: "relative", }); if (columnSize !== "auto") { if (columnSize === "fill" || columnSize === "") { - if (o.horizontalAlign !== BI.HorizontalAlign.Stretch) { + if (o.horizontalAlign !== HorizontalAlign.Stretch) { if (o.scrollable === true || o.scrollx === true) { w.element.addClass("f-s-n"); } @@ -93,12 +103,12 @@ BI.FlexHorizontalLayout = BI.inherit(BI.Layout, { w.element.addClass("l-c"); } this._handleGap(w, item, i); + return w; - }, + } - populate: function (items) { - BI.FlexHorizontalLayout.superclass.populate.apply(this, arguments); + populate(...args) { + super.populate(...args); this._mount(); } -}); -BI.shortcut("bi.flex_horizontal", BI.FlexHorizontalLayout); +} diff --git a/src/core/wrapper/layout/flex/flex.leftrightvertical.center.js b/src/core/wrapper/layout/flex/flex.leftrightvertical.center.js index b52b1e456..db2aeadc7 100644 --- a/src/core/wrapper/layout/flex/flex.leftrightvertical.center.js +++ b/src/core/wrapper/layout/flex/flex.leftrightvertical.center.js @@ -1,6 +1,13 @@ -BI.FlexLeftRightVerticalAdaptLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FlexLeftRightVerticalAdaptLayout.superclass.props.apply(this, arguments), { +import { shortcut } from "@/core/decorator"; +import { extend, isArray, each, map, stripEL } from "@/core/2.base"; +import { Layout } from "../../layout"; + +@shortcut() +export class FlexLeftRightVerticalAdaptLayout extends Layout { + static xtype = "bi.flex_left_right_vertical_adapt"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-f-lr-v-c", columnSize: [], items: {}, @@ -15,33 +22,35 @@ BI.FlexLeftRightVerticalAdaptLayout = BI.inherit(BI.Layout, { rhgap: 0, rtgap: 0, rbgap: 0, - rvgap: 0 + rvgap: 0, }); - }, - render: function () { - var o = this.options, self = this; - BI.FlexLeftRightVerticalAdaptLayout.superclass.render.apply(this, arguments); - var items = this._formatItems(o.items); + } + + render() { + const o = this.options; + super.render(...arguments); + const items = this._formatItems(o.items); + return { type: "bi.flex_vertical_adapt", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, columnSize: o.columnSize.slice(0, (o.items.left || []).length).concat((o.items.right || []).length > 0 ? [""] : []), - items: items, + items, scrollx: o.scrollx, scrolly: o.scrolly, scrollable: o.scrollable, innerHgap: o.innerHgap, - innerVgap: o.innerVgap + innerVgap: o.innerVgap, }; - }, + } - _formatItems: function (items) { - var self = this, o = this.options; - var left, right; - if (BI.isArray(items)) { - BI.each(items, function (i, item) { + _formatItems(items) { + const o = this.options; + let left, right; + if (isArray(items)) { + each(items, (i, item) => { if (item.left) { left = item.left; } @@ -50,32 +59,34 @@ BI.FlexLeftRightVerticalAdaptLayout = BI.inherit(BI.Layout, { } }); } - var leftItems = left || items.left || []; - var rightItems = right || items.right || []; - leftItems = BI.map(leftItems, function (i, item) { - var json = { - el: BI.stripEL(item) + let leftItems = left || items.left || []; + const rightItems = right || items.right || []; + leftItems = map(leftItems, (i, item) => { + const json = { + el: stripEL(item), }; - if (o.lvgap + o.ltgap + self._optimiseItemTgap(item) + self._optimiseItemVgap(item) !== 0) { - json.tgap = o.lvgap + o.ltgap + self._optimiseItemTgap(item) + self._optimiseItemVgap(item); + if (o.lvgap + o.ltgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item) !== 0) { + json.tgap = o.lvgap + o.ltgap + this._optimiseItemTgap(item) + this._optimiseItemVgap(item); } - if (o.lhgap + o.llgap + self._optimiseItemLgap(item) + self._optimiseItemHgap(item) !== 0) { - json.lgap = (i === 0 ? o.lhgap : 0) + o.llgap + self._optimiseItemLgap(item) + self._optimiseItemHgap(item); + if (o.lhgap + o.llgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item) !== 0) { + json.lgap = (i === 0 ? o.lhgap : 0) + o.llgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item); } - if (o.lhgap + o.lrgap + self._optimiseItemRgap(item) + self._optimiseItemHgap(item) !== 0) { - json.rgap = o.lhgap + o.lrgap + self._optimiseItemRgap(item) + self._optimiseItemHgap(item); + if (o.lhgap + o.lrgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item) !== 0) { + json.rgap = o.lhgap + o.lrgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item); } - if (o.lvgap + o.lbgap + self._optimiseItemBgap(item) + self._optimiseItemVgap(item) !== 0) { - json.bgap = o.lvgap + o.lbgap + self._optimiseItemBgap(item) + self._optimiseItemVgap(item); + if (o.lvgap + o.lbgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item) !== 0) { + json.bgap = o.lvgap + o.lbgap + this._optimiseItemBgap(item) + this._optimiseItemVgap(item); } + return json; }); + return leftItems.concat({ el: { type: "bi.flex_vertical_adapt", columnSize: o.columnSize.slice(leftItems.length), css: { - "margin-left": "auto" + "margin-left": "auto", }, hgap: o.rhgap, vgap: o.rvgap, @@ -83,22 +94,21 @@ BI.FlexLeftRightVerticalAdaptLayout = BI.inherit(BI.Layout, { rgap: o.rrgap, tgap: o.rtgap, bgap: o.rbgap, - items: rightItems - } + items: rightItems, + }, }); - }, + } - resize: function () { + resize() { this.layout.stroke(this._formatItems(this.options.items)); - }, + } - addItem: function () { + addItem() { // do nothing throw new Error("不能添加子组件"); - }, + } - populate: function (items) { + populate(items) { this.layout.populate(this._formatItems(items)); } -}); -BI.shortcut("bi.flex_left_right_vertical_adapt", BI.FlexLeftRightVerticalAdaptLayout); +} diff --git a/src/core/wrapper/layout/flex/flex.vertical.center.js b/src/core/wrapper/layout/flex/flex.vertical.center.js index cf2e55077..a4a830862 100644 --- a/src/core/wrapper/layout/flex/flex.vertical.center.js +++ b/src/core/wrapper/layout/flex/flex.vertical.center.js @@ -1,16 +1,24 @@ +import { shortcut } from "@/core/decorator"; +import { extend } from "@/core/2.base"; +import { HorizontalAlign, VerticalAlign } from "@/core/constant"; +import { Layout } from "../../layout"; + /** *自适应水平和垂直方向都居中容器 * Created by GUY on 2016/12/2. * - * @class BI.FlexVerticalCenter - * @extends BI.Layout + * @class FlexVerticalCenter + * @extends Layout */ -BI.FlexVerticalCenter = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FlexVerticalCenter.superclass.props.apply(this, arguments), { +@shortcut() +export class FlexVerticalCenter extends Layout { + static xtype = "bi.flex_vertical_adapt"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-f-v-c", - horizontalAlign: BI.HorizontalAlign.Left, - verticalAlign: BI.VerticalAlign.Middle, + horizontalAlign: HorizontalAlign.Left, + verticalAlign: VerticalAlign.Middle, columnSize: [], scrollx: false, hgap: 0, @@ -18,15 +26,17 @@ BI.FlexVerticalCenter = BI.inherit(BI.Layout, { lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, - render: function () { - var self = this, o = this.options; + } + + render() { + const o = this.options; + return { type: "bi.flex_horizontal", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, verticalAlign: o.verticalAlign, horizontalAlign: o.horizontalAlign, @@ -41,17 +51,20 @@ BI.FlexVerticalCenter = BI.inherit(BI.Layout, { hgap: o.hgap, innerHgap: o.innerHgap, innerVgap: o.innerVgap, - items: o.items + items: o.items, }; - }, + } - resize: function () { + resize() { this.layout.resize(); - }, + } - populate: function (items) { + populate(items) { this.layout.populate(items); } -}); -BI.shortcut("bi.flex_vertical_adapt", BI.FlexVerticalCenter); -BI.shortcut("bi.flex_vertical_center_adapt", BI.FlexVerticalCenter); +} + +@shortcut() +export class FlexVerticalCenterAdapt extends FlexVerticalCenter { + static xtype = "bi.flex_vertical_center_adapt" +} diff --git a/src/core/wrapper/layout/flex/flex.vertical.js b/src/core/wrapper/layout/flex/flex.vertical.js index 1c56586cc..7847d7009 100644 --- a/src/core/wrapper/layout/flex/flex.vertical.js +++ b/src/core/wrapper/layout/flex/flex.vertical.js @@ -1,15 +1,21 @@ +import { shortcut } from "@/core/decorator"; +import { extend, isFunction, some } from "@/core/2.base"; +import { HorizontalAlign, VerticalAlign } from "@/core/constant"; +import { Layout } from "../../layout"; + /** * Created by GUY on 2016/12/2. * - * @class BI.FlexVerticalLayout - * @extends BI.Layout + * @class FlexVerticalLayout + * @extends Layout */ -BI.FlexVerticalLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FlexVerticalLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class FlexVerticalLayout extends Layout { + props() { + return extend(super.props(...arguments), { baseCls: "bi-f-v", - horizontalAlign: BI.HorizontalAlign.Left, - verticalAlign: BI.VerticalAlign.Top, + horizontalAlign: HorizontalAlign.Left, + verticalAlign: VerticalAlign.Top, rowSize: [], scrolly: true, hgap: 0, @@ -17,52 +23,54 @@ BI.FlexVerticalLayout = BI.inherit(BI.Layout, { lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, - render: function () { - BI.FlexVerticalLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - this.element.addClass("h-" + o.horizontalAlign).addClass("v-" + o.verticalAlign); + } + + render() { + super.render(...arguments); + const self = this, o = this.options; + this.element.addClass(`h-${o.horizontalAlign}`).addClass(`v-${o.verticalAlign}`); if (o.scrollable === true || o.scrollx === true) { this.element.addClass("f-scroll-x"); } if (o.scrollable === true || o.scrolly === true) { this.element.addClass("f-scroll-y"); } - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { self.populate(newValue); }) : o.items; this.populate(items); - }, + } - _hasFill: function () { - var o = this.options; + _hasFill() { + const o = this.options; if (o.rowSize.length > 0) { return o.rowSize.indexOf("fill") >= 0 || o.rowSize.indexOf("auto") >= 0; } - return BI.some(o.items, function (i, item) { + + return some(o.items, (i, item) => { if (item.height === "fill" || item.height === "auto") { return true; } }); - }, + } - _addElement: function (i, item) { - var o = this.options; - var w = BI.FlexVerticalLayout.superclass._addElement.apply(this, arguments); - var rowSize = o.rowSize.length > 0 ? o.rowSize[i] : item.height; + _addElement(i, item) { + const o = this.options; + const w = super._addElement.apply(this, arguments); + let rowSize = o.rowSize.length > 0 ? o.rowSize[i] : item.height; if (o.rowSize.length > 0) { if (item.height >= 1 && o.rowSize[i] >= 1 && o.rowSize[i] !== item.height) { rowSize = null; } } w.element.css({ - position: "relative" + position: "relative", }); if (rowSize !== "auto") { if (rowSize === "fill" || rowSize === "") { - if (o.verticalAlign !== BI.VerticalAlign.Stretch) { + if (o.verticalAlign !== VerticalAlign.Stretch) { if (o.scrollable === true || o.scrolly === true) { w.element.addClass("f-s-n"); } @@ -92,12 +100,12 @@ BI.FlexVerticalLayout = BI.inherit(BI.Layout, { w.element.addClass("l-c"); } this._handleGap(w, item, null, i); + return w; - }, + } - populate: function (items) { - BI.FlexVerticalLayout.superclass.populate.apply(this, arguments); + populate(items) { + super.populate.apply(this, arguments); this._mount(); } -}); -BI.shortcut("bi.flex_vertical", BI.FlexVerticalLayout); +} diff --git a/src/core/wrapper/layout/flex/index.js b/src/core/wrapper/layout/flex/index.js new file mode 100644 index 000000000..1625f8ad0 --- /dev/null +++ b/src/core/wrapper/layout/flex/index.js @@ -0,0 +1,7 @@ +export { FlexCenterLayout } from "./flex.center"; +export { FlexHorizontalCenter, FlexHorizontalCenterAdapt } from "./flex.horizontal.center"; +export { FlexHorizontalLayout } from "./flex.horizontal"; +export { FlexLeftRightVerticalAdaptLayout } from "./flex.leftrightvertical.center"; +export { FlexVerticalCenter, FlexVerticalCenterAdapt } from "./flex.vertical.center"; +export { FlexVerticalLayout } from "./flex.vertical"; +export * from "./wrapper"; diff --git a/src/core/wrapper/layout/flex/wrapper/flex.wrapper.center.js b/src/core/wrapper/layout/flex/wrapper/flex.wrapper.center.js index ee44e9823..347ab62a9 100644 --- a/src/core/wrapper/layout/flex/wrapper/flex.wrapper.center.js +++ b/src/core/wrapper/layout/flex/wrapper/flex.wrapper.center.js @@ -1,16 +1,24 @@ +import { shortcut } from "@/core/decorator"; +import { extend } from "@/core/2.base"; +import { HorizontalAlign, VerticalAlign } from "@/core/constant"; +import { Layout } from "@/core/wrapper/layout"; + /** *自适应水平和垂直方向都居中容器 * Created by GUY on 2016/12/2. * - * @class BI.FlexWrapperCenterLayout - * @extends BI.Layout + * @class FlexWrapperCenterLayout + * @extends Layout */ -BI.FlexWrapperCenterLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FlexWrapperCenterLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class FlexWrapperCenterLayout extends Layout { + static xtype = "bi.flex_scrollable_center_adapt"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-f-s-c", - horizontalAlign: BI.HorizontalAlign.Center, - verticalAlign: BI.VerticalAlign.Middle, + horizontalAlign: HorizontalAlign.Center, + verticalAlign: VerticalAlign.Middle, columnSize: [], scrollx: false, scrollable: true, @@ -19,15 +27,17 @@ BI.FlexWrapperCenterLayout = BI.inherit(BI.Layout, { lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, - render: function () { - var self = this, o = this.options; + } + + render() { + const o = this.options; + return { type: "bi.flex_scrollable_horizontal", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, horizontalAlign: o.horizontalAlign, verticalAlign: o.verticalAlign, @@ -40,16 +50,15 @@ BI.FlexWrapperCenterLayout = BI.inherit(BI.Layout, { vgap: o.vgap, lgap: o.lgap, rgap: o.rgap, - items: o.items + items: o.items, }; - }, + } - resize: function () { + resize() { this.layout.resize(); - }, + } - populate: function (items) { + populate(items) { this.layout.populate(items); } -}); -BI.shortcut("bi.flex_scrollable_center_adapt", BI.FlexWrapperCenterLayout); +} diff --git a/src/core/wrapper/layout/flex/wrapper/flex.wrapper.horizontal.center.js b/src/core/wrapper/layout/flex/wrapper/flex.wrapper.horizontal.center.js index 1735c25ff..c15e28369 100644 --- a/src/core/wrapper/layout/flex/wrapper/flex.wrapper.horizontal.center.js +++ b/src/core/wrapper/layout/flex/wrapper/flex.wrapper.horizontal.center.js @@ -1,16 +1,24 @@ +import { shortcut } from "@/core/decorator"; +import { extend } from "@/core/2.base"; +import { HorizontalAlign, VerticalAlign } from "@/core/constant"; +import { Layout } from "@/core/wrapper/layout"; + /** *自适应水平和垂直方向都居中容器 * Created by GUY on 2016/12/2. * - * @class BI.FlexVerticalCenter - * @extends BI.Layout + * @class FlexVerticalCenter + * @extends Layout */ -BI.FlexWrapperHorizontalCenter = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FlexWrapperHorizontalCenter.superclass.props.apply(this, arguments), { +@shortcut() +export class FlexWrapperHorizontalCenter extends Layout { + static xtype = "bi.flex_scrollable_horizontal_adapt"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-f-s-v-c", - horizontalAlign: BI.HorizontalAlign.Center, - verticalAlign: BI.VerticalAlign.Top, + horizontalAlign: HorizontalAlign.Center, + verticalAlign: VerticalAlign.Top, rowSize: [], scrollable: true, scrolly: false, @@ -19,15 +27,17 @@ BI.FlexWrapperHorizontalCenter = BI.inherit(BI.Layout, { lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, - render: function () { - var self = this, o = this.options; + } + + render() { + const o = this.options; + return { type: "bi.flex_scrollable_vertical", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, horizontalAlign: o.horizontalAlign, verticalAlign: o.verticalAlign, @@ -40,17 +50,20 @@ BI.FlexWrapperHorizontalCenter = BI.inherit(BI.Layout, { vgap: o.vgap, tgap: o.tgap, bgap: o.bgap, - items: o.items + items: o.items, }; - }, + } - resize: function () { + resize() { this.layout.resize(); - }, + } - populate: function (items) { + populate(items) { this.layout.populate(items); } -}); -BI.shortcut("bi.flex_scrollable_horizontal_adapt", BI.FlexWrapperHorizontalCenter); -BI.shortcut("bi.flex_scrollable_horizontal_center_adapt", BI.FlexWrapperHorizontalCenter); +} + +@shortcut() +export class FlexWrapperHorizontalCenterAdapt extends FlexWrapperHorizontalCenter { + static xtype = "bi.flex_scrollable_horizontal_center_adapt"; +} diff --git a/src/core/wrapper/layout/flex/wrapper/flex.wrapper.horizontal.js b/src/core/wrapper/layout/flex/wrapper/flex.wrapper.horizontal.js index fa90b0543..4e3cee14a 100644 --- a/src/core/wrapper/layout/flex/wrapper/flex.wrapper.horizontal.js +++ b/src/core/wrapper/layout/flex/wrapper/flex.wrapper.horizontal.js @@ -1,16 +1,25 @@ +import { shortcut } from "@/core/decorator"; +import { extend, isFunction, some } from "@/core/2.base"; +import { Widget } from "@/core/4.widget"; +import { HorizontalAlign, VerticalAlign } from "@/core/constant"; +import { Layout } from "@/core/wrapper/layout"; + /** *自适应水平和垂直方向都居中容器 * Created by GUY on 2016/12/2. * - * @class BI.FlexHorizontalLayout - * @extends BI.Layout + * @class FlexHorizontalLayout + * @extends Layout */ -BI.FlexWrapperHorizontalLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FlexWrapperHorizontalLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class FlexWrapperHorizontalLayout extends Layout { + static xtype = "bi.flex_scrollable_horizontal"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-f-s-h", - verticalAlign: BI.VerticalAlign.Top, - horizontalAlign: BI.HorizontalAlign.Left, + verticalAlign: VerticalAlign.Top, + horizontalAlign: HorizontalAlign.Left, columnSize: [], scrollable: null, scrollx: true, @@ -19,47 +28,49 @@ BI.FlexWrapperHorizontalLayout = BI.inherit(BI.Layout, { lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, - render: function () { - BI.FlexWrapperHorizontalLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - this.element.addClass("v-" + o.verticalAlign).addClass("h-" + o.horizontalAlign); - this.$wrapper = BI.Widget._renderEngine.createElement("
").addClass("f-s-h-w v-" + o.verticalAlign).addClass("h-" + o.horizontalAlign); - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + } + + render() { + super.render(...arguments); + const o = this.options; + this.element.addClass(`v-${o.verticalAlign}`).addClass(`h-${o.horizontalAlign}`); + this.$wrapper = Widget._renderEngine.createElement("
").addClass(`f-s-h-w v-${o.verticalAlign}`).addClass(`h-${o.horizontalAlign}`); + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - _hasFill: function () { - var o = this.options; + _hasFill() { + const o = this.options; if (o.columnSize.length > 0) { return o.columnSize.indexOf("fill") >= 0 || o.columnSize.indexOf("auto") >= 0; } - return BI.some(o.items, function (i, item) { + + return some(o.items, (i, item) => { if (item.width === "fill" || item.width === "auto") { return true; } }); - }, + } - _addElement: function (i, item) { - var o = this.options; - var w = BI.FlexWrapperHorizontalLayout.superclass._addElement.apply(this, arguments); - var columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; + _addElement(i, item) { + const o = this.options; + const w = super._addElement(...arguments); + let columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; if (o.columnSize.length > 0) { if (item.width >= 1 && o.columnSize[i] >= 1 && o.columnSize[i] !== item.width) { columnSize = null; } } w.element.css({ - position: "relative" + position: "relative", }); if (columnSize !== "auto") { if (columnSize === "fill" || columnSize === "") { - if (o.horizontalAlign !== BI.HorizontalAlign.Stretch) { + if (o.horizontalAlign !== HorizontalAlign.Stretch) { if (o.scrollable === true || o.scrollx === true) { w.element.addClass("f-s-n"); } @@ -91,21 +102,21 @@ BI.FlexWrapperHorizontalLayout = BI.inherit(BI.Layout, { w.element.addClass("l-c"); } this._handleGap(w, item, i); + return w; - }, + } - appendFragment: function (frag) { + appendFragment(frag) { this.$wrapper.append(frag); this.element.append(this.$wrapper); - }, + } - _getWrapper: function () { + _getWrapper() { return this.$wrapper; - }, + } - populate: function (items) { - BI.FlexWrapperHorizontalLayout.superclass.populate.apply(this, arguments); + populate(items) { + super.populate(...arguments); this._mount(); } -}); -BI.shortcut("bi.flex_scrollable_horizontal", BI.FlexWrapperHorizontalLayout); +} diff --git a/src/core/wrapper/layout/flex/wrapper/flex.wrapper.vertical.center.js b/src/core/wrapper/layout/flex/wrapper/flex.wrapper.vertical.center.js index 5b9e7e11d..98c340452 100644 --- a/src/core/wrapper/layout/flex/wrapper/flex.wrapper.vertical.center.js +++ b/src/core/wrapper/layout/flex/wrapper/flex.wrapper.vertical.center.js @@ -1,16 +1,24 @@ +import { shortcut } from "@/core/decorator"; +import { extend } from "@/core/2.base"; +import { HorizontalAlign, VerticalAlign } from "@/core/constant"; +import { Layout } from "@/core/wrapper/layout"; + /** *自适应水平和垂直方向都居中容器 * Created by GUY on 2016/12/2. * - * @class BI.FlexVerticalCenter - * @extends BI.Layout + * @class FlexVerticalCenter + * @extends Layout */ -BI.FlexWrapperVerticalCenter = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FlexWrapperVerticalCenter.superclass.props.apply(this, arguments), { +@shortcut() +export class FlexWrapperVerticalCenter extends Layout { + static xtype = "bi.flex_scrollable_vertical_adapt"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-f-s-v-c", - horizontalAlign: BI.HorizontalAlign.Left, - verticalAlign: BI.VerticalAlign.Middle, + horizontalAlign: HorizontalAlign.Left, + verticalAlign: VerticalAlign.Middle, columnSize: [], scrollx: false, scrollable: true, @@ -19,15 +27,17 @@ BI.FlexWrapperVerticalCenter = BI.inherit(BI.Layout, { lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, - render: function () { - var self = this, o = this.options; + } + + render() { + const o = this.options; + return { type: "bi.flex_scrollable_horizontal", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, verticalAlign: o.verticalAlign, horizontalAlign: o.horizontalAlign, @@ -40,17 +50,20 @@ BI.FlexWrapperVerticalCenter = BI.inherit(BI.Layout, { vgap: o.vgap, lgap: o.lgap, rgap: o.rgap, - items: o.items + items: o.items, }; - }, + } - resize: function () { + resize() { this.layout.resize(); - }, + } - populate: function (items) { + populate(items) { this.layout.populate(items); } -}); -BI.shortcut("bi.flex_scrollable_vertical_adapt", BI.FlexWrapperVerticalCenter); -BI.shortcut("bi.flex_scrollable_vertical_center_adapt", BI.FlexWrapperVerticalCenter); +} + +@shortcut() +export class FlexWrapperVerticalCenterAdapt extends FlexWrapperVerticalCenter { + static xtype = "bi.flex_scrollable_vertical_center_adapt"; +} diff --git a/src/core/wrapper/layout/flex/wrapper/flex.wrapper.vertical.js b/src/core/wrapper/layout/flex/wrapper/flex.wrapper.vertical.js index 76beeb601..f557ba543 100644 --- a/src/core/wrapper/layout/flex/wrapper/flex.wrapper.vertical.js +++ b/src/core/wrapper/layout/flex/wrapper/flex.wrapper.vertical.js @@ -1,16 +1,25 @@ +import { shortcut } from "@/core/decorator"; +import { extend, isFunction, some } from "@/core/2.base"; +import { Widget } from "@/core/4.widget"; +import { HorizontalAlign, VerticalAlign } from "@/core/constant"; +import { Layout } from "@/core/wrapper/layout"; + /** *自适应水平和垂直方向都居中容器 * Created by GUY on 2016/12/2. * - * @class BI.FlexWrapperVerticalLayout - * @extends BI.Layout + * @class FlexWrapperVerticalLayout + * @extends Layout */ -BI.FlexWrapperVerticalLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FlexWrapperVerticalLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class FlexWrapperVerticalLayout extends Layout { + static xtype = "bi.flex_scrollable_vertical"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-f-s-v", - horizontalAlign: BI.HorizontalAlign.Left, - verticalAlign: BI.VerticalAlign.Top, + horizontalAlign: HorizontalAlign.Left, + verticalAlign: VerticalAlign.Top, rowSize: [], scrollable: null, scrolly: true, @@ -19,47 +28,49 @@ BI.FlexWrapperVerticalLayout = BI.inherit(BI.Layout, { lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, - render: function () { - BI.FlexWrapperVerticalLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - this.element.addClass("v-" + o.verticalAlign).addClass("h-" + o.horizontalAlign); - this.$wrapper = BI.Widget._renderEngine.createElement("
").addClass("f-s-v-w h-" + o.horizontalAlign).addClass("v-" + o.verticalAlign); - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + } + + render() { + super.render(...arguments); + const o = this.options; + this.element.addClass(`v-${o.verticalAlign}`).addClass(`h-${o.horizontalAlign}`); + this.$wrapper = Widget._renderEngine.createElement("
").addClass(`f-s-v-w h-${o.horizontalAlign}`).addClass(`v-${o.verticalAlign}`); + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - _hasFill: function () { - var o = this.options; + _hasFill() { + const o = this.options; if (o.rowSize.length > 0) { return o.rowSize.indexOf("fill") >= 0 || o.rowSize.indexOf("auto") >= 0; } - return BI.some(o.items, function (i, item) { + + return some(o.items, (i, item) => { if (item.height === "fill" || item.height === "auto") { return true; } }); - }, + } - _addElement: function (i, item) { - var o = this.options; - var w = BI.FlexWrapperVerticalLayout.superclass._addElement.apply(this, arguments); - var rowSize = o.rowSize.length > 0 ? o.rowSize[i] : item.height; + _addElement(i, item) { + const o = this.options; + const w = super._addElement(...arguments); + let rowSize = o.rowSize.length > 0 ? o.rowSize[i] : item.height; if (o.rowSize.length > 0) { if (item.height >= 1 && o.rowSize[i] >= 1 && o.rowSize[i] !== item.height) { rowSize = null; } } w.element.css({ - position: "relative" + position: "relative", }); if (rowSize !== "auto") { if (rowSize === "fill" || rowSize === "") { - if (o.verticalAlign !== BI.VerticalAlign.Stretch) { + if (o.verticalAlign !== VerticalAlign.Stretch) { if (o.scrollable === true || o.scrolly === true) { w.element.addClass("f-s-n"); } @@ -91,21 +102,21 @@ BI.FlexWrapperVerticalLayout = BI.inherit(BI.Layout, { w.element.addClass("l-c"); } this._handleGap(w, item, null, i); + return w; - }, + } - appendFragment: function (frag) { + appendFragment(frag) { this.$wrapper.append(frag); this.element.append(this.$wrapper); - }, + } - _getWrapper: function () { + _getWrapper() { return this.$wrapper; - }, + } - populate: function (items) { - BI.FlexWrapperVerticalLayout.superclass.populate.apply(this, arguments); + populate(items) { + super.populate(...arguments); this._mount(); } -}); -BI.shortcut("bi.flex_scrollable_vertical", BI.FlexWrapperVerticalLayout); +} diff --git a/src/core/wrapper/layout/flex/wrapper/index.js b/src/core/wrapper/layout/flex/wrapper/index.js new file mode 100644 index 000000000..5257a1b70 --- /dev/null +++ b/src/core/wrapper/layout/flex/wrapper/index.js @@ -0,0 +1,5 @@ +export { FlexWrapperCenterLayout } from "./flex.wrapper.center"; +export { FlexWrapperHorizontalCenter, FlexWrapperHorizontalCenterAdapt } from "./flex.wrapper.horizontal.center"; +export { FlexWrapperHorizontalLayout } from "./flex.wrapper.horizontal"; +export { FlexWrapperVerticalCenter, FlexWrapperVerticalCenterAdapt } from "./flex.wrapper.vertical.center"; +export { FlexWrapperVerticalLayout } from "./flex.wrapper.vertical"; diff --git a/src/core/wrapper/layout/float/float.absolute.center.js b/src/core/wrapper/layout/float/float.absolute.center.js index 08cc5b326..6aefbc1ac 100644 --- a/src/core/wrapper/layout/float/float.absolute.center.js +++ b/src/core/wrapper/layout/float/float.absolute.center.js @@ -1,36 +1,42 @@ +import { shortcut } from "@/core/decorator"; +import { extend, isFunction } from "@/core/2.base"; +import { Layout } from "../../layout"; + /** * absolute实现的居中布局 - * @class BI.FloatAbsoluteCenterLayout - * @extends BI.Layout + * @class FloatAbsoluteCenterLayout + * @extends Layout */ -BI.FloatAbsoluteCenterLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FloatAbsoluteCenterLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class FloatAbsoluteCenterLayout extends Layout { + static xtype = "bi.absolute_center_float"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-abs-c-fl", }); - }, + } - render: function () { - BI.FloatAbsoluteCenterLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); + render() { + super.render(...arguments); + const o = this.options; + const items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); }) : o.items; this.populate(items); - }, + } - _addElement: function (i, item) { - var o = this.options; - var w = BI.FloatAbsoluteCenterLayout.superclass._addElement.apply(this, arguments); + _addElement(i, item) { + const w = super._addElement(...arguments); w.element.addClass("bi-abs-c-item").css({ position: "absolute", }); + return w; - }, + } - populate: function (items) { - BI.FloatAbsoluteCenterLayout.superclass.populate.apply(this, arguments); + populate(items) { + super.populate(...arguments); this._mount(); } -}); -BI.shortcut("bi.absolute_center_float", BI.FloatAbsoluteCenterLayout); +} diff --git a/src/core/wrapper/layout/float/float.absolute.horizontal.js b/src/core/wrapper/layout/float/float.absolute.horizontal.js index b9aae3708..8d2757217 100644 --- a/src/core/wrapper/layout/float/float.absolute.horizontal.js +++ b/src/core/wrapper/layout/float/float.absolute.horizontal.js @@ -1,23 +1,32 @@ +import { shortcut } from "@/core/decorator"; +import { extend, map, isEmptyObject, stripEL, isWidget } from "@/core/2.base"; +import { HorizontalAlign } from "@/core/constant"; +import { Layout } from "../../layout"; + /** * absolute实现的居中布局 - * @class BI.FloatAbsoluteHorizontalLayout - * @extends BI.Layout + * @class FloatAbsoluteHorizontalLayout + * @extends Layout */ -BI.FloatAbsoluteHorizontalLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FloatAbsoluteHorizontalLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class FloatAbsoluteHorizontalLayout extends Layout { + static xtype = "bi.absolute_horizontal_float"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-abs-h-fl", - horizontalAlign: BI.HorizontalAlign.Center, + horizontalAlign: HorizontalAlign.Center, rowSize: [], vgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, + } - render: function () { - var self = this, o = this.options; - BI.FloatAbsoluteHorizontalLayout.superclass.render.apply(this, arguments); + render() { + const o = this.options; + super.render(...arguments); + return { type: "bi.vtape", horizontalAlign: o.horizontalAlign, @@ -26,8 +35,8 @@ BI.FloatAbsoluteHorizontalLayout = BI.inherit(BI.Layout, { scrollx: o.scrollx, scrolly: o.scrolly, scrollable: o.scrollable, - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, hgap: "50%", vgap: o.vgap, @@ -39,34 +48,35 @@ BI.FloatAbsoluteHorizontalLayout = BI.inherit(BI.Layout, { innerHgap: o.innerHgap, innerVgap: o.innerVgap, }; - }, + } - _formatItems: function (items) { - var o = this.options; - if (o.horizontalAlign === BI.HorizontalAlign.Left) { + _formatItems(items) { + const o = this.options; + if (o.horizontalAlign === HorizontalAlign.Left) { return items; } - var cls = o.horizontalAlign === BI.HorizontalAlign.Right ? "bi-abs-r-x-item" : "bi-abs-c-x-item"; - return BI.map(items, function (i, item) { - if (!item || BI.isEmptyObject(item)) { + const cls = o.horizontalAlign === HorizontalAlign.Right ? "bi-abs-r-x-item" : "bi-abs-c-x-item"; + + return map(items, (i, item) => { + if (!item || isEmptyObject(item)) { return item; } - var el = BI.stripEL(item); - if (BI.isWidget(el)) { + const el = stripEL(item); + if (isWidget(el)) { el.element.addClass(cls); } else { el.cls = (el.cls || "") + cls; } + return item; }); - }, + } - resize: function () { + resize() { this.layout.stroke(this._formatItems(this.options.items)); - }, + } - populate: function (items) { + populate(items) { this.layout.populate(this._formatItems(items)); } -}); -BI.shortcut("bi.absolute_horizontal_float", BI.FloatAbsoluteHorizontalLayout); +} diff --git a/src/core/wrapper/layout/float/float.absolute.leftrightvertical.js b/src/core/wrapper/layout/float/float.absolute.leftrightvertical.js index 9de105651..0b545c822 100644 --- a/src/core/wrapper/layout/float/float.absolute.leftrightvertical.js +++ b/src/core/wrapper/layout/float/float.absolute.leftrightvertical.js @@ -1,8 +1,16 @@ -BI.FloatAbsoluteLeftRightVerticalAdaptLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FloatAbsoluteLeftRightVerticalAdaptLayout.superclass.props.apply(this, arguments), { +import { shortcut } from "@/core/decorator"; +import { extend, map, isEmptyObject, stripEL, isWidget, isArray, each } from "@/core/2.base"; +import { VerticalAlign } from "@/core/constant"; +import { Layout } from "../../layout"; + +@shortcut() +export class FloatAbsoluteLeftRightVerticalAdaptLayout extends Layout { + static xtype = "bi.absolute_left_right_vertical_float"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-abs-lr-v-fl", - verticalAlign: BI.VerticalAlign.Middle, + verticalAlign: VerticalAlign.Middle, items: {}, llgap: 0, lrgap: 0, @@ -15,16 +23,18 @@ BI.FloatAbsoluteLeftRightVerticalAdaptLayout = BI.inherit(BI.Layout, { rhgap: 0, rtgap: 0, rbgap: 0, - rvgap: 0 + rvgap: 0, }); - }, - render: function () { - var o = this.options, self = this; - BI.FloatAbsoluteLeftRightVerticalAdaptLayout.superclass.render.apply(this, arguments); + } + + render() { + const o = this.options; + super.render(...arguments); + return { type: "bi.htape", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, verticalAlign: o.verticalAlign, items: this._formatItems(o.items), @@ -33,15 +43,15 @@ BI.FloatAbsoluteLeftRightVerticalAdaptLayout = BI.inherit(BI.Layout, { innerVgap: o.innerVgap, scrollx: o.scrollx, scrolly: o.scrolly, - scrollable: o.scrollable + scrollable: o.scrollable, }; - }, + } - _formatItems: function (items) { - var self = this, o = this.options; - var left, right; - if (BI.isArray(items)) { - BI.each(items, function (i, item) { + _formatItems(items) { + const o = this.options; + let left, right; + if (isArray(items)) { + each(items, (i, item) => { if (item.left) { left = item.left; } @@ -50,98 +60,105 @@ BI.FloatAbsoluteLeftRightVerticalAdaptLayout = BI.inherit(BI.Layout, { } }); } - var leftItems = left || items.left || []; - var rightItems = right || items.right || []; - leftItems = BI.map(leftItems, function (i, item) { - var el = BI.stripEL(item); - if (o.verticalAlign === BI.VerticalAlign.Middle) { - if (BI.isWidget(el)) { + let leftItems = left || items.left || []; + let rightItems = right || items.right || []; + leftItems = map(leftItems, (i, item) => { + const el = stripEL(item); + if (o.verticalAlign === VerticalAlign.Middle) { + if (isWidget(el)) { el.element.addClass("bi-abs-c-y-item"); } else { - el.cls = (el.cls || "") + "bi-abs-c-y-item"; + el.cls = `${el.cls || ""}bi-abs-c-y-item`; } } - var json = { - el: el, - width: item.width + const json = { + el, + width: item.width, }; // if (o.lvgap + o.ltgap + (item.tgap || 0) + (item.vgap || 0) !== 0) { // json.tgap = o.lvgap + o.ltgap + (item.tgap || 0) + (item.vgap || 0); // } - if (o.lhgap + o.llgap + self._optimiseItemLgap(item) + self._optimiseItemHgap(item) !== 0) { - json.lgap = (i === 0 ? o.lhgap : 0) + o.llgap + self._optimiseItemLgap(item) + self._optimiseItemHgap(item); + if (o.lhgap + o.llgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item) !== 0) { + json.lgap = (i === 0 ? o.lhgap : 0) + o.llgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item); } - if (o.lhgap + o.lrgap + self._optimiseItemRgap(item) + self._optimiseItemHgap(item) !== 0) { - json.rgap = o.lhgap + o.lrgap + self._optimiseItemRgap(item) + self._optimiseItemHgap(item); + if (o.lhgap + o.lrgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item) !== 0) { + json.rgap = o.lhgap + o.lrgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item); } // if (o.lvgap + o.lbgap + (item.bgap || 0) + (item.vgap || 0) !== 0) { // json.bgap = o.lvgap + o.lbgap + (item.bgap || 0) + (item.vgap || 0); // } + return json; }); - rightItems = BI.map(rightItems, function (i, item) { - var el = BI.stripEL(item); - if (o.verticalAlign === BI.VerticalAlign.Middle) { - if (BI.isWidget(el)) { + rightItems = map(rightItems, (i, item) => { + const el = stripEL(item); + if (o.verticalAlign === VerticalAlign.Middle) { + if (isWidget(el)) { el.element.addClass("bi-abs-c-y-item"); } else { - el.cls = (el.cls || "") + "bi-abs-c-y-item"; + el.cls = `${el.cls || ""}bi-abs-c-y-item`; } } - var json = { - el: el, - width: item.width + const json = { + el, + width: item.width, }; // if (o.rvgap + o.rtgap + (item.tgap || 0) + (item.vgap || 0) !== 0) { // json.tgap = o.rvgap + o.rtgap + (item.tgap || 0) + (item.vgap || 0); // } - if (o.rhgap + o.rlgap + self._optimiseItemLgap(item) + self._optimiseItemHgap(item) !== 0) { - json.lgap = (i === 0 ? o.rhgap : 0) + o.rlgap + self._optimiseItemLgap(item) + self._optimiseItemHgap(item); + if (o.rhgap + o.rlgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item) !== 0) { + json.lgap = (i === 0 ? o.rhgap : 0) + o.rlgap + this._optimiseItemLgap(item) + this._optimiseItemHgap(item); } - if (o.rhgap + o.rrgap + self._optimiseItemRgap(item) + self._optimiseItemHgap(item) !== 0) { - json.rgap = o.rhgap + o.rrgap + self._optimiseItemRgap(item) + self._optimiseItemHgap(item); + if (o.rhgap + o.rrgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item) !== 0) { + json.rgap = o.rhgap + o.rrgap + this._optimiseItemRgap(item) + this._optimiseItemHgap(item); } // if (o.rvgap + o.rbgap + (item.bgap || 0) + (item.vgap || 0) !== 0) { // json.bgap = o.rvgap + o.rbgap + (item.bgap || 0) + (item.vgap || 0); // } + return json; }); + return leftItems.concat({}, rightItems); - }, + } - resize: function () { + resize() { this.layout.stroke(this._formatItems(this.options.items)); - }, + } - addItem: function () { + addItem() { // do nothing throw new Error("不能添加子组件"); - }, + } - populate: function (items) { + populate(items) { this.layout.populate(this._formatItems(items)); } -}); -BI.shortcut("bi.absolute_left_right_vertical_float", BI.FloatAbsoluteLeftRightVerticalAdaptLayout); +} + +@shortcut() +export class FloatAbsoluteRightVerticalAdaptLayout extends Layout { + static xtype = "bi.absolute_right_vertical_float"; -BI.FloatAbsoluteRightVerticalAdaptLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FloatAbsoluteRightVerticalAdaptLayout.superclass.props.apply(this, arguments), { + props() { + return extend(super.props(...arguments), { baseCls: "bi-abs-r-v-fl", - verticalAlign: BI.VerticalAlign.Middle, + verticalAlign: VerticalAlign.Middle, items: [], lgap: 0, rgap: 0, - hgap: 0 + hgap: 0, }); - }, - render: function () { - var o = this.options, self = this; - BI.FloatAbsoluteRightVerticalAdaptLayout.superclass.render.apply(this, arguments); + } + + render() { + const o = this.options; + super.render(...arguments); + return { type: "bi.htape", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, verticalAlign: o.verticalAlign, items: [{}].concat(this._formatItems(o.items)), @@ -151,39 +168,40 @@ BI.FloatAbsoluteRightVerticalAdaptLayout = BI.inherit(BI.Layout, { vgap: "50%", scrollx: o.scrollx, scrolly: o.scrolly, - scrollable: o.scrollable + scrollable: o.scrollable, }; - }, + } - _formatItems: function (items) { - if (this.options.verticalAlign !== BI.VerticalAlign.Middle) { + _formatItems(items) { + if (this.options.verticalAlign !== VerticalAlign.Middle) { return items; } - return BI.map(items, function (i, item) { - if (!item || BI.isEmptyObject(item)) { + + return map(items, (i, item) => { + if (!item || isEmptyObject(item)) { return item; } - var el = BI.stripEL(item); - if (BI.isWidget(el)) { + const el = stripEL(item); + if (isWidget(el)) { el.element.addClass("bi-abs-c-y-item"); } else { - el.cls = (el.cls || "") + "bi-abs-c-y-item"; + el.cls = `${el.cls || ""}bi-abs-c-y-item`; } + return item; }); - }, + } - resize: function () { + resize() { this.layout.stroke([{}].concat(this._formatItems(this.options.items))); - }, + } - addItem: function () { + addItem() { // do nothing throw new Error("不能添加子组件"); - }, + } - populate: function (items) { + populate(items) { this.layout.populate([{}].concat(this._formatItems(items))); } -}); -BI.shortcut("bi.absolute_right_vertical_float", BI.FloatAbsoluteRightVerticalAdaptLayout); +} diff --git a/src/core/wrapper/layout/float/float.absolute.vertical.js b/src/core/wrapper/layout/float/float.absolute.vertical.js index 01b949b06..d55dba779 100644 --- a/src/core/wrapper/layout/float/float.absolute.vertical.js +++ b/src/core/wrapper/layout/float/float.absolute.vertical.js @@ -1,23 +1,32 @@ +import { shortcut } from "@/core/decorator"; +import { extend, map, isEmptyObject, stripEL, isWidget } from "@/core/2.base"; +import { VerticalAlign } from "@/core/constant"; +import { Layout } from "../../layout"; + /** * absolute实现的居中布局 - * @class BI.FloatAbsoluteVerticalLayout - * @extends BI.Layout + * @class FloatAbsoluteVerticalLayout + * @extends Layout */ -BI.FloatAbsoluteVerticalLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FloatAbsoluteVerticalLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class FloatAbsoluteVerticalLayout extends Layout { + static xtype = "bi.absolute_vertical_float"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-abs-h-fl", - verticalAlign: BI.VerticalAlign.Middle, + verticalAlign: VerticalAlign.Middle, columnSize: [], hgap: 0, lgap: 0, - rgap: 0 + rgap: 0, }); - }, + } - render: function () { - var self = this, o = this.options; - BI.FloatAbsoluteVerticalLayout.superclass.render.apply(this, arguments); + render() { + const o = this.options; + super.render(...arguments); + return { type: "bi.htape", verticalAlign: o.verticalAlign, @@ -26,8 +35,8 @@ BI.FloatAbsoluteVerticalLayout = BI.inherit(BI.Layout, { scrollx: o.scrollx, scrolly: o.scrolly, scrollable: o.scrollable, - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, vgap: "50%", hgap: o.hgap, @@ -39,34 +48,35 @@ BI.FloatAbsoluteVerticalLayout = BI.inherit(BI.Layout, { innerHgap: o.innerHgap, innerVgap: o.innerVgap, }; - }, + } - _formatItems: function (items) { - var o = this.options; - if (o.verticalAlign === BI.VerticalAlign.Top) { + _formatItems(items) { + const o = this.options; + if (o.verticalAlign === VerticalAlign.Top) { return items; } - var cls = o.verticalAlign === BI.VerticalAlign.Bottom ? "bi-abs-b-y-item" : "bi-abs-c-y-item"; - return BI.map(items, function (i, item) { - if (!item || BI.isEmptyObject(item)) { + const cls = o.verticalAlign === VerticalAlign.Bottom ? "bi-abs-b-y-item" : "bi-abs-c-y-item"; + + return map(items, (i, item) => { + if (!item || isEmptyObject(item)) { return item; } - var el = BI.stripEL(item); - if (BI.isWidget(el)) { + const el = stripEL(item); + if (isWidget(el)) { el.element.addClass(cls); } else { el.cls = (el.cls || "") + cls; } + return item; }); - }, + } - resize: function () { + resize() { this.layout.stroke(this._formatItems(this.options.items)); - }, + } - populate: function (items) { + populate(items) { this.layout.populate(this._formatItems(items)); } -}); -BI.shortcut("bi.absolute_vertical_float", BI.FloatAbsoluteVerticalLayout); +} diff --git a/src/core/wrapper/layout/float/float.horizontal.js b/src/core/wrapper/layout/float/float.horizontal.js index 97ac66b49..9b3da1f9d 100644 --- a/src/core/wrapper/layout/float/float.horizontal.js +++ b/src/core/wrapper/layout/float/float.horizontal.js @@ -1,30 +1,37 @@ +import { shortcut } from "@/core/decorator"; +import { extend, map } from "@/core/2.base"; +import { VerticalAlign, HorizontalAlign } from "@/core/constant"; +import { Layout } from "../../layout"; + /** * 浮动的水平居中布局 */ -BI.FloatHorizontalLayout = BI.inherit(BI.Layout, { +@shortcut() +export class FloatHorizontalLayout extends Layout { + static xtype = "bi.horizontal_float"; - props: function () { - return BI.extend(BI.InlineHorizontalAdaptLayout.superclass.props.apply(this, arguments), { + props() { + return extend(super.props(...arguments), { baseCls: "bi-h-fl", - horizontalAlign: BI.HorizontalAlign.Center, - verticalAlign: BI.VerticalAlign.Top, + horizontalAlign: HorizontalAlign.Center, + verticalAlign: VerticalAlign.Top, rowSize: [], hgap: 0, vgap: 0, lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, + } - render: function () { - var self = this, o = this.options; - if (o.verticalAlign === BI.VerticalAlign.Top) { + render() { + const o = this.options; + if (o.verticalAlign === VerticalAlign.Top) { return { type: "bi.vertical", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, items: this._formatItems(o.items), vgap: o.vgap, @@ -32,22 +39,23 @@ BI.FloatHorizontalLayout = BI.inherit(BI.Layout, { bgap: o.bgap, scrollx: o.scrollx, scrolly: o.scrolly, - scrollable: o.scrollable + scrollable: o.scrollable, }; } + return { type: "bi.inline", items: [{ el: { type: "bi.vertical", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, items: this._formatItems(o.items), vgap: o.vgap, tgap: o.tgap, - bgap: o.bgap - } + bgap: o.bgap, + }, }], horizontalAlign: o.horizontalAlign, verticalAlign: o.verticalAlign, @@ -55,13 +63,14 @@ BI.FloatHorizontalLayout = BI.inherit(BI.Layout, { innerVgap: o.innerVgap, scrollx: o.scrollx, scrolly: o.scrolly, - scrollable: o.scrollable + scrollable: o.scrollable, }; - }, + } - _formatItems: function (items) { - var o = this.options; - return BI.map(items, function (i, item) { + _formatItems(items) { + const o = this.options; + + return map(items, (i, item) => { return { el: { type: "bi.inline_horizontal_adapt", @@ -69,18 +78,17 @@ BI.FloatHorizontalLayout = BI.inherit(BI.Layout, { items: [item], hgap: o.hgap, lgap: o.lgap, - rgap: o.rgap - } + rgap: o.rgap, + }, }; }); - }, + } - resize: function () { + resize() { this.layout.stroke(this._formatItems(this.options.items)); - }, + } - populate: function (items) { + populate(items) { this.layout.populate(this._formatItems(items)); } -}); -BI.shortcut("bi.horizontal_float", BI.FloatHorizontalLayout); +} diff --git a/src/core/wrapper/layout/float/index.js b/src/core/wrapper/layout/float/index.js new file mode 100644 index 000000000..97d5b1ff2 --- /dev/null +++ b/src/core/wrapper/layout/float/index.js @@ -0,0 +1,5 @@ +export { FloatAbsoluteCenterLayout } from "./float.absolute.center"; +export { FloatAbsoluteHorizontalLayout } from "./float.absolute.horizontal"; +export { FloatAbsoluteLeftRightVerticalAdaptLayout, FloatAbsoluteRightVerticalAdaptLayout } from "./float.absolute.leftrightvertical"; +export { FloatAbsoluteVerticalLayout } from "./float.absolute.vertical"; +export { FloatHorizontalLayout } from "./float.horizontal"; diff --git a/src/core/wrapper/layout/index.js b/src/core/wrapper/layout/index.js index 03bd1cf74..9fd652878 100644 --- a/src/core/wrapper/layout/index.js +++ b/src/core/wrapper/layout/index.js @@ -15,3 +15,9 @@ export { TdLayout } from "./layout.td"; export { VerticalLayout } from "./layout.vertical"; export { WindowLayout } from "./layout.window"; export * from "./adapt"; +export * from "./fill"; +export * from "./flex"; +export * from "./float"; +export * from "./middle"; +export * from "./responsive"; +export * from "./sticky"; diff --git a/src/core/wrapper/layout/middle/index.js b/src/core/wrapper/layout/middle/index.js new file mode 100644 index 000000000..c564fe1a6 --- /dev/null +++ b/src/core/wrapper/layout/middle/index.js @@ -0,0 +1,4 @@ +export { CenterLayout } from "./middle.center"; +export { FloatCenterLayout } from "./middle.float.center"; +export { HorizontalCenterLayout } from "./middle.horizontal"; +export { VerticalCenterLayout } from "./middle.vertical"; diff --git a/src/core/wrapper/layout/middle/middle.center.js b/src/core/wrapper/layout/middle/middle.center.js index 9d80a094f..039d90a19 100644 --- a/src/core/wrapper/layout/middle/middle.center.js +++ b/src/core/wrapper/layout/middle/middle.center.js @@ -1,72 +1,80 @@ +import { shortcut } from "@/core/decorator"; +import { extend, each } from "@/core/2.base"; +import { _lazyCreateWidget } from "@/core/5.inject"; +import { Layout } from "../../layout"; + /** * 水平和垂直方向都居中容器, 非自适应,用于宽度高度固定的面板 - * @class BI.CenterLayout - * @extends BI.Layout + * @class CenterLayout + * @extends Layout */ -BI.CenterLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.CenterLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class CenterLayout extends Layout { + static xtype = "bi.center"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-center", hgap: 0, vgap: 0, lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, + } - render: function () { - BI.CenterLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options; - var list = [], items = o.items; - BI.each(items, function (i) { + render() { + super.render(...arguments); + const o = this.options; + const list = [], items = o.items; + each(items, i => { list.push({ column: i, row: 0, - el: BI._lazyCreateWidget({ + el: _lazyCreateWidget({ type: "bi.default", - cls: "center-element " + (i === 0 ? "first-element " : "") + (i === items.length - 1 ? "last-element" : "") - }) + cls: `center-element ${i === 0 ? "first-element " : ""}${i === items.length - 1 ? "last-element" : ""}`, + }), }); }); - BI.each(items, function (i, item) { + each(items, (i, item) => { if (item) { - var w = BI._lazyCreateWidget(item); + const w = _lazyCreateWidget(item); w.element.css({ position: "absolute", - left: self._optimiseGap(o.hgap + o.lgap), - right: self._optimiseGap(o.hgap + o.rgap), - top: self._optimiseGap(o.vgap + o.tgap), - bottom: self._optimiseGap(o.vgap + o.bgap), + left: this._optimiseGap(o.hgap + o.lgap), + right: this._optimiseGap(o.hgap + o.rgap), + top: this._optimiseGap(o.vgap + o.tgap), + bottom: this._optimiseGap(o.vgap + o.bgap), width: "auto", - height: "auto" + height: "auto", }); list[i].el.addItem(w); } }); + return { type: "bi.grid", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, columns: list.length, rows: 1, - items: list + items: list, }; - }, + } - resize: function () { + resize() { // console.log("center布局不需要resize"); - }, + } - addItem: function (item) { + addItem(item) { // do nothing throw new Error("不能添加子组件"); - }, + } - populate: function (items) { - this.layout.populate.apply(this.layout, arguments); + populate(items) { + this.layout.populate(...arguments); } -}); -BI.shortcut("bi.center", BI.CenterLayout); +} diff --git a/src/core/wrapper/layout/middle/middle.float.center.js b/src/core/wrapper/layout/middle/middle.float.center.js index d1e2a4695..63b6f157d 100644 --- a/src/core/wrapper/layout/middle/middle.float.center.js +++ b/src/core/wrapper/layout/middle/middle.float.center.js @@ -1,71 +1,80 @@ +import { shortcut } from "@/core/decorator"; +import { extend, each } from "@/core/2.base"; +import { _lazyCreateWidget } from "@/core/5.inject"; +import { Layout } from "../../layout"; + /** * 浮动布局实现的居中容器 - * @class BI.FloatCenterLayout - * @extends BI.Layout + * @class FloatCenterLayout + * @extends Layout */ -BI.FloatCenterLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.FloatCenterLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class FloatCenterLayout extends Layout { + static xtype = "bi.float_center"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-float-center", hgap: 0, vgap: 0, lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, - render: function () { - BI.FloatCenterLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options, items = o.items; - var list = [], width = 100 / items.length; - BI.each(items, function (i) { - var widget = BI._lazyCreateWidget({ - type: "bi.default" + } + + render() { + super.render(...arguments); + const o = this.options, items = o.items; + const list = [], width = 100 / items.length; + each(items, i => { + const widget = _lazyCreateWidget({ + type: "bi.default", }); - widget.element.addClass("center-element " + (i === 0 ? "first-element " : "") + (i === items.length - 1 ? "last-element" : "")).css({ - width: width + "%", - height: "100%" + widget.element.addClass(`center-element ${i === 0 ? "first-element " : ""}${i === items.length - 1 ? "last-element" : ""}`).css({ + width: `${width}%`, + height: "100%", }); list.push({ - el: widget + el: widget, }); }); - BI.each(items, function (i, item) { + each(items, (i, item) => { if (item) { - var w = BI._lazyCreateWidget(item); + const w = _lazyCreateWidget(item); w.element.css({ position: "absolute", - left: self._optimiseGap(o.hgap + o.lgap), - right: self._optimiseGap(o.hgap + o.rgap), - top: self._optimiseGap(o.vgap + o.tgap), - bottom: self._optimiseGap(o.vgap + o.bgap), + left: this._optimiseGap(o.hgap + o.lgap), + right: this._optimiseGap(o.hgap + o.rgap), + top: this._optimiseGap(o.vgap + o.tgap), + bottom: this._optimiseGap(o.vgap + o.bgap), width: "auto", - height: "auto" + height: "auto", }); list[i].el.addItem(w); } }); + return { type: "bi.left", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, - items: list + items: list, }; - }, + } - resize: function () { + resize() { // console.log("floatcenter布局不需要resize"); - }, + } - addItem: function (item) { + addItem(item) { // do nothing throw new Error("不能添加子组件"); - }, + } - populate: function (items) { - this.layout.populate.apply(this.layout, arguments); + populate(items) { + this.layout.populate(...arguments); } -}); -BI.shortcut("bi.float_center", BI.FloatCenterLayout); +} diff --git a/src/core/wrapper/layout/middle/middle.horizontal.js b/src/core/wrapper/layout/middle/middle.horizontal.js index c42fde9c0..b6fff379c 100644 --- a/src/core/wrapper/layout/middle/middle.horizontal.js +++ b/src/core/wrapper/layout/middle/middle.horizontal.js @@ -1,70 +1,79 @@ +import { shortcut } from "@/core/decorator"; +import { extend, each } from "@/core/2.base"; +import { _lazyCreateWidget } from "@/core/5.inject"; +import { Layout } from "../../layout"; + /** * 水平和垂直方向都居中容器, 非自适应,用于宽度高度固定的面板 - * @class BI.HorizontalCenterLayout - * @extends BI.Layout + * @class HorizontalCenterLayout + * @extends Layout */ -BI.HorizontalCenterLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.HorizontalCenterLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class HorizontalCenterLayout extends Layout { + static xtype = "bi.horizontal_center"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-h-center", hgap: 0, vgap: 0, lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, - render: function () { - BI.HorizontalCenterLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options, items = o.items; - var list = []; - BI.each(items, function (i) { + } + + render() { + super.render(...arguments); + const o = this.options, items = o.items; + const list = []; + each(items, i => { list.push({ column: i, row: 0, - el: BI._lazyCreateWidget({ + el: _lazyCreateWidget({ type: "bi.default", - cls: "center-element " + (i === 0 ? "first-element " : "") + (i === items.length - 1 ? "last-element" : "") - }) + cls: `center-element ${i === 0 ? "first-element " : ""}${i === items.length - 1 ? "last-element" : ""}`, + }), }); }); - BI.each(items, function (i, item) { + each(items, (i, item) => { if (item) { - var w = BI._lazyCreateWidget(item); + const w = _lazyCreateWidget(item); w.element.css({ position: "absolute", - left: self._optimiseGap(o.hgap + o.lgap), - right: self._optimiseGap(o.hgap + o.rgap), - top: self._optimiseGap(o.vgap + o.tgap), - bottom: self._optimiseGap(o.vgap + o.bgap), - width: "auto" + left: this._optimiseGap(o.hgap + o.lgap), + right: this._optimiseGap(o.hgap + o.rgap), + top: this._optimiseGap(o.vgap + o.tgap), + bottom: this._optimiseGap(o.vgap + o.bgap), + width: "auto", }); list[i].el.addItem(w); } }); + return { type: "bi.grid", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, columns: list.length, rows: 1, - items: list + items: list, }; - }, + } - resize: function () { + resize() { // console.log("horizontal_center布局不需要resize"); - }, + } - addItem: function (item) { + addItem(item) { // do nothing throw new Error("不能添加子组件"); - }, + } - populate: function (items) { - this.layout.populate.apply(this.layout, arguments); + populate(items) { + this.layout.populate(...arguments); } -}); -BI.shortcut("bi.horizontal_center", BI.HorizontalCenterLayout); +} diff --git a/src/core/wrapper/layout/middle/middle.vertical.js b/src/core/wrapper/layout/middle/middle.vertical.js index b835bc4f6..a203e205f 100644 --- a/src/core/wrapper/layout/middle/middle.vertical.js +++ b/src/core/wrapper/layout/middle/middle.vertical.js @@ -1,71 +1,79 @@ +import { shortcut } from "@/core/decorator"; +import { extend, each } from "@/core/2.base"; +import { _lazyCreateWidget } from "@/core/5.inject"; +import { Layout } from "../../layout"; + /** * 垂直方向都居中容器, 非自适应,用于高度不固定的面板 - * @class BI.VerticalCenterLayout - * @extends BI.Layout + * @class VerticalCenterLayout + * @extends Layout */ -BI.VerticalCenterLayout = BI.inherit(BI.Layout, { - props: function () { - return BI.extend(BI.VerticalCenterLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class VerticalCenterLayout extends Layout { + static xtype = "bi.vertical_center"; + + props() { + return extend(super.props(...arguments), { baseCls: "bi-v-center", hgap: 0, vgap: 0, lgap: 0, rgap: 0, tgap: 0, - bgap: 0 + bgap: 0, }); - }, + } - render: function () { - BI.VerticalCenterLayout.superclass.render.apply(this, arguments); - var self = this, o = this.options, items = o.items; - var list = []; - BI.each(items, function (i) { + render() { + super.render(...arguments); + const self = this, o = this.options, items = o.items; + const list = []; + each(items, i => { list.push({ column: 0, row: i, - el: BI._lazyCreateWidget({ + el: _lazyCreateWidget({ type: "bi.default", - cls: "center-element " + (i === 0 ? "first-element " : "") + (i === items.length - 1 ? "last-element" : "") - }) + cls: `center-element ${i === 0 ? "first-element " : ""}${i === items.length - 1 ? "last-element" : ""}`, + }), }); }); - BI.each(items, function (i, item) { + each(items, (i, item) => { if (item) { - var w = BI._lazyCreateWidget(item); + const w = _lazyCreateWidget(item); w.element.css({ position: "absolute", left: self._optimiseGap(o.hgap + o.lgap), right: self._optimiseGap(o.hgap + o.rgap), top: self._optimiseGap(o.vgap + o.tgap), bottom: self._optimiseGap(o.vgap + o.bgap), - height: "auto" + height: "auto", }); list[i].el.addItem(w); } }); + return { type: "bi.grid", - ref: function (_ref) { - self.layout = _ref; + ref: _ref => { + this.layout = _ref; }, columns: 1, rows: list.length, - items: list + items: list, }; - }, + } - resize: function () { + resize() { // console.log("vertical_center布局不需要resize"); - }, + } - addItem: function (item) { + addItem(item) { // do nothing throw new Error("不能添加子组件"); - }, + } - populate: function (items) { - this.layout.populate.apply(this.layout, arguments); + populate(items) { + this.layout.populate(...arguments); } -}); -BI.shortcut("bi.vertical_center", BI.VerticalCenterLayout); +} diff --git a/src/core/wrapper/layout/responsive/index.js b/src/core/wrapper/layout/responsive/index.js new file mode 100644 index 000000000..89f0bb09d --- /dev/null +++ b/src/core/wrapper/layout/responsive/index.js @@ -0,0 +1,3 @@ +export { ResponsiveFlexHorizontalLayout } from "./responsive.flex.horizontal"; +export { ResponsiveFlexWrapperHorizontalLayout } from "./responsive.flex.wrapper.horizontal"; +export { ResponsiveInlineLayout } from "./responsive.inline"; diff --git a/src/core/wrapper/layout/responsive/responsive.flex.horizontal.js b/src/core/wrapper/layout/responsive/responsive.flex.horizontal.js index 592d50641..7cfceede4 100644 --- a/src/core/wrapper/layout/responsive/responsive.flex.horizontal.js +++ b/src/core/wrapper/layout/responsive/responsive.flex.horizontal.js @@ -1,57 +1,59 @@ +import { shortcut } from "@/core/decorator"; +import { each } from "@/core/2.base"; +import { HorizontalAlign } from "@/core/constant"; +import { Resizers } from "@/base"; +import { FlexHorizontalLayout } from "../flex"; + /** * 横向响应式布局 * Created by GUY on 2016/12/2. * - * @class BI.ResponsiveFlexHorizontalLayout - * @extends BI.FlexHorizontalLayout + * @class ResponsiveFlexHorizontalLayout + * @extends FlexHorizontalLayout */ -BI.ResponsiveFlexHorizontalLayout = BI.inherit(BI.FlexHorizontalLayout, { - // props: function () { - // return BI.extend(BI.ResponsiveFlexHorizontalLayout.superclass.props.apply(this, arguments), { - // // extraCls: "bi-responsive-f-h" - // }); - // }, +@shortcut() +export class ResponsiveFlexHorizontalLayout extends FlexHorizontalLayout { + static xtype = "bi.responsive_flex_horizontal"; - mounted: function () { - var self = this, o = this.options; - if (o.horizontalAlign !== BI.HorizontalAlign.Center){ + mounted() { + const o = this.options; + if (o.horizontalAlign !== HorizontalAlign.Center) { return; } - var defaultResize = function () { + const defaultResize = () => { if (o.scrollable !== true && o.scrollx !== true) { - var clientWidth = document.body.clientWidth; - if(self.element.width() > 2/3 * clientWidth){ + const clientWidth = document.body.clientWidth; + if (this.element.width() > 2 / 3 * clientWidth) { if (clientWidth <= 768) { - BI.each(self._children, function (i, child) { - self._clearGap(child); - self._handleReverseGap(child, o.items[i], i | 0); + each(this._children, (i, child) => { + this._clearGap(child); + this._handleReverseGap(child, o.items[i], i | 0); }); - self.element.css("flex-direction", "column"); + this.element.css("flex-direction", "column"); } } } - } - var resize = function () { + }; + const resize = () => { defaultResize(); if (o.scrollable !== true && o.scrollx !== true) { - var clientWidth = document.body.clientWidth; - if(self.element.width() > 2/3 * clientWidth){ + const clientWidth = document.body.clientWidth; + if (this.element.width() > 2 / 3 * clientWidth) { if (clientWidth > 768) { - BI.each(self._children, function (i, child) { - self._clearGap(child); - }) - self.resize(); - self.element.css("flex-direction", "row"); + each(this._children, (i, child) => { + this._clearGap(child); + }); + this.resize(); + this.element.css("flex-direction", "row"); } } } - } - this.unResize = BI.Resizers.add(this.getName(), resize); + }; + this.unResize = Resizers.add(this.getName(), resize); defaultResize(); - }, + } - destroyed: function () { + destroyed() { this.unResize?.(); } -}); -BI.shortcut("bi.responsive_flex_horizontal", BI.ResponsiveFlexHorizontalLayout); +} diff --git a/src/core/wrapper/layout/responsive/responsive.flex.wrapper.horizontal.js b/src/core/wrapper/layout/responsive/responsive.flex.wrapper.horizontal.js index 5e8fcfd95..90677598a 100644 --- a/src/core/wrapper/layout/responsive/responsive.flex.wrapper.horizontal.js +++ b/src/core/wrapper/layout/responsive/responsive.flex.wrapper.horizontal.js @@ -1,59 +1,61 @@ +import { shortcut } from "@/core/decorator"; +import { each } from "@/core/2.base"; +import { HorizontalAlign } from "@/core/constant"; +import { Resizers } from "@/base"; +import { FlexWrapperHorizontalLayout } from "../flex"; + /** * 横向响应式布局 * Created by GUY on 2016/12/2. * - * @class BI.ResponsiveFlexWrapperHorizontalLayout - * @extends BI.FlexWrapperHorizontalLayout + * @class ResponsiveFlexWrapperHorizontalLayout + * @extends FlexWrapperHorizontalLayout */ -BI.ResponsiveFlexWrapperHorizontalLayout = BI.inherit(BI.FlexWrapperHorizontalLayout, { - // props: function () { - // return BI.extend(BI.ResponsiveFlexWrapperHorizontalLayout.superclass.props.apply(this, arguments), { - // extraCls: "bi-responsive-f-h" - // }); - // }, +@shortcut() +export class ResponsiveFlexWrapperHorizontalLayout extends FlexWrapperHorizontalLayout { + static xtype = "bi.responsive_flex_scrollable_horizontal"; - mounted: function () { - var self = this, o = this.options; - if (o.horizontalAlign !== BI.HorizontalAlign.Center){ + mounted() { + const o = this.options; + if (o.horizontalAlign !== HorizontalAlign.Center) { return; } - var defaultResize = function () { + const defaultResize = () => { if (o.scrollable !== true && o.scrollx !== true) { - var clientWidth = document.body.clientWidth; - if(self.element.width() > 2/3 * clientWidth){ + const clientWidth = document.body.clientWidth; + if (this.element.width() > 2 / 3 * clientWidth) { if (clientWidth <= 768) { - BI.each(self._children, function (i, child) { - self._clearGap(child); - self._handleReverseGap(child, o.items[i], i | 0); + each(this._children, (i, child) => { + this._clearGap(child); + this._handleReverseGap(child, o.items[i], i | 0); }); - self.element.css("flex-direction", "column"); - self.$wrapper.element.css("flex-direction", "column"); + this.element.css("flex-direction", "column"); + this.$wrapper.element.css("flex-direction", "column"); } } } - } - var resize = function () { + }; + const resize = () => { defaultResize(); if (o.scrollable !== true && o.scrollx !== true) { - var clientWidth = document.body.clientWidth; - if(self.element.width() > 2/3 * clientWidth){ + const clientWidth = document.body.clientWidth; + if (this.element.width() > 2 / 3 * clientWidth) { if (clientWidth > 768) { - BI.each(self._children, function (i, child) { - self._clearGap(child); - }) - self.resize(); - self.element.css("flex-direction", "row"); - self.$wrapper.element.css("flex-direction", "row"); + each(this._children, (i, child) => { + this._clearGap(child); + }); + this.resize(); + this.element.css("flex-direction", "row"); + this.$wrapper.element.css("flex-direction", "row"); } } } - } - this.unResize = BI.Resizers.add(this.getName(), resize); + }; + this.unResize = Resizers.add(this.getName(), resize); defaultResize(); - }, + } - destroyed: function () { + destroyed() { this.unResize(); } -}); -BI.shortcut("bi.responsive_flex_scrollable_horizontal", BI.ResponsiveFlexWrapperHorizontalLayout); +} diff --git a/src/core/wrapper/layout/responsive/responsive.inline..js b/src/core/wrapper/layout/responsive/responsive.inline..js deleted file mode 100644 index 08f27fcfc..000000000 --- a/src/core/wrapper/layout/responsive/responsive.inline..js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 横向响应式布局 - * Created by GUY on 2016/12/2. - * - * @class BI.ResponsiveInlineLayout - * @extends BI.InlineLayout - */ -BI.ResponsiveInlineLayout = BI.inherit(BI.InlineLayout, { - mounted: function () { - var self = this, o = this.options; - if (o.horizontalAlign !== BI.HorizontalAlign.Center){ - return; - } - var defaultResize = function () { - if (o.scrollable !== true && o.scrollx !== true) { - var clientWidth = document.body.clientWidth; - if(self.element.width() > 2/3 * clientWidth){ - if (clientWidth <= 768) { - BI.each(self._children, function (i, child) { - self._clearGap(child); - self._handleReverseGap(child, o.items[i], i | 0); - child.elemenet.css("display", ""); - }); - } - } - } - } - var resize = function () { - defaultResize(); - if (o.scrollable !== true && o.scrollx !== true) { - var clientWidth = document.body.clientWidth; - if(self.element.width() > 2/3 * clientWidth){ - if (clientWidth > 768) { - BI.each(self._children, function (i, child) { - self._clearGap(child); - }) - self.resize(); - } - } - } - } - this.unResize = BI.Resizers.add(this.getName(), resize); - defaultResize(); - }, - - destroyed: function () { - this.unResize(); - } -}); -BI.shortcut("bi.responsive_inline", BI.ResponsiveInlineLayout); diff --git a/src/core/wrapper/layout/responsive/responsive.inline.js b/src/core/wrapper/layout/responsive/responsive.inline.js new file mode 100644 index 000000000..747a9d9cf --- /dev/null +++ b/src/core/wrapper/layout/responsive/responsive.inline.js @@ -0,0 +1,58 @@ +import { shortcut } from "@/core/decorator"; +import { each } from "@/core/2.base"; +import { HorizontalAlign } from "@/core/constant"; +import { Resizers } from "@/base"; +import { InlineLayout } from "../layout.inline"; + +/** + * 横向响应式布局 + * Created by GUY on 2016/12/2. + * + * @class ResponsiveInlineLayout + * @extends InlineLayout + */ +@shortcut() +export class ResponsiveInlineLayout extends InlineLayout { + static xtype = "bi.responsive_inline"; + + mounted() { + const o = this.options; + if (o.horizontalAlign !== HorizontalAlign.Center) { + return; + } + const defaultResize = () => { + if (o.scrollable !== true && o.scrollx !== true) { + const clientWidth = document.body.clientWidth; + if (this.element.width() > 2 / 3 * clientWidth) { + if (clientWidth <= 768) { + each(this._children, (i, child) => { + this._clearGap(child); + this._handleReverseGap(child, o.items[i], i | 0); + child.element.css("display", ""); + }); + } + } + } + }; + const resize = () => { + defaultResize(); + if (o.scrollable !== true && o.scrollx !== true) { + const clientWidth = document.body.clientWidth; + if (this.element.width() > 2 / 3 * clientWidth) { + if (clientWidth > 768) { + each(this._children, (i, child) => { + this._clearGap(child); + }); + this.resize(); + } + } + } + }; + this.unResize = Resizers.add(this.getName(), resize); + defaultResize(); + } + + destroyed() { + this.unResize(); + } +} diff --git a/src/core/wrapper/layout/sticky/index.js b/src/core/wrapper/layout/sticky/index.js new file mode 100644 index 000000000..e4d9a91be --- /dev/null +++ b/src/core/wrapper/layout/sticky/index.js @@ -0,0 +1,2 @@ +export { HorizontalStickyLayout } from "./sticky.horizontal"; +export { VerticalStickyLayout } from "./sticky.vertical"; diff --git a/src/core/wrapper/layout/sticky/sticky.horizontal.js b/src/core/wrapper/layout/sticky/sticky.horizontal.js index d88f28b6d..d4b15cd66 100644 --- a/src/core/wrapper/layout/sticky/sticky.horizontal.js +++ b/src/core/wrapper/layout/sticky/sticky.horizontal.js @@ -1,29 +1,37 @@ +import { shortcut } from "@/core/decorator"; +import { extend, count, isNotNull } from "@/core/2.base"; +import { VerticalAlign } from "@/core/constant"; +import { FlexHorizontalLayout } from "../flex"; + /** * 横向黏性布局 */ -BI.HorizontalStickyLayout = BI.inherit(BI.FlexHorizontalLayout, { - props: function () { - return BI.extend(BI.HorizontalStickyLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class HorizontalStickyLayout extends FlexHorizontalLayout { + static xtype = "bi.horizontal_sticky"; + + props() { + return extend(super.props(...arguments), { extraCls: "bi-h-sticky", scrollx: true, - // horizontalAlign: BI.HorizontalAlign.Stretch, - verticalAlign: BI.VerticalAlign.Stretch + // horizontalAlign: HorizontalAlign.Stretch, + verticalAlign: VerticalAlign.Stretch, }); - }, + } - _addElement: function (i, item) { - var o = this.options; - var w = BI.HorizontalStickyLayout.superclass._addElement.apply(this, arguments); - var columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; + _addElement(i, item) { + const o = this.options; + const w = super._addElement(...arguments); + let columnSize = o.columnSize.length > 0 ? o.columnSize[i] : item.width; if (o.columnSize.length > 0) { if (item.width >= 1 && o.columnSize[i] >= 1 && o.columnSize[i] !== item.width) { columnSize = null; } } if (columnSize !== "fill") { - var fillIndex; - BI.count(0, o.items.length, index => { - if (BI.isNotNull(fillIndex)) { + let fillIndex; + count(0, o.items.length, index => { + if (isNotNull(fillIndex)) { return; } if ((o.columnSize[index] === "fill" || o.items[index].width === "fill")) { @@ -41,15 +49,15 @@ BI.HorizontalStickyLayout = BI.inherit(BI.FlexHorizontalLayout, { w.element.css({ position: "sticky", zIndex: 1, - right: 0 + right: 0, }); } } else { w.element.css({ - overflow: "" + overflow: "", }); } + return w; } -}); -BI.shortcut("bi.horizontal_sticky", BI.HorizontalStickyLayout); +} diff --git a/src/core/wrapper/layout/sticky/sticky.vertical.js b/src/core/wrapper/layout/sticky/sticky.vertical.js index 71dc3ed8c..7a05bb78b 100644 --- a/src/core/wrapper/layout/sticky/sticky.vertical.js +++ b/src/core/wrapper/layout/sticky/sticky.vertical.js @@ -1,29 +1,37 @@ +import { shortcut } from "@/core/decorator"; +import { extend, count, isNotNull } from "@/core/2.base"; +import { HorizontalAlign } from "@/core/constant"; +import { FlexVerticalLayout } from "../flex"; + /** * 纵向黏性布局 */ -BI.VerticalStickyLayout = BI.inherit(BI.FlexVerticalLayout, { - props: function () { - return BI.extend(BI.VerticalStickyLayout.superclass.props.apply(this, arguments), { +@shortcut() +export class VerticalStickyLayout extends FlexVerticalLayout { + static xtype = "bi.vertical_sticky"; + + props() { + return extend(super.props(...arguments), { extraCls: "bi-v-sticky", scrolly: true, - horizontalAlign: BI.HorizontalAlign.Stretch, - // verticalAlign: BI.VerticalAlign.Stretch + horizontalAlign: HorizontalAlign.Stretch, + // verticalAlign: VerticalAlign.Stretch }); - }, + } - _addElement: function (i, item) { - var o = this.options; - var w = BI.VerticalStickyLayout.superclass._addElement.apply(this, arguments); - var rowSize = o.rowSize.length > 0 ? o.rowSize[i] : item.height; + _addElement(i, item) { + const o = this.options; + const w = super._addElement(...arguments); + let rowSize = o.rowSize.length > 0 ? o.rowSize[i] : item.height; if (o.rowSize.length > 0) { if (item.height >= 1 && o.rowSize[i] >= 1 && o.rowSize[i] !== item.height) { rowSize = null; } } if (rowSize !== "fill") { - var fillIndex; - BI.count(0, o.items.length, index => { - if (BI.isNotNull(fillIndex)) { + let fillIndex; + count(0, o.items.length, index => { + if (isNotNull(fillIndex)) { return; } if ((o.rowSize[index] === "fill" || o.items[index].height === "fill")) { @@ -41,15 +49,15 @@ BI.VerticalStickyLayout = BI.inherit(BI.FlexVerticalLayout, { w.element.css({ position: "sticky", zIndex: 1, - bottom: 0 + bottom: 0, }); } } else { w.element.css({ - overflow: "" + overflow: "", }); } + return w; } -}); -BI.shortcut("bi.vertical_sticky", BI.VerticalStickyLayout); +} From 99b19a440b283e7ad8ae12a22077ed7c0bb0fc04 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Tue, 10 Jan 2023 22:01:11 +0800 Subject: [PATCH 061/300] =?UTF-8?q?KERNEL-14073=20refactor:=20case/editor?= =?UTF-8?q?=E7=9A=84es6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.js | 8 + src/case/editor/editor.clear.js | 230 +++++++-------- src/case/editor/editor.defaulttext.js | 304 ++++++++++---------- src/case/editor/editor.shelter.js | 352 ++++++++++++----------- src/case/editor/editor.sign.js | 315 ++++++++++---------- src/case/editor/editor.state.js | 384 +++++++++++++------------ src/case/editor/editor.state.simple.js | 312 ++++++++++---------- src/case/editor/index.js | 6 + src/case/index.js | 3 + 9 files changed, 978 insertions(+), 936 deletions(-) create mode 100644 src/case/editor/index.js diff --git a/es6.js b/es6.js index d2be104d0..9c0b18bf4 100644 --- a/es6.js +++ b/es6.js @@ -89,6 +89,14 @@ collection.methods.forEach(el => { clzName, "createWidget", "Events", + "emptyFn", + "nextTick", + "bind", + "i18nText", + "isNotNull", + "isString", + "isNumber", + "isEmpty", ]; target.forEach(t => { diff --git a/src/case/editor/editor.clear.js b/src/case/editor/editor.clear.js index e18ab9599..c536e3ec1 100644 --- a/src/case/editor/editor.clear.js +++ b/src/case/editor/editor.clear.js @@ -1,28 +1,56 @@ +import { shortcut, Widget, extend, emptyFn, isKey, isFunction, createWidget, Controller, Events } from "@/core"; +import { Editor, IconButton } from "@/base"; + /** - * 有清楚按钮的文本框 + * 有清除按钮的文本框 * Created by GUY on 2015/9/29. - * @class BI.SmallTextEditor - * @extends BI.SearchEditor + * @class ClearEditor + * @extends Widget */ -BI.ClearEditor = BI.inherit(BI.Widget, { - _defaultConfig: function () { - var conf = BI.ClearEditor.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { +@shortcut() +export class ClearEditor extends Widget { + static xtype = "bi.clear_editor" + + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_FOCUS = "EVENT_FOCUS" + static EVENT_BLUR = "EVENT_BLUR" + static EVENT_CLICK = "EVENT_CLICK" + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" + static EVENT_SPACE = "EVENT_SPACE" + static EVENT_BACKSPACE = "EVENT_BACKSPACE" + static EVENT_CLEAR = "EVENT_CLEAR" + static EVENT_START = "EVENT_START" + static EVENT_PAUSE = "EVENT_PAUSE" + static EVENT_STOP = "EVENT_STOP" + static EVENT_CONFIRM = "EVENT_CONFIRM" + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM" + static EVENT_VALID = "EVENT_VALID" + static EVENT_ERROR = "EVENT_ERROR" + static EVENT_ENTER = "EVENT_ENTER" + static EVENT_RESTRICT = "EVENT_RESTRICT" + static EVENT_REMOVE = "EVENT_REMOVE" + static EVENT_EMPTY = "EVENT_EMPTY" + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { baseCls: "bi-clear-editor", height: 24, errorText: "", watermark: "", - validationChecker: BI.emptyFn, - quitChecker: BI.emptyFn - }); - }, - _init: function () { - var self = this, o = this.options; - o.value = BI.isFunction(o.value) ? this.__watch(o.value, function (context, newValue) { - self.setValue(newValue); + validationChecker: emptyFn, + quitChecker: emptyFn, + }); + } + + _init() { + const o = this.options; + o.value = isFunction(o.value) ? this.__watch(o.value, (context, newValue) => { + this.setValue(newValue); }) : o.value; - BI.ClearEditor.superclass._init.apply(this, arguments); - this.editor = BI.createWidget({ + super._init(...arguments); + this.editor = createWidget({ type: "bi.editor", simple: o.simple, height: o.height, @@ -34,150 +62,128 @@ BI.ClearEditor = BI.inherit(BI.Widget, { value: o.value, autoTrim: o.autoTrim, }); - this.clear = BI.createWidget({ + this.clear = createWidget({ type: "bi.icon_button", stopEvent: true, - invisible: !BI.isKey(o.value), - cls: "search-close-h-font" + invisible: !isKey(o.value), + cls: "search-close-h-font", }); - this.clear.on(BI.IconButton.EVENT_CHANGE, function () { - self.setValue(""); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.STOPEDIT); - self.fireEvent(BI.ClearEditor.EVENT_CLEAR); + this.clear.on(IconButton.EVENT_CHANGE, () => { + this.setValue(""); + this.fireEvent(Controller.EVENT_CHANGE, Events.STOPEDIT); + this.fireEvent(ClearEditor.EVENT_CLEAR); }); - BI.createWidget({ + createWidget({ element: this, type: "bi.htape", - items: [ - { - el: this.editor - }, - { - el: this.clear, - width: 24 - } - ] - }); - this.editor.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + items: [{ + el: this.editor, + }, + { + el: this.clear, + width: 24, + } + ], + }); + this.editor.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.editor.on(BI.Editor.EVENT_FOCUS, function () { - self.fireEvent(BI.ClearEditor.EVENT_FOCUS); + this.editor.on(Editor.EVENT_FOCUS, () => { + this.fireEvent(ClearEditor.EVENT_FOCUS); }); - this.editor.on(BI.Editor.EVENT_BLUR, function () { - self.fireEvent(BI.ClearEditor.EVENT_BLUR); + this.editor.on(Editor.EVENT_BLUR, () => { + this.fireEvent(ClearEditor.EVENT_BLUR); }); - this.editor.on(BI.Editor.EVENT_CLICK, function () { - self.fireEvent(BI.ClearEditor.EVENT_CLICK); + this.editor.on(Editor.EVENT_CLICK, () => { + this.fireEvent(ClearEditor.EVENT_CLICK); }); - this.editor.on(BI.Editor.EVENT_CHANGE, function () { - self._checkClear(); - self.fireEvent(BI.ClearEditor.EVENT_CHANGE); + this.editor.on(Editor.EVENT_CHANGE, () => { + this._checkClear(); + this.fireEvent(ClearEditor.EVENT_CHANGE); }); - this.editor.on(BI.Editor.EVENT_KEY_DOWN, function (v) { - self.fireEvent(BI.ClearEditor.EVENT_KEY_DOWN, v); + this.editor.on(Editor.EVENT_KEY_DOWN, v => { + this.fireEvent(ClearEditor.EVENT_KEY_DOWN, v); }); - this.editor.on(BI.Editor.EVENT_SPACE, function () { - self.fireEvent(BI.ClearEditor.EVENT_SPACE); + this.editor.on(Editor.EVENT_SPACE, () => { + this.fireEvent(ClearEditor.EVENT_SPACE); }); - this.editor.on(BI.Editor.EVENT_BACKSPACE, function () { - self.fireEvent(BI.ClearEditor.EVENT_BACKSPACE); + this.editor.on(Editor.EVENT_BACKSPACE, () => { + this.fireEvent(ClearEditor.EVENT_BACKSPACE); }); - this.editor.on(BI.Editor.EVENT_VALID, function () { - self.fireEvent(BI.ClearEditor.EVENT_VALID); + this.editor.on(Editor.EVENT_VALID, () => { + this.fireEvent(ClearEditor.EVENT_VALID); }); - this.editor.on(BI.Editor.EVENT_ERROR, function () { - self.fireEvent(BI.ClearEditor.EVENT_ERROR); + this.editor.on(Editor.EVENT_ERROR, () => { + this.fireEvent(ClearEditor.EVENT_ERROR); }); - this.editor.on(BI.Editor.EVENT_ENTER, function () { - self.fireEvent(BI.ClearEditor.EVENT_ENTER); + this.editor.on(Editor.EVENT_ENTER, () => { + this.fireEvent(ClearEditor.EVENT_ENTER); }); - this.editor.on(BI.Editor.EVENT_RESTRICT, function () { - self.fireEvent(BI.ClearEditor.EVENT_RESTRICT); + this.editor.on(Editor.EVENT_RESTRICT, () => { + this.fireEvent(ClearEditor.EVENT_RESTRICT); }); - this.editor.on(BI.Editor.EVENT_EMPTY, function () { - self._checkClear(); - self.fireEvent(BI.ClearEditor.EVENT_EMPTY); + this.editor.on(Editor.EVENT_EMPTY, () => { + this._checkClear(); + this.fireEvent(ClearEditor.EVENT_EMPTY); }); - this.editor.on(BI.Editor.EVENT_REMOVE, function () { - self.fireEvent(BI.ClearEditor.EVENT_REMOVE); + this.editor.on(Editor.EVENT_REMOVE, () => { + this.fireEvent(ClearEditor.EVENT_REMOVE); }); - this.editor.on(BI.Editor.EVENT_CONFIRM, function () { - self.fireEvent(BI.ClearEditor.EVENT_CONFIRM); + this.editor.on(Editor.EVENT_CONFIRM, () => { + this.fireEvent(ClearEditor.EVENT_CONFIRM); }); - this.editor.on(BI.Editor.EVENT_CHANGE_CONFIRM, function () { - self.fireEvent(BI.ClearEditor.EVENT_CHANGE_CONFIRM); + this.editor.on(Editor.EVENT_CHANGE_CONFIRM, () => { + this.fireEvent(ClearEditor.EVENT_CHANGE_CONFIRM); }); - this.editor.on(BI.Editor.EVENT_START, function () { - self.fireEvent(BI.ClearEditor.EVENT_START); + this.editor.on(Editor.EVENT_START, () => { + this.fireEvent(ClearEditor.EVENT_START); }); - this.editor.on(BI.Editor.EVENT_PAUSE, function () { - self.fireEvent(BI.ClearEditor.EVENT_PAUSE); + this.editor.on(Editor.EVENT_PAUSE, () => { + this.fireEvent(ClearEditor.EVENT_PAUSE); }); - this.editor.on(BI.Editor.EVENT_STOP, function () { - self.fireEvent(BI.ClearEditor.EVENT_STOP); + this.editor.on(Editor.EVENT_STOP, () => { + this.fireEvent(ClearEditor.EVENT_STOP); }); - }, + } - _checkClear: function () { + _checkClear() { if (!this.getValue()) { this.clear.invisible(); } else { this.clear.visible(); } - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.options.watermark = v; this.editor.setWaterMark(v); - }, + } - focus: function () { + focus() { this.editor.focus(); - }, + } - blur: function () { + blur() { this.editor.blur(); - }, + } - getValue: function () { + getValue() { if (this.isValid()) { return this.editor.getValue(); } - }, + } - setValue: function (v) { + setValue(v) { this.editor.setValue(v); - if (BI.isKey(v)) { + if (isKey(v)) { this.clear.visible(); } - }, + } - isValid: function () { + isValid() { return this.editor.isValid(); } -}); -BI.ClearEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.ClearEditor.EVENT_FOCUS = "EVENT_FOCUS"; -BI.ClearEditor.EVENT_BLUR = "EVENT_BLUR"; -BI.ClearEditor.EVENT_CLICK = "EVENT_CLICK"; -BI.ClearEditor.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.ClearEditor.EVENT_SPACE = "EVENT_SPACE"; -BI.ClearEditor.EVENT_BACKSPACE = "EVENT_BACKSPACE"; -BI.ClearEditor.EVENT_CLEAR = "EVENT_CLEAR"; - -BI.ClearEditor.EVENT_START = "EVENT_START"; -BI.ClearEditor.EVENT_PAUSE = "EVENT_PAUSE"; -BI.ClearEditor.EVENT_STOP = "EVENT_STOP"; -BI.ClearEditor.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.ClearEditor.EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; -BI.ClearEditor.EVENT_VALID = "EVENT_VALID"; -BI.ClearEditor.EVENT_ERROR = "EVENT_ERROR"; -BI.ClearEditor.EVENT_ENTER = "EVENT_ENTER"; -BI.ClearEditor.EVENT_RESTRICT = "EVENT_RESTRICT"; -BI.ClearEditor.EVENT_REMOVE = "EVENT_REMOVE"; -BI.ClearEditor.EVENT_EMPTY = "EVENT_EMPTY"; -BI.shortcut("bi.clear_editor", BI.ClearEditor); +} diff --git a/src/case/editor/editor.defaulttext.js b/src/case/editor/editor.defaulttext.js index fe88d27bb..7597347d7 100644 --- a/src/case/editor/editor.defaulttext.js +++ b/src/case/editor/editor.defaulttext.js @@ -1,11 +1,36 @@ + +import { shortcut, Widget, emptyFn, isKey, isFunction, createWidget, nextTick, Controller } from "@/core"; +import { Editor, TextButton } from "@/base"; + /** * dailer * 有默认提示文字的输入框 - * @class BI.DefaultTextEditor - * @extends BI.Widget + * @class DefaultTextEditor + * @extends Widget */ -BI.DefaultTextEditor = BI.inherit(BI.Widget, { - props: function () { +@shortcut() +export class DefaultTextEditor extends Widget { + static xtype = "bi.default_text_editor" + + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_FOCUS = "EVENT_FOCUS" + static EVENT_BLUR = "EVENT_BLUR" + static EVENT_CLICK = "EVENT_CLICK" + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" + static EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL" + static EVENT_START = "EVENT_START" + static EVENT_PAUSE = "EVENT_PAUSE" + static EVENT_STOP = "EVENT_STOP" + static EVENT_CONFIRM = "EVENT_CONFIRM" + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM" + static EVENT_VALID = "EVENT_VALID" + static EVENT_ERROR = "EVENT_ERROR" + static EVENT_ENTER = "EVENT_ENTER" + static EVENT_RESTRICT = "EVENT_RESTRICT" + static EVENT_SPACE = "EVENT_SPACE" + static EVENT_EMPTY = "EVENT_EMPTY" + + props() { return { baseCls: "bi-default-text-editor", hgap: 4, @@ -14,21 +39,21 @@ BI.DefaultTextEditor = BI.inherit(BI.Widget, { rgap: 0, tgap: 0, bgap: 0, - validationChecker: BI.emptyFn, - quitChecker: BI.emptyFn, + validationChecker: emptyFn, + quitChecker: emptyFn, allowBlank: true, watermark: "", errorText: "", height: 24, defaultText: "", // 默认显示值,默认显示值与显示值的区别是默认显示值标记灰色 text: "", // 显示值 - el: {} + el: {}, }; - }, + } - render: function () { - var self = this, o = this.options; - this.editor = BI.createWidget(o.el, { + render() { + const o = this.options; + this.editor = createWidget(o.el, { type: "bi.editor", simple: o.simple, height: o.height, @@ -48,239 +73,218 @@ BI.DefaultTextEditor = BI.inherit(BI.Widget, { autoTrim: o.autoTrim, }); - var showText = BI.isFunction(o.text) ? o.text() : o.text; + const showText = isFunction(o.text) ? o.text() : o.text; - this.text = BI.createWidget({ + this.text = createWidget({ type: "bi.text_button", - cls: BI.isKey(showText) ? "tip-text-style" : "bi-water-mark tip-text-style", + cls: isKey(showText) ? "tip-text-style" : "bi-water-mark tip-text-style", textAlign: "left", height: o.height, text: showText || o.defaultText, hgap: o.hgap + 2, - handler: function () { - self._showInput(); - self.editor.focus(); - self.editor.setValue(""); + handler: () => { + this._showInput(); + this.editor.focus(); + this.editor.setValue(""); }, title: o.title, warningTitle: o.warningTitle, - tipType: o.tipType + tipType: o.tipType, }); - this.text.on(BI.TextButton.EVENT_CHANGE, function () { - BI.nextTick(function () { - self.fireEvent(BI.DefaultTextEditor.EVENT_CLICK_LABEL); + this.text.on(TextButton.EVENT_CHANGE, () => { + nextTick(() => { + this.fireEvent(DefaultTextEditor.EVENT_CLICK_LABEL); }); }); - this.editor.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.editor.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.editor.on(BI.Editor.EVENT_FOCUS, function () { - self.fireEvent(BI.DefaultTextEditor.EVENT_FOCUS, arguments); + this.editor.on(Editor.EVENT_FOCUS, (...args) => { + this.fireEvent(DefaultTextEditor.EVENT_FOCUS, ...args); }); - this.editor.on(BI.Editor.EVENT_BLUR, function () { - self.fireEvent(BI.DefaultTextEditor.EVENT_BLUR, arguments); + this.editor.on(Editor.EVENT_BLUR, (...args) => { + this.fireEvent(DefaultTextEditor.EVENT_BLUR, ...args); }); - this.editor.on(BI.Editor.EVENT_CLICK, function () { - self.fireEvent(BI.DefaultTextEditor.EVENT_CLICK, arguments); + this.editor.on(Editor.EVENT_CLICK, (...args) => { + this.fireEvent(DefaultTextEditor.EVENT_CLICK, ...args); }); - this.editor.on(BI.Editor.EVENT_CHANGE, function () { - self.fireEvent(BI.DefaultTextEditor.EVENT_CHANGE, arguments); + this.editor.on(Editor.EVENT_CHANGE, (...args) => { + this.fireEvent(DefaultTextEditor.EVENT_CHANGE, ...args); }); - this.editor.on(BI.Editor.EVENT_KEY_DOWN, function (v) { - self.fireEvent(BI.DefaultTextEditor.EVENT_KEY_DOWN, arguments); + this.editor.on(Editor.EVENT_KEY_DOWN, (...args) => { + this.fireEvent(DefaultTextEditor.EVENT_KEY_DOWN, ...args); }); - this.editor.on(BI.Editor.EVENT_VALID, function () { - self.fireEvent(BI.DefaultTextEditor.EVENT_VALID, arguments); + this.editor.on(Editor.EVENT_VALID, (...args) => { + this.fireEvent(DefaultTextEditor.EVENT_VALID, ...args); }); - this.editor.on(BI.Editor.EVENT_CONFIRM, function () { - self._showHint(); - self.fireEvent(BI.DefaultTextEditor.EVENT_CONFIRM, arguments); + this.editor.on(Editor.EVENT_CONFIRM, (...args) => { + this._showHint(); + this.fireEvent(DefaultTextEditor.EVENT_CONFIRM, ...args); }); - this.editor.on(BI.Editor.EVENT_CHANGE_CONFIRM, function () { - self._showHint(); - self.fireEvent(BI.DefaultTextEditor.EVENT_CHANGE_CONFIRM, arguments); + this.editor.on(Editor.EVENT_CHANGE_CONFIRM, (...args) => { + this._showHint(); + this.fireEvent(DefaultTextEditor.EVENT_CHANGE_CONFIRM, ...args); }); - this.editor.on(BI.Editor.EVENT_START, function () { - self.fireEvent(BI.DefaultTextEditor.EVENT_START, arguments); + this.editor.on(Editor.EVENT_START, (...args) => { + this.fireEvent(DefaultTextEditor.EVENT_START, ...args); }); - this.editor.on(BI.Editor.EVENT_PAUSE, function () { - self.fireEvent(BI.DefaultTextEditor.EVENT_PAUSE, arguments); + this.editor.on(Editor.EVENT_PAUSE, (...args) => { + this.fireEvent(DefaultTextEditor.EVENT_PAUSE, ...args); }); - this.editor.on(BI.Editor.EVENT_STOP, function () { - self.fireEvent(BI.DefaultTextEditor.EVENT_STOP, arguments); + this.editor.on(Editor.EVENT_STOP, (...args) => { + this.fireEvent(DefaultTextEditor.EVENT_STOP, ...args); }); - this.editor.on(BI.Editor.EVENT_SPACE, function () { - self.fireEvent(BI.DefaultTextEditor.EVENT_SPACE, arguments); + this.editor.on(Editor.EVENT_SPACE, (...args) => { + this.fireEvent(DefaultTextEditor.EVENT_SPACE, ...args); }); - this.editor.on(BI.Editor.EVENT_ERROR, function () { - self.fireEvent(BI.DefaultTextEditor.EVENT_ERROR, arguments); + this.editor.on(Editor.EVENT_ERROR, (...args) => { + this.fireEvent(DefaultTextEditor.EVENT_ERROR, ...args); }); - this.editor.on(BI.Editor.EVENT_ENTER, function () { - self.fireEvent(BI.DefaultTextEditor.EVENT_ENTER, arguments); + this.editor.on(Editor.EVENT_ENTER, (...args) => { + this.fireEvent(DefaultTextEditor.EVENT_ENTER, ...args); }); - this.editor.on(BI.Editor.EVENT_RESTRICT, function () { - self.fireEvent(BI.DefaultTextEditor.EVENT_RESTRICT, arguments); + this.editor.on(Editor.EVENT_RESTRICT, (...args) => { + this.fireEvent(DefaultTextEditor.EVENT_RESTRICT, ...args); }); - this.editor.on(BI.Editor.EVENT_EMPTY, function () { - self.fireEvent(BI.DefaultTextEditor.EVENT_EMPTY, arguments); + this.editor.on(Editor.EVENT_EMPTY, (...args) => { + this.fireEvent(DefaultTextEditor.EVENT_EMPTY, ...args); }); return { type: "bi.absolute", - items: [ - { - el: this.editor, - left: 0, - right: 0, - top: 0, - bottom: 0 - }, { - el: this.text, - left: 0, - right: 0, - top: 0, - bottom: 0 - } - ] + items: [{ + el: this.editor, + left: 0, + right: 0, + top: 0, + bottom: 0, + }, { + el: this.text, + left: 0, + right: 0, + top: 0, + bottom: 0, + }], }; - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.options.watermark = v; this.editor.setWaterMark(v); - }, + } - setTitle: function (title) { + setTitle(title) { this.text.setTitle(title); - }, + } - setWarningTitle: function (title) { + setWarningTitle(title) { this.text.setWarningTitle(title); - }, + } - doRedMark: function () { - if (this.editor.getValue() === "" && BI.isKey(this.options.watermark)) { + doRedMark() { + if (this.editor.getValue() === "" && isKey(this.options.watermark)) { return; } - this.text.doRedMark.apply(this.text, arguments); - }, + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doHighLight: function () { - if (this.editor.getValue() === "" && BI.isKey(this.options.watermark)) { + doHighLight() { + if (this.editor.getValue() === "" && isKey(this.options.watermark)) { return; } - this.text.doHighLight.apply(this.text, arguments); - }, + this.text.doHighLight(...arguments); + } - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - }, + unHighLight() { + this.text.unHighLight(...arguments); + } - focus: function () { + focus() { if (this.options.disabled === false) { this._showInput(); this.editor.focus(); } - }, + } - blur: function () { + blur() { this.editor.blur(); this._showHint(); - }, + } - _showInput: function () { + _showInput() { this.editor.visible(); this.text.invisible(); - }, + } - _showHint: function () { + _showHint() { this.editor.invisible(); this.text.visible(); - }, + } - _setText: function (v) { + _setText(v) { this.text.setText(v); this.text.setTitle(v); - }, + } - isValid: function () { + isValid() { return this.editor.isValid(); - }, + } - setErrorText: function (text) { + setErrorText(text) { this.editor.setErrorText(text); - }, + } - getErrorText: function () { + getErrorText() { return this.editor.getErrorText(); - }, + } - isEditing: function () { + isEditing() { return this.editor.isEditing(); - }, + } - getLastValidValue: function () { + getLastValidValue() { return this.editor.getLastValidValue(); - }, + } - getLastChangedValue: function () { + getLastChangedValue() { return this.editor.getLastChangedValue(); - }, + } - setValue: function (k) { + setValue(k) { this.editor.setValue(k); - }, + } - getValue: function () { + getValue() { return this.editor.getValue(); - }, + } - getState: function () { + getState() { return this.text.getValue(); - }, + } - setState: function (v) { - var o = this.options; - if (BI.isKey(v)) { + setState(v) { + const o = this.options; + if (isKey(v)) { this.text.setText(v); this.text.element.removeClass("bi-water-mark"); + return; } this.text.setText(o.defaultText); this.text.element.addClass("bi-water-mark"); - }, + } - setTipType: function (v) { + setTipType(v) { this.text.options.tipType = v; - }, + } - getText: function () { + getText() { return this.text.getText(); } -}); -BI.DefaultTextEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.DefaultTextEditor.EVENT_FOCUS = "EVENT_FOCUS"; -BI.DefaultTextEditor.EVENT_BLUR = "EVENT_BLUR"; -BI.DefaultTextEditor.EVENT_CLICK = "EVENT_CLICK"; -BI.DefaultTextEditor.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.DefaultTextEditor.EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL"; - -BI.DefaultTextEditor.EVENT_START = "EVENT_START"; -BI.DefaultTextEditor.EVENT_PAUSE = "EVENT_PAUSE"; -BI.DefaultTextEditor.EVENT_STOP = "EVENT_STOP"; -BI.DefaultTextEditor.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.DefaultTextEditor.EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; -BI.DefaultTextEditor.EVENT_VALID = "EVENT_VALID"; -BI.DefaultTextEditor.EVENT_ERROR = "EVENT_ERROR"; -BI.DefaultTextEditor.EVENT_ENTER = "EVENT_ENTER"; -BI.DefaultTextEditor.EVENT_RESTRICT = "EVENT_RESTRICT"; -BI.DefaultTextEditor.EVENT_SPACE = "EVENT_SPACE"; -BI.DefaultTextEditor.EVENT_EMPTY = "EVENT_EMPTY"; - -BI.shortcut("bi.default_text_editor", BI.DefaultTextEditor); +} diff --git a/src/case/editor/editor.shelter.js b/src/case/editor/editor.shelter.js index 4cb8e4d75..7517c6320 100644 --- a/src/case/editor/editor.shelter.js +++ b/src/case/editor/editor.shelter.js @@ -1,37 +1,62 @@ +import { shortcut, Widget, extend, emptyFn, isFunction, createWidget, Controller, isKey, nextTick, bind } from "@/core"; +import { Editor, TextButton } from "@/base"; + /** * 带标记的文本框 * Created by GUY on 2016/1/25. - * @class BI.ShelterEditor - * @extends BI.Widget + * @class ShelterEditor + * @extends Widget */ -BI.ShelterEditor = BI.inherit(BI.Widget, { - _defaultConfig: function () { - var conf = BI.ShelterEditor.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-shelter-editor", +@shortcut() +export class ShelterEditor extends Widget { + static xtype = "bi.shelter_editor" + + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_FOCUS = "EVENT_FOCUS" + static EVENT_BLUR = "EVENT_BLUR" + static EVENT_CLICK = "EVENT_CLICK" + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" + static EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL" + static EVENT_START = "EVENT_START" + static EVENT_PAUSE = "EVENT_PAUSE" + static EVENT_STOP = "EVENT_STOP" + static EVENT_CONFIRM = "EVENT_CONFIRM" + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM" + static EVENT_VALID = "EVENT_VALID" + static EVENT_ERROR = "EVENT_ERROR" + static EVENT_ENTER = "EVENT_ENTER" + static EVENT_RESTRICT = "EVENT_RESTRICT" + static EVENT_SPACE = "EVENT_SPACE" + static EVENT_EMPTY = "EVENT_EMPTY" + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-shelter-editor`, hgap: 4, vgap: 2, lgap: 0, rgap: 0, tgap: 0, bgap: 0, - validationChecker: BI.emptyFn, - quitChecker: BI.emptyFn, + validationChecker: emptyFn, + quitChecker: emptyFn, allowBlank: true, watermark: "", errorText: "", height: 24, - textAlign: "left" + textAlign: "left", }); - }, - - _init: function () { - var self = this, o = this.options; - o.value = BI.isFunction(o.value) ? this.__watch(o.value, function (context, newValue) { - self.setValue(newValue); + } + + _init() { + const o = this.options; + o.value = isFunction(o.value) ? this.__watch(o.value, (context, newValue) => { + this.setValue(newValue); }) : o.value; - BI.ShelterEditor.superclass._init.apply(this, arguments); - this.editor = BI.createWidget({ + super._init(...arguments); + this.editor = createWidget({ type: "bi.editor", simple: o.simple, height: o.height, @@ -49,7 +74,7 @@ BI.ShelterEditor = BI.inherit(BI.Widget, { errorText: o.errorText, autoTrim: o.autoTrim, }); - this.text = BI.createWidget({ + this.text = createWidget({ type: "bi.text_button", cls: "shelter-editor-text", title: o.title, @@ -57,92 +82,90 @@ BI.ShelterEditor = BI.inherit(BI.Widget, { tipType: o.tipType, textAlign: o.textAlign, height: o.height, - hgap: o.hgap + 2 + hgap: o.hgap + 2, }); - this.text.on(BI.Controller.EVENT_CHANGE, function () { - arguments[2] = self; - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.text.on(Controller.EVENT_CHANGE, (...args) => { + args[2] = this; + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.text.on(BI.TextButton.EVENT_CHANGE, function () { - self.fireEvent(BI.ShelterEditor.EVENT_CLICK_LABEL); + this.text.on(TextButton.EVENT_CHANGE, () => { + this.fireEvent(ShelterEditor.EVENT_CLICK_LABEL); }); - this.editor.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.editor.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.editor.on(BI.Editor.EVENT_FOCUS, function () { - self.fireEvent(BI.ShelterEditor.EVENT_FOCUS, arguments); + this.editor.on(Editor.EVENT_FOCUS, (...args) => { + this.fireEvent(ShelterEditor.EVENT_FOCUS, ...args); }); - this.editor.on(BI.Editor.EVENT_BLUR, function () { - self.fireEvent(BI.ShelterEditor.EVENT_BLUR, arguments); + this.editor.on(Editor.EVENT_BLUR, (...args) => { + this.fireEvent(ShelterEditor.EVENT_BLUR, ...args); }); - this.editor.on(BI.Editor.EVENT_CLICK, function () { - self.fireEvent(BI.ShelterEditor.EVENT_CLICK, arguments); + this.editor.on(Editor.EVENT_CLICK, (...args) => { + this.fireEvent(ShelterEditor.EVENT_CLICK, ...args); }); - this.editor.on(BI.Editor.EVENT_CHANGE, function () { - self.fireEvent(BI.ShelterEditor.EVENT_CHANGE, arguments); + this.editor.on(Editor.EVENT_CHANGE, (...args) => { + this.fireEvent(ShelterEditor.EVENT_CHANGE, ...args); }); - this.editor.on(BI.Editor.EVENT_KEY_DOWN, function (v) { - self.fireEvent(BI.ShelterEditor.EVENT_KEY_DOWN, arguments); + this.editor.on(Editor.EVENT_KEY_DOWN, (...args) => { + this.fireEvent(ShelterEditor.EVENT_KEY_DOWN, ...args); }); - this.editor.on(BI.Editor.EVENT_VALID, function () { - self.fireEvent(BI.ShelterEditor.EVENT_VALID, arguments); + this.editor.on(Editor.EVENT_VALID, (...args) => { + this.fireEvent(ShelterEditor.EVENT_VALID, ...args); }); - this.editor.on(BI.Editor.EVENT_CONFIRM, function () { - self._showHint(); - self._checkText(); - self.fireEvent(BI.ShelterEditor.EVENT_CONFIRM, arguments); + this.editor.on(Editor.EVENT_CONFIRM, (...args) => { + this._showHint(); + this._checkText(); + this.fireEvent(ShelterEditor.EVENT_CONFIRM, ...args); }); - this.editor.on(BI.Editor.EVENT_CHANGE_CONFIRM, function () { - self._showHint(); - self._checkText(); - self.fireEvent(BI.ShelterEditor.EVENT_CHANGE_CONFIRM, arguments); + this.editor.on(Editor.EVENT_CHANGE_CONFIRM, (...args) => { + this._showHint(); + this._checkText(); + this.fireEvent(ShelterEditor.EVENT_CHANGE_CONFIRM, ...args); }); - this.editor.on(BI.Editor.EVENT_START, function () { - self.fireEvent(BI.ShelterEditor.EVENT_START, arguments); + this.editor.on(Editor.EVENT_START, (...args) => { + this.fireEvent(ShelterEditor.EVENT_START, ...args); }); - this.editor.on(BI.Editor.EVENT_PAUSE, function () { - self.fireEvent(BI.ShelterEditor.EVENT_PAUSE, arguments); + this.editor.on(Editor.EVENT_PAUSE, (...args) => { + this.fireEvent(ShelterEditor.EVENT_PAUSE, ...args); }); - this.editor.on(BI.Editor.EVENT_STOP, function () { - self.fireEvent(BI.ShelterEditor.EVENT_STOP, arguments); + this.editor.on(Editor.EVENT_STOP, (...args) => { + this.fireEvent(ShelterEditor.EVENT_STOP, ...args); }); - this.editor.on(BI.Editor.EVENT_SPACE, function () { - self.fireEvent(BI.ShelterEditor.EVENT_SPACE, arguments); + this.editor.on(Editor.EVENT_SPACE, (...args) => { + this.fireEvent(ShelterEditor.EVENT_SPACE, ...args); }); - this.editor.on(BI.Editor.EVENT_ERROR, function () { - self._checkText(); - self.fireEvent(BI.ShelterEditor.EVENT_ERROR, arguments); + this.editor.on(Editor.EVENT_ERROR, (...args) => { + this._checkText(); + this.fireEvent(ShelterEditor.EVENT_ERROR, ...args); }); - this.editor.on(BI.Editor.EVENT_ENTER, function () { - self.fireEvent(BI.ShelterEditor.EVENT_ENTER, arguments); + this.editor.on(Editor.EVENT_ENTER, (...args) => { + this.fireEvent(ShelterEditor.EVENT_ENTER, ...args); }); - this.editor.on(BI.Editor.EVENT_RESTRICT, function () { - self.fireEvent(BI.ShelterEditor.EVENT_RESTRICT, arguments); + this.editor.on(Editor.EVENT_RESTRICT, (...args) => { + this.fireEvent(ShelterEditor.EVENT_RESTRICT, ...args); }); - this.editor.on(BI.Editor.EVENT_EMPTY, function () { - self.fireEvent(BI.ShelterEditor.EVENT_EMPTY, arguments); + this.editor.on(Editor.EVENT_EMPTY, (...args) => { + this.fireEvent(ShelterEditor.EVENT_EMPTY, ...args); }); - BI.createWidget({ + createWidget({ type: "bi.absolute", element: this, - items: [ - { - el: this.text, - inset: 0, - }, { - el: this.editor, - inset: 0, - } - ] + items: [{ + el: this.text, + inset: 0, + }, { + el: this.editor, + inset: 0, + }], }); this._showHint(); - self._checkText(); - }, - - _checkText: function () { - var o = this.options; - BI.nextTick(BI.bind(function () { + this._checkText(); + } + + _checkText() { + const o = this.options; + nextTick(bind(function () { if (this.editor.getValue() === "") { this.text.setValue(o.watermark || ""); this.text.element.addClass("bi-water-mark"); @@ -150,130 +173,109 @@ BI.ShelterEditor = BI.inherit(BI.Widget, { this.text.setValue(this.editor.getValue()); this.text.element.removeClass("bi-water-mark"); } - BI.isKey(o.keyword) && this.text.doRedMark(o.keyword); + isKey(o.keyword) && this.text.doRedMark(o.keyword); }, this)); - }, - - _showInput: function () { + } + + _showInput() { this.editor.visible(); this.text.invisible(); - }, - - _showHint: function () { + } + + _showHint() { this.editor.invisible(); this.text.visible(); - }, - - setWaterMark: function (v) { + } + + setWaterMark(v) { this.options.watermark = v; this.editor.setWaterMark(v); - }, - - setTitle: function (title) { + } + + setTitle(title) { this.text.setTitle(title); - }, - - setWarningTitle: function (title) { + } + + setWarningTitle(title) { this.text.setWarningTitle(title); - }, - - focus: function () { + } + + focus() { this._showInput(); this.editor.focus(); - }, - - blur: function () { + } + + blur() { this.editor.blur(); this._showHint(); this._checkText(); - }, - - doRedMark: function () { - if (this.editor.getValue() === "" && BI.isKey(this.options.watermark)) { + } + + doRedMark() { + if (this.editor.getValue() === "" && isKey(this.options.watermark)) { return; } - this.text.doRedMark.apply(this.text, arguments); - }, - - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, - - doHighLight: function () { - if (this.editor.getValue() === "" && BI.isKey(this.options.watermark)) { + this.text.doRedMark(...arguments); + } + + unRedMark() { + this.text.unRedMark(...arguments); + } + + doHighLight() { + if (this.editor.getValue() === "" && isKey(this.options.watermark)) { return; } - this.text.doHighLight.apply(this.text, arguments); - }, - - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - }, - - isValid: function () { + this.text.doHighLight(...arguments); + } + + unHighLight() { + this.text.unHighLight(...arguments); + } + + isValid() { return this.editor.isValid(); - }, - - setErrorText: function (text) { + } + + setErrorText(text) { this.editor.setErrorText(text); - }, - - getErrorText: function () { + } + + getErrorText() { return this.editor.getErrorText(); - }, - - isEditing: function () { + } + + isEditing() { return this.editor.isEditing(); - }, - - getLastValidValue: function () { + } + + getLastValidValue() { return this.editor.getLastValidValue(); - }, - - getLastChangedValue: function () { + } + + getLastChangedValue() { return this.editor.getLastChangedValue(); - }, - - setTextStyle: function (style) { + } + + setTextStyle(style) { this.text.setStyle(style); - }, - - setValue: function (k) { - var o = this.options; + } + + setValue(k) { this.editor.setValue(k); this._checkText(); - }, - - getValue: function () { + } + + getValue() { return this.editor.getValue(); - }, - - getState: function () { + } + + getState() { return this.text.getValue(); - }, - - setState: function (v) { + } + + setState(v) { this._showHint(); this.text.setValue(v); } -}); -BI.ShelterEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.ShelterEditor.EVENT_FOCUS = "EVENT_FOCUS"; -BI.ShelterEditor.EVENT_BLUR = "EVENT_BLUR"; -BI.ShelterEditor.EVENT_CLICK = "EVENT_CLICK"; -BI.ShelterEditor.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.ShelterEditor.EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL"; - -BI.ShelterEditor.EVENT_START = "EVENT_START"; -BI.ShelterEditor.EVENT_PAUSE = "EVENT_PAUSE"; -BI.ShelterEditor.EVENT_STOP = "EVENT_STOP"; -BI.ShelterEditor.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.ShelterEditor.EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; -BI.ShelterEditor.EVENT_VALID = "EVENT_VALID"; -BI.ShelterEditor.EVENT_ERROR = "EVENT_ERROR"; -BI.ShelterEditor.EVENT_ENTER = "EVENT_ENTER"; -BI.ShelterEditor.EVENT_RESTRICT = "EVENT_RESTRICT"; -BI.ShelterEditor.EVENT_SPACE = "EVENT_SPACE"; -BI.ShelterEditor.EVENT_EMPTY = "EVENT_EMPTY"; - -BI.shortcut("bi.shelter_editor", BI.ShelterEditor); +} diff --git a/src/case/editor/editor.sign.js b/src/case/editor/editor.sign.js index a624d78a2..08feca088 100644 --- a/src/case/editor/editor.sign.js +++ b/src/case/editor/editor.sign.js @@ -1,37 +1,63 @@ +import { shortcut, Widget, extend, emptyFn, isFunction, createWidget, nextTick, isKey, bind, Controller } from "@/core"; +import { Editor, TextButton } from "@/base"; + /** * 带标记的文本框 * Created by GUY on 2015/8/28. - * @class BI.SignEditor - * @extends BI.Widget + * @class SignEditor + * @extends Widget */ -BI.SignEditor = BI.inherit(BI.Widget, { - _defaultConfig: function () { - var conf = BI.SignEditor.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-sign-editor", +@shortcut() +export class SignEditor extends Widget { + static xtype = "bi.sign_editor" + + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_FOCUS = "EVENT_FOCUS" + static EVENT_BLUR = "EVENT_BLUR" + static EVENT_CLICK = "EVENT_CLICK" + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" + static EVENT_QUICK_DOWN = "EVENT_QUICK_DOWN" + static EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL" + static EVENT_START = "EVENT_START" + static EVENT_PAUSE = "EVENT_PAUSE" + static EVENT_STOP = "EVENT_STOP" + static EVENT_CONFIRM = "EVENT_CONFIRM" + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM" + static EVENT_VALID = "EVENT_VALID" + static EVENT_ERROR = "EVENT_ERROR" + static EVENT_ENTER = "EVENT_ENTER" + static EVENT_RESTRICT = "EVENT_RESTRICT" + static EVENT_SPACE = "EVENT_SPACE" + static EVENT_EMPTY = "EVENT_EMPTY" + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-sign-editor`, hgap: 4, vgap: 2, lgap: 0, rgap: 0, tgap: 0, bgap: 0, - validationChecker: BI.emptyFn, - quitChecker: BI.emptyFn, + validationChecker: emptyFn, + quitChecker: emptyFn, allowBlank: true, watermark: "", errorText: "", textAlign: "left", - height: 24 + height: 24, }); - }, + } - _init: function () { - var self = this, o = this.options; - o.value = BI.isFunction(o.value) ? this.__watch(o.value, function (context, newValue) { - self.setValue(newValue); + _init() { + const o = this.options; + o.value = isFunction(o.value) ? this.__watch(o.value, (context, newValue) => { + this.setValue(newValue); }) : o.value; - BI.SignEditor.superclass._init.apply(this, arguments); - this.editor = BI.createWidget({ + super._init(...arguments); + this.editor = createWidget({ type: "bi.editor", simple: o.simple, height: o.height, @@ -49,7 +75,7 @@ BI.SignEditor = BI.inherit(BI.Widget, { errorText: o.errorText, autoTrim: o.autoTrim, }); - this.text = BI.createWidget({ + this.text = createWidget({ type: "bi.text_button", cls: "sign-editor-text", title: o.title, @@ -58,229 +84,206 @@ BI.SignEditor = BI.inherit(BI.Widget, { textAlign: o.textAlign, height: o.height, hgap: o.hgap + 2, - handler: function () { - self._showInput(); - self.editor.focus(); - self.editor.selectAll(); - } + handler: () => { + this._showInput(); + this.editor.focus(); + this.editor.selectAll(); + }, }); - this.text.on(BI.TextButton.EVENT_CHANGE, function () { - BI.nextTick(function () { - self.fireEvent(BI.SignEditor.EVENT_CLICK_LABEL); + this.text.on(TextButton.EVENT_CHANGE, () => { + nextTick(() => { + this.fireEvent(SignEditor.EVENT_CLICK_LABEL); }); }); - this.editor.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.editor.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.editor.on(BI.Editor.EVENT_FOCUS, function () { - self.fireEvent(BI.SignEditor.EVENT_FOCUS, arguments); + this.editor.on(Editor.EVENT_FOCUS, (...args) => { + this.fireEvent(SignEditor.EVENT_FOCUS, ...args); }); - this.editor.on(BI.Editor.EVENT_BLUR, function () { - self.fireEvent(BI.SignEditor.EVENT_BLUR, arguments); + this.editor.on(Editor.EVENT_BLUR, (...args) => { + this.fireEvent(SignEditor.EVENT_BLUR, ...args); }); - this.editor.on(BI.Editor.EVENT_CLICK, function () { - self.fireEvent(BI.SignEditor.EVENT_CLICK, arguments); + this.editor.on(Editor.EVENT_CLICK, (...args) => { + this.fireEvent(SignEditor.EVENT_CLICK, ...args); }); - this.editor.on(BI.Editor.EVENT_CHANGE, function () { - self.fireEvent(BI.SignEditor.EVENT_CHANGE, arguments); + this.editor.on(Editor.EVENT_CHANGE, (...args) => { + this.fireEvent(SignEditor.EVENT_CHANGE, ...args); }); - this.editor.on(BI.Editor.EVENT_KEY_DOWN, function (v) { - self.fireEvent(BI.SignEditor.EVENT_KEY_DOWN, arguments); + this.editor.on(Editor.EVENT_KEY_DOWN, (...args) => { + this.fireEvent(SignEditor.EVENT_KEY_DOWN, ...args); }); - this.editor.on(BI.Editor.EVENT_QUICK_DOWN, function () { - self.fireEvent(BI.SignEditor.EVENT_QUICK_DOWN, arguments); + this.editor.on(Editor.EVENT_QUICK_DOWN, (...args) => { + this.fireEvent(SignEditor.EVENT_QUICK_DOWN, ...args); }); - this.editor.on(BI.Editor.EVENT_VALID, function () { - self.fireEvent(BI.SignEditor.EVENT_VALID, arguments); + this.editor.on(Editor.EVENT_VALID, (...args) => { + this.fireEvent(SignEditor.EVENT_VALID, ...args); }); - this.editor.on(BI.Editor.EVENT_CONFIRM, function () { - self._showHint(); - self._checkText(); - self.fireEvent(BI.SignEditor.EVENT_CONFIRM, arguments); + this.editor.on(Editor.EVENT_CONFIRM, (...args) => { + this._showHint(); + this._checkText(); + this.fireEvent(SignEditor.EVENT_CONFIRM, ...args); }); - this.editor.on(BI.Editor.EVENT_CHANGE_CONFIRM, function () { - self._showHint(); - self._checkText(); - self.fireEvent(BI.SignEditor.EVENT_CHANGE_CONFIRM, arguments); + this.editor.on(Editor.EVENT_CHANGE_CONFIRM, (...args) => { + this._showHint(); + this._checkText(); + this.fireEvent(SignEditor.EVENT_CHANGE_CONFIRM, ...args); }); - this.editor.on(BI.Editor.EVENT_START, function () { - self.fireEvent(BI.SignEditor.EVENT_START, arguments); + this.editor.on(Editor.EVENT_START, (...args) => { + this.fireEvent(SignEditor.EVENT_START, ...args); }); - this.editor.on(BI.Editor.EVENT_PAUSE, function () { - self.fireEvent(BI.SignEditor.EVENT_PAUSE, arguments); + this.editor.on(Editor.EVENT_PAUSE, (...args) => { + this.fireEvent(SignEditor.EVENT_PAUSE, ...args); }); - this.editor.on(BI.Editor.EVENT_STOP, function () { - self.fireEvent(BI.SignEditor.EVENT_STOP, arguments); + this.editor.on(Editor.EVENT_STOP, (...args) => { + this.fireEvent(SignEditor.EVENT_STOP, ...args); }); - this.editor.on(BI.Editor.EVENT_SPACE, function () { - self.fireEvent(BI.SignEditor.EVENT_SPACE, arguments); + this.editor.on(Editor.EVENT_SPACE, (...args) => { + this.fireEvent(SignEditor.EVENT_SPACE, ...args); }); - this.editor.on(BI.Editor.EVENT_ERROR, function () { - self._checkText(); - self.fireEvent(BI.SignEditor.EVENT_ERROR, arguments); + this.editor.on(Editor.EVENT_ERROR, (...args) => { + this._checkText(); + this.fireEvent(SignEditor.EVENT_ERROR, ...args); }); - this.editor.on(BI.Editor.EVENT_ENTER, function () { - self.fireEvent(BI.SignEditor.EVENT_ENTER, arguments); + this.editor.on(Editor.EVENT_ENTER, (...args) => { + this.fireEvent(SignEditor.EVENT_ENTER, ...args); }); - this.editor.on(BI.Editor.EVENT_RESTRICT, function () { - self.fireEvent(BI.SignEditor.EVENT_RESTRICT, arguments); + this.editor.on(Editor.EVENT_RESTRICT, (...args) => { + this.fireEvent(SignEditor.EVENT_RESTRICT, ...args); }); - this.editor.on(BI.Editor.EVENT_EMPTY, function () { - self.fireEvent(BI.SignEditor.EVENT_EMPTY, arguments); + this.editor.on(Editor.EVENT_EMPTY, (...args) => { + this.fireEvent(SignEditor.EVENT_EMPTY, ...args); }); - BI.createWidget({ + createWidget({ type: "bi.absolute", element: this, - items: [ - { - el: this.text, - inset: 0, - }, { - el: this.editor, - inset: 0, - } - ] + items: [{ + el: this.text, + inset: 0, + }, { + el: this.editor, + inset: 0, + }], }); this._showHint(); - self._checkText(); - }, + this._checkText(); + } - _checkText: function () { - var o = this.options; - BI.nextTick(BI.bind(function () { + _checkText() { + const o = this.options; + nextTick(bind(function () { if (this.editor.getValue() === "") { this.text.setValue(o.watermark || ""); this.text.element.addClass("bi-water-mark"); } else { this.text.setValue(this.editor.getValue()); this.text.element.removeClass("bi-water-mark"); - BI.isKey(o.keyword) && this.text.doRedMark(o.keyword); + isKey(o.keyword) && this.text.doRedMark(o.keyword); } }, this)); - }, + } - _showInput: function () { + _showInput() { this.editor.visible(); this.text.invisible(); - }, + } - _showHint: function () { + _showHint() { this.editor.invisible(); this.text.visible(); - }, + } - setTitle: function (title) { + setTitle(title) { this.text.setTitle(title); - }, + } - setTipType: function (v) { + setTipType(v) { this.text.setTipType(v); - }, + } - setWarningTitle: function (title) { + setWarningTitle(title) { this.text.setWarningTitle(title); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.options.watermark = v; this._checkText(); this.editor.setWaterMark(v); - }, + } - focus: function () { + focus() { this._showInput(); this.editor.focus(); - }, + } - blur: function () { + blur() { this.editor.blur(); this._showHint(); this._checkText(); - }, + } - doRedMark: function () { - if (this.editor.getValue() === "" && BI.isKey(this.options.watermark)) { + doRedMark() { + if (this.editor.getValue() === "" && isKey(this.options.watermark)) { return; } - this.text.doRedMark.apply(this.text, arguments); - }, + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doHighLight: function () { - if (this.editor.getValue() === "" && BI.isKey(this.options.watermark)) { + doHighLight() { + if (this.editor.getValue() === "" && isKey(this.options.watermark)) { return; } - this.text.doHighLight.apply(this.text, arguments); - }, + this.text.doHighLight(...arguments); + } - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - }, + unHighLight() { + this.text.unHighLight(...arguments); + } - isValid: function () { + isValid() { return this.editor.isValid(); - }, + } - setErrorText: function (text) { + setErrorText(text) { this.editor.setErrorText(text); - }, + } - getErrorText: function () { + getErrorText() { return this.editor.getErrorText(); - }, - - isEditing: function () { + } + + isEditing() { return this.editor.isEditing(); - }, + } - getLastValidValue: function () { + getLastValidValue() { return this.editor.getLastValidValue(); - }, + } - getLastChangedValue: function () { + getLastChangedValue() { return this.editor.getLastChangedValue(); - }, + } - setValue: function (k) { + setValue(k) { this.editor.setValue(k); this._checkText(); - }, + } - getValue: function () { + getValue() { return this.editor.getValue(); - }, + } - getState: function () { + getState() { return this.text.getValue(); - }, + } - setState: function (v) { + setState(v) { this._showHint(); this.text.setValue(v); } -}); -BI.SignEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.SignEditor.EVENT_FOCUS = "EVENT_FOCUS"; -BI.SignEditor.EVENT_BLUR = "EVENT_BLUR"; -BI.SignEditor.EVENT_CLICK = "EVENT_CLICK"; -BI.SignEditor.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.SignEditor.EVENT_QUICK_DOWN = "EVENT_QUICK_DOWN"; -BI.SignEditor.EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL"; - -BI.SignEditor.EVENT_START = "EVENT_START"; -BI.SignEditor.EVENT_PAUSE = "EVENT_PAUSE"; -BI.SignEditor.EVENT_STOP = "EVENT_STOP"; -BI.SignEditor.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.SignEditor.EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; -BI.SignEditor.EVENT_VALID = "EVENT_VALID"; -BI.SignEditor.EVENT_ERROR = "EVENT_ERROR"; -BI.SignEditor.EVENT_ENTER = "EVENT_ENTER"; -BI.SignEditor.EVENT_RESTRICT = "EVENT_RESTRICT"; -BI.SignEditor.EVENT_SPACE = "EVENT_SPACE"; -BI.SignEditor.EVENT_EMPTY = "EVENT_EMPTY"; - -BI.shortcut("bi.sign_editor", BI.SignEditor); +} diff --git a/src/case/editor/editor.state.js b/src/case/editor/editor.state.js index 9c3f340f9..d11dc059d 100644 --- a/src/case/editor/editor.state.js +++ b/src/case/editor/editor.state.js @@ -1,36 +1,61 @@ +import { shortcut, Widget, extend, emptyFn, i18nText, isArray, createWidget, nextTick, Controller, isNotNull, isString, isKey, isFunction, isNumber, isEmpty } from "@/core"; +import { TextButton, Editor } from "@/base"; + /** * guy * 记录状态的输入框 - * @class BI.StateEditor - * @extends BI.Single + * @class StateEditor + * @extends Single */ -BI.StateEditor = BI.inherit(BI.Widget, { - _defaultConfig: function () { - var conf = BI.StateEditor.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-state-editor", +@shortcut() +export class StateEditor extends Widget { + static xtype = "bi.state_editor" + + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_FOCUS = "EVENT_FOCUS" + static EVENT_BLUR = "EVENT_BLUR" + static EVENT_CLICK = "EVENT_CLICK" + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" + static EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL" + static EVENT_START = "EVENT_START" + static EVENT_PAUSE = "EVENT_PAUSE" + static EVENT_STOP = "EVENT_STOP" + static EVENT_CONFIRM = "EVENT_CONFIRM" + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM" + static EVENT_VALID = "EVENT_VALID" + static EVENT_ERROR = "EVENT_ERROR" + static EVENT_ENTER = "EVENT_ENTER" + static EVENT_RESTRICT = "EVENT_RESTRICT" + static EVENT_SPACE = "EVENT_SPACE" + static EVENT_EMPTY = "EVENT_EMPTY" + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-state-editor`, hgap: 4, vgap: 2, lgap: 0, rgap: 0, tgap: 0, bgap: 0, - validationChecker: BI.emptyFn, - quitChecker: BI.emptyFn, + validationChecker: emptyFn, + quitChecker: emptyFn, allowBlank: true, watermark: "", errorText: "", height: 24, - defaultText: BI.i18nText("BI-Basic_Unrestricted"), // 默认显示值,默认显示值与显示值的区别是默认显示值标记灰色 + defaultText: i18nText("BI-Basic_Unrestricted"), // 默认显示值,默认显示值与显示值的区别是默认显示值标记灰色 text: "", // 显示值 - el: {} + el: {}, }); - }, - - _init: function () { - BI.StateEditor.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.editor = BI.createWidget(o.el, { + } + + _init() { + super._init(...arguments); + const o = this.options; + this.editor = createWidget(o.el, { type: "bi.editor", simple: o.simple, height: o.height, @@ -48,262 +73,243 @@ BI.StateEditor = BI.inherit(BI.Widget, { errorText: o.errorText, autoTrim: o.autoTrim, }); - this.text = BI.createWidget({ + this.text = createWidget({ type: "bi.text_button", cls: "bi-water-mark tip-text-style", textAlign: "left", height: o.height, text: o.text, hgap: o.hgap + 2, - handler: function () { - self._showInput(); - self.editor.focus(); - self.editor.setValue(""); + handler: () => { + this._showInput(); + this.editor.focus(); + this.editor.setValue(""); }, - title: BI.isNotNull(o.tipText) ? o.tipText : function () { - var title = ""; - if (BI.isString(self.stateValue)) { - title = self.stateValue; + title: isNotNull(o.tipText) ? o.tipText : () => { + let title = ""; + if (isString(this.stateValue)) { + title = this.stateValue; } - if (BI.isArray(self.stateValue) && self.stateValue.length === 1) { - title = self.stateValue[0]; + if (isArray(this.stateValue) && this.stateValue.length === 1) { + title = this.stateValue[0]; } + return title; }, warningTitle: o.warningTitle, - tipType: o.tipType + tipType: o.tipType, }); - this.text.on(BI.TextButton.EVENT_CHANGE, function () { - BI.nextTick(function () { - self.fireEvent(BI.StateEditor.EVENT_CLICK_LABEL); + this.text.on(TextButton.EVENT_CHANGE, () => { + nextTick(() => { + this.fireEvent(StateEditor.EVENT_CLICK_LABEL); }); }); - this.editor.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.editor.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.editor.on(BI.Editor.EVENT_FOCUS, function () { - self.fireEvent(BI.StateEditor.EVENT_FOCUS, arguments); + this.editor.on(Editor.EVENT_FOCUS, (...args) => { + this.fireEvent(StateEditor.EVENT_FOCUS, ...args); }); - this.editor.on(BI.Editor.EVENT_BLUR, function () { - self.fireEvent(BI.StateEditor.EVENT_BLUR, arguments); + this.editor.on(Editor.EVENT_BLUR, (...args) => { + this.fireEvent(StateEditor.EVENT_BLUR, ...args); }); - this.editor.on(BI.Editor.EVENT_CLICK, function () { - self.fireEvent(BI.StateEditor.EVENT_CLICK, arguments); + this.editor.on(Editor.EVENT_CLICK, (...args) => { + this.fireEvent(StateEditor.EVENT_CLICK, ...args); }); - this.editor.on(BI.Editor.EVENT_CHANGE, function () { - self.fireEvent(BI.StateEditor.EVENT_CHANGE, arguments); + this.editor.on(Editor.EVENT_CHANGE, (...args) => { + this.fireEvent(StateEditor.EVENT_CHANGE, ...args); }); - this.editor.on(BI.Editor.EVENT_KEY_DOWN, function (v) { - self.fireEvent(BI.StateEditor.EVENT_KEY_DOWN, arguments); + this.editor.on(Editor.EVENT_KEY_DOWN, (...args) => { + this.fireEvent(StateEditor.EVENT_KEY_DOWN, ...args); }); - this.editor.on(BI.Editor.EVENT_VALID, function () { - self.fireEvent(BI.StateEditor.EVENT_VALID, arguments); + this.editor.on(Editor.EVENT_VALID, (...args) => { + this.fireEvent(StateEditor.EVENT_VALID, ...args); }); - this.editor.on(BI.Editor.EVENT_CONFIRM, function () { - self._showHint(); - self.fireEvent(BI.StateEditor.EVENT_CONFIRM, arguments); + this.editor.on(Editor.EVENT_CONFIRM, (...args) => { + this._showHint(); + this.fireEvent(StateEditor.EVENT_CONFIRM, ...args); }); - this.editor.on(BI.Editor.EVENT_CHANGE_CONFIRM, function () { - self._showHint(); - self.fireEvent(BI.StateEditor.EVENT_CHANGE_CONFIRM, arguments); + this.editor.on(Editor.EVENT_CHANGE_CONFIRM, (...args) => { + this._showHint(); + this.fireEvent(StateEditor.EVENT_CHANGE_CONFIRM, ...args); }); - this.editor.on(BI.Editor.EVENT_START, function () { - self.fireEvent(BI.StateEditor.EVENT_START, arguments); + this.editor.on(Editor.EVENT_START, (...args) => { + this.fireEvent(StateEditor.EVENT_START, ...args); }); - this.editor.on(BI.Editor.EVENT_PAUSE, function () { - self.fireEvent(BI.StateEditor.EVENT_PAUSE, arguments); + this.editor.on(Editor.EVENT_PAUSE, (...args) => { + this.fireEvent(StateEditor.EVENT_PAUSE, ...args); }); - this.editor.on(BI.Editor.EVENT_STOP, function () { - self.fireEvent(BI.StateEditor.EVENT_STOP, arguments); + this.editor.on(Editor.EVENT_STOP, (...args) => { + this.fireEvent(StateEditor.EVENT_STOP, ...args); }); - this.editor.on(BI.Editor.EVENT_SPACE, function () { - self.fireEvent(BI.StateEditor.EVENT_SPACE, arguments); + this.editor.on(Editor.EVENT_SPACE, (...args) => { + this.fireEvent(StateEditor.EVENT_SPACE, ...args); }); - this.editor.on(BI.Editor.EVENT_ERROR, function () { - self.fireEvent(BI.StateEditor.EVENT_ERROR, arguments); + this.editor.on(Editor.EVENT_ERROR, (...args) => { + this.fireEvent(StateEditor.EVENT_ERROR, ...args); }); - this.editor.on(BI.Editor.EVENT_ENTER, function () { - self.fireEvent(BI.StateEditor.EVENT_ENTER, arguments); + this.editor.on(Editor.EVENT_ENTER, (...args) => { + this.fireEvent(StateEditor.EVENT_ENTER, ...args); }); - this.editor.on(BI.Editor.EVENT_RESTRICT, function () { - self.fireEvent(BI.StateEditor.EVENT_RESTRICT, arguments); + this.editor.on(Editor.EVENT_RESTRICT, (...args) => { + this.fireEvent(StateEditor.EVENT_RESTRICT, ...args); }); - this.editor.on(BI.Editor.EVENT_EMPTY, function () { - self.fireEvent(BI.StateEditor.EVENT_EMPTY, arguments); + this.editor.on(Editor.EVENT_EMPTY, (...args) => { + this.fireEvent(StateEditor.EVENT_EMPTY, ...args); }); - BI.createWidget({ + createWidget({ type: "bi.absolute", element: this, - items: [ - { - el: this.text, - inset: 0, - }, { - el: this.editor, - inset: 0, - } - ] + items: [{ + el: this.text, + inset: 0, + }, { + el: this.editor, + inset: 0, + }], }); this._showHint(); - if (BI.isNotNull(o.text)) { + if (isNotNull(o.text)) { this.setState(o.text); } - }, - - setWaterMark: function (v) { + } + + setWaterMark(v) { this.options.watermark = v; this.editor.setWaterMark(v); - }, - - doRedMark: function () { - if (this.editor.getValue() === "" && BI.isKey(this.options.watermark)) { + } + + doRedMark() { + if (this.editor.getValue() === "" && isKey(this.options.watermark)) { return; } - this.text.doRedMark.apply(this.text, arguments); - }, - - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, - - doHighLight: function () { - if (this.editor.getValue() === "" && BI.isKey(this.options.watermark)) { + this.text.doRedMark(...arguments); + } + + unRedMark() { + this.text.unRedMark(...arguments); + } + + doHighLight() { + if (this.editor.getValue() === "" && isKey(this.options.watermark)) { return; } - this.text.doHighLight.apply(this.text, arguments); - }, - - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - }, - - focus: function () { + this.text.doHighLight(...arguments); + } + + unHighLight() { + this.text.unHighLight(...arguments); + } + + focus() { if (this.options.disabled === false) { this._showInput(); this.editor.focus(); } - }, - - blur: function () { + } + + blur() { this.editor.blur(); this._showHint(); - }, - - _showInput: function () { + } + + _showInput() { this.editor.visible(); this.text.invisible(); - }, - - _showHint: function () { + } + + _showHint() { this.editor.invisible(); this.text.visible(); - }, - - _setText: function (v) { + } + + _setText(v) { this.text.setText(v); this.text.setTitle(v); - }, - - isValid: function () { + } + + isValid() { return this.editor.isValid(); - }, - - setErrorText: function (text) { + } + + setErrorText(text) { this.editor.setErrorText(text); - }, - - getErrorText: function () { + } + + getErrorText() { return this.editor.getErrorText(); - }, - - isEditing: function () { + } + + isEditing() { return this.editor.isEditing(); - }, - - getLastValidValue: function () { + } + + getLastValidValue() { return this.editor.getLastValidValue(); - }, - - getLastChangedValue: function () { + } + + getLastChangedValue() { return this.editor.getLastChangedValue(); - }, - - setValue: function (k) { + } + + setValue(k) { this.editor.setValue(k); - }, - - getValue: function () { + } + + getValue() { return this.editor.getValue(); - }, - - getState: function () { + } + + getState() { return this.editor.getValue().match(/[^\s]+/g); - }, - - setState: function (v) { - var o = this.options; - var defaultText = BI.isFunction(o.defaultText) ? o.defaultText() : o.defaultText; - BI.StateEditor.superclass.setValue.apply(this, arguments); + } + + setState(v) { + const o = this.options; + const defaultText = isFunction(o.defaultText) ? o.defaultText() : o.defaultText; + super.setValue(...arguments); this.stateValue = v; - if (BI.isNumber(v)) { - if (v === BI.Selection.All) { - this._setText(BI.i18nText("BI-Select_All")); + if (isNumber(v)) { + if (v === Selection.All) { + this._setText(i18nText("BI-Select_All")); this.text.element.removeClass("bi-water-mark"); - } else if (v === BI.Selection.Multi) { - this._setText(BI.i18nText("BI-Select_Part")); + } else if (v === Selection.Multi) { + this._setText(i18nText("BI-Select_Part")); this.text.element.removeClass("bi-water-mark"); } else { - this._setText(BI.isKey(defaultText) ? defaultText : o.text); - BI.isKey(defaultText) ? this.text.element.addClass("bi-water-mark") : this.text.element.removeClass("bi-water-mark"); + this._setText(isKey(defaultText) ? defaultText : o.text); + isKey(defaultText) ? this.text.element.addClass("bi-water-mark") : this.text.element.removeClass("bi-water-mark"); } + return; } - if (BI.isString(v)) { + if (isString(v)) { this._setText(v); // 配置了defaultText才判断标灰,其他情况不标灰 - (BI.isKey(defaultText) && defaultText === v) ? this.text.element.addClass("bi-water-mark") : this.text.element.removeClass("bi-water-mark"); + (isKey(defaultText) && defaultText === v) ? this.text.element.addClass("bi-water-mark") : this.text.element.removeClass("bi-water-mark"); + return; } - if (BI.isArray(v)) { - if (BI.isEmpty(v)) { - this._setText(BI.isKey(defaultText) ? defaultText : o.text); - BI.isKey(defaultText) ? this.text.element.addClass("bi-water-mark") : this.text.element.removeClass("bi-water-mark"); + if (isArray(v)) { + if (isEmpty(v)) { + this._setText(isKey(defaultText) ? defaultText : o.text); + isKey(defaultText) ? this.text.element.addClass("bi-water-mark") : this.text.element.removeClass("bi-water-mark"); } else if (v.length === 1) { this._setText(v[0]); this.text.element.removeClass("bi-water-mark"); } else { - this._setText(BI.i18nText("BI-Select_Part")); + this._setText(i18nText("BI-Select_Part")); this.text.element.removeClass("bi-water-mark"); } } - }, - - setTipType: function (v) { + } + + setTipType(v) { this.text.options.tipType = v; - }, - - getText: function () { + } + + getText() { return this.text.getText(); } -}); -BI.StateEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.StateEditor.EVENT_FOCUS = "EVENT_FOCUS"; -BI.StateEditor.EVENT_BLUR = "EVENT_BLUR"; -BI.StateEditor.EVENT_CLICK = "EVENT_CLICK"; -BI.StateEditor.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.StateEditor.EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL"; - -BI.StateEditor.EVENT_START = "EVENT_START"; -BI.StateEditor.EVENT_PAUSE = "EVENT_PAUSE"; -BI.StateEditor.EVENT_STOP = "EVENT_STOP"; -BI.StateEditor.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.StateEditor.EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; -BI.StateEditor.EVENT_VALID = "EVENT_VALID"; -BI.StateEditor.EVENT_ERROR = "EVENT_ERROR"; -BI.StateEditor.EVENT_ENTER = "EVENT_ENTER"; -BI.StateEditor.EVENT_RESTRICT = "EVENT_RESTRICT"; -BI.StateEditor.EVENT_SPACE = "EVENT_SPACE"; -BI.StateEditor.EVENT_EMPTY = "EVENT_EMPTY"; - -BI.shortcut("bi.state_editor", BI.StateEditor); +} diff --git a/src/case/editor/editor.state.simple.js b/src/case/editor/editor.state.simple.js index 96be87aa1..807a8c158 100644 --- a/src/case/editor/editor.state.simple.js +++ b/src/case/editor/editor.state.simple.js @@ -1,36 +1,61 @@ +import { shortcut, Widget, extend, emptyFn, i18nText, Controller, createWidget, nextTick, isNotNull, isKey, isFunction, isArray, isNumber, isEmpty } from "@/core"; +import { Editor, TextButton } from "@/base"; + /** * 无限制-已选择状态输入框 * Created by GUY on 2016/5/18. - * @class BI.SimpleStateEditor - * @extends BI.Single + * @class SimpleStateEditor + * @extends Single */ -BI.SimpleStateEditor = BI.inherit(BI.Widget, { - _defaultConfig: function () { - var conf = BI.SimpleStateEditor.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-simple-state-editor", +@shortcut() +export class SimpleStateEditor extends Widget { + static xtype = "bi.simple_state_editor" + + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_FOCUS = "EVENT_FOCUS" + static EVENT_BLUR = "EVENT_BLUR" + static EVENT_CLICK = "EVENT_CLICK" + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" + static EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL" + static EVENT_START = "EVENT_START" + static EVENT_PAUSE = "EVENT_PAUSE" + static EVENT_STOP = "EVENT_STOP" + static EVENT_CONFIRM = "EVENT_CONFIRM" + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM" + static EVENT_VALID = "EVENT_VALID" + static EVENT_ERROR = "EVENT_ERROR" + static EVENT_ENTER = "EVENT_ENTER" + static EVENT_RESTRICT = "EVENT_RESTRICT" + static EVENT_SPACE = "EVENT_SPACE" + static EVENT_EMPTY = "EVENT_EMPTY" + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-simple-state-editor`, hgap: 4, vgap: 2, lgap: 0, rgap: 0, tgap: 0, bgap: 0, - validationChecker: BI.emptyFn, - quitChecker: BI.emptyFn, + validationChecker: emptyFn, + quitChecker: emptyFn, mouseOut: false, allowBlank: true, watermark: "", errorText: "", height: 24, text: "", - defaultText: BI.i18nText("BI-Basic_Unrestricted"), + defaultText: i18nText("BI-Basic_Unrestricted"), }); - }, + } - _init: function () { - BI.SimpleStateEditor.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.editor = BI.createWidget({ + _init() { + super._init(...arguments); + const o = this.options; + this.editor = createWidget({ type: "bi.editor", simple: o.simple, height: o.height, @@ -48,241 +73,220 @@ BI.SimpleStateEditor = BI.inherit(BI.Widget, { errorText: o.errorText, autoTrim: o.autoTrim, }); - this.text = BI.createWidget({ + this.text = createWidget({ type: "bi.text_button", cls: "bi-water-mark", textAlign: "left", text: o.text, height: o.height, hgap: o.hgap + 2, - handler: function () { - self._showInput(); - self.editor.focus(); - self.editor.setValue(""); - } + handler: () => { + this._showInput(); + this.editor.focus(); + this.editor.setValue(""); + }, }); - this.text.on(BI.TextButton.EVENT_CHANGE, function () { - BI.nextTick(function () { - self.fireEvent(BI.SimpleStateEditor.EVENT_CLICK_LABEL); + this.text.on(TextButton.EVENT_CHANGE, () => { + nextTick(() => { + this.fireEvent(SimpleStateEditor.EVENT_CLICK_LABEL); }); }); - BI.createWidget({ + createWidget({ type: "bi.absolute", element: this, - items: [ - { - el: this.text, - left: 0, - right: 0, - top: 0, - bottom: 0 - } - ] + items: [{ + el: this.text, + left: 0, + right: 0, + top: 0, + bottom: 0, + }], }); - this.editor.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.editor.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.editor.on(BI.Editor.EVENT_FOCUS, function () { - self.fireEvent(BI.SimpleStateEditor.EVENT_FOCUS, arguments); + this.editor.on(Editor.EVENT_FOCUS, (...args) => { + this.fireEvent(SimpleStateEditor.EVENT_FOCUS, ...args); }); - this.editor.on(BI.Editor.EVENT_BLUR, function () { - self.fireEvent(BI.SimpleStateEditor.EVENT_BLUR, arguments); + this.editor.on(Editor.EVENT_BLUR, (...args) => { + this.fireEvent(SimpleStateEditor.EVENT_BLUR, ...args); }); - this.editor.on(BI.Editor.EVENT_CLICK, function () { - self.fireEvent(BI.SimpleStateEditor.EVENT_CLICK, arguments); + this.editor.on(Editor.EVENT_CLICK, (...args) => { + this.fireEvent(SimpleStateEditor.EVENT_CLICK, ...args); }); - this.editor.on(BI.Editor.EVENT_CHANGE, function () { - self.fireEvent(BI.SimpleStateEditor.EVENT_CHANGE, arguments); + this.editor.on(Editor.EVENT_CHANGE, (...args) => { + this.fireEvent(SimpleStateEditor.EVENT_CHANGE, ...args); }); - this.editor.on(BI.Editor.EVENT_KEY_DOWN, function (v) { - self.fireEvent(BI.SimpleStateEditor.EVENT_KEY_DOWN, arguments); + this.editor.on(Editor.EVENT_KEY_DOWN, (...args) => { + this.fireEvent(SimpleStateEditor.EVENT_KEY_DOWN, ...args); }); - this.editor.on(BI.Editor.EVENT_VALID, function () { - self.fireEvent(BI.SimpleStateEditor.EVENT_VALID, arguments); + this.editor.on(Editor.EVENT_VALID, (...args) => { + this.fireEvent(SimpleStateEditor.EVENT_VALID, ...args); }); - this.editor.on(BI.Editor.EVENT_CONFIRM, function () { - self._showHint(); - self.fireEvent(BI.SimpleStateEditor.EVENT_CONFIRM, arguments); + this.editor.on(Editor.EVENT_CONFIRM, (...args) => { + this._showHint(); + this.fireEvent(SimpleStateEditor.EVENT_CONFIRM, ...args); }); - this.editor.on(BI.Editor.EVENT_CHANGE_CONFIRM, function () { - self._showHint(); - self.fireEvent(BI.SimpleStateEditor.EVENT_CHANGE_CONFIRM, arguments); + this.editor.on(Editor.EVENT_CHANGE_CONFIRM, (...args) => { + this._showHint(); + this.fireEvent(SimpleStateEditor.EVENT_CHANGE_CONFIRM, ...args); }); - this.editor.on(BI.Editor.EVENT_START, function () { - self.fireEvent(BI.SimpleStateEditor.EVENT_START, arguments); + this.editor.on(Editor.EVENT_START, (...args) => { + this.fireEvent(SimpleStateEditor.EVENT_START, ...args); }); - this.editor.on(BI.Editor.EVENT_PAUSE, function () { - self.fireEvent(BI.SimpleStateEditor.EVENT_PAUSE, arguments); + this.editor.on(Editor.EVENT_PAUSE, (...args) => { + this.fireEvent(SimpleStateEditor.EVENT_PAUSE, ...args); }); - this.editor.on(BI.Editor.EVENT_STOP, function () { - self.fireEvent(BI.SimpleStateEditor.EVENT_STOP, arguments); + this.editor.on(Editor.EVENT_STOP, (...args) => { + this.fireEvent(SimpleStateEditor.EVENT_STOP, ...args); }); - this.editor.on(BI.Editor.EVENT_SPACE, function () { - self.fireEvent(BI.SimpleStateEditor.EVENT_SPACE, arguments); + this.editor.on(Editor.EVENT_SPACE, (...args) => { + this.fireEvent(SimpleStateEditor.EVENT_SPACE, ...args); }); - this.editor.on(BI.Editor.EVENT_ERROR, function () { - self.fireEvent(BI.SimpleStateEditor.EVENT_ERROR, arguments); + this.editor.on(Editor.EVENT_ERROR, (...args) => { + this.fireEvent(SimpleStateEditor.EVENT_ERROR, ...args); }); - this.editor.on(BI.Editor.EVENT_ENTER, function () { - self.fireEvent(BI.SimpleStateEditor.EVENT_ENTER, arguments); + this.editor.on(Editor.EVENT_ENTER, (...args) => { + this.fireEvent(SimpleStateEditor.EVENT_ENTER, ...args); }); - this.editor.on(BI.Editor.EVENT_RESTRICT, function () { - self.fireEvent(BI.SimpleStateEditor.EVENT_RESTRICT, arguments); + this.editor.on(Editor.EVENT_RESTRICT, (...args) => { + this.fireEvent(SimpleStateEditor.EVENT_RESTRICT, ...args); }); - this.editor.on(BI.Editor.EVENT_EMPTY, function () { - self.fireEvent(BI.SimpleStateEditor.EVENT_EMPTY, arguments); + this.editor.on(Editor.EVENT_EMPTY, (...args) => { + this.fireEvent(SimpleStateEditor.EVENT_EMPTY, ...args); }); - BI.createWidget({ + createWidget({ type: "bi.vertical", scrolly: false, element: this, - items: [this.editor] + items: [this.editor], }); this._showHint(); - if (BI.isNotNull(o.text)) { + if (isNotNull(o.text)) { this.setState(o.text); } - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.options.watermark = v; this.editor.setWaterMark(v); - }, + } - doRedMark: function () { - if (this.editor.getValue() === "" && BI.isKey(this.options.watermark)) { + doRedMark() { + if (this.editor.getValue() === "" && isKey(this.options.watermark)) { return; } - this.text.doRedMark.apply(this.text, arguments); - }, + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doHighLight: function () { - if (this.editor.getValue() === "" && BI.isKey(this.options.watermark)) { + doHighLight() { + if (this.editor.getValue() === "" && isKey(this.options.watermark)) { return; } - this.text.doHighLight.apply(this.text, arguments); - }, + this.text.doHighLight(...arguments); + } - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - }, + unHighLight() { + this.text.unHighLight(...arguments); + } - focus: function () { + focus() { this._showInput(); this.editor.focus(); - }, + } - blur: function () { + blur() { this.editor.blur(); this._showHint(); - }, + } - _showInput: function () { + _showInput() { this.editor.visible(); this.text.invisible(); - }, + } - _showHint: function () { + _showHint() { this.editor.invisible(); this.text.visible(); - }, + } - _setText: function (v) { + _setText(v) { this.text.setText(v); this.text.setTitle(v); - }, + } - isValid: function () { + isValid() { return this.editor.isValid(); - }, + } - setErrorText: function (text) { + setErrorText(text) { this.editor.setErrorText(text); - }, + } - getErrorText: function () { + getErrorText() { return this.editor.getErrorText(); - }, + } - isEditing: function () { + isEditing() { return this.editor.isEditing(); - }, + } - getLastValidValue: function () { + getLastValidValue() { return this.editor.getLastValidValue(); - }, + } - getLastChangedValue: function () { + getLastChangedValue() { return this.editor.getLastChangedValue(); - }, + } - setValue: function (k) { + setValue(k) { this.editor.setValue(k); - }, + } - getValue: function () { + getValue() { return this.editor.getValue(); - }, + } - getState: function () { + getState() { return this.editor.getValue().match(/[^\s]+/g); - }, + } - setState: function (v) { - var o = this.options; - BI.SimpleStateEditor.superclass.setValue.apply(this, arguments); - var defaultText = BI.isFunction(o.defaultText) ? o.defaultText() : o.defaultText; - if (BI.isNumber(v)) { - if (v === BI.Selection.All) { - this._setText(BI.i18nText("BI-Already_Selected")); + setState(v) { + const o = this.options; + super.setValue(...arguments); + const defaultText = isFunction(o.defaultText) ? o.defaultText() : o.defaultText; + if (isNumber(v)) { + if (v === Selection.All) { + this._setText(i18nText("BI-Already_Selected")); this.text.element.removeClass("bi-water-mark"); - } else if (v === BI.Selection.Multi) { - this._setText(BI.i18nText("BI-Already_Selected")); + } else if (v === Selection.Multi) { + this._setText(i18nText("BI-Already_Selected")); this.text.element.removeClass("bi-water-mark"); } else { - this._setText(BI.isKey(defaultText) ? defaultText : o.text); + this._setText(isKey(defaultText) ? defaultText : o.text); this.text.element.addClass("bi-water-mark"); } + return; } - if (!BI.isArray(v) || v.length === 1) { + if (!isArray(v) || v.length === 1) { this._setText(v); this.text.element.removeClass("bi-water-mark"); - } else if (BI.isEmpty(v)) { + } else if (isEmpty(v)) { this._setText(o.text); this.text.element.addClass("bi-water-mark"); } else { - this._setText(BI.i18nText("BI-Already_Selected")); + this._setText(i18nText("BI-Already_Selected")); this.text.element.removeClass("bi-water-mark"); } - }, + } - getText: function () { + getText() { return this.text.getText(); } -}); -BI.SimpleStateEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.SimpleStateEditor.EVENT_FOCUS = "EVENT_FOCUS"; -BI.SimpleStateEditor.EVENT_BLUR = "EVENT_BLUR"; -BI.SimpleStateEditor.EVENT_CLICK = "EVENT_CLICK"; -BI.SimpleStateEditor.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.SimpleStateEditor.EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL"; - -BI.SimpleStateEditor.EVENT_START = "EVENT_START"; -BI.SimpleStateEditor.EVENT_PAUSE = "EVENT_PAUSE"; -BI.SimpleStateEditor.EVENT_STOP = "EVENT_STOP"; -BI.SimpleStateEditor.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.SimpleStateEditor.EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; -BI.SimpleStateEditor.EVENT_VALID = "EVENT_VALID"; -BI.SimpleStateEditor.EVENT_ERROR = "EVENT_ERROR"; -BI.SimpleStateEditor.EVENT_ENTER = "EVENT_ENTER"; -BI.SimpleStateEditor.EVENT_RESTRICT = "EVENT_RESTRICT"; -BI.SimpleStateEditor.EVENT_SPACE = "EVENT_SPACE"; -BI.SimpleStateEditor.EVENT_EMPTY = "EVENT_EMPTY"; - -BI.shortcut("bi.simple_state_editor", BI.SimpleStateEditor); +} diff --git a/src/case/editor/index.js b/src/case/editor/index.js new file mode 100644 index 000000000..487c0f3f6 --- /dev/null +++ b/src/case/editor/index.js @@ -0,0 +1,6 @@ +export { ClearEditor } from "./editor.clear"; +export { DefaultTextEditor } from "./editor.defaulttext"; +export { ShelterEditor } from "./editor.shelter"; +export { SignEditor } from "./editor.sign"; +export { StateEditor } from "./editor.state"; +export { SimpleStateEditor } from "./editor.state.simple"; diff --git a/src/case/index.js b/src/case/index.js index 5e8b11baf..33f250645 100644 --- a/src/case/index.js +++ b/src/case/index.js @@ -1,7 +1,10 @@ import * as button from "./button"; +import * as editor from "./editor"; Object.assign(BI, { ...button, + ...editor, }); export * from "./button"; +export * from "./editor"; From 0c009add2c665799a3a2c38b98b7ced980bcdb45 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Wed, 11 Jan 2023 10:31:14 +0800 Subject: [PATCH 062/300] =?UTF-8?q?KERNEL-14071=20refactor:=20case/trigger?= =?UTF-8?q?=E7=9A=84es6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.js | 7 + src/base/single/trigger/trigger.js | 2 +- src/case/index.js | 3 + src/case/trigger/index.js | 8 + src/case/trigger/trigger.editor.js | 105 ++++++------ src/case/trigger/trigger.icon.js | 33 ++-- src/case/trigger/trigger.icon.text.js | 84 ++++----- src/case/trigger/trigger.icon.text.select.js | 67 ++++---- src/case/trigger/trigger.text.js | 159 +++++++++--------- src/case/trigger/trigger.text.select.js | 102 +++++------ src/case/trigger/trigger.text.select.small.js | 66 ++++---- src/case/trigger/trigger.text.small.js | 64 +++---- 12 files changed, 374 insertions(+), 326 deletions(-) create mode 100644 src/case/trigger/index.js diff --git a/es6.js b/es6.js index 9c0b18bf4..2fa0181eb 100644 --- a/es6.js +++ b/es6.js @@ -97,6 +97,13 @@ collection.methods.forEach(el => { "isString", "isNumber", "isEmpty", + "isEmptyString", + "any", + "deepContains", + "isNotEmptyString", + "each", + "contains", + "remove", ]; target.forEach(t => { diff --git a/src/base/single/trigger/trigger.js b/src/base/single/trigger/trigger.js index 3755fc8ae..af9db4078 100644 --- a/src/base/single/trigger/trigger.js +++ b/src/base/single/trigger/trigger.js @@ -12,7 +12,7 @@ export class Trigger extends Single { const conf = super._defaultConfig(...arguments); return extend(conf, { - _baseCls: (conf._baseCls || "") + " bi-trigger cursor-pointer", + _baseCls: `${conf._baseCls || ""} bi-trigger cursor-pointer`, height: 24, }); } diff --git a/src/case/index.js b/src/case/index.js index 1b8b33c0b..515a45107 100644 --- a/src/case/index.js +++ b/src/case/index.js @@ -2,16 +2,19 @@ import * as button from "./button"; import * as calendarItem from "./calendar"; import * as pager from "./pager"; import * as editor from "./editor"; +import * as trigger from "./trigger"; Object.assign(BI, { ...button, ...calendarItem, ...pager, ...editor, + ...trigger, }); export * from "./button"; export * from "./calendar"; export * from "./pager"; export * from "./editor"; +export * from "./trigger"; diff --git a/src/case/trigger/index.js b/src/case/trigger/index.js new file mode 100644 index 000000000..df4e68ab5 --- /dev/null +++ b/src/case/trigger/index.js @@ -0,0 +1,8 @@ +export { EditorTrigger } from "./trigger.editor"; +export { IconTrigger } from "./trigger.icon"; +export { IconTextTrigger } from "./trigger.icon.text"; +export { SelectIconTextTrigger } from "./trigger.icon.text.select"; +export { TextTrigger } from "./trigger.text"; +export { SelectTextTrigger } from "./trigger.text.select"; +export { SmallSelectTextTrigger } from "./trigger.text.select.small"; +export { SmallTextTrigger } from "./trigger.text.small"; diff --git a/src/case/trigger/trigger.editor.js b/src/case/trigger/trigger.editor.js index 5bdcc8f56..3bb8439ac 100644 --- a/src/case/trigger/trigger.editor.js +++ b/src/case/trigger/trigger.editor.js @@ -1,93 +1,98 @@ +import { shortcut, extend, emptyFn, createWidget, toPix, Controller } from "@/core"; +import { Trigger } from "@/base"; +import { SignEditor } from "../editor"; + /** * 文本输入框trigger * * Created by GUY on 2015/9/15. - * @class BI.EditorTrigger - * @extends BI.Trigger + * @class EditorTrigger + * @extends Trigger */ -BI.EditorTrigger = BI.inherit(BI.Trigger, { - _defaultConfig: function (config) { - var conf = BI.EditorTrigger.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-editor-trigger bi-border-radius " + (config.simple ? "bi-border-bottom" : "bi-border"), +@shortcut() +export class EditorTrigger extends Trigger { + static xtype = "bi.editor_trigger"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_EMPTY = "EVENT_EMPTY"; + static EVENT_VALID = "EVENT_VALID"; + static EVENT_ERROR = "EVENT_ERROR"; + + _defaultConfig(config) { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-editor-trigger bi-border-radius ${config.simple ? "bi-border-bottom" : "bi-border"}`, height: 24, - validationChecker: BI.emptyFn, - quitChecker: BI.emptyFn, + validationChecker: emptyFn, + quitChecker: emptyFn, allowBlank: false, watermark: "", - errorText: "" + errorText: "", }); - }, + } - _init: function () { - BI.EditorTrigger.superclass._init.apply(this, arguments); - var self = this, o = this.options, c = this._const; - this.editor = BI.createWidget({ + _init() { + super._init(...arguments); + const o = this.options; + this.editor = createWidget({ type: "bi.sign_editor", - height: BI.toPix(o.height, 2), + height: toPix(o.height, 2), value: o.value, validationChecker: o.validationChecker, quitChecker: o.quitChecker, allowBlank: o.allowBlank, watermark: o.watermark, errorText: o.errorText, - title: function () { - return self.getValue(); - } + title: () => this.getValue(), }); - this.editor.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.editor.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.editor.on(BI.SignEditor.EVENT_CHANGE, function () { - self.fireEvent(BI.EditorTrigger.EVENT_CHANGE, arguments); + this.editor.on(SignEditor.EVENT_CHANGE, (...args) => { + this.fireEvent(EditorTrigger.EVENT_CHANGE, ...args); }); - this.editor.on(BI.SignEditor.EVENT_FOCUS, function () { - self.fireEvent(BI.EditorTrigger.EVENT_FOCUS, arguments); + this.editor.on(SignEditor.EVENT_FOCUS, (...args) => { + this.fireEvent(EditorTrigger.EVENT_FOCUS, ...args); }); - this.editor.on(BI.SignEditor.EVENT_EMPTY, function () { - self.fireEvent(BI.EditorTrigger.EVENT_EMPTY, arguments); + this.editor.on(SignEditor.EVENT_EMPTY, (...args) => { + this.fireEvent(EditorTrigger.EVENT_EMPTY, ...args); }); - this.editor.on(BI.SignEditor.EVENT_VALID, function () { - self.fireEvent(BI.EditorTrigger.EVENT_VALID, arguments); + this.editor.on(SignEditor.EVENT_VALID, (...args) => { + this.fireEvent(EditorTrigger.EVENT_VALID, ...args); }); - this.editor.on(BI.SignEditor.EVENT_ERROR, function () { - self.fireEvent(BI.EditorTrigger.EVENT_ERROR, arguments); + this.editor.on(SignEditor.EVENT_ERROR, (...args) => { + this.fireEvent(EditorTrigger.EVENT_ERROR, ...args); }); - BI.createWidget({ + createWidget({ element: this, type: "bi.horizontal_fill", - height: BI.toPix(o.height, 2), + height: toPix(o.height, 2), items: [ { el: this.editor, - width: "fill" + width: "fill", }, { el: { type: "bi.trigger_icon_button", - width: o.triggerWidth || BI.toPix(o.height, 2) + width: o.triggerWidth || toPix(o.height, 2), }, - width: "" + width: "", } - ] + ], }); - }, + } - getValue: function () { + getValue() { return this.editor.getValue(); - }, + } - setValue: function (value) { + setValue(value) { this.editor.setValue(value); - }, + } - setText: function (text) { + setText(text) { this.editor.setState(text); } -}); -BI.EditorTrigger.EVENT_CHANGE = "EVENT_CHANGE"; -BI.EditorTrigger.EVENT_FOCUS = "EVENT_FOCUS"; -BI.EditorTrigger.EVENT_EMPTY = "EVENT_EMPTY"; -BI.EditorTrigger.EVENT_VALID = "EVENT_VALID"; -BI.EditorTrigger.EVENT_ERROR = "EVENT_ERROR"; -BI.shortcut("bi.editor_trigger", BI.EditorTrigger); +} diff --git a/src/case/trigger/trigger.icon.js b/src/case/trigger/trigger.icon.js index 2da61d480..3368dd070 100644 --- a/src/case/trigger/trigger.icon.js +++ b/src/case/trigger/trigger.icon.js @@ -1,30 +1,35 @@ +import { shortcut, extend, createWidget } from "@/core"; +import { Trigger } from "@/base"; + /** * 图标按钮trigger * * Created by GUY on 2015/10/8. - * @class BI.IconTrigger - * @extends BI.Trigger + * @class IconTrigger + * @extends Trigger */ -BI.IconTrigger = BI.inherit(BI.Trigger, { +@shortcut() +export class IconTrigger extends Trigger { + static xtype = "bi.icon_trigger" - _defaultConfig: function () { - return BI.extend(BI.IconTrigger.superclass._defaultConfig.apply(this, arguments), { + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-icon-trigger", extraCls: "pull-down-font", el: {}, - height: 24 + height: 24, }); - }, - _init: function () { - var o = this.options; - BI.IconTrigger.superclass._init.apply(this, arguments); - this.iconButton = BI.createWidget(o.el, { + } + + _init() { + const o = this.options; + super._init(...arguments); + this.iconButton = createWidget(o.el, { type: "bi.trigger_icon_button", element: this, width: o.width, height: o.height, - extraCls: o.extraCls + extraCls: o.extraCls, }); } -}); -BI.shortcut("bi.icon_trigger", BI.IconTrigger); \ No newline at end of file +} diff --git a/src/case/trigger/trigger.icon.text.js b/src/case/trigger/trigger.icon.text.js index a102b5d0c..b93c3181b 100644 --- a/src/case/trigger/trigger.icon.text.js +++ b/src/case/trigger/trigger.icon.text.js @@ -1,29 +1,35 @@ +import { shortcut, extend, isKey, createWidget, isEmptyString } from "@/core"; +import { Trigger } from "@/base"; + /** * 文字trigger * * Created by GUY on 2015/9/15. - * @class BI.IconTextTrigger - * @extends BI.Trigger + * @class IconTextTrigger + * @extends Trigger */ -BI.IconTextTrigger = BI.inherit(BI.Trigger, { +@shortcut() +export class IconTextTrigger extends Trigger { + static xtype = "bi.icon_text_trigger" - _defaultConfig: function () { - var conf = BI.IconTextTrigger.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-text-trigger", + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-text-trigger`, height: 24, iconHeight: null, iconWidth: null, - textCls: "" + textCls: "", }); - }, + } - _init: function () { - BI.IconTextTrigger.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.text = BI.createWidget({ + _init() { + super._init(...arguments); + const o = this.options; + this.text = createWidget({ type: "bi.label", - cls: "select-text-label" + (BI.isKey(o.textCls) ? (" " + o.textCls) : ""), + cls: `select-text-label${isKey(o.textCls) ? (` ${o.textCls}`) : ""}`, textAlign: "left", height: o.height, hgap: o.textHgap, @@ -32,19 +38,19 @@ BI.IconTextTrigger = BI.inherit(BI.Trigger, { rgap: o.textRgap, tgap: o.textTgap, bgap: o.textBgap, - text: o.text + text: o.text, }); - this.trigerButton = BI.createWidget({ + this.trigerButton = createWidget({ type: "bi.trigger_icon_button", - width: o.triggerWidth || o.height + width: o.triggerWidth || o.height, }); - BI.createWidget({ + createWidget({ element: this, type: "bi.horizontal_fill", columnSize: ["", "fill", ""], - ref: function (_ref) { - self.wrapper = _ref; + ref: _ref => { + this.wrapper = _ref; }, items: [{ el: { @@ -53,41 +59,39 @@ BI.IconTextTrigger = BI.inherit(BI.Trigger, { width: o.triggerWidth || o.height, iconCls: o.iconCls, invisible: !o.iconCls, - ref: function (_ref) { - self.icon = _ref; + ref: _ref => { + this.icon = _ref; }, iconHeight: o.iconHeight, iconWidth: o.iconWidth, - disableSelected: true - } + disableSelected: true, + }, }, { el: this.text, - lgap: BI.isEmptyString(o.iconCls) ? 5 : 0 + lgap: isEmptyString(o.iconCls) ? 5 : 0, }, { - el: this.trigerButton - }] + el: this.trigerButton, + }], }); - }, + } - setValue: function (value) { + setValue(value) { this.text.setValue(value); - }, + } - setIcon: function (iconCls) { - var o = this.options; + setIcon(iconCls) { this.icon.setIcon(iconCls); this.icon.setVisible(!!iconCls); - }, + } - setTextCls: function (cls) { - var o = this.options; - var oldCls = o.textCls; + setTextCls(cls) { + const o = this.options; + const oldCls = o.textCls; o.textCls = cls; this.text.element.removeClass(oldCls).addClass(cls); - }, + } - setText: function (text) { + setText(text) { this.text.setText(text); } -}); -BI.shortcut("bi.icon_text_trigger", BI.IconTextTrigger); +} diff --git a/src/case/trigger/trigger.icon.text.select.js b/src/case/trigger/trigger.icon.text.select.js index b0142b91e..0045972a4 100644 --- a/src/case/trigger/trigger.icon.text.select.js +++ b/src/case/trigger/trigger.icon.text.select.js @@ -1,23 +1,28 @@ +import { shortcut, extend, createWidget, isFunction, isArray, isNotNull, any, deepContains, Tree } from "@/core"; +import { Trigger } from "@/base"; + /** * Created by Windy on 2017/12/12. */ -BI.SelectIconTextTrigger = BI.inherit(BI.Trigger, { +@shortcut() +export class SelectIconTextTrigger extends Trigger { + static xtype = "bi.select_icon_text_trigger" - _defaultConfig: function () { - return BI.extend(BI.SelectIconTextTrigger.superclass._defaultConfig.apply(this, arguments), { + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-select-text-trigger", height: 24, iconHeight: null, iconWidth: null, - iconCls: "" + iconCls: "", }); - }, + } - _init: function () { - BI.SelectIconTextTrigger.superclass._init.apply(this, arguments); - var self = this, o = this.options; - var obj = this._digist(o.value, o.items); - this.trigger = BI.createWidget({ + _init() { + super._init(...arguments); + const o = this.options; + const obj = this._digist(o.value, o.items); + this.trigger = createWidget({ type: "bi.icon_text_trigger", element: this, text: obj.text, @@ -32,49 +37,49 @@ BI.SelectIconTextTrigger = BI.inherit(BI.Trigger, { height: o.height, iconHeight: o.iconHeight, iconWidth: o.iconWidth, - iconWrapperWidth: o.iconWrapperWidth + iconWrapperWidth: o.iconWrapperWidth, }); - }, + } - _digist: function (vals, items) { - var o = this.options; - vals = BI.isArray(vals) ? vals : [vals]; - var result; - var formatItems = BI.Tree.transformToArrayFormat(items); - BI.any(formatItems, function (i, item) { - if (BI.deepContains(vals, item.value)) { + _digist(vals, items) { + const o = this.options; + vals = isArray(vals) ? vals : [vals]; + let result; + const formatItems = Tree.transformToArrayFormat(items); + any(formatItems, (i, item) => { + if (deepContains(vals, item.value)) { result = { text: item.text || item.value, - iconCls: item.iconCls + iconCls: item.iconCls, }; + return true; } }); - if (BI.isNotNull(result)) { + if (isNotNull(result)) { return { text: result.text, textCls: "", - iconCls: result.iconCls + iconCls: result.iconCls, }; } else { return { - text: BI.isFunction(o.text) ? o.text() : o.text, + text: isFunction(o.text) ? o.text() : o.text, textCls: "bi-water-mark", - iconCls: o.iconCls + iconCls: o.iconCls, }; } - }, + } - setValue: function (vals) { - var obj = this._digist(vals, this.options.items); + setValue(vals) { + const obj = this._digist(vals, this.options.items); this.trigger.setText(obj.text); this.trigger.setIcon(obj.iconCls); this.trigger.setTextCls(obj.textCls); - }, + } - populate: function (items) { + populate(items) { this.options.items = items; } -}); -BI.shortcut("bi.select_icon_text_trigger", BI.SelectIconTextTrigger); +} diff --git a/src/case/trigger/trigger.text.js b/src/case/trigger/trigger.text.js index 6e7273252..f4e15110d 100644 --- a/src/case/trigger/trigger.text.js +++ b/src/case/trigger/trigger.text.js @@ -1,41 +1,45 @@ +import { shortcut, isFunction, isKey, isNotEmptyString } from "@/core"; +import { Trigger } from "@/base"; + /** * 文字trigger * * Created by GUY on 2015/9/15. - * @class BI.TextTrigger - * @extends BI.Trigger + * @class TextTrigger + * @extends Trigger */ -BI.TextTrigger = BI.inherit(BI.Trigger, { +@shortcut() +export class TextTrigger extends Trigger { + static xtype = "bi.text_trigger" + + static EVENT_CLEAR = "EVENT_CLEAR" - props: function () { - var self = this; + props() { return { baseCls: "bi-text-trigger", height: 24, textHgap: 6, textCls: "", allowClear: false, - title: function () { - return self.text.getText(); - }, + title: () => this.text.getText(), defaultText: "", text: "", }; - }, + } - render: function () { - var self = this, o = this.options, c = this._const; + render() { + const o = this.options; - var text = this.getText(); + const text = this.getText(); - var defaultText = this.getDefaultText(); + const defaultText = this.getDefaultText(); - var label = { + const label = { type: "bi.label", - ref: function (_ref) { - self.text = _ref; + ref: _ref => { + this.text = _ref; }, - cls: `select-text-label ${o.textCls} ${!BI.isNotEmptyString(text) && BI.isNotEmptyString(defaultText) ? "bi-tips" : ""}`, + cls: `select-text-label ${o.textCls} ${!isNotEmptyString(text) && isNotEmptyString(defaultText) ? "bi-tips" : ""}`, textAlign: "left", height: o.height, text: text || o.defaultText, @@ -47,98 +51,93 @@ BI.TextTrigger = BI.inherit(BI.Trigger, { rgap: o.textRgap, tgap: o.textTgap, bgap: o.textBgap, - readonly: o.readonly + readonly: o.readonly, }; - var triggerButton = { + const triggerButton = { type: "bi.trigger_icon_button", - ref: function (_ref) { - self.triggerButton = _ref; + ref: _ref => { + this.triggerButton = _ref; }, - width: o.triggerWidth || o.height + width: o.triggerWidth || o.height, }; return ({ type: "bi.horizontal_fill", columnSize: ["fill", ""], - items: [ - { - el: label, - width: "fill" - }, { - el: o.allowClear ? { - type: "bi.vertical_adapt", - width: o.triggerWidth || o.height, - height: o.height, - horizontalAlign: "left", - scrollable: false, - items: [ - { - el: { - type: "bi.icon_button", - ref: function (_ref) { - self.clearBtn = _ref; - }, - cls: "close-h-font " + (o.allowClear ? "clear-button" : ""), - stopPropagation: true, - width: o.triggerWidth || o.height, - invisible: !BI.isNotEmptyString(o.text), - handler: function () { - self.fireEvent(BI.TextTrigger.EVENT_CLEAR); - }, - }, - }, { - el: triggerButton, - } - ] - } : triggerButton, - } - ] + items: [{ + el: label, + width: "fill", + }, { + el: o.allowClear ? { + type: "bi.vertical_adapt", + width: o.triggerWidth || o.height, + height: o.height, + horizontalAlign: "left", + scrollable: false, + items: [{ + el: { + type: "bi.icon_button", + ref: _ref => { + this.clearBtn = _ref; + }, + cls: `close-h-font ${o.allowClear ? "clear-button" : ""}`, + stopPropagation: true, + width: o.triggerWidth || o.height, + invisible: !isNotEmptyString(o.text), + handler: () => { + this.fireEvent(TextTrigger.EVENT_CLEAR); + }, + }, + }, { + el: triggerButton, + }], + } : triggerButton, + }], }); - }, + } - getText: function () { - var o = this.options; - return BI.isFunction(o.text) ? o.text() : o.text; - }, + getText() { + const o = this.options; + + return isFunction(o.text) ? o.text() : o.text; + } - getDefaultText: function () { - var o = this.options; - return BI.isFunction(o.defaultText) ? o.defaultText() : o.defaultText; - }, + getDefaultText() { + const o = this.options; + + return isFunction(o.defaultText) ? o.defaultText() : o.defaultText; + } - getTextor: function () { + getTextor() { return this.text; - }, + } - setTextCls: function (cls) { - var o = this.options; - var oldCls = o.textCls; + setTextCls(cls) { + const o = this.options; + const oldCls = o.textCls; o.textCls = cls; this.text.element.removeClass(oldCls).addClass(cls); - }, + } - setText: function (text) { + setText(text) { if (this.options.allowClear) { - this.clearBtn.setVisible(BI.isNotEmptyString(text)); + this.clearBtn.setVisible(isNotEmptyString(text)); } - if (BI.isKey(text)) { + if (isKey(text)) { this.text.setText(text); this.text.element.removeClass("bi-tips"); - } else if (BI.isKey(this.options.defaultText)) { + } else if (isKey(this.options.defaultText)) { this.text.setText(this.options.defaultText); this.text.element.addClass("bi-tips"); } else { this.text.setText(""); this.text.element.removeClass("bi-tips"); } - }, + } - setTipType: function (v) { + setTipType(v) { this.text.options.tipType = v; this.options.tipType = v; } -}); - -BI.TextTrigger.EVENT_CLEAR = "EVENT_CLEAR"; -BI.shortcut("bi.text_trigger", BI.TextTrigger); +} diff --git a/src/case/trigger/trigger.text.select.js b/src/case/trigger/trigger.text.select.js index 005ac241b..8094a424d 100644 --- a/src/case/trigger/trigger.text.select.js +++ b/src/case/trigger/trigger.text.select.js @@ -1,32 +1,40 @@ +import { shortcut, extend, emptyFn, createWidget, isFunction, isArray, Tree, each, contains, remove } from "@/core"; +import { Trigger } from "@/base"; +import { TextTrigger } from "./trigger.text"; + /** * 选择字段trigger * * Created by GUY on 2015/9/15. - * @class BI.SelectTextTrigger - * @extends BI.Trigger + * @class SelectTextTrigger + * @extends Trigger */ -BI.SelectTextTrigger = BI.inherit(BI.Trigger, { +@shortcut() +export class SelectTextTrigger extends Trigger { + static xtype = "bi.select_text_trigger" + + static EVENT_CLEAR = "EVENT_CLEAR" - _defaultConfig: function () { - return BI.extend(BI.SelectTextTrigger.superclass._defaultConfig.apply(this, arguments), { + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-select-text-trigger", height: 24, allowClear: false, - valueFormatter: BI.emptyFn, + valueFormatter: emptyFn, defaultText: "", }); - }, + } - _init: function () { - BI.SelectTextTrigger.superclass._init.apply(this, arguments); - var self = this, o = this.options; - var text = this._digest(o.value, o.items); - this.trigger = BI.createWidget({ + _init() { + super._init(...arguments); + const o = this.options; + const text = this._digest(o.value, o.items); + this.trigger = createWidget({ type: "bi.text_trigger", element: this, height: o.height, readonly: o.readonly, - text: text, + text, defaultText: o.defaultText, textHgap: o.textHgap, textVgap: o.textVgap, @@ -37,71 +45,67 @@ BI.SelectTextTrigger = BI.inherit(BI.Trigger, { tipType: o.tipType, title: null, allowClear: o.allowClear, - listeners: [ - { - eventName: BI.TextTrigger.EVENT_CLEAR, - action: function () { - self.setText(""); - self.fireEvent(BI.SelectTextTrigger.EVENT_CLEAR); - } - } - ] + listeners: [{ + eventName: TextTrigger.EVENT_CLEAR, + action: () => { + this.setText(""); + this.fireEvent(SelectTextTrigger.EVENT_CLEAR); + }, + }], }); - }, + } - _digest: function (val, items) { - var o = this.options; + _digest(val, items) { + const o = this.options; - val = BI.isArray(val) ? val.slice() : [val]; + val = isArray(val) ? val.slice() : [val]; - var result = []; + const result = []; // 提升valueFormatter的优先级 - if (o.valueFormatter !== BI.emptyFn && BI.isFunction(o.valueFormatter)) { - BI.each(val, function (index, v) { + if (o.valueFormatter !== emptyFn && isFunction(o.valueFormatter)) { + each(val, (index, v) => { result.push(o.valueFormatter(v)); }); + return result.join(","); } - var formatItems = BI.Tree.transformToArrayFormat(items); - BI.each(formatItems, function (i, item) { - if (BI.contains(val, item.value) && !BI.contains(result, item.text || item.value)) { + const formatItems = Tree.transformToArrayFormat(items); + each(formatItems, (i, item) => { + if (contains(val, item.value) && !contains(result, item.text || item.value)) { result.push(item.text || item.value); - BI.remove(val, item.value); + remove(val, item.value); } }); if (result.length > 0 && val.length === 0) { return result.join(","); } else { - return BI.isFunction(o.text) ? o.text() : o.text; + return isFunction(o.text) ? o.text() : o.text; } - }, + } - setText: function (text) { + setText(text) { this.options.text = text; this.trigger.setText(text); - }, + } - setValue: function (val) { - var formatText = this._digest(val, this.options.items); + setValue(val) { + const formatText = this._digest(val, this.options.items); this.trigger.setText(formatText); - }, + } - setTipType: function (v) { + setTipType(v) { this.options.tipType = v; this.trigger.setTipType(v); - }, + } - getTextor: function () { + getTextor() { return this.trigger.getTextor(); - }, + } - populate: function (items) { + populate(items) { this.options.items = items; } -}); - -BI.SelectTextTrigger.EVENT_CLEAR = "EVENT_CLEAR"; -BI.shortcut("bi.select_text_trigger", BI.SelectTextTrigger); +} diff --git a/src/case/trigger/trigger.text.select.small.js b/src/case/trigger/trigger.text.select.small.js index adbd5603c..944ee1a51 100644 --- a/src/case/trigger/trigger.text.select.small.js +++ b/src/case/trigger/trigger.text.select.small.js @@ -1,26 +1,31 @@ +import { shortcut, extend, toPix, createWidget, isArray, deepContains, each, contains, Tree } from "@/core"; +import { Trigger } from "@/base"; + /** * 选择字段trigger小一号的 * - * @class BI.SmallSelectTextTrigger - * @extends BI.Trigger + * @class SmallSelectTextTrigger + * @extends Trigger */ -BI.SmallSelectTextTrigger = BI.inherit(BI.Trigger, { +@shortcut() +export class SmallSelectTextTrigger extends Trigger { + static xtype = "bi.small_select_text_trigger" - _defaultConfig: function () { - return BI.extend(BI.SmallSelectTextTrigger.superclass._defaultConfig.apply(this, arguments), { + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-small-select-text-trigger bi-border", height: 20, }); - }, + } - _init: function () { - BI.SmallSelectTextTrigger.superclass._init.apply(this, arguments); - var self = this, o = this.options; - var obj = this._digest(o.value, o.items); - this.trigger = BI.createWidget({ + _init() { + super._init(...arguments); + const o = this.options; + const obj = this._digest(o.value, o.items); + this.trigger = createWidget({ type: "bi.small_text_trigger", element: this, - height: BI.toPix(o.height, 2), + height: toPix(o.height, 2), text: obj.text, cls: obj.cls, textHgap: o.textHgap, @@ -30,15 +35,15 @@ BI.SmallSelectTextTrigger = BI.inherit(BI.Trigger, { textTgap: o.textTgap, textBgap: o.textBgap, }); - }, + } - _digest: function(vals, items){ - var o = this.options; - vals = BI.isArray(vals) ? vals : [vals]; - var result = []; - var formatItems = BI.Tree.transformToArrayFormat(items); - BI.each(formatItems, function (i, item) { - if (BI.deepContains(vals, item.value) && !BI.contains(result, item.text || item.value)) { + _digest(vals, items) { + const o = this.options; + vals = isArray(vals) ? vals : [vals]; + const result = []; + const formatItems = Tree.transformToArrayFormat(items); + each(formatItems, (i, item) => { + if (deepContains(vals, item.value) && !contains(result, item.text || item.value)) { result.push(item.text || item.value); } }); @@ -46,24 +51,23 @@ BI.SmallSelectTextTrigger = BI.inherit(BI.Trigger, { if (result.length > 0) { return { cls: "", - text: result.join(",") - } + text: result.join(","), + }; } else { return { cls: "bi-water-mark", - text: o.text - } + text: o.text, + }; } - }, + } - setValue: function (vals) { - var formatValue = this._digest(vals, this.options.items); + setValue(vals) { + const formatValue = this._digest(vals, this.options.items); this.trigger.element.removeClass("bi-water-mark").addClass(formatValue.cls); this.trigger.setText(formatValue.text); - }, + } - populate: function (items) { + populate(items) { this.options.items = items; } -}); -BI.shortcut("bi.small_select_text_trigger", BI.SmallSelectTextTrigger); +} diff --git a/src/case/trigger/trigger.text.small.js b/src/case/trigger/trigger.text.small.js index 27c395a69..9269a4210 100644 --- a/src/case/trigger/trigger.text.small.js +++ b/src/case/trigger/trigger.text.small.js @@ -1,23 +1,30 @@ +import { shortcut, extend, createWidget } from "@/core"; +import { Trigger } from "@/base"; + /** * 文字trigger(右边小三角小一号的) == * - * @class BI.SmallTextTrigger - * @extends BI.Trigger + * @class SmallTextTrigger + * @extends Trigger */ -BI.SmallTextTrigger = BI.inherit(BI.Trigger, { - _defaultConfig: function () { - var conf = BI.SmallTextTrigger.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-text-trigger", +@shortcut() +export class SmallTextTrigger extends Trigger { + static xtype = "bi.small_text_trigger" + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-text-trigger`, height: 20, textHgap: 6, }); - }, + } - _init: function () { - BI.SmallTextTrigger.superclass._init.apply(this, arguments); - var self = this, o = this.options, c = this._const; - this.text = BI.createWidget({ + _init() { + super._init(...arguments); + const o = this.options; + this.text = createWidget({ type: "bi.label", textAlign: "left", height: o.height, @@ -29,32 +36,29 @@ BI.SmallTextTrigger = BI.inherit(BI.Trigger, { tgap: o.textTgap, bgap: o.textBgap, }); - this.trigerButton = BI.createWidget({ + this.trigerButton = createWidget({ type: "bi.trigger_icon_button", - width: o.triggerWidth || o.height + width: o.triggerWidth || o.height, }); - BI.createWidget({ + createWidget({ element: this, type: "bi.horizontal_fill", - items: [ - { - el: this.text, - width: "fill" - }, { - el: this.trigerButton, - width: "" - } - ] + items: [{ + el: this.text, + width: "fill", + }, { + el: this.trigerButton, + width: "", + }], }); - }, + } - setValue: function (value) { + setValue(value) { this.text.setValue(value); - }, + } - setText: function (text) { + setText(text) { this.text.setText(text); } -}); -BI.shortcut("bi.small_text_trigger", BI.SmallTextTrigger); +} From 36d186f4c08b3776f8a4bdb3b43e98cf715c4d42 Mon Sep 17 00:00:00 2001 From: "crawford.zhou" Date: Wed, 11 Jan 2023 11:00:07 +0800 Subject: [PATCH 063/300] =?UTF-8?q?KERNEL-14067=20feat:checkbox=E7=9A=84es?= =?UTF-8?q?6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/case/checkbox/check.arrownode.js | 26 +++++++++------ src/case/checkbox/check.checkingmarknode.js | 24 +++++++------ src/case/checkbox/check.first.treenode.js | 37 ++++++++++++--------- src/case/checkbox/check.last.treenode.js | 35 ++++++++++--------- src/case/checkbox/check.mid.treenode.js | 37 ++++++++++++--------- src/case/checkbox/check.treenode.js | 37 ++++++++++++--------- 6 files changed, 112 insertions(+), 84 deletions(-) diff --git a/src/case/checkbox/check.arrownode.js b/src/case/checkbox/check.arrownode.js index 3347f83d0..625e7a6e4 100644 --- a/src/case/checkbox/check.arrownode.js +++ b/src/case/checkbox/check.arrownode.js @@ -2,24 +2,28 @@ * Created by roy on 15/10/16. * 右与下箭头切换的树节点 */ -BI.ArrowTreeGroupNodeCheckbox = BI.inherit(BI.IconButton, { +import { shortcut } from "@/core"; +import { IconButton } from "@/base"; - props: function (conf) { +@shortcut() +export class ArrowTreeGroupNodeCheckbox extends IconButton { + static xtype = "bi.arrow_group_node_checkbox"; + + props(conf) { return { - extraCls: "bi-arrow-group-node-checkbox " + (conf.collapseIcon || "expander-right-font"), + extraCls: `bi-arrow-group-node-checkbox ${conf.collapseIcon || "expander-right-font"}`, expandIcon: "expander-down-font", - collapseIcon: "expander-right-font" + collapseIcon: "expander-right-font", }; - }, + } - setSelected: function (v) { - var o = this.options; - BI.ArrowTreeGroupNodeCheckbox.superclass.setSelected.apply(this, arguments); - if(v) { + setSelected(v) { + const o = this.options; + super.setSelected(...arguments); + if (v) { this.element.removeClass(o.collapseIcon).addClass(o.expandIcon); } else { this.element.removeClass(o.expandIcon).addClass(o.collapseIcon); } } -}); -BI.shortcut("bi.arrow_group_node_checkbox", BI.ArrowTreeGroupNodeCheckbox); +} diff --git a/src/case/checkbox/check.checkingmarknode.js b/src/case/checkbox/check.checkingmarknode.js index b3996691e..4f51a02c1 100644 --- a/src/case/checkbox/check.checkingmarknode.js +++ b/src/case/checkbox/check.checkingmarknode.js @@ -3,19 +3,23 @@ * @class BI.CheckingMarkNode * @extends BI.IconButton */ -BI.CheckingMarkNode = BI.inherit(BI.IconButton, { - _defaultConfig: function () { - return BI.extend( BI.CheckingMarkNode.superclass._defaultConfig.apply(this, arguments), { - }); - }, +import { extend, shortcut } from "@/core"; +import { IconButton } from "@/base"; - setSelected: function (v) { - BI.CheckingMarkNode.superclass.setSelected.apply(this, arguments); - if(v === true) { +@shortcut() +export class CheckingMarkNode extends IconButton { + static xtype = "bi.checking_mark_node"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), {}); + } + + setSelected(v) { + super.setSelected(...arguments); + if (v === true) { this.element.addClass("check-mark-font"); } else { this.element.removeClass("check-mark-font"); } } -}); -BI.shortcut("bi.checking_mark_node", BI.CheckingMarkNode); +} diff --git a/src/case/checkbox/check.first.treenode.js b/src/case/checkbox/check.first.treenode.js index aa808488f..bade32c4d 100644 --- a/src/case/checkbox/check.first.treenode.js +++ b/src/case/checkbox/check.first.treenode.js @@ -3,31 +3,36 @@ * @class BI.FirstTreeNodeCheckbox * @extends BI.IconButton */ -BI.FirstTreeNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function () { - return BI.extend( BI.FirstTreeNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { +import { extend, shortcut } from "@/core"; +import { IconButton } from "@/base"; + +@shortcut() +export class FirstTreeNodeCheckbox extends IconButton { + static xtype = "bi.first_tree_node_checkbox"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { extraCls: BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? "tree-solid-collapse-icon-type2" : "tree-collapse-icon-type2", iconWidth: 24, - iconHeight: 24 + iconHeight: 24, }); - }, + } - getLineCls: function () { + getLineCls() { switch (BI.STYLE_CONSTANTS.LINK_LINE_TYPE) { - case "solid": - return "tree-solid-expand-icon-type2"; - default: - return "tree-expand-icon-type2"; + case "solid": + return "tree-solid-expand-icon-type2"; + default: + return "tree-expand-icon-type2"; } - }, + } - setSelected: function (v) { - BI.FirstTreeNodeCheckbox.superclass.setSelected.apply(this, arguments); - if(v === true) { + setSelected(v) { + super.setSelected(...arguments); + if (v === true) { this.element.addClass(this.getLineCls()); } else { this.element.removeClass(this.getLineCls()); } } -}); -BI.shortcut("bi.first_tree_node_checkbox", BI.FirstTreeNodeCheckbox); \ No newline at end of file +} diff --git a/src/case/checkbox/check.last.treenode.js b/src/case/checkbox/check.last.treenode.js index cb536f8cc..93ebc9c66 100644 --- a/src/case/checkbox/check.last.treenode.js +++ b/src/case/checkbox/check.last.treenode.js @@ -3,31 +3,36 @@ * @class BI.LastTreeNodeCheckbox * @extends BI.IconButton */ -BI.LastTreeNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function () { - return BI.extend(BI.LastTreeNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { +import { extend, shortcut } from "@/core"; +import { IconButton } from "@/base"; + +@shortcut() +export class LastTreeNodeCheckbox extends IconButton { + static xtype = "bi.last_tree_node_checkbox"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { extraCls: BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? "tree-solid-collapse-icon-type4" : "tree-collapse-icon-type4", iconWidth: 24, - iconHeight: 24 + iconHeight: 24, }); - }, + } - getLineCls: function () { + getLineCls() { switch (BI.STYLE_CONSTANTS.LINK_LINE_TYPE) { - case "solid": - return "tree-solid-expand-icon-type4"; - default: - return "tree-expand-icon-type4"; + case "solid": + return "tree-solid-expand-icon-type4"; + default: + return "tree-expand-icon-type4"; } - }, + } - setSelected: function (v) { - BI.LastTreeNodeCheckbox.superclass.setSelected.apply(this, arguments); + setSelected(v) { + super.setSelected(...arguments); if (v === true) { this.element.addClass(this.getLineCls()); } else { this.element.removeClass(this.getLineCls()); } } -}); -BI.shortcut("bi.last_tree_node_checkbox", BI.LastTreeNodeCheckbox); \ No newline at end of file +} diff --git a/src/case/checkbox/check.mid.treenode.js b/src/case/checkbox/check.mid.treenode.js index 7ec4e5230..a9d44de0e 100644 --- a/src/case/checkbox/check.mid.treenode.js +++ b/src/case/checkbox/check.mid.treenode.js @@ -3,31 +3,36 @@ * @class BI.MidTreeNodeCheckbox * @extends BI.IconButton */ -BI.MidTreeNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function () { - return BI.extend( BI.MidTreeNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { +import { extend, shortcut } from "@/core"; +import { IconButton } from "@/base"; + +@shortcut() +export class MidTreeNodeCheckbox extends IconButton { + static xtype = "bi.mid_tree_node_checkbox"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { extraCls: BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? "tree-solid-collapse-icon-type3" : "tree-collapse-icon-type3", iconWidth: 24, - iconHeight: 24 + iconHeight: 24, }); - }, + } - getLineCls: function () { + getLineCls() { switch (BI.STYLE_CONSTANTS.LINK_LINE_TYPE) { - case "solid": - return "tree-solid-expand-icon-type3"; - default: - return "tree-expand-icon-type3"; + case "solid": + return "tree-solid-expand-icon-type3"; + default: + return "tree-expand-icon-type3"; } - }, + } - setSelected: function (v) { - BI.MidTreeNodeCheckbox.superclass.setSelected.apply(this, arguments); - if(v === true) { + setSelected(v) { + super.setSelected(...arguments); + if (v === true) { this.element.addClass(this.getLineCls()); } else { this.element.removeClass(this.getLineCls()); } } -}); -BI.shortcut("bi.mid_tree_node_checkbox", BI.MidTreeNodeCheckbox); \ No newline at end of file +} diff --git a/src/case/checkbox/check.treenode.js b/src/case/checkbox/check.treenode.js index 128bb73c6..fa1b54404 100644 --- a/src/case/checkbox/check.treenode.js +++ b/src/case/checkbox/check.treenode.js @@ -3,31 +3,36 @@ * @class BI.TreeNodeCheckbox * @extends BI.IconButton */ -BI.TreeNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function () { - return BI.extend( BI.TreeNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { +import { extend, shortcut } from "@/core"; +import { IconButton } from "@/base"; + +@shortcut() +export class TreeNodeCheckbox extends IconButton { + static xtype = "bi.tree_node_checkbox"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { extraCls: BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? "tree-solid-collapse-icon-type1" : "tree-collapse-icon-type1", iconWidth: 24, - iconHeight: 24 + iconHeight: 24, }); - }, + } - getLineCls: function () { + getLineCls() { switch (BI.STYLE_CONSTANTS.LINK_LINE_TYPE) { - case "solid": - return "tree-solid-expand-icon-type1"; - default: - return "tree-expand-icon-type1"; + case "solid": + return "tree-solid-expand-icon-type1"; + default: + return "tree-expand-icon-type1"; } - }, + } - setSelected: function (v) { - BI.TreeNodeCheckbox.superclass.setSelected.apply(this, arguments); - if(v) { + setSelected(v) { + super.setSelected(...arguments); + if (v) { this.element.addClass(this.getLineCls()); } else { this.element.removeClass(this.getLineCls()); } } -}); -BI.shortcut("bi.tree_node_checkbox", BI.TreeNodeCheckbox); \ No newline at end of file +} From 0591f0ded9876dcd1ed46f59d12350488cd1621b Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Wed, 11 Jan 2023 11:38:55 +0800 Subject: [PATCH 064/300] =?UTF-8?q?KERNEL-14081=20refactor:=20case/loader?= =?UTF-8?q?=E3=80=81segment=E3=80=81toolbar?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.js | 2 + src/case/index.js | 12 +- src/case/loader/index.js | 3 + src/case/loader/loader.lazy.js | 131 ++++----- src/case/loader/loader.list.js | 188 ++++++------ src/case/loader/sort.list.js | 171 +++++------ src/case/segment/button.segment.js | 49 ++-- src/case/segment/index.js | 2 + src/case/segment/segment.js | 77 ++--- src/case/toolbar/toolbar.multiselect.js | 134 +++++---- src/core/platform/web/dom.js | 367 ++++++++++++------------ src/core/utils/color.js | 3 + 12 files changed, 598 insertions(+), 541 deletions(-) create mode 100644 src/case/loader/index.js create mode 100644 src/case/segment/index.js diff --git a/es6.js b/es6.js index 2fa0181eb..005b6f512 100644 --- a/es6.js +++ b/es6.js @@ -104,6 +104,8 @@ collection.methods.forEach(el => { "each", "contains", "remove", + "createItems", + "makeArrayByArray", ]; target.forEach(t => { diff --git a/src/case/index.js b/src/case/index.js index 515a45107..40e8a73e4 100644 --- a/src/case/index.js +++ b/src/case/index.js @@ -3,6 +3,9 @@ import * as calendarItem from "./calendar"; import * as pager from "./pager"; import * as editor from "./editor"; import * as trigger from "./trigger"; +import * as loader from "./loader"; +import * as segment from "./segment"; +import { MultiSelectBar } from "./toolbar/toolbar.multiselect"; Object.assign(BI, { ...button, @@ -10,6 +13,9 @@ Object.assign(BI, { ...pager, ...editor, ...trigger, + ...loader, + ...segment, + MultiSelectBar, }); export * from "./button"; @@ -17,4 +23,8 @@ export * from "./calendar"; export * from "./pager"; export * from "./editor"; export * from "./trigger"; - +export * from "./loader"; +export * from "./segment"; +export { + MultiSelectBar +}; diff --git a/src/case/loader/index.js b/src/case/loader/index.js new file mode 100644 index 000000000..0fe9aa242 --- /dev/null +++ b/src/case/loader/index.js @@ -0,0 +1,3 @@ +export { LazyLoader } from "./loader.lazy"; +export { ListLoader } from "./loader.list"; +export { SortList } from "./sort.list"; diff --git a/src/case/loader/loader.lazy.js b/src/case/loader/loader.lazy.js index 339940077..54f983ee6 100644 --- a/src/case/loader/loader.lazy.js +++ b/src/case/loader/loader.lazy.js @@ -1,103 +1,106 @@ -/** - * Created by roy on 15/11/6. - */ -BI.LazyLoader = BI.inherit(BI.Widget, { - _const: { - PAGE: 100 - }, - _defaultConfig: function () { - return BI.extend(BI.LazyLoader.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, Widget, extend, createWidget, takeRight, take } from "@/core"; +import { Loader } from "@/base"; + +@shortcut() +export class LazyLoader extends Widget { + static xtype = "bi.lazy_loader" + + _const = { + PAGE: 100, + }; + + static EVENT_CHANGE = "EVENT_CHANGE" + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-lazy-loader", el: {}, - items: [] + items: [], }); - }, + } - _init: function () { - var self = this, o = this.options; - BI.LazyLoader.superclass._init.apply(this, arguments); - var all = o.items.length; - this.loader = BI.createWidget({ + _init() { + const o = this.options; + super._init(...arguments); + const all = o.items.length; + this.loader = createWidget({ type: "bi.loader", element: this, // 下面是button_group的属性 el: o.el, - - itemsCreator: function (options, populate) { - populate(self._getNextItems(options)); + itemsCreator: (options, populate) => { + populate(this._getNextItems(options)); }, - hasNext: function (option) { - return option.count < all; - } + hasNext: option => option.count < all, }); - this.loader.on(BI.Loader.EVENT_CHANGE, function (obj) { - self.fireEvent(BI.LazyLoader.EVENT_CHANGE, obj); + this.loader.on(Loader.EVENT_CHANGE, obj => { + this.fireEvent(LazyLoader.EVENT_CHANGE, obj); }); - }, - _getNextItems: function (options) { - var self = this, o = this.options; - var lastNum = o.items.length - this._const.PAGE * (options.times - 1); - var lastItems = BI.takeRight(o.items, lastNum); - var nextItems = BI.take(lastItems, this._const.PAGE); + } + + _getNextItems(options) { + const o = this.options; + const lastNum = o.items.length - this._const.PAGE * (options.times - 1); + const lastItems = takeRight(o.items, lastNum); + const nextItems = take(lastItems, this._const.PAGE); + return nextItems; - }, + } - populate: function (items) { + populate(items) { this.loader.populate(items); - }, + } - addItems: function (items) { + addItems(items) { this.loader.addItems(items); - }, + } - empty: function () { + empty() { this.loader.empty(); - }, + } - setNotSelectedValue: function () { - this.loader.setNotSelectedValue.apply(this.loader, arguments); - }, + setNotSelectedValue() { + this.loader.setNotSelectedValue(...arguments); + } - getNotSelectedValue: function () { + getNotSelectedValue() { return this.loader.getNotSelectedValue(); - }, + } - setValue: function () { - this.loader.setValue.apply(this.loader, arguments); - }, + setValue() { + this.loader.setValue(...arguments); + } - getValue: function () { - return this.loader.getValue.apply(this.loader, arguments); - }, + getValue() { + return this.loader.getValue(...arguments); + } - getAllButtons: function () { + getAllButtons() { return this.loader.getAllButtons(); - }, + } - getAllLeaves: function () { + getAllLeaves() { return this.loader.getAllLeaves(); - }, + } - getSelectedButtons: function () { + getSelectedButtons() { return this.loader.getSelectedButtons(); - }, + } - getNotSelectedButtons: function () { + getNotSelectedButtons() { return this.loader.getNotSelectedButtons(); - }, + } - getIndexByValue: function (value) { + getIndexByValue(value) { return this.loader.getIndexByValue(value); - }, + } - getNodeById: function (id) { + getNodeById(id) { return this.loader.getNodeById(id); - }, + } - getNodeByValue: function (value) { + getNodeByValue(value) { return this.loader.getNodeByValue(value); } -}); -BI.LazyLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.lazy_loader", BI.LazyLoader); \ No newline at end of file +} diff --git a/src/case/loader/loader.list.js b/src/case/loader/loader.list.js index aeb3ad959..a8aa011e3 100644 --- a/src/case/loader/loader.list.js +++ b/src/case/loader/loader.list.js @@ -1,105 +1,112 @@ +import { shortcut, Widget, extend, emptyFn, Controller, createWidget, Events, nextTick, bind, isEmpty, isNumber, isObject, isFunction, each, isNotEmptyArray, DOM } from "@/core"; + /** * 恶心的加载控件, 为解决排序问题引入的控件 * * Created by GUY on 2015/11/12. - * @class BI.ListLoader - * @extends BI.Widget + * @class ListLoader + * @extends Widget */ -BI.ListLoader = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.ListLoader.superclass._defaultConfig.apply(this, arguments), { - baseCls: "bi-list-loader", +@shortcut() +export class ListLoader extends Widget { + static xtype = "bi.list_loader" - isDefaultInit: true, // 是否默认初始化数据 + static EVENT_CHANGE = "EVENT_CHANGE" + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { + baseCls: "bi-list-loader", + isDefaultInit: true, // 是否默认初始化数据 // 下面是button_group的属性 el: { - type: "bi.button_group" + type: "bi.button_group", }, - items: [], - itemsCreator: BI.emptyFn, - onLoaded: BI.emptyFn, - + itemsCreator: emptyFn, + onLoaded: emptyFn, // 下面是分页信息 count: false, next: {}, - hasNext: BI.emptyFn + hasNext: emptyFn, }); - }, + } - _nextLoad: function () { - var self = this, o = this.options; + _nextLoad() { + const o = this.options; this.next.setLoading(); - o.itemsCreator.apply(this, [{times: ++this.times}, function () { - self.next.setLoaded(); - self.addItems.apply(self, arguments); + o.itemsCreator.apply(this, [{ + times: ++this.times, + }, (...args) => { + this.next.setLoaded(); + this.addItems(...args); }]); - }, + } - _init: function () { - BI.ListLoader.superclass._init.apply(this, arguments); - var self = this, o = this.options; + _init() { + super._init(...arguments); + const o = this.options; if (o.itemsCreator === false) { o.next = false; } - this.button_group = BI.createWidget(o.el, { + this.button_group = createWidget(o.el, { type: "bi.button_group", element: this, chooseType: 0, items: o.items, behaviors: {}, layouts: [{ - type: "bi.vertical" - }] + type: "bi.vertical", + }], }); - this.button_group.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if (type === BI.Events.CLICK) { - self.fireEvent(BI.ListLoader.EVENT_CHANGE, obj); + this.button_group.on(Controller.EVENT_CHANGE, (...args) => { + const [type, , obj] = args; + this.fireEvent(Controller.EVENT_CHANGE, ...args); + if (type === Events.CLICK) { + this.fireEvent(ListLoader.EVENT_CHANGE, obj); } }); if (o.next !== false) { - this.next = BI.createWidget(BI.extend({ - type: "bi.loading_bar" + this.next = createWidget(extend({ + type: "bi.loading_bar", }, o.next)); - this.next.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) { - self._nextLoad(); + this.next.on(Controller.EVENT_CHANGE, type => { + if (type === Events.CLICK) { + this._nextLoad(); } }); } - BI.createWidget({ + createWidget({ type: "bi.vertical", element: this, - items: [this.next] + items: [this.next], }); - o.isDefaultInit && BI.isEmpty(o.items) && BI.nextTick(BI.bind(function () { + o.isDefaultInit && isEmpty(o.items) && nextTick(bind(function () { this.populate(); }, this)); - if (BI.isNotEmptyArray(o.items)) { + if (isNotEmptyArray(o.items)) { this.populate(o.items); } - }, + } - hasNext: function () { - var o = this.options; - if (BI.isNumber(o.count)) { + hasNext() { + const o = this.options; + if (isNumber(o.count)) { return this.count < o.count; } + return !!o.hasNext.apply(this, [{ times: this.times, - count: this.count + count: this.count, }]); - }, + } - addItems: function (items) { + addItems(items) { this.count += items.length; - if (BI.isObject(this.next)) { + if (isObject(this.next)) { this.options.items = this.options.items.concat(items); if (this.hasNext()) { this.next.setLoaded(); @@ -107,90 +114,91 @@ BI.ListLoader = BI.inherit(BI.Widget, { this.next.setEnd(); } } - this.button_group.addItems.apply(this.button_group, arguments); + this.button_group.addItems(...arguments); this.next.element.appendTo(this.element); - }, + } - populate: function (items) { - var self = this, o = this.options; - if (arguments.length === 0 && (BI.isFunction(o.itemsCreator))) { - o.itemsCreator.apply(this, [{times: 1}, function () { - if (arguments.length === 0) { + populate(items) { + const o = this.options; + if (arguments.length === 0 && (isFunction(o.itemsCreator))) { + o.itemsCreator.apply(this, [{ + times: 1, + }, (...args) => { + if (args.length === 0) { throw new Error("参数不能为空"); } - self.populate.apply(self, arguments); + this.populate(...args); o.onLoaded(); }]); + return; } this.options.items = items; this.times = 1; this.count = 0; this.count += items.length; - if (BI.isObject(this.next)) { + if (isObject(this.next)) { if (this.hasNext()) { this.next.setLoaded(); } else { this.next.invisible(); } } - BI.DOM.hang([this.next]); - this.button_group.populate.apply(this.button_group, arguments); + DOM.hang([this.next]); + this.button_group.populate(...arguments); this.next.element.appendTo(this.element); - }, + } - empty: function () { - BI.DOM.hang([this.next]); + empty() { + DOM.hang([this.next]); this.button_group.empty(); this.next.element.appendTo(this.element); - BI.each([this.next], function (i, ob) { + each([this.next], (i, ob) => { ob && ob.setVisible(false); }); - }, + } - setNotSelectedValue: function () { - this.button_group.setNotSelectedValue.apply(this.button_group, arguments); - }, + setNotSelectedValue() { + this.button_group.setNotSelectedValue(...arguments); + } - getNotSelectedValue: function () { + getNotSelectedValue() { return this.button_group.getNotSelectedValue(); - }, + } - setValue: function () { - this.button_group.setValue.apply(this.button_group, arguments); - }, + setValue() { + this.button_group.setValue(...arguments); + } - getValue: function () { - return this.button_group.getValue.apply(this.button_group, arguments); - }, + getValue() { + return this.button_group.getValue(...arguments); + } - getAllButtons: function () { + getAllButtons() { return this.button_group.getAllButtons(); - }, + } - getAllLeaves: function () { + getAllLeaves() { return this.button_group.getAllLeaves(); - }, + } - getSelectedButtons: function () { + getSelectedButtons() { return this.button_group.getSelectedButtons(); - }, + } - getNotSelectedButtons: function () { + getNotSelectedButtons() { return this.button_group.getNotSelectedButtons(); - }, + } - getIndexByValue: function (value) { + getIndexByValue(value) { return this.button_group.getIndexByValue(value); - }, + } - getNodeById: function (id) { + getNodeById(id) { return this.button_group.getNodeById(id); - }, + } - getNodeByValue: function (value) { + getNodeByValue(value) { return this.button_group.getNodeByValue(value); } -}); -BI.ListLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.list_loader", BI.ListLoader); \ No newline at end of file +} diff --git a/src/case/loader/sort.list.js b/src/case/loader/sort.list.js index c4606a7cb..b3d147fe3 100644 --- a/src/case/loader/sort.list.js +++ b/src/case/loader/sort.list.js @@ -1,58 +1,61 @@ +import { shortcut, Widget, extend, emptyFn, Controller, createWidget, Events, each, stripEL } from "@/core"; + /** * Created by GUY on 2016/4/29. * - * @class BI.SortList - * @extends BI.Widget + * @class SortList + * @extends Widget */ -BI.SortList = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.SortList.superclass._defaultConfig.apply(this, arguments), { - baseCls: "bi-sort-list", +@shortcut() +export class SortList extends Widget { + static xtype = "bi.sort_list" - isDefaultInit: true, // 是否默认初始化数据 + static EVENT_CHANGE = "EVENT_CHANGE" + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { + baseCls: "bi-sort-list", + isDefaultInit: true, // 是否默认初始化数据 // 下面是button_group的属性 el: { - type: "bi.button_group" + type: "bi.button_group", }, - items: [], - itemsCreator: BI.emptyFn, - onLoaded: BI.emptyFn, - + itemsCreator: emptyFn, + onLoaded: emptyFn, // 下面是分页信息 count: false, next: {}, - hasNext: BI.emptyFn - + hasNext: emptyFn, // containment: this.element, // connectWith: ".bi-sort-list", }); - }, + } - _init: function () { - BI.SortList.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.loader = BI.createWidget({ + _init() { + super._init(...arguments); + const o = this.options; + this.loader = createWidget({ type: "bi.list_loader", element: this, isDefaultInit: o.isDefaultInit, el: o.el, items: this._formatItems(o.items), - itemsCreator: function (op, callback) { - o.itemsCreator(op, function (items) { - callback(self._formatItems(items)); + itemsCreator (op, callback) { + o.itemsCreator(op, items => { + callback(this._formatItems(items)); }); }, onLoaded: o.onLoaded, count: o.count, next: o.next, - hasNext: o.hasNext + hasNext: o.hasNext, }); - this.loader.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if (type === BI.Events.CLICK) { - self.fireEvent(BI.SortList.EVENT_CHANGE, value, obj); + this.loader.on(Controller.EVENT_CHANGE, (...args) => { + const [type, value, obj] = args; + this.fireEvent(Controller.EVENT_CHANGE, ...args); + if (type === Events.CLICK) { + this.fireEvent(SortList.EVENT_CHANGE, value, obj); } }); @@ -63,114 +66,116 @@ BI.SortList = BI.inherit(BI.Widget, { cursor: o.cursor || "drag", tolerance: o.tolerance || "intersect", placeholder: { - element: function ($currentItem) { - var holder = BI.createWidget({ + element ($currentItem) { + const holder = createWidget({ type: "bi.layout", cls: "bi-sortable-holder", - height: $currentItem.outerHeight() + height: $currentItem.outerHeight(), }); holder.element.css({ "margin-left": $currentItem.css("margin-left"), "margin-right": $currentItem.css("margin-right"), "margin-top": $currentItem.css("margin-top"), "margin-bottom": $currentItem.css("margin-bottom"), - margin: $currentItem.css("margin") + margin: $currentItem.css("margin"), }); + return holder.element; }, - update: function () { + update () { - } + }, }, - start: function (event, ui) { + start (event, ui) { }, - stop: function (event, ui) { - self.fireEvent(BI.SortList.EVENT_CHANGE); + stop: (event, ui) => { + this.fireEvent(SortList.EVENT_CHANGE); }, - over: function (event, ui) { + over (event, ui) { - } + }, }); - }, + } - _formatItems: function (items) { - BI.each(items, function (i, item) { - item = BI.stripEL(item); - item.cls = item.cls ? item.cls + " sort-item" : "sort-item"; + _formatItems(items) { + each(items, (i, item) => { + item = stripEL(item); + item.cls = item.cls ? `${item.cls} sort-item` : "sort-item"; item.attributes = { - sorted: item.value + sorted: item.value, }; }); + return items; - }, + } - hasNext: function () { + hasNext() { return this.loader.hasNext(); - }, + } - addItems: function (items) { + addItems(items) { this.loader.addItems(items); - }, + } - populate: function (items) { + populate(items) { if (items) { arguments[0] = this._formatItems(items); } - this.loader.populate.apply(this.loader, arguments); - }, + this.loader.populate(...arguments); + } - empty: function () { + empty() { this.loader.empty(); - }, + } - setNotSelectedValue: function () { - this.loader.setNotSelectedValue.apply(this.loader, arguments); - }, + setNotSelectedValue() { + this.loader.setNotSelectedValue(...arguments); + } - getNotSelectedValue: function () { + getNotSelectedValue() { return this.loader.getNotSelectedValue(); - }, + } - setValue: function () { - this.loader.setValue.apply(this.loader, arguments); - }, + setValue() { + this.loader.setValue(...arguments); + } - getValue: function () { + getValue() { return this.loader.getValue(); - }, + } - getAllButtons: function () { + getAllButtons() { return this.loader.getAllButtons(); - }, + } - getAllLeaves: function () { + getAllLeaves() { return this.loader.getAllLeaves(); - }, + } - getSelectedButtons: function () { + getSelectedButtons() { return this.loader.getSelectedButtons(); - }, + } - getNotSelectedButtons: function () { + getNotSelectedButtons() { return this.loader.getNotSelectedButtons(); - }, + } - getIndexByValue: function (value) { + getIndexByValue(value) { return this.loader.getIndexByValue(value); - }, + } - getNodeById: function (id) { + getNodeById(id) { return this.loader.getNodeById(id); - }, + } - getNodeByValue: function (value) { + getNodeByValue(value) { return this.loader.getNodeByValue(value); - }, + } - getSortedValues: function () { - return this.loader.element.sortable("toArray", {attribute: "sorted"}); + getSortedValues() { + return this.loader.element.sortable("toArray", { + attribute: "sorted", + }); } -}); -BI.SortList.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.sort_list", BI.SortList); +} diff --git a/src/case/segment/button.segment.js b/src/case/segment/button.segment.js index 05d0a3d83..9508a686c 100644 --- a/src/case/segment/button.segment.js +++ b/src/case/segment/button.segment.js @@ -1,43 +1,48 @@ +import { shortcut, extend, createWidget } from "@/core"; +import { BasicButton } from "@/base"; + /** * 分段控件使用的button * * Created by GUY on 2015/9/7. - * @class BI.SegmentButton - * @extends BI.BasicButton + * @class SegmentButton + * @extends BasicButton */ -BI.SegmentButton = BI.inherit(BI.BasicButton, { +@shortcut() +export class SegmentButton extends BasicButton { + static xtype = "bi.segment_button" - _defaultConfig: function () { - var conf = BI.SegmentButton.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-segment-button bi-list-item-select bi-card", + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-segment-button bi-list-item-select bi-card`, shadow: true, readonly: true, - hgap: 5 + hgap: 5, }); - }, + } - _init: function () { - BI.SegmentButton.superclass._init.apply(this, arguments); - var opts = this.options, self = this; - this.text = BI.createWidget({ + _init() { + super._init(...arguments); + const opts = this.options; + this.text = createWidget({ type: "bi.label", element: this, textHeight: opts.height, whiteSpace: opts.whiteSpace, text: opts.text, value: opts.value, - hgap: opts.hgap + hgap: opts.hgap, }); - }, + } - setSelected: function () { - BI.SegmentButton.superclass.setSelected.apply(this, arguments); - }, + setSelected() { + super.setSelected(...arguments); + } - setText: function (text) { - BI.SegmentButton.superclass.setText.apply(this, arguments); + setText(text) { + super.setText(...arguments); this.text.setText(text); } -}); -BI.shortcut("bi.segment_button", BI.SegmentButton); +} diff --git a/src/case/segment/index.js b/src/case/segment/index.js new file mode 100644 index 000000000..59c90b855 --- /dev/null +++ b/src/case/segment/index.js @@ -0,0 +1,2 @@ +export { SegmentButton } from "./button.segment"; +export { Segment } from "./segment"; diff --git a/src/case/segment/segment.js b/src/case/segment/segment.js index 2c1dda918..ac16eba20 100644 --- a/src/case/segment/segment.js +++ b/src/case/segment/segment.js @@ -1,72 +1,79 @@ +import { shortcut, Widget, extend, toPix, Controller, createWidget, createItems, makeArrayByArray } from "@/core"; +import { ButtonGroup } from "@/base"; + /** * 单选按钮组 * * Created by GUY on 2015/9/7. - * @class BI.Segment - * @extends BI.Widget + * @class Segment + * @extends Widget */ -BI.Segment = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.Segment.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class Segment extends Widget { + static xtype = "bi.segment" + + static EVENT_CHANGE = "EVENT_CHANGE" + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-segment", items: [], height: 24, }); - }, - _init: function () { - BI.Segment.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.buttonGroup = BI.createWidget({ + } + + _init() { + super._init(...arguments); + const o = this.options; + this.buttonGroup = createWidget({ element: this, type: "bi.button_group", value: o.value, - items: [BI.createItems(o.items, { + items: [createItems(o.items, { type: "bi.segment_button", - height: BI.toPix(o.height, 2), + height: toPix(o.height, 2), whiteSpace: o.whiteSpace, })], layouts: [{ type: "bi.table", - columnSize: BI.makeArrayByArray(o.items, "fill"), + columnSize: makeArrayByArray(o.items, "fill"), }], }); - this.buttonGroup.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.buttonGroup.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.buttonGroup.on(BI.ButtonGroup.EVENT_CHANGE, function (value, obj) { - self.fireEvent(BI.Segment.EVENT_CHANGE, value, obj); + this.buttonGroup.on(ButtonGroup.EVENT_CHANGE, (value, obj) => { + this.fireEvent(Segment.EVENT_CHANGE, value, obj); }); - }, + } - _setEnable: function (enable) { - BI.Segment.superclass._setEnable.apply(this, arguments); + _setEnable(enable) { + super._setEnable(...arguments); if (enable === true) { this.element.removeClass("base-disabled disabled"); } else if (enable === false) { this.element.addClass("base-disabled disabled"); } - }, + } - setValue: function (v) { + setValue(v) { this.buttonGroup.setValue(v); - }, + } - setEnabledValue: function (v) { + setEnabledValue(v) { this.buttonGroup.setEnabledValue(v); - }, + } - getValue: function () { + getValue() { return this.buttonGroup.getValue(); - }, + } - populate: function (buttons) { - var o = this.options; - this.buttonGroup.populate([BI.createItems(buttons, { + populate(buttons) { + const o = this.options; + this.buttonGroup.populate([createItems(buttons, { type: "bi.segment_button", - height: BI.toPix(o.height, 2), + height: toPix(o.height, 2), whiteSpace: o.whiteSpace, })]); - }, -}); -BI.Segment.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.segment", BI.Segment); + } +} diff --git a/src/case/toolbar/toolbar.multiselect.js b/src/case/toolbar/toolbar.multiselect.js index f18677b85..f5fb1bf45 100644 --- a/src/case/toolbar/toolbar.multiselect.js +++ b/src/case/toolbar/toolbar.multiselect.js @@ -1,20 +1,29 @@ +import { shortcut, extend, emptyFn, i18nText, Controller, createWidget, Events } from "@/core"; +import { BasicButton, Checkbox } from "@/base"; +import { HalfIconButton } from "../button"; + /** * guy * 复选导航条 * Created by GUY on 2015/8/25. - * @class BI.MultiSelectBar - * @extends BI.BasicButton + * @class MultiSelectBar + * @extends BasicButton */ -BI.MultiSelectBar = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - return BI.extend(BI.MultiSelectBar.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class MultiSelectBar extends BasicButton { + static xtype = "bi.multi_select_bar" + + static EVENT_CHANGE = "EVENT_CHANGE" + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-multi-select-bar", height: 25, - text: BI.i18nText("BI-Select_All"), - isAllCheckedBySelectedValue: BI.emptyFn, + text: i18nText("BI-Select_All"), + isAllCheckedBySelectedValue: emptyFn, // 手动控制选中 disableSelected: true, - isHalfCheckedBySelectedValue: function (selectedValues) { + isHalfCheckedBySelectedValue (selectedValues) { return selectedValues.length > 0; }, halfSelected: false, @@ -22,46 +31,47 @@ BI.MultiSelectBar = BI.inherit(BI.BasicButton, { iconWidth: 14, iconHeight: 14, }); - }, - _init: function () { - BI.MultiSelectBar.superclass._init.apply(this, arguments); - var self = this, o = this.options; - var isSelect = o.selected === true; - var isHalfSelect = !o.selected && o.halfSelected; - this.checkbox = BI.createWidget({ + } + + _init() { + super._init(...arguments); + const o = this.options; + const isSelect = o.selected === true; + const isHalfSelect = !o.selected && o.halfSelected; + this.checkbox = createWidget({ type: "bi.checkbox", stopPropagation: true, - handler: function () { - self.setSelected(self.isSelected()); + handler: () => { + this.setSelected(this.isSelected()); }, selected: isSelect, invisible: isHalfSelect, iconWidth: o.iconWidth, - iconHeight: o.iconHeight + iconHeight: o.iconHeight, }); - this.half = BI.createWidget({ + this.half = createWidget({ type: "bi.half_icon_button", stopPropagation: true, - handler: function () { - self.setSelected(true); + handler: () => { + this.setSelected(true); }, invisible: isSelect || !isHalfSelect, iconWidth: o.iconWidth, - iconHeight: o.iconHeight + iconHeight: o.iconHeight, }); - this.checkbox.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.CLICK, self.isSelected(), self); + this.checkbox.on(Controller.EVENT_CHANGE, () => { + this.fireEvent(Controller.EVENT_CHANGE, Events.CLICK, this.isSelected(), this); }); - this.checkbox.on(BI.Checkbox.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiSelectBar.EVENT_CHANGE, self.isSelected(), self); + this.checkbox.on(Checkbox.EVENT_CHANGE, () => { + this.fireEvent(MultiSelectBar.EVENT_CHANGE, this.isSelected(), this); }); - this.half.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.CLICK, self.isSelected(), self); + this.half.on(Controller.EVENT_CHANGE, () => { + this.fireEvent(Controller.EVENT_CHANGE, Events.CLICK, this.isSelected(), this); }); - this.half.on(BI.HalfIconButton.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiSelectBar.EVENT_CHANGE, self.isSelected(), self); + this.half.on(HalfIconButton.EVENT_CHANGE, () => { + this.fireEvent(MultiSelectBar.EVENT_CHANGE, this.isSelected(), this); }); - this.text = BI.createWidget({ + this.text = createWidget({ type: "bi.label", textAlign: "left", whiteSpace: "nowrap", @@ -71,43 +81,43 @@ BI.MultiSelectBar = BI.inherit(BI.BasicButton, { text: o.text, keyword: o.keyword, value: o.value, - py: o.py + py: o.py, }); - BI.createWidget({ + createWidget({ type: "bi.htape", element: this, items: [{ width: o.iconWrapperWidth, el: { type: "bi.center_adapt", - items: [this.checkbox, this.half] - } + items: [this.checkbox, this.half], + }, }, { - el: this.text - }] + el: this.text, + }], }); - }, + } - _setSelected: function (v) { + _setSelected(v) { this.checkbox.setSelected(!!v); - }, + } - // 自己手动控制选中 - beforeClick: function () { - var isHalf = this.isHalfSelected(), isSelected = this.isSelected(); + beforeClick() { + const isHalf = this.isHalfSelected(), + isSelected = this.isSelected(); if (isHalf === true) { this.setSelected(true); } else { this.setSelected(!isSelected); } - }, + } - setSelected: function (v) { + setSelected(v) { this.checkbox.setSelected(v); this.setHalfSelected(false); - }, + } - setHalfSelected: function (b) { + setHalfSelected(b) { this.halfSelected = !!b; if (b === true) { this.checkbox.setSelected(false); @@ -117,29 +127,27 @@ BI.MultiSelectBar = BI.inherit(BI.BasicButton, { this.half.invisible(); this.checkbox.visible(); } - }, + } - isHalfSelected: function () { + isHalfSelected() { return !this.isSelected() && !!this.halfSelected; - }, + } - isSelected: function () { + isSelected() { return this.checkbox.isSelected(); - }, + } - setValue: function (selectedValues) { - BI.MultiSelectBar.superclass.setValue.apply(this, arguments); - var isAllChecked = this.options.isAllCheckedBySelectedValue.apply(this, arguments); + setValue(selectedValues) { + super.setValue(...arguments); + const isAllChecked = this.options.isAllCheckedBySelectedValue.apply(this, arguments); this.setSelected(isAllChecked); !isAllChecked && this.setHalfSelected(this.options.isHalfCheckedBySelectedValue.apply(this, arguments)); - }, + } - doClick: function () { - BI.MultiSelectBar.superclass.doClick.apply(this, arguments); - if(this.isValid()) { - this.fireEvent(BI.MultiSelectBar.EVENT_CHANGE, this.isSelected(), this); + doClick() { + super.doClick(...arguments); + if (this.isValid()) { + this.fireEvent(MultiSelectBar.EVENT_CHANGE, this.isSelected(), this); } } -}); -BI.MultiSelectBar.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multi_select_bar", BI.MultiSelectBar); +} diff --git a/src/core/platform/web/dom.js b/src/core/platform/web/dom.js index 5835df64f..1fca2871b 100644 --- a/src/core/platform/web/dom.js +++ b/src/core/platform/web/dom.js @@ -502,207 +502,208 @@ export function getComboPositionByDirections(combo, popup, extraWidth, extraHeig for (i = 0; i < directions.length; i++) { direct = directions[i]; switch (direct) { - case "left": - leftRight.push(direct); - break; - case "right": - leftRight.push(direct); - break; - case "top": - topBottom.push(direct); - break; - case "bottom": - topBottom.push(direct); - break; - case "innerLeft": - innerLeftRight.push(direct); - break; - case "innerRight": - innerLeftRight.push(direct); - break; - default: - break; + case "left": + leftRight.push(direct); + break; + case "right": + leftRight.push(direct); + break; + case "top": + topBottom.push(direct); + break; + case "bottom": + topBottom.push(direct); + break; + case "innerLeft": + innerLeftRight.push(direct); + break; + case "innerRight": + innerLeftRight.push(direct); + break; + default: + break; } } for (i = 0; i < directions.length; i++) { + let tW, tH; direct = directions[i]; switch (direct) { - case "left": - if (!isNeedAdaptHeight) { - var tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? 0 : extraHeight; - if (isLeftSpaceEnough(combo, popup, tW)) { - left = getLeftPosition(combo, popup, tW, container).left; - if (topBottom[0] === "bottom") { - pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight, container); - } else { - pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight, container); - } - pos.dir = `left,${pos.dir}`; - if (tbFirst) { - pos.change = "left"; - } - pos.left = left; - - return pos; + case "left": + if (!isNeedAdaptHeight) { + tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? 0 : extraHeight; + if (isLeftSpaceEnough(combo, popup, tW)) { + left = getLeftPosition(combo, popup, tW, container).left; + if (topBottom[0] === "bottom") { + pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight, container); + } else { + pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight, container); } - } - lrFirst = true; - break; - case "right": - if (!isNeedAdaptHeight) { - var tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? extraWidth : extraHeight; - if (isRightSpaceEnough(combo, popup, tW)) { - left = getRightPosition(combo, popup, tW, container).left; - if (topBottom[0] === "bottom") { - pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight, container); - } else { - pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight, container); - } - pos.dir = `right,${pos.dir}`; - if (tbFirst) { - pos.change = "right"; - } - pos.left = left; - - return pos; + pos.dir = `left,${pos.dir}`; + if (tbFirst) { + pos.change = "left"; } + pos.left = left; + + return pos; } - lrFirst = true; - break; - case "top": - var tW = lrFirst ? extraHeight : extraWidth, tH = lrFirst ? extraWidth : extraHeight; - if (isTopSpaceEnough(combo, popup, tH)) { - top = getTopPosition(combo, popup, tH, container).top; - if (leftRight[0] === "right") { - pos = getLeftAlignPosition(combo, popup, tW, container); + } + lrFirst = true; + break; + case "right": + if (!isNeedAdaptHeight) { + tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? extraWidth : extraHeight; + if (isRightSpaceEnough(combo, popup, tW)) { + left = getRightPosition(combo, popup, tW, container).left; + if (topBottom[0] === "bottom") { + pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight, container); } else { - pos = getRightAlignPosition(combo, popup, tW, container); + pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight, container); } - pos.dir = `top,${pos.dir}`; - if (lrFirst) { - pos.change = "top"; + pos.dir = `right,${pos.dir}`; + if (tbFirst) { + pos.change = "right"; } - pos.top = top; + pos.left = left; return pos; } - if (needAdaptHeight) { - isNeedAdaptHeight = true; + } + lrFirst = true; + break; + case "top": + tW = lrFirst ? extraHeight : extraWidth, tH = lrFirst ? extraWidth : extraHeight; + if (isTopSpaceEnough(combo, popup, tH)) { + top = getTopPosition(combo, popup, tH, container).top; + if (leftRight[0] === "right") { + pos = getLeftAlignPosition(combo, popup, tW, container); + } else { + pos = getRightAlignPosition(combo, popup, tW, container); + } + pos.dir = `top,${pos.dir}`; + if (lrFirst) { + pos.change = "top"; } - tbFirst = true; - break; - case "bottom": - var tW = lrFirst ? extraHeight : extraWidth, tH = lrFirst ? extraWidth : extraHeight; - if (isBottomSpaceEnough(combo, popup, tH)) { - top = getBottomPosition(combo, popup, tH, container).top; - if (leftRight[0] === "right") { - pos = getLeftAlignPosition(combo, popup, tW, container); + pos.top = top; + + return pos; + } + if (needAdaptHeight) { + isNeedAdaptHeight = true; + } + tbFirst = true; + break; + case "bottom": + tW = lrFirst ? extraHeight : extraWidth, tH = lrFirst ? extraWidth : extraHeight; + if (isBottomSpaceEnough(combo, popup, tH)) { + top = getBottomPosition(combo, popup, tH, container).top; + if (leftRight[0] === "right") { + pos = getLeftAlignPosition(combo, popup, tW, container); + } else { + pos = getRightAlignPosition(combo, popup, tW, container); + } + pos.dir = `bottom,${pos.dir}`; + if (lrFirst) { + pos.change = "bottom"; + } + pos.top = top; + + return pos; + } + if (needAdaptHeight) { + isNeedAdaptHeight = true; + } + tbFirst = true; + break; + case "innerLeft": + if (!isNeedAdaptHeight) { + tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? 0 : extraHeight; + if (isInnerLeftSpaceEnough(combo, popup, tW)) { + left = getInnerLeftPosition(combo, popup, tW).left; + if (topBottom[0] === "bottom") { + pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight); } else { - pos = getRightAlignPosition(combo, popup, tW, container); + pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight); } - pos.dir = `bottom,${pos.dir}`; - if (lrFirst) { - pos.change = "bottom"; + pos.dir = `innerLeft,${pos.dir}`; + if (tbFirst) { + pos.change = "innerLeft"; } - pos.top = top; + pos.left = left; return pos; } - if (needAdaptHeight) { - isNeedAdaptHeight = true; - } - tbFirst = true; - break; - case "innerLeft": - if (!isNeedAdaptHeight) { - var tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? 0 : extraHeight; - if (isInnerLeftSpaceEnough(combo, popup, tW)) { - left = getInnerLeftPosition(combo, popup, tW).left; - if (topBottom[0] === "bottom") { - pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight); - } else { - pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight); - } - pos.dir = `innerLeft,${pos.dir}`; - if (tbFirst) { - pos.change = "innerLeft"; - } - pos.left = left; - - return pos; + } + lrFirst = true; + break; + case "innerRight": + if (!isNeedAdaptHeight) { + tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? extraWidth : extraHeight; + if (isInnerRightSpaceEnough(combo, popup, tW)) { + left = getInnerRightPosition(combo, popup, tW).left; + if (topBottom[0] === "bottom") { + pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight); + } else { + pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight); } - } - lrFirst = true; - break; - case "innerRight": - if (!isNeedAdaptHeight) { - var tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? extraWidth : extraHeight; - if (isInnerRightSpaceEnough(combo, popup, tW)) { - left = getInnerRightPosition(combo, popup, tW).left; - if (topBottom[0] === "bottom") { - pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight); - } else { - pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight); - } - pos.dir = `innerLeft,${pos.dir}`; - if (tbFirst) { - pos.change = "innerRight"; - } - pos.left = left; - - return pos; + pos.dir = `innerLeft,${pos.dir}`; + if (tbFirst) { + pos.change = "innerRight"; } + pos.left = left; + + return pos; } - break; - default: - break; + } + break; + default: + break; } } // 此处为四个方向放不下时挑空间最大的方向去放置, 也就是说我设置了弹出方向为"bottom,left", // 最后发现实际弹出方向可能是"top,left",那么此时外界获取popup的方向应该是"top,left" switch (directions[0]) { - case "left": - case "right": - if (isRightSpaceLarger(combo)) { - left = getRightAdaptPosition(combo, popup, extraWidth, container).left; - firstDir = "right"; - } else { - left = getLeftAdaptPosition(combo, popup, extraWidth, container).left; - firstDir = "left"; - } - if (topBottom[0] === "bottom") { - pos = getTopAlignPosition(combo, popup, extraHeight, needAdaptHeight); - pos.left = left; - pos.dir = `${firstDir},${pos.dir}`; - - return pos; - } - pos = getBottomAlignPosition(combo, popup, extraHeight, needAdaptHeight); + case "left": + case "right": + if (isRightSpaceLarger(combo)) { + left = getRightAdaptPosition(combo, popup, extraWidth, container).left; + firstDir = "right"; + } else { + left = getLeftAdaptPosition(combo, popup, extraWidth, container).left; + firstDir = "left"; + } + if (topBottom[0] === "bottom") { + pos = getTopAlignPosition(combo, popup, extraHeight, needAdaptHeight); pos.left = left; pos.dir = `${firstDir},${pos.dir}`; return pos; - default : - if (isBottomSpaceLarger(combo)) { - top = getBottomAdaptPosition(combo, popup, extraHeight, needAdaptHeight, container).top; - firstDir = "bottom"; - } else { - top = getTopAdaptPosition(combo, popup, extraHeight, needAdaptHeight, container).top; - firstDir = "top"; - } - if (leftRight[0] === "right") { - pos = getLeftAlignPosition(combo, popup, extraWidth, container); - pos.top = top; - pos.dir = `${firstDir},${pos.dir}`; - - return pos; - } - pos = getRightAlignPosition(combo, popup, extraWidth, container); + } + pos = getBottomAlignPosition(combo, popup, extraHeight, needAdaptHeight); + pos.left = left; + pos.dir = `${firstDir},${pos.dir}`; + + return pos; + default : + if (isBottomSpaceLarger(combo)) { + top = getBottomAdaptPosition(combo, popup, extraHeight, needAdaptHeight, container).top; + firstDir = "bottom"; + } else { + top = getTopAdaptPosition(combo, popup, extraHeight, needAdaptHeight, container).top; + firstDir = "top"; + } + if (leftRight[0] === "right") { + pos = getLeftAlignPosition(combo, popup, extraWidth, container); pos.top = top; pos.dir = `${firstDir},${pos.dir}`; return pos; + } + pos = getRightAlignPosition(combo, popup, extraWidth, container); + pos.top = top; + pos.dir = `${firstDir},${pos.dir}`; + + return pos; } } @@ -715,26 +716,26 @@ export function getComboPosition(combo, popup, extraWidth, extraHeight, needAdap popup.resetHeight && popup.resetHeight(maxHeight); const position = getComboPositionByDirections(combo, popup, extraWidth, extraHeight, needAdaptHeight, directions || ["bottom", "top", "right", "left"], positionRelativeElement); switch (offsetStyle) { - case "center": - if (position.change) { - var p = getMiddleAdaptPosition(combo, popup, positionRelativeElement); - position.top = p.top; - } else { - var p = getCenterAdaptPosition(combo, popup, positionRelativeElement); - position.left = p.left; - } - break; - case "middle": - if (position.change) { - var p = getCenterAdaptPosition(combo, popup, positionRelativeElement); - position.left = p.left; - } else { - var p = getMiddleAdaptPosition(combo, popup, positionRelativeElement); - position.top = p.top; - } - break; - default: - break; + case "center": + if (position.change) { + const p = getMiddleAdaptPosition(combo, popup, positionRelativeElement); + position.top = p.top; + } else { + const p = getCenterAdaptPosition(combo, popup, positionRelativeElement); + position.left = p.left; + } + break; + case "middle": + if (position.change) { + const p = getCenterAdaptPosition(combo, popup, positionRelativeElement); + position.left = p.left; + } else { + const p = getMiddleAdaptPosition(combo, popup, positionRelativeElement); + position.top = p.top; + } + break; + default: + break; } if (needAdaptHeight === true) { popup.resetHeight && popup.resetHeight(Math.min(viewportBounds.height - position.top - (positionRelativeElement ? positionRelativeElement.getBoundingClientRect().top : 0), maxHeight)); diff --git a/src/core/utils/color.js b/src/core/utils/color.js index 2eff91b95..a219a4f7d 100644 --- a/src/core/utils/color.js +++ b/src/core/utils/color.js @@ -1,4 +1,5 @@ import { parseInt, parseFloat, isNull, isKey } from "../2.base"; +import * as DOMUtils from "../platform/web/dom"; export const DOM = { isColor(color) { @@ -198,4 +199,6 @@ export const DOM = { Math.floor(255 * (bgColor * (1 - A)) + G * A)},${ Math.floor(255 * (bgColor * (1 - A)) + B * A)})`; }, + + ...DOMUtils, }; From 43c2313d55fe59f0f6226c083bf5677286c7979e Mon Sep 17 00:00:00 2001 From: Treecat Date: Wed, 11 Jan 2023 11:38:54 +0800 Subject: [PATCH 065/300] =?UTF-8?q?KERNEL-14076=20feat:=20es6=20=E8=84=9A?= =?UTF-8?q?=E6=9C=AC=E9=80=92=E5=BD=92=E6=96=87=E4=BB=B6=E5=A4=B9=EF=BC=8C?= =?UTF-8?q?eslint=20=E8=87=AA=E5=8A=A8=20fix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.js | 269 ++++++++++++++++++++++++++++++--------------------- package.json | 3 +- 2 files changed, 160 insertions(+), 112 deletions(-) diff --git a/es6.js b/es6.js index 9c0b18bf4..b3e9e1b6f 100644 --- a/es6.js +++ b/es6.js @@ -1,121 +1,137 @@ const fs = require("fs"); - -const srcName = process.argv[2]; - -const sourceCode = fs.readFileSync(srcName).toString(); - -const clzName = /BI\.(.*?)\s\=\sBI\.inherit\(/.exec(sourceCode)[1]; - -const superName = /inherit\(BI\.(.*?),/.exec(sourceCode)[1]; - -// const xtype = /BI.shortcut\(\"(.*?)\"/.exec(sourceCode)[1]; - -const collection = { - "static": {}, - attr: {}, -}; - -const BI = { - inherit(_, options) { - collection.methods = Object.keys(options) - .filter(key => typeof options[key] === "function") - .map(key => options[key]); - Object.keys(options) - .filter(key => typeof options[key] !== "function") - .forEach(key => { - collection.attr[key] = options[key]; - }); - - return collection.static; - }, - shortcut(xtype) { - collection.xtype = xtype; - }, -}; - -eval(sourceCode); - -let M = ""; -let E = ""; -let I = ""; -let A = ""; - -const coreImport = { - shortcut: true, -}; - -if (superName === "Widget") { - coreImport.Widget = true; +const path = require("path"); +const prettier = require("prettier"); +const { exec } = require("child_process"); + +async function fix(path) { + new Promise(res => { + exec(`yarn eslint --fix ${path}`, () => { + res(); + }); + }); } -Object.keys(collection.attr).forEach(key => { - A = `${key} = ${JSON.stringify(collection.attr[key])};`; -}); - -// 静态方法 -Object.keys(collection.static).forEach(key => { - E += `\tstatic ${key} = "${collection.static[key]}"\n`; -}); - -// 对函数进行替换 -collection.methods.forEach(el => { - let f = `${el.toString().replace(/^function/, el.name)}\n`; - - // 换 BI.Button.superclass - f = f.replace(`BI.${clzName}.superclass`, "super"); - // 换 super._defaultConfig - f = f.replace( - `super\._defaultConfig\.apply\(this\,\sarguments\)`, - "super._defaultConfig(arguments)" - ); - // 换 super.xxx.apply - f = f.replace(/super\.(.*?)\.apply\(this\,\sarguments\)/, a => { - const f = /super\.(.*?)\.apply\(this\,\sarguments\)/.exec(a); - - return `super.${f[1]}(...arguments)`; +async function handleFile(srcName) { + const sourceCode = fs.readFileSync(srcName).toString(); + + const result = /BI\.(.*?)\s\=\sBI\.inherit\(/.exec(sourceCode); + if (!result) { + console.log(`可能是已经es6过了 ${srcName}`); + + return; + } + const clzName = result[1]; + + const superName = /inherit\(BI\.(.*?),/.exec(sourceCode)[1]; + + // const xtype = /BI.shortcut\(\"(.*?)\"/.exec(sourceCode)[1]; + + const collection = { + "static": {}, + attr: {}, + }; + + const BI = { + inherit(_, options) { + collection.methods = Object.keys(options) + .filter(key => typeof options[key] === "function") + .map(key => options[key]); + Object.keys(options) + .filter(key => typeof options[key] !== "function") + .forEach(key => { + collection.attr[key] = options[key]; + }); + + return collection.static; + }, + shortcut(xtype) { + collection.xtype = xtype; + }, + }; + + eval(sourceCode); + + let M = ""; + let E = ""; + let I = ""; + let A = ""; + + const coreImport = { + shortcut: true, + }; + + if (superName === "Widget") { + coreImport.Widget = true; + } + + Object.keys(collection.attr).forEach(key => { + A = `${key} = ${JSON.stringify(collection.attr[key])};`; }); - const target = [ - "isNull", - "toPix", - "isKey", - "isObject", - "map", - "extend", - "isFunction", - "isEmptyArray", - "isArray", - "Controller", - clzName, - "createWidget", - "Events", - "emptyFn", - "nextTick", - "bind", - "i18nText", - "isNotNull", - "isString", - "isNumber", - "isEmpty", - ]; - - target.forEach(t => { - const arr = f.split(`BI.${t}`); - // nodejs 低版本没有 replaceAll - if (arr.length > 1) { - if (t !== clzName) coreImport[t] = true; - f = arr.join(t); - } + // 静态方法 + Object.keys(collection.static).forEach(key => { + E += `\tstatic ${key} = "${collection.static[key]}"\n`; }); - M += `${f}\n`; -}); + // 对函数进行替换 + collection.methods.forEach(el => { + let f = `${el.toString().replace(/^function/, el.name)}\n`; + + // 换 BI.Button.superclass + f = f.replace(`BI.${clzName}.superclass`, "super"); + // 换 super._defaultConfig + f = f.replace( + `super\._defaultConfig\.apply\(this\,\sarguments\)`, + "super._defaultConfig(arguments)" + ); + // 换 super.xxx.apply + f = f.replace(/super\.(.*?)\.apply\(this\,\sarguments\)/, a => { + const f = /super\.(.*?)\.apply\(this\,\sarguments\)/.exec(a); + + return `super.${f[1]}(...arguments)`; + }); + + const target = [ + "isNull", + "toPix", + "isKey", + "isObject", + "map", + "extend", + "isFunction", + "isEmptyArray", + "isArray", + "Controller", + clzName, + "createWidget", + "Events", + "emptyFn", + "nextTick", + "bind", + "i18nText", + "isNotNull", + "isString", + "isNumber", + "isEmpty", + ]; + + target.forEach(t => { + const arr = f.split(`BI.${t}`); + // nodejs 低版本没有 replaceAll + if (arr.length > 1) { + if (t !== clzName) coreImport[t] = true; + f = arr.join(t); + } + }); + + M += `${f}\n`; + }); -Object.keys(coreImport).forEach(el => { - I += `${el},`; -}); + Object.keys(coreImport).forEach(el => { + I += `${el},`; + }); -const outputCode = ` + const outputCode = ` import {${I}} from "@/core" @shortcut() @@ -130,5 +146,36 @@ ${M} } `; -// fs.writeFileSync(`${srcName}.js.raw`, sourceCode); -fs.writeFileSync(srcName, outputCode); + const prettierCode = prettier.format(outputCode); + fs.writeFileSync(srcName, prettierCode); + await fix(srcName); + + return clzName; +} + +async function traverse(srcName) { + if (srcName.indexOf("__test__") >= 0) return; + + if (srcName.endsWith(".js")) { + return await handleFile(srcName); + } else { + const stat = fs.statSync(srcName); + const flag = stat.isDirectory(); + if (flag) { + const files = fs.readdirSync(srcName); + // let indexContent = ""; + for (let i = 0; i < files.length; i++) { + const file = files[i]; + await traverse(path.resolve(srcName, file)); + // const clzName = await traverse(path.resolve(srcName, file)); + // const moduleName = path.basename(srcName).replace(/.js$/, ""); + // if (clzName) { + // indexContent += `export { ${clzName} } from '${moduleName}'\n`; + // } + } + } + } +} + +const srcName = process.argv[2]; +traverse(srcName); diff --git a/package.json b/package.json index f5b71dcc2..cc33beee2 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ "cross-env": "6.0.0", "css-loader": "3.0.0", "es6-promise": "4.2.8", - "eslint": "6.0.1", + "eslint": "7.32.0", "expose-loader": "0.7.5", "express": "4.15.2", "fork-ts-checker-webpack-plugin": "1.4.3", @@ -47,6 +47,7 @@ "optimize-css-assets-webpack-plugin": "5.0.3", "postcss-loader": "3.0.0", "postcss-simple-vars": "5.0.2", + "prettier": "2.8.2", "puppeteer": "^13.3.0", "rimraf": "3.0.2", "script-loader": "0.7.2", From c9c65cfbbfb8d6ca4501fe0005b2f46bcc78458d Mon Sep 17 00:00:00 2001 From: "crawford.zhou" Date: Wed, 11 Jan 2023 13:50:20 +0800 Subject: [PATCH 066/300] =?UTF-8?q?KERNEL-14067=20feat:checkbox=E7=9A=84es?= =?UTF-8?q?6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/case/checkbox/index.js | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 src/case/checkbox/index.js diff --git a/src/case/checkbox/index.js b/src/case/checkbox/index.js new file mode 100644 index 000000000..aaaf21a68 --- /dev/null +++ b/src/case/checkbox/index.js @@ -0,0 +1,6 @@ +export { ArrowTreeGroupNodeCheckbox } from "./check.arrownode"; +export { CheckingMarkNode } from "./check.checkingmarknode"; +export { FirstTreeNodeCheckbox } from "./check.first.treenode"; +export { LastTreeNodeCheckbox } from "./check.last.treenode"; +export { MidTreeNodeCheckbox } from "./check.mid.treenode"; +export { TreeNodeCheckbox } from "./check.treenode"; From edc9e565bb98789e74bb40a5e12812ed09232f96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Wed, 11 Jan 2023 14:41:20 +0800 Subject: [PATCH 067/300] =?UTF-8?q?KERNEL-14069=20refactor:=20case/layer?= =?UTF-8?q?=E3=80=81linearsegment=E3=80=81list=20es6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/case/index.js | 12 +- src/case/layer/index.js | 4 + src/case/layer/layer.multipopup.js | 54 +-- src/case/layer/layer.panel.js | 57 +-- src/case/layer/pane.list.js | 403 +++++++++++++----- src/case/layer/panel.js | 70 +-- .../linearsegment/button.linear.segment.js | 53 +-- src/case/linearsegment/index.js | 2 + src/case/linearsegment/linear.segment.js | 74 ++-- src/case/list/list.select.js | 249 +++++------ src/core/platform/web/dom.js | 8 +- 11 files changed, 606 insertions(+), 380 deletions(-) create mode 100644 src/case/layer/index.js create mode 100644 src/case/linearsegment/index.js diff --git a/src/case/index.js b/src/case/index.js index 40e8a73e4..11ee09f0b 100644 --- a/src/case/index.js +++ b/src/case/index.js @@ -6,6 +6,9 @@ import * as trigger from "./trigger"; import * as loader from "./loader"; import * as segment from "./segment"; import { MultiSelectBar } from "./toolbar/toolbar.multiselect"; +import * as layer from "./layer"; +import * as linearSegment from "./linearsegment"; +import { SelectList } from "./list/list.select"; Object.assign(BI, { ...button, @@ -16,6 +19,9 @@ Object.assign(BI, { ...loader, ...segment, MultiSelectBar, + ...layer, + ...linearSegment, + SelectList, }); export * from "./button"; @@ -25,6 +31,10 @@ export * from "./editor"; export * from "./trigger"; export * from "./loader"; export * from "./segment"; +export * from "./layer"; +export * from "./linearsegment"; export { - MultiSelectBar + MultiSelectBar, + SelectList }; + diff --git a/src/case/layer/index.js b/src/case/layer/index.js new file mode 100644 index 000000000..73a7ea575 --- /dev/null +++ b/src/case/layer/index.js @@ -0,0 +1,4 @@ +export { MultiPopupView } from "./layer.multipopup"; +export { PopupPanel } from "./layer.panel"; +export { ListPane } from "./pane.list"; +export { Panel } from "./panel"; diff --git a/src/case/layer/layer.multipopup.js b/src/case/layer/layer.multipopup.js index 5b69dabe3..d531f57c7 100644 --- a/src/case/layer/layer.multipopup.js +++ b/src/case/layer/layer.multipopup.js @@ -4,57 +4,57 @@ * @extends BI.Widget */ -BI.MultiPopupView = BI.inherit(BI.PopupView, { - - _defaultConfig: function () { - var conf = BI.MultiPopupView.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - _baseCls: (conf._baseCls || "") + " bi-multi-list-view", - buttons: [BI.i18nText("BI-Basic_OK")] +import { shortcut, extend, i18nText, each, createWidget, createItems } from "@/core"; +import { PopupView, ButtonGroup } from "@/base"; +@shortcut() +export class MultiPopupView extends PopupView { + static xtype = "bi.multi_popup_view"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_CLICK_TOOLBAR_BUTTON = "EVENT_CLICK_TOOLBAR_BUTTON"; + _defaultConfig () { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + _baseCls: `${conf._baseCls || ""} bi-multi-list-view`, + buttons: [i18nText("BI-Basic_OK")], }); - }, + } - _createToolBar: function () { - var o = this.options, self = this; + _createToolBar () { + const o = this.options; if (o.buttons.length === 0) { return; } - var text = []; // 构造[{text:content},……] - BI.each(o.buttons, function (idx, item) { + const text = []; // 构造[{text:content},……] + each(o.buttons, (idx, item) => { text.push({ text: item, - value: idx + value: idx, }); }); - this.buttongroup = BI.createWidget({ + this.buttongroup = createWidget({ type: "bi.button_group", cls: "list-view-toolbar bi-high-light bi-split-top", height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - items: BI.createItems(text, { + items: createItems(text, { type: "bi.text_button", once: false, shadow: true, - isShadowShowingOnSelected: true + isShadowShowingOnSelected: true, }), layouts: [{ type: "bi.center", hgap: 0, - vgap: 0 - }] + vgap: 0, + }], }); - this.buttongroup.on(BI.ButtonGroup.EVENT_CHANGE, function (value, obj) { - self.fireEvent(BI.MultiPopupView.EVENT_CLICK_TOOLBAR_BUTTON, value, obj); + this.buttongroup.on(ButtonGroup.EVENT_CHANGE, (value, obj) => { + this.fireEvent(MultiPopupView.EVENT_CLICK_TOOLBAR_BUTTON, value, obj); }); return this.buttongroup; } - -}); - -BI.MultiPopupView.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiPopupView.EVENT_CLICK_TOOLBAR_BUTTON = "EVENT_CLICK_TOOLBAR_BUTTON"; - -BI.shortcut("bi.multi_popup_view", BI.MultiPopupView); +} diff --git a/src/case/layer/layer.panel.js b/src/case/layer/layer.panel.js index c136cc0e9..cc5701e61 100644 --- a/src/case/layer/layer.panel.js +++ b/src/case/layer/layer.panel.js @@ -4,29 +4,38 @@ * @extends BI.MultiPopupView */ -BI.PopupPanel = BI.inherit(BI.MultiPopupView, { - - _defaultConfig: function () { - var conf = BI.PopupPanel.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-popup-panel", - title: "" +import { shortcut, extend, createWidget } from "@/core"; +import { IconButton } from "@/base"; +import { MultiPopupView } from "./layer.multipopup"; +@shortcut() +export class PopupPanel extends MultiPopupView { + static xtype = "bi.popup_panel"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_CLOSE = "EVENT_CLOSE"; + static EVENT_CLICK_TOOLBAR_BUTTON = "EVENT_CLICK_TOOLBAR_BUTTON"; + _defaultConfig () { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-popup-panel`, + title: "", }); - }, + } - _createTool: function () { - var self = this, o = this.options; - var close = BI.createWidget({ + _createTool () { + const o = this.options; + const close = createWidget({ type: "bi.icon_button", cls: "close-h-font", width: 25, - height: 25 + height: 25, }); - close.on(BI.IconButton.EVENT_CHANGE, function () { - self.setVisible(false); - self.fireEvent(BI.PopupPanel.EVENT_CLOSE); + close.on(IconButton.EVENT_CHANGE, () => { + this.setVisible(false); + this.fireEvent(PopupPanel.EVENT_CLOSE); }); - return BI.createWidget({ + + return createWidget({ type: "bi.htape", cls: "popup-panel-title bi-header-background", height: 25, @@ -36,18 +45,12 @@ BI.PopupPanel = BI.inherit(BI.MultiPopupView, { textAlign: "left", text: o.title, height: 25, - lgap: 10 - } + lgap: 10, + }, }, { el: close, - width: 25 - }] + width: 25, + }], }); } -}); - -BI.PopupPanel.EVENT_CHANGE = "EVENT_CHANGE"; -BI.PopupPanel.EVENT_CLOSE = "EVENT_CLOSE"; -BI.PopupPanel.EVENT_CLICK_TOOLBAR_BUTTON = "EVENT_CLICK_TOOLBAR_BUTTON"; - -BI.shortcut("bi.popup_panel", BI.PopupPanel); +} diff --git a/src/case/layer/pane.list.js b/src/case/layer/pane.list.js index d4b774d00..21d9ebeb7 100644 --- a/src/case/layer/pane.list.js +++ b/src/case/layer/pane.list.js @@ -5,14 +5,19 @@ * @class BI.ListPane * @extends BI.Pane */ -BI.ListPane = BI.inherit(BI.Pane, { - - _defaultConfig: function () { - var conf = BI.ListPane.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-list-pane", +import { shortcut, extend, each, createWidget, emptyFn, nextTick, concat, get, Controller, Events, LogicFactory, Direction, isNull, removeAt, isFunction, isNotEmptyString, isEmptyArray } from "@/core"; +import { Pane, ButtonGroup } from "@/base"; +@shortcut() +export class ListPane extends Pane { + static xtype = "bi.list_pane"; + static EVENT_CHANGE = "EVENT_CHANGE"; + _defaultConfig () { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-list-pane`, logic: { - dynamic: true + dynamic: true, }, lgap: 0, rgap: 0, @@ -21,181 +26,373 @@ BI.ListPane = BI.inherit(BI.Pane, { vgap: 0, hgap: 0, items: [], - itemsCreator: BI.emptyFn, - hasNext: BI.emptyFn, - onLoaded: BI.emptyFn, + itemsCreator: emptyFn, + hasNext: emptyFn, + onLoaded: emptyFn, el: { - type: "bi.button_group" - } + type: "bi.button_group", + }, }); - }, - _init: function () { - BI.ListPane.superclass._init.apply(this, arguments); - var self = this, o = this.options; - - this.button_group = BI.createWidget(o.el, { + } + _init () { + super._init(...arguments); + const o = this.options; + this.button_group = createWidget(o.el, { type: "bi.button_group", - chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, + chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, behaviors: {}, items: o.items, value: o.value, - itemsCreator: function (op, calback) { + itemsCreator: (op, callback) => { if (op.times === 1) { - self.empty(); - BI.nextTick(function () { - self.loading(); + this.empty(); + nextTick(() => { + this.loading(); }); } - o.itemsCreator(op, function () { - calback.apply(self, arguments); - o.items = BI.concat(o.items, BI.get(arguments, [0], [])); + o.itemsCreator(op, (...args) => { + callback(...args); + o.items = concat(o.items, get(...args, [0], [])); if (op.times === 1) { - o.items = BI.get(arguments, [0], []); - BI.nextTick(function () { - self.loaded(); + o.items = get(...args, [0], []); + nextTick(() => { + this.loaded(); // callback可能在loading之前执行, check保证显示正确 - self.check(); + this.check(); }); } }); }, hasNext: o.hasNext, layouts: [{ - type: "bi.vertical" - }] + type: "bi.vertical", + }], }); - this.button_group.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if (type === BI.Events.CLICK) { - self.fireEvent(BI.ListPane.EVENT_CHANGE, value, obj); + this.button_group.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); + if (type === Events.CLICK) { + this.fireEvent(ListPane.EVENT_CHANGE, value, obj); } }); this.check(); - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Top), BI.extend({ + createWidget(extend({ + element: this, + }, LogicFactory.createLogic(LogicFactory.createLogicTypeByDirection(Direction.Top), extend({ scrolly: true, lgap: o.lgap, rgap: o.rgap, tgap: o.tgap, bgap: o.bgap, vgap: o.vgap, - hgap: o.hgap + hgap: o.hgap, }, o.logic, { - items: BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Top, this.button_group) + items: LogicFactory.createLogicItemsByDirection(Direction.Top, this.button_group), })))); - }, + } - hasPrev: function () { + hasPrev () { return this.button_group.hasPrev && this.button_group.hasPrev(); - }, + } - hasNext: function () { + hasNext () { return this.button_group.hasNext && this.button_group.hasNext(); - }, + } - prependItems: function (items) { + prependItems (items) { this.options.items = items.concat(this.options.items); - this.button_group.prependItems.apply(this.button_group, arguments); + this.button_group.prependItems(...arguments); this.check(); - }, + } - addItems: function (items) { + addItems (items) { this.options.items = this.options.items.concat(items); - this.button_group.addItems.apply(this.button_group, arguments); + this.button_group.addItems(...arguments); this.check(); - }, + } - removeItemAt: function (indexes) { - indexes = BI.isNull(indexes) ? [] : indexes; - BI.removeAt(this.options.items, indexes); - this.button_group.removeItemAt.apply(this.button_group, arguments); + removeItemAt (indexes) { + indexes = isNull(indexes) ? [] : indexes; + removeAt(this.options.items, indexes); + this.button_group.removeItemAt(...arguments); this.check(); - }, + } - populate: function (items) { - var self = this, o = this.options; - if (arguments.length === 0 && (BI.isFunction(this.button_group.attr("itemsCreator")))) {// 接管loader的populate方法 - this.button_group.attr("itemsCreator").apply(this, [{ times: 1 }, function () { - if (arguments.length === 0) { + populate (items) { + const o = this.options; + if (arguments.length === 0 && (isFunction(this.button_group.attr("itemsCreator")))) {// 接管loader的populate方法 + this.button_group.attr("itemsCreator").apply(this, [{ times: 1 }, (...args) => { + if (args.length === 0) { throw new Error("参数不能为空"); } - self.populate.apply(self, arguments); + this.populate(...args); }]); + return; } - var context = BI.get(arguments, [2], {}); - var tipText = context.tipText || ''; - if (BI.isNotEmptyString(tipText)) { - BI.ListPane.superclass.populate.apply(this, []); + const context = get(arguments, [2], {}); + const tipText = context.tipText || ""; + if (isNotEmptyString(tipText)) { + super.populate.apply(this, []); this.setTipText(tipText); } else { - BI.ListPane.superclass.populate.apply(this, arguments); - this.button_group.populate.apply(this.button_group, arguments); - BI.isEmptyArray(BI.get(arguments, [0], [])) && this.setTipText(o.tipText); + super.populate(...arguments); + this.button_group.populate(...arguments); + isEmptyArray(get(arguments, [0], [])) && this.setTipText(o.tipText); } - }, + } - empty: function () { + empty () { this.button_group.empty(); - }, + } - setNotSelectedValue: function () { - this.button_group.setNotSelectedValue.apply(this.button_group, arguments); - }, + setNotSelectedValue () { + this.button_group.setNotSelectedValue(...arguments); + } - getNotSelectedValue: function () { + getNotSelectedValue () { return this.button_group.getNotSelectedValue(); - }, + } - setValue: function () { - this.button_group.setValue.apply(this.button_group, arguments); - }, + setValue () { + this.button_group.setValue(...arguments); + } - setAllSelected: function (v) { + setAllSelected (v) { if (this.button_group.setAllSelected) { this.button_group.setAllSelected(v); } else { - BI.each(this.getAllButtons(), function (i, btn) { + each(this.getAllButtons(), (i, btn) => { (btn.setSelected || btn.setAllSelected).apply(btn, [v]); }); } - }, + } - getValue: function () { - return this.button_group.getValue.apply(this.button_group, arguments); - }, + getValue () { + return this.button_group.getValue(...arguments); + } - getAllButtons: function () { + getAllButtons () { return this.button_group.getAllButtons(); - }, + } - getAllLeaves: function () { + getAllLeaves () { return this.button_group.getAllLeaves(); - }, + } - getSelectedButtons: function () { + getSelectedButtons () { return this.button_group.getSelectedButtons(); - }, + } - getNotSelectedButtons: function () { + getNotSelectedButtons () { return this.button_group.getNotSelectedButtons(); - }, + } - getIndexByValue: function (value) { + getIndexByValue (value) { return this.button_group.getIndexByValue(value); - }, + } - getNodeById: function (id) { + getNodeById (id) { return this.button_group.getNodeById(id); - }, + } - getNodeByValue: function (value) { + getNodeByValue (value) { return this.button_group.getNodeByValue(value); } -}); -BI.ListPane.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.list_pane", BI.ListPane); +} +// BI.ListPane = BI.inherit(BI.Pane, { + +// _defaultConfig: function () { +// var conf = BI.ListPane.superclass._defaultConfig.apply(this, arguments); +// return BI.extend(conf, { +// baseCls: (conf.baseCls || "") + " bi-list-pane", +// logic: { +// dynamic: true +// }, +// lgap: 0, +// rgap: 0, +// tgap: 0, +// bgap: 0, +// vgap: 0, +// hgap: 0, +// items: [], +// itemsCreator: BI.emptyFn, +// hasNext: BI.emptyFn, +// onLoaded: BI.emptyFn, +// el: { +// type: "bi.button_group" +// } +// }); +// }, +// _init: function () { +// BI.ListPane.superclass._init.apply(this, arguments); +// var self = this, o = this.options; + +// this.button_group = BI.createWidget(o.el, { +// type: "bi.button_group", +// chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, +// behaviors: {}, +// items: o.items, +// value: o.value, +// itemsCreator: function (op, calback) { +// if (op.times === 1) { +// self.empty(); +// BI.nextTick(function () { +// self.loading(); +// }); +// } +// o.itemsCreator(op, function () { +// calback.apply(self, arguments); +// o.items = BI.concat(o.items, BI.get(arguments, [0], [])); +// if (op.times === 1) { +// o.items = BI.get(arguments, [0], []); +// BI.nextTick(function () { +// self.loaded(); +// // callback可能在loading之前执行, check保证显示正确 +// self.check(); +// }); +// } +// }); +// }, +// hasNext: o.hasNext, +// layouts: [{ +// type: "bi.vertical" +// }] +// }); + +// this.button_group.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { +// self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); +// if (type === BI.Events.CLICK) { +// self.fireEvent(BI.ListPane.EVENT_CHANGE, value, obj); +// } +// }); +// this.check(); + +// BI.createWidget(BI.extend({ +// element: this +// }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Top), BI.extend({ +// scrolly: true, +// lgap: o.lgap, +// rgap: o.rgap, +// tgap: o.tgap, +// bgap: o.bgap, +// vgap: o.vgap, +// hgap: o.hgap +// }, o.logic, { +// items: BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Top, this.button_group) +// })))); +// }, + +// hasPrev: function () { +// return this.button_group.hasPrev && this.button_group.hasPrev(); +// }, + +// hasNext: function () { +// return this.button_group.hasNext && this.button_group.hasNext(); +// }, + +// prependItems: function (items) { +// this.options.items = items.concat(this.options.items); +// this.button_group.prependItems.apply(this.button_group, arguments); +// this.check(); +// }, + +// addItems: function (items) { +// this.options.items = this.options.items.concat(items); +// this.button_group.addItems.apply(this.button_group, arguments); +// this.check(); +// }, + +// removeItemAt: function (indexes) { +// indexes = BI.isNull(indexes) ? [] : indexes; +// BI.removeAt(this.options.items, indexes); +// this.button_group.removeItemAt.apply(this.button_group, arguments); +// this.check(); +// }, + +// populate: function (items) { +// var self = this, o = this.options; +// if (arguments.length === 0 && (BI.isFunction(this.button_group.attr("itemsCreator")))) {// 接管loader的populate方法 +// this.button_group.attr("itemsCreator").apply(this, [{ times: 1 }, function () { +// if (arguments.length === 0) { +// throw new Error("参数不能为空"); +// } +// self.populate.apply(self, arguments); +// }]); +// return; +// } + +// var context = BI.get(arguments, [2], {}); +// var tipText = context.tipText || ''; +// if (BI.isNotEmptyString(tipText)) { +// BI.ListPane.superclass.populate.apply(this, []); +// this.setTipText(tipText); +// } else { +// BI.ListPane.superclass.populate.apply(this, arguments); +// this.button_group.populate.apply(this.button_group, arguments); +// BI.isEmptyArray(BI.get(arguments, [0], [])) && this.setTipText(o.tipText); +// } +// }, + +// empty: function () { +// this.button_group.empty(); +// }, + +// setNotSelectedValue: function () { +// this.button_group.setNotSelectedValue.apply(this.button_group, arguments); +// }, + +// getNotSelectedValue: function () { +// return this.button_group.getNotSelectedValue(); +// }, + +// setValue: function () { +// this.button_group.setValue.apply(this.button_group, arguments); +// }, + +// setAllSelected: function (v) { +// if (this.button_group.setAllSelected) { +// this.button_group.setAllSelected(v); +// } else { +// BI.each(this.getAllButtons(), function (i, btn) { +// (btn.setSelected || btn.setAllSelected).apply(btn, [v]); +// }); +// } +// }, + +// getValue: function () { +// return this.button_group.getValue.apply(this.button_group, arguments); +// }, + +// getAllButtons: function () { +// return this.button_group.getAllButtons(); +// }, + +// getAllLeaves: function () { +// return this.button_group.getAllLeaves(); +// }, + +// getSelectedButtons: function () { +// return this.button_group.getSelectedButtons(); +// }, + +// getNotSelectedButtons: function () { +// return this.button_group.getNotSelectedButtons(); +// }, + +// getIndexByValue: function (value) { +// return this.button_group.getIndexByValue(value); +// }, + +// getNodeById: function (id) { +// return this.button_group.getNodeById(id); +// }, + +// getNodeByValue: function (value) { +// return this.button_group.getNodeByValue(value); +// } +// }); +// BI.ListPane.EVENT_CHANGE = "EVENT_CHANGE"; +// BI.shortcut("bi.list_pane", BI.ListPane); diff --git a/src/case/layer/panel.js b/src/case/layer/panel.js index 4ec115b51..51bd4fc50 100644 --- a/src/case/layer/panel.js +++ b/src/case/layer/panel.js @@ -1,11 +1,18 @@ -/** - * 带有标题栏的pane - * @class BI.Panel - * @extends BI.Widget - */ -BI.Panel = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.Panel.superclass._defaultConfig.apply(this, arguments), { + +import { shortcut, Widget, extend, toPix, Controller, createWidget } from "@/core"; +import { ButtonGroup } from "@/base"; + +@shortcut() +export class Panel extends Widget { + static xtype = "bi.panel" + + + + static EVENT_CHANGE = "EVENT_CHANGE" + + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-panel bi-border", title: "", titleHeight: 30, @@ -15,62 +22,59 @@ BI.Panel = BI.inherit(BI.Widget, { // dynamic: false // } }); - }, + } - render: function () { + render() { return { type: "bi.vertical_fill", rowSize: ["", "fill"], - items: [this._createTitle(), this.options.el] + items: [this._createTitle(), this.options.el], }; - }, + } - _createTitle: function () { - var self = this, o = this.options; - this.text = BI.createWidget({ + _createTitle() { + const o = this.options; + this.text = createWidget({ type: "bi.label", cls: "panel-title-text", text: o.title, - height: o.titleHeight + height: o.titleHeight, }); - this.button_group = BI.createWidget({ + this.button_group = createWidget({ type: "bi.button_group", items: o.titleButtons, layouts: [{ type: "bi.center_adapt", - lgap: 10 - }] + lgap: 10, + }], }); - this.button_group.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.button_group.on(Controller.EVENT_CHANGE, () => { + this.fireEvent(Controller.EVENT_CHANGE, ...arguments); }); - this.button_group.on(BI.ButtonGroup.EVENT_CHANGE, function (value, obj) { - self.fireEvent(BI.Panel.EVENT_CHANGE, value, obj); + this.button_group.on(ButtonGroup.EVENT_CHANGE, (value, obj) => { + this.fireEvent(Panel.EVENT_CHANGE, value, obj); }); return { // el: { type: "bi.left_right_vertical_adapt", cls: "panel-title bi-header-background bi-border-bottom", - height: BI.toPix(o.titleHeight, 1), + height: toPix(o.titleHeight, 1), items: { left: [this.text], - right: [this.button_group] + right: [this.button_group], }, lhgap: 10, - rhgap: 10 + rhgap: 10, // }, - // height: BI.toPix(o.titleHeight, 1) + // height: toPix(o.titleHeight, 1) }; - }, + } - setTitle: function (title) { + setTitle(title) { this.text.setValue(title); } -}); -BI.Panel.EVENT_CHANGE = "EVENT_CHANGE"; - -BI.shortcut("bi.panel", BI.Panel); +} diff --git a/src/case/linearsegment/button.linear.segment.js b/src/case/linearsegment/button.linear.segment.js index c9954925c..11c2b20b5 100644 --- a/src/case/linearsegment/button.linear.segment.js +++ b/src/case/linearsegment/button.linear.segment.js @@ -1,26 +1,28 @@ -BI.LinearSegmentButton = BI.inherit(BI.BasicButton, { - props: { - extraCls: "bi-line-segment-button bi-list-item-effect", - once: true, - readonly: true, - hgap: 10, - height: 24 - }, +import { shortcut, toPix } from "@/core"; +import { BasicButton } from "@/base"; - render: function () { - var self = this, o = this.options; +@shortcut() +export class LinearSegmentButton extends BasicButton { + static xtype = "bi.linear_segment_button" + + props = { extraCls:"bi-line-segment-button bi-list-item-effect", once:true, readonly:true, hgap:10, height:24 }; + + + + render () { + const o = this.options; return [{ type: "bi.label", text: o.text, height: o.height, - textHeight: BI.toPix(o.height, 2), + textHeight: toPix(o.height, 2), value: o.value, hgap: o.hgap, - ref: function () { - self.text = this; - } + ref : _ref => { + this.text = _ref; + }, }, { type: "bi.absolute", items: [{ @@ -28,28 +30,27 @@ BI.LinearSegmentButton = BI.inherit(BI.BasicButton, { type: "bi.layout", cls: "line-segment-button-line", height: 2, - ref: function () { - self.line = this; - } + ref : _ref => { + this.line = _ref; + }, }, left: 0, right: 0, - bottom: 0 - }] + bottom: 0, + }], }]; - }, + } - setSelected: function (v) { - BI.LinearSegmentButton.superclass.setSelected.apply(this, arguments); + setSelected (v) { + super.setSelected(...arguments); if (v) { this.line.element.addClass("bi-high-light-background"); } else { this.line.element.removeClass("bi-high-light-background"); } - }, + } - setText: function (text) { + setText (text) { this.text.setText(text); } -}); -BI.shortcut("bi.linear_segment_button", BI.LinearSegmentButton); +} diff --git a/src/case/linearsegment/index.js b/src/case/linearsegment/index.js new file mode 100644 index 000000000..bf437ca2b --- /dev/null +++ b/src/case/linearsegment/index.js @@ -0,0 +1,2 @@ +export { LinearSegmentButton } from "./button.linear.segment"; +export { LinearSegment } from "./linear.segment"; diff --git a/src/case/linearsegment/linear.segment.js b/src/case/linearsegment/linear.segment.js index 41d282263..b34771c3b 100644 --- a/src/case/linearsegment/linear.segment.js +++ b/src/case/linearsegment/linear.segment.js @@ -1,60 +1,62 @@ -BI.LinearSegment = BI.inherit(BI.Widget, { - props: { - baseCls: "bi-linear-segment", - items: [], - height: 30 - }, +import { shortcut, Widget, createItems, makeArrayByArray } from "@/core"; - render: function () { - var self = this, o = this.options; +@shortcut() +export class LinearSegment extends Widget { + static xtype = "bi.linear_segment" + + props = { baseCls:"bi-linear-segment", items:[], height:30 }; + + + + render () { + const o = this.options; + return { type: "bi.button_group", - items: [BI.createItems(o.items, { + items: [createItems(o.items, { type: "bi.linear_segment_button", - height: o.height + height: o.height, })], layouts: [{ type: "bi.table", - columnSize: BI.makeArrayByArray(o.items, "fill"), + columnSize: makeArrayByArray(o.items, "fill"), }], value: o.value, listeners: [{ eventName: "__EVENT_CHANGE__", - action: function () { - self.fireEvent("__EVENT_CHANGE__", arguments); - } + action () { + this.fireEvent("__EVENT_CHANGE__", arguments); + }, }, { eventName: "EVENT_CHANGE", - action: function () { - self.fireEvent("EVENT_CHANGE"); - } + action () { + this.fireEvent("EVENT_CHANGE"); + }, }], - ref: function () { - self.buttonGroup = this; - } + ref: _ref => { + this.buttonGroup = _ref; + }, }; - }, + } - setValue: function (v) { + setValue (v) { this.buttonGroup.setValue(v); - }, + } - setEnabledValue: function (v) { + setEnabledValue (v) { this.buttonGroup.setEnabledValue(v); - }, - + } - getValue: function () { + getValue () { return this.buttonGroup.getValue(); - }, + } - populate: function (buttons) { - var o = this.options; - this.buttonGroup.populate([BI.createItems(buttons, { + populate (buttons) { + const o = this.options; + this.buttonGroup.populate([createItems(buttons, { type: "bi.linear_segment_button", - height: o.height - })]) - }, -}); -BI.shortcut("bi.linear_segment", BI.LinearSegment); + height: o.height, + })]); + } +} diff --git a/src/case/list/list.select.js b/src/case/list/list.select.js index dfb3d7c1a..a6fb459db 100644 --- a/src/case/list/list.select.js +++ b/src/case/list/list.select.js @@ -1,100 +1,105 @@ -/** - * 选择列表 - * - * Created by GUY on 2015/11/1. - * @class BI.SelectList - * @extends BI.Widget - */ -BI.SelectList = BI.inherit(BI.Widget, { - - _defaultConfig: function () { - return BI.extend(BI.SelectList.superclass._defaultConfig.apply(this, arguments), { +/* eslint-disable no-mixed-spaces-and-tabs */ + +import { shortcut, Widget, extend, emptyFn, Controller, createWidget, Events, isNotNull, isEmptyString, isEmptyArray, Direction, get, LogicFactory, each, pixFormat } from "@/core"; +import { ButtonGroup } from "@/base"; +@shortcut() +export class SelectList extends Widget { + static xtype = "bi.select_list"; + + + + static EVENT_CHANGE = "EVENT_CHANGE"; + + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-select-list", - direction: BI.Direction.Top, // toolbar的位置 + direction: Direction.Top, // toolbar的位置 logic: { - dynamic: true + dynamic: true, }, items: [], - itemsCreator: BI.emptyFn, - hasNext: BI.emptyFn, - onLoaded: BI.emptyFn, + itemsCreator: emptyFn, + hasNext: emptyFn, + onLoaded: emptyFn, toolbar: { type: "bi.multi_select_bar", - iconWrapperWidth: 36 + iconWrapperWidth: 36, }, el: { - type: "bi.list_pane" - } + type: "bi.list_pane", + }, }); - }, - _init: function () { - BI.SelectList.superclass._init.apply(this, arguments); - var self = this, o = this.options; + } + + _init() { + super._init(...arguments); + const o = this.options; // 全选 - this.toolbar = BI.createWidget(o.toolbar); + this.toolbar = createWidget(o.toolbar); this.allSelected = false; - this.toolbar.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - self.allSelected = this.isSelected(); - if (type === BI.Events.CLICK) { - self.setAllSelected(self.allSelected); - self.fireEvent(BI.SelectList.EVENT_CHANGE, value, obj); + this.toolbar.on(Controller.EVENT_CHANGE, (type, value, obj) => { + this.allSelected = this.toolbar.isSelected(); + if (type === Events.CLICK) { + this.setAllSelected(this.allSelected); + this.fireEvent(SelectList.EVENT_CHANGE, value, obj); } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.list = BI.createWidget(o.el, { + this.list = createWidget(o.el, { type: "bi.list_pane", items: o.items, - itemsCreator: function (op, callback) { - op.times === 1 && self.toolbar.setVisible(false); - o.itemsCreator(op, function (items, keywords, context) { - callback.apply(self, arguments); + itemsCreator(op, callback) { + op.times === 1 && this.toolbar.setVisible(false); + o.itemsCreator(op, (items, keywords, context, ...args) => { + callback(items, keywords, context, ...args); if (op.times === 1) { - var tipText = BI.get(context, 'tipText', ''); - var visible = BI.isEmptyString(tipText) && items && items.length > 0; - self.toolbar.setVisible(visible); - self.toolbar.setEnable(self.isEnabled() && visible); + const tipText = get(context, "tipText", ""); + const visible = isEmptyString(tipText) && items && items.length > 0; + this.toolbar.setVisible(visible); + this.toolbar.setEnable(this.isEnabled() && visible); } - self._checkAllSelected(); + this._checkAllSelected(); }); }, onLoaded: o.onLoaded, - hasNext: o.hasNext + hasNext: o.hasNext, }); - this.list.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - if (type === BI.Events.CLICK) { - self._checkAllSelected(); - self.fireEvent(BI.SelectList.EVENT_CHANGE, value, obj); + this.list.on(Controller.EVENT_CHANGE, (type, value, obj) => { + if (type === Events.CLICK) { + this._checkAllSelected(); + this.fireEvent(SelectList.EVENT_CHANGE, value, obj); } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.fireEvent(Controller.EVENT_CHANGE, arguments); }); - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend({ - scrolly: true + createWidget(extend({ + element: this, + }, LogicFactory.createLogic(LogicFactory.createLogicTypeByDirection(o.direction), extend({ + scrolly: true, }, o.logic, { - items: BI.LogicFactory.createLogicItemsByDirection(o.direction, this.toolbar, this.list) + items: LogicFactory.createLogicItemsByDirection(o.direction, this.toolbar, this.list), })))); if (o.items.length <= 0) { this.toolbar.setVisible(false); this.toolbar.setEnable(false); } - if(BI.isNotNull(o.value)){ + if (isNotNull(o.value)) { this.setValue(o.value); } - }, + } - _checkAllSelected: function () { - var selectLength = this.list.getValue().length; - var notSelectLength = this.getAllLeaves().length - selectLength; - var hasNext = this.list.hasNext(); - var isAlreadyAllSelected = this.toolbar.isSelected(); - var isHalf = selectLength > 0 && notSelectLength > 0; - var allSelected = selectLength > 0 && notSelectLength <= 0 && (!hasNext || isAlreadyAllSelected); + _checkAllSelected() { + const selectLength = this.list.getValue().length; + const notSelectLength = this.getAllLeaves().length - selectLength; + const hasNext = this.list.hasNext(); + const isAlreadyAllSelected = this.toolbar.isSelected(); + let isHalf = selectLength > 0 && notSelectLength > 0; + let allSelected = selectLength > 0 && notSelectLength <= 0 && (!hasNext || isAlreadyAllSelected); if (this.isAllSelected() === false) { hasNext && (isHalf = selectLength > 0); @@ -110,127 +115,125 @@ BI.SelectList = BI.inherit(BI.Widget, { this.toolbar.setHalfSelected(isHalf); !isHalf && this.toolbar.setSelected(allSelected); - }, + } - setAllSelected: function (v) { + setAllSelected(v) { if (this.list.setAllSelected) { this.list.setAllSelected(v); } else { - BI.each(this.getAllButtons(), function (i, btn) { + each(this.getAllButtons(), (i, btn) => { (btn.setSelected || btn.setAllSelected).apply(btn, [v]); }); } this.allSelected = !!v; this.toolbar.setSelected(v); this.toolbar.setHalfSelected(false); - }, + } - setToolBarVisible: function (b) { + setToolBarVisible(b) { this.toolbar.setVisible(b); - }, + } - isAllSelected: function () { + isAllSelected() { return this.allSelected; // return this.toolbar.isSelected(); - }, + } - hasPrev: function () { + hasPrev() { return this.list.hasPrev(); - }, + } - hasNext: function () { + hasNext() { return this.list.hasNext(); - }, + } - prependItems: function (items) { - this.list.prependItems.apply(this.list, arguments); - }, + prependItems(items) { + this.list.prependItems(...arguments); + } - addItems: function (items) { - this.list.addItems.apply(this.list, arguments); - }, + addItems(items) { + this.list.addItems(...arguments); + } - setValue: function (data) { - var selectAll = data.type === BI.ButtonGroup.CHOOSE_TYPE_ALL; + setValue(data) { + const selectAll = data.type === ButtonGroup.CHOOSE_TYPE_ALL; this.setAllSelected(selectAll); this.list[selectAll ? "setNotSelectedValue" : "setValue"](data.value); this._checkAllSelected(); - }, + } - getValue: function () { + getValue() { if (this.isAllSelected() === false) { return { - type: BI.ButtonGroup.CHOOSE_TYPE_MULTI, + type: ButtonGroup.CHOOSE_TYPE_MULTI, value: this.list.getValue(), - assist: this.list.getNotSelectedValue() + assist: this.list.getNotSelectedValue(), }; } + return { - type: BI.ButtonGroup.CHOOSE_TYPE_ALL, + type: ButtonGroup.CHOOSE_TYPE_ALL, value: this.list.getNotSelectedValue(), - assist: this.list.getValue() + assist: this.list.getValue(), }; + } - }, - - empty: function () { + empty() { this.list.empty(); - }, + } - populate: function (items) { - this.toolbar.setVisible(!BI.isEmptyArray(items)); - this.toolbar.setEnable(this.isEnabled() && !BI.isEmptyArray(items)); - this.list.populate.apply(this.list, arguments); + populate(items) { + this.toolbar.setVisible(!isEmptyArray(items)); + this.toolbar.setEnable(this.isEnabled() && !isEmptyArray(items)); + this.list.populate(...arguments); this._checkAllSelected(); - }, + } - _setEnable: function (enable) { - BI.SelectList.superclass._setEnable.apply(this, arguments); + _setEnable(enable) { + super._setEnable(...arguments); this.toolbar.setEnable(enable); - }, + } - resetHeight: function (h) { - var toolHeight = ( this.toolbar.element.outerHeight() || 25) * ( this.toolbar.isVisible() ? 1 : 0); + resetHeight(h) { + const toolHeight = (this.toolbar.element.outerHeight() || 25) * (this.toolbar.isVisible() ? 1 : 0); this.list.resetHeight ? this.list.resetHeight(h - toolHeight) : - this.list.element.css({"max-height": BI.pixFormat(h - toolHeight)}); - }, + this.list.element.css({ "max-height": pixFormat(h - toolHeight) }); + } - setNotSelectedValue: function () { - this.list.setNotSelectedValue.apply(this.list, arguments); + setNotSelectedValue() { + this.list.setNotSelectedValue(...arguments); this._checkAllSelected(); - }, + } - getNotSelectedValue: function () { + getNotSelectedValue() { return this.list.getNotSelectedValue(); - }, + } - getAllButtons: function () { + getAllButtons() { return this.list.getAllButtons(); - }, + } - getAllLeaves: function () { + getAllLeaves() { return this.list.getAllLeaves(); - }, + } - getSelectedButtons: function () { + getSelectedButtons() { return this.list.getSelectedButtons(); - }, + } - getNotSelectedButtons: function () { + getNotSelectedButtons() { return this.list.getNotSelectedButtons(); - }, + } - getIndexByValue: function (value) { + getIndexByValue(value) { return this.list.getIndexByValue(value); - }, + } - getNodeById: function (id) { + getNodeById(id) { return this.list.getNodeById(id); - }, + } - getNodeByValue: function (value) { + getNodeByValue(value) { return this.list.getNodeByValue(value); } -}); -BI.SelectList.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.select_list", BI.SelectList); +} diff --git a/src/core/platform/web/dom.js b/src/core/platform/web/dom.js index 1fca2871b..95a348e7e 100644 --- a/src/core/platform/web/dom.js +++ b/src/core/platform/web/dom.js @@ -265,12 +265,12 @@ export function _getLeftAlignPosition(combo, popup, extraWidth, container) { } export function getLeftAlignPosition(combo, popup, extraWidth, container) { - let left = this._getLeftAlignPosition(combo, popup, extraWidth, container); + let left = _getLeftAlignPosition(combo, popup, extraWidth, container); let dir = ""; // 如果放不下,优先使用RightAlign, 如果RightAlign也放不下, 再使用left=0 const containerRect = container ? container.getBoundingClientRect() : { left: 0 }; if (left + containerRect.left < 0) { - left = this._getRightAlignPosition(combo, popup, extraWidth); + left = _getRightAlignPosition(combo, popup, extraWidth); dir = "left"; } if (left + containerRect.left < 0) { @@ -302,11 +302,11 @@ export function _getRightAlignPosition(combo, popup, extraWidth, container) { } export function getRightAlignPosition(combo, popup, extraWidth, container) { - let left = this._getRightAlignPosition(combo, popup, extraWidth, container); + let left = _getRightAlignPosition(combo, popup, extraWidth, container); let dir = ""; // 如果放不下,优先使用LeftAlign, 如果LeftAlign也放不下, 再使用left=0 if (left < 0) { - left = this._getLeftAlignPosition(combo, popup, extraWidth, container); + left = _getLeftAlignPosition(combo, popup, extraWidth, container); dir = "right"; } if (left < 0) { From 7d86ad53c162248503f839fbfcd947aabafccba9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Wed, 11 Jan 2023 14:44:54 +0800 Subject: [PATCH 068/300] =?UTF-8?q?KERNEL-14069=20refactor:=20=E5=88=A0?= =?UTF-8?q?=E9=99=A4=E6=97=A0=E7=94=A8=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/case/layer/pane.list.js | 193 ------------------------------------ 1 file changed, 193 deletions(-) diff --git a/src/case/layer/pane.list.js b/src/case/layer/pane.list.js index 21d9ebeb7..69d6f4df1 100644 --- a/src/case/layer/pane.list.js +++ b/src/case/layer/pane.list.js @@ -202,197 +202,4 @@ export class ListPane extends Pane { return this.button_group.getNodeByValue(value); } } -// BI.ListPane = BI.inherit(BI.Pane, { -// _defaultConfig: function () { -// var conf = BI.ListPane.superclass._defaultConfig.apply(this, arguments); -// return BI.extend(conf, { -// baseCls: (conf.baseCls || "") + " bi-list-pane", -// logic: { -// dynamic: true -// }, -// lgap: 0, -// rgap: 0, -// tgap: 0, -// bgap: 0, -// vgap: 0, -// hgap: 0, -// items: [], -// itemsCreator: BI.emptyFn, -// hasNext: BI.emptyFn, -// onLoaded: BI.emptyFn, -// el: { -// type: "bi.button_group" -// } -// }); -// }, -// _init: function () { -// BI.ListPane.superclass._init.apply(this, arguments); -// var self = this, o = this.options; - -// this.button_group = BI.createWidget(o.el, { -// type: "bi.button_group", -// chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, -// behaviors: {}, -// items: o.items, -// value: o.value, -// itemsCreator: function (op, calback) { -// if (op.times === 1) { -// self.empty(); -// BI.nextTick(function () { -// self.loading(); -// }); -// } -// o.itemsCreator(op, function () { -// calback.apply(self, arguments); -// o.items = BI.concat(o.items, BI.get(arguments, [0], [])); -// if (op.times === 1) { -// o.items = BI.get(arguments, [0], []); -// BI.nextTick(function () { -// self.loaded(); -// // callback可能在loading之前执行, check保证显示正确 -// self.check(); -// }); -// } -// }); -// }, -// hasNext: o.hasNext, -// layouts: [{ -// type: "bi.vertical" -// }] -// }); - -// this.button_group.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { -// self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); -// if (type === BI.Events.CLICK) { -// self.fireEvent(BI.ListPane.EVENT_CHANGE, value, obj); -// } -// }); -// this.check(); - -// BI.createWidget(BI.extend({ -// element: this -// }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Top), BI.extend({ -// scrolly: true, -// lgap: o.lgap, -// rgap: o.rgap, -// tgap: o.tgap, -// bgap: o.bgap, -// vgap: o.vgap, -// hgap: o.hgap -// }, o.logic, { -// items: BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Top, this.button_group) -// })))); -// }, - -// hasPrev: function () { -// return this.button_group.hasPrev && this.button_group.hasPrev(); -// }, - -// hasNext: function () { -// return this.button_group.hasNext && this.button_group.hasNext(); -// }, - -// prependItems: function (items) { -// this.options.items = items.concat(this.options.items); -// this.button_group.prependItems.apply(this.button_group, arguments); -// this.check(); -// }, - -// addItems: function (items) { -// this.options.items = this.options.items.concat(items); -// this.button_group.addItems.apply(this.button_group, arguments); -// this.check(); -// }, - -// removeItemAt: function (indexes) { -// indexes = BI.isNull(indexes) ? [] : indexes; -// BI.removeAt(this.options.items, indexes); -// this.button_group.removeItemAt.apply(this.button_group, arguments); -// this.check(); -// }, - -// populate: function (items) { -// var self = this, o = this.options; -// if (arguments.length === 0 && (BI.isFunction(this.button_group.attr("itemsCreator")))) {// 接管loader的populate方法 -// this.button_group.attr("itemsCreator").apply(this, [{ times: 1 }, function () { -// if (arguments.length === 0) { -// throw new Error("参数不能为空"); -// } -// self.populate.apply(self, arguments); -// }]); -// return; -// } - -// var context = BI.get(arguments, [2], {}); -// var tipText = context.tipText || ''; -// if (BI.isNotEmptyString(tipText)) { -// BI.ListPane.superclass.populate.apply(this, []); -// this.setTipText(tipText); -// } else { -// BI.ListPane.superclass.populate.apply(this, arguments); -// this.button_group.populate.apply(this.button_group, arguments); -// BI.isEmptyArray(BI.get(arguments, [0], [])) && this.setTipText(o.tipText); -// } -// }, - -// empty: function () { -// this.button_group.empty(); -// }, - -// setNotSelectedValue: function () { -// this.button_group.setNotSelectedValue.apply(this.button_group, arguments); -// }, - -// getNotSelectedValue: function () { -// return this.button_group.getNotSelectedValue(); -// }, - -// setValue: function () { -// this.button_group.setValue.apply(this.button_group, arguments); -// }, - -// setAllSelected: function (v) { -// if (this.button_group.setAllSelected) { -// this.button_group.setAllSelected(v); -// } else { -// BI.each(this.getAllButtons(), function (i, btn) { -// (btn.setSelected || btn.setAllSelected).apply(btn, [v]); -// }); -// } -// }, - -// getValue: function () { -// return this.button_group.getValue.apply(this.button_group, arguments); -// }, - -// getAllButtons: function () { -// return this.button_group.getAllButtons(); -// }, - -// getAllLeaves: function () { -// return this.button_group.getAllLeaves(); -// }, - -// getSelectedButtons: function () { -// return this.button_group.getSelectedButtons(); -// }, - -// getNotSelectedButtons: function () { -// return this.button_group.getNotSelectedButtons(); -// }, - -// getIndexByValue: function (value) { -// return this.button_group.getIndexByValue(value); -// }, - -// getNodeById: function (id) { -// return this.button_group.getNodeById(id); -// }, - -// getNodeByValue: function (value) { -// return this.button_group.getNodeByValue(value); -// } -// }); -// BI.ListPane.EVENT_CHANGE = "EVENT_CHANGE"; -// BI.shortcut("bi.list_pane", BI.ListPane); From eebd1002b37b1926a9ec2bd323c4887acbe344f1 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Wed, 11 Jan 2023 15:06:22 +0800 Subject: [PATCH 069/300] =?UTF-8?q?=E6=97=A0JIRA=E4=BB=BB=E5=8A=A1=20fix:?= =?UTF-8?q?=20=E4=BF=AE=E5=A4=8D=E4=B8=80=E4=BA=9B=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .eslintrc | 6 +++--- es6.js | 4 +++- src/core/index.js | 2 +- src/core/wrapper/layout/flex/flex.vertical.js | 2 ++ 4 files changed, 9 insertions(+), 5 deletions(-) diff --git a/.eslintrc b/.eslintrc index f5b262e6e..a2c317000 100644 --- a/.eslintrc +++ b/.eslintrc @@ -41,8 +41,8 @@ }, { "files": ["webpack/*.js", "./*.js", "lib/**/*.js", "lib/*.js", "./bin/*.js", "./bin/**/*.js"], "extends": "plugin:@fui/esnext" - }, { - "files": ["types/*.ts", "typescript/*.ts","typescript/**/*.ts"], - "extends": "plugin:@fui/typescript" + // }, { + // "files": ["types/*.ts", "typescript/*.ts","typescript/**/*.ts"], + // "extends": "plugin:@fui/typescript" }] } diff --git a/es6.js b/es6.js index 7b7734593..d067c861a 100644 --- a/es6.js +++ b/es6.js @@ -155,7 +155,9 @@ ${M} } `; - const prettierCode = prettier.format(outputCode); + const prettierCode = prettier.format(outputCode, { + tabWidth: 4, + }); fs.writeFileSync(srcName, prettierCode); await fix(srcName); diff --git a/src/core/index.js b/src/core/index.js index c8ea3d91a..d3a64ffc7 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -32,9 +32,9 @@ export * from "./structure"; export * from "./h"; export * from "./constant"; export * from "./logic"; -export * from "./utils"; export * from "./wrapper"; export * from "./platform/web"; +export * from "./utils"; export { StyleLoaderManager, diff --git a/src/core/wrapper/layout/flex/flex.vertical.js b/src/core/wrapper/layout/flex/flex.vertical.js index 7847d7009..fefc7abad 100644 --- a/src/core/wrapper/layout/flex/flex.vertical.js +++ b/src/core/wrapper/layout/flex/flex.vertical.js @@ -11,6 +11,8 @@ import { Layout } from "../../layout"; */ @shortcut() export class FlexVerticalLayout extends Layout { + static xtype = "bi.flex_vertical"; + props() { return extend(super.props(...arguments), { baseCls: "bi-f-v", From 752f1475791cdc7cabee18e76c58848da771c040 Mon Sep 17 00:00:00 2001 From: zsmj Date: Wed, 11 Jan 2023 15:17:51 +0800 Subject: [PATCH 070/300] =?UTF-8?q?KERNEL-14066=20feat:=20case/tree?= =?UTF-8?q?=E5=92=8Ccase/ztree?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/case/index.js | 6 + src/case/tree/index.js | 3 + src/case/tree/tree.level.js | 141 ++- src/case/tree/treeexpander/tree.expander.js | 142 +-- .../tree/treeexpander/tree.expander.popup.js | 117 +- .../ztree/{1.asynctree.js => asynctree.js} | 228 ++-- src/case/ztree/index.js | 14 + src/case/ztree/jquery.ztree.core-3.5.js | 1 + src/case/ztree/jquery.ztree.excheck-3.5.js | 1087 +++++++++-------- src/case/ztree/list/0.listtreeview.js | 118 -- src/case/ztree/list/1.listasynctree.js | 123 -- src/case/ztree/list/listasynctree.js | 122 ++ src/case/ztree/list/listparttree.js | 76 +- src/case/ztree/list/listtreeview.js | 121 ++ src/case/ztree/parttree.js | 173 +-- src/case/ztree/tree.display.js | 67 +- src/case/ztree/tree.list.display.js | 84 +- src/case/ztree/tree.simple.js | 132 +- src/case/ztree/treerender.page.service.js | 72 ++ src/case/ztree/treerender.scroll.service.js | 219 ++-- src/case/ztree/treetrender.page.service.js | 76 -- src/case/ztree/{0.treeview.js => treeview.js} | 442 +++---- .../platform/web/jquery/jquery.mousewheel.js | 111 +- 23 files changed, 1882 insertions(+), 1793 deletions(-) create mode 100644 src/case/tree/index.js rename src/case/ztree/{1.asynctree.js => asynctree.js} (61%) create mode 100644 src/case/ztree/index.js delete mode 100644 src/case/ztree/list/0.listtreeview.js delete mode 100644 src/case/ztree/list/1.listasynctree.js create mode 100644 src/case/ztree/list/listasynctree.js create mode 100644 src/case/ztree/list/listtreeview.js create mode 100644 src/case/ztree/treerender.page.service.js delete mode 100644 src/case/ztree/treetrender.page.service.js rename src/case/ztree/{0.treeview.js => treeview.js} (58%) diff --git a/src/case/index.js b/src/case/index.js index 1b8b33c0b..2c9d4cafc 100644 --- a/src/case/index.js +++ b/src/case/index.js @@ -2,16 +2,22 @@ import * as button from "./button"; import * as calendarItem from "./calendar"; import * as pager from "./pager"; import * as editor from "./editor"; +import * as tree from "./tree"; +import * as ztree from "./ztree"; Object.assign(BI, { ...button, ...calendarItem, ...pager, ...editor, + ...ztree, + ...tree, }); export * from "./button"; export * from "./calendar"; export * from "./pager"; export * from "./editor"; +export * from "./tree"; +export * from "./ztree"; diff --git a/src/case/tree/index.js b/src/case/tree/index.js new file mode 100644 index 000000000..2e24e6651 --- /dev/null +++ b/src/case/tree/index.js @@ -0,0 +1,3 @@ +export * from "./tree.level"; +export * from "./treeexpander/tree.expander"; +export * from "./treeexpander/tree.expander.popup"; diff --git a/src/case/tree/tree.level.js b/src/case/tree/tree.level.js index 81609217e..bd522ce3a 100644 --- a/src/case/tree/tree.level.js +++ b/src/case/tree/tree.level.js @@ -1,130 +1,127 @@ -/** - * guy - * 二级树 - * @class BI.LevelTree - * @extends BI.Single - */ -BI.LevelTree = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.LevelTree.superclass._defaultConfig.apply(this, arguments), { - baseCls: "bi-level-tree", - el: { - chooseType: 0 - }, - expander: {}, - items: [], - value: "" - }); - }, +import { shortcut, Widget, extend, isKey, each, UUID, defaults, isNotEmptyArray, Tree, createWidget } from "@/core"; + +@shortcut() +export class LevelTree extends Widget { + static xtype = "bi.level_tree"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + props = { + baseCls: "bi-level-tree", + el: { + chooseType: 0, + }, + expander: {}, + items: [], + value: "", + }; - _init: function () { - BI.LevelTree.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); this.initTree(this.options.items); - }, + } - _formatItems: function (nodes, layer, pNode) { - var self = this; - BI.each(nodes, function (i, node) { - var extend = { - layer: layer, + _formatItems(nodes, layer, pNode) { + const self = this; + each(nodes, (i, node) => { + const extend = { + layer, height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, isFirstNode: i === 0, isLastNode: i === nodes.length - 1, }; - if (!BI.isKey(node.id)) { - node.id = BI.UUID(); + if (!isKey(node.id)) { + node.id = UUID(); } extend.pNode = pNode; - if (node.isParent === true || node.parent === true || BI.isNotEmptyArray(node.children)) { + if (node.isParent === true || node.parent === true || isNotEmptyArray(node.children)) { extend.type = "bi.tree_node"; extend.selectable = false; - BI.defaults(node, extend); + defaults(node, extend); self._formatItems(node.children, layer + 1, node); } else { extend.type = "bi.tree_item"; - BI.defaults(node, extend); + defaults(node, extend); } }); + return nodes; - }, + } - _assertId: function (sNodes) { - BI.each(sNodes, function (i, node) { - if (!BI.isKey(node.id)) { - node.id = BI.UUID(); + _assertId(sNodes) { + each(sNodes, (i, node) => { + if (!isKey(node.id)) { + node.id = UUID(); } }); - }, + } - // 构造树结构, - initTree: function (nodes) { - var self = this, o = this.options; + initTree(nodes) { + const self = this, o = this.options; this.empty(); this._assertId(nodes); - this.tree = BI.createWidget({ + this.tree = createWidget({ type: "bi.custom_tree", element: this, - expander: BI.extend({ + expander: extend({ type: "bi.tree_expander", el: {}, isDefaultInit: false, selectable: false, popup: { - type: "bi.custom_tree" - } + type: "bi.custom_tree", + }, }, o.expander), - items: this._formatItems(BI.Tree.transformToTreeFormat(nodes), 0), + items: this._formatItems(Tree.transformToTreeFormat(nodes), 0), value: o.value, - el: BI.extend({ + el: extend({ type: "bi.button_tree", chooseType: 0, - layouts: [{ - type: "bi.vertical" - }] - }, o.el) + layouts: [ + { + type: "bi.vertical", + } + ], + }, o.el), }); this.tree.on(BI.Controller.EVENT_CHANGE, function (type, value, ob) { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); if (type === BI.Events.CLICK) { - self.fireEvent(BI.LevelTree.EVENT_CHANGE, value, ob); + self.fireEvent(LevelTree.EVENT_CHANGE, value, ob); self.setValue(value); } }); - }, + } - // 生成树方法 - stroke: function (nodes) { - this.tree.stroke.apply(this.tree, arguments); - }, + stroke(nodes) { + this.tree.stroke(nodes); + } - populate: function (items, keyword) { - items = this._formatItems(BI.Tree.transformToTreeFormat(items), 0); + populate(items, keyword) { + items = this._formatItems(Tree.transformToTreeFormat(items), 0); this.tree.populate(items, keyword); - }, + } - setValue: function (v) { + setValue(v) { this.tree.setValue(v); - }, + } - getValue: function () { + getValue() { return this.tree.getValue(); - }, + } - getAllLeaves: function () { + getAllLeaves() { return this.tree.getAllLeaves(); - }, + } - getNodeById: function (id) { + getNodeById(id) { return this.tree.getNodeById(id); - }, + } - getNodeByValue: function (id) { + getNodeByValue(id) { return this.tree.getNodeByValue(id); } -}); -BI.LevelTree.EVENT_CHANGE = "EVENT_CHANGE"; - -BI.shortcut("bi.level_tree", BI.LevelTree); +} diff --git a/src/case/tree/treeexpander/tree.expander.js b/src/case/tree/treeexpander/tree.expander.js index 8dde0807b..c9e8185f5 100644 --- a/src/case/tree/treeexpander/tree.expander.js +++ b/src/case/tree/treeexpander/tree.expander.js @@ -1,80 +1,82 @@ -!(function () { - var Widget = BI.inherit(BI.Widget, { - props: { - baseCls: "bi-tree-expander", - layer: 0, // 第几层级 - isLastNode: false, // 是不是最后一个 - isFirstNode: false, // 是不是第一个 - selectable: false, - showLine: true, - }, +import { contains, Controller, createWidget, isArray, shortcut, Widget } from "@/core"; - render: function () { +@shortcut() +export class TreeExpander extends Widget { + static xtype = "bi.tree_expander"; - var self = this; - var o = this.options; + props = { + baseCls: "bi-tree-expander", + layer: 0, // 第几层级 + isLastNode: false, // 是不是最后一个 + isFirstNode: false, // 是不是第一个 + selectable: false, + showLine: true, + }; - this.trigger = BI.createWidget(o.el, { - forceNotSelected: !o.selectable, - }); - this.trigger.on(BI.Controller.EVENT_CHANGE, function (type) { - o.selectable && self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }); + render() { + const self = this; + const o = this.options; - return { - type: "bi.expander", - ref: function (_ref) { - self.expander = _ref; - }, - trigger: o.selectable ? "" : "click", - el: this.trigger, - isDefaultInit: o.isDefaultInit, - popup: { - type: "bi.tree_expander.popup", - layer: o.layer || o.el.layer, - isLastNode: o.isLastNode || o.el.isLastNode, - isFirstNode: o.isFirstNode || o.el.isFirstNode, - showLine: o.showLine, - el: o.popup, - }, - value: o.value, - listeners: [ - { - eventName: BI.Controller.EVENT_CHANGE, - action: function (type) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }, - }, - ], - }; - }, + this.trigger = createWidget(o.el, { + forceNotSelected: !o.selectable, + }); + this.trigger.on(Controller.EVENT_CHANGE, function (type) { + o.selectable && self.fireEvent(Controller.EVENT_CHANGE, arguments); + }); - setValue: function (v) { - if (BI.contains(v, this.trigger.getValue())) { - this.trigger.setSelected(true); - this.expander.setValue([]); - } else { - this.trigger.setSelected(false); - this.expander.setValue(v); - } - }, + return { + type: "bi.expander", + ref(_ref) { + self.expander = _ref; + }, + trigger: o.selectable ? "" : "click", + el: this.trigger, + isDefaultInit: o.isDefaultInit, + popup: { + type: "bi.tree_expander.popup", + layer: o.layer || o.el.layer, + isLastNode: o.isLastNode || o.el.isLastNode, + isFirstNode: o.isFirstNode || o.el.isFirstNode, + showLine: o.showLine, + el: o.popup, + }, + value: o.value, + listeners: [ + { + eventName: Controller.EVENT_CHANGE, + action: (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); + }, + } + ], + }; + } - getValue: function () { - if (this.trigger.isSelected()) { - var value = this.trigger.getValue(); - return BI.isArray(value) ? value : [value]; - } - return this.expander.getValue(); - }, + setValue(v) { + if (contains(v, this.trigger.getValue())) { + this.trigger.setSelected(true); + this.expander.setValue([]); + } else { + this.trigger.setSelected(false); + this.expander.setValue(v); + } + } - populate: function (items) { - this.expander.populate(items); - }, + getValue() { + if (this.trigger.isSelected()) { + const value = this.trigger.getValue(); - getAllLeaves: function () { - return this.expander && this.expander.getAllLeaves(); + return isArray(value) ? value : [value]; } - }); - BI.shortcut("bi.tree_expander", Widget); -}()); + return this.expander.getValue(); + } + + populate(items) { + this.expander.populate(items); + } + + getAllLeaves() { + return this.expander && this.expander.getAllLeaves(); + } +} diff --git a/src/case/tree/treeexpander/tree.expander.popup.js b/src/case/tree/treeexpander/tree.expander.popup.js index ada979b0e..ac12b708c 100644 --- a/src/case/tree/treeexpander/tree.expander.popup.js +++ b/src/case/tree/treeexpander/tree.expander.popup.js @@ -1,60 +1,61 @@ -!(function () { - var Widget = BI.inherit(BI.Widget, { - props: function () { - return { - baseCls: "bi-tree-expander-popup", - layer: 0, // 第几层级 - el: {}, - isLastNode: false, - showLine: true, - }; - }, - - render: function () { - - var self = this; - var o = this.options; - var offset = BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2; - - this.popupView = BI.createWidget(BI.extend(o.el, { - value: o.value - }), this); - - this.popupView.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }); - - if (o.showLine) { - this.popupView.element.css("margin-left", BI.pixFormat(-offset * (o.layer + 1))); - this.element.css("margin-left", BI.pixFormat(offset * (o.layer + 1))); - } - - return { - type: "bi.vertical", - cls: (o.showLine && !o.isLastNode) ? (BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? "line solid" : "line") : "", - scrolly: null, - items: [ - this.popupView, - ], - }; - }, - - setValue: function (v) { - this.popupView.setValue(v); - }, - - getValue: function () { - return this.popupView.getValue(); - }, - - populate: function (items) { - this.popupView.populate(items); - }, - - getAllLeaves: function () { - return this.popupView && this.popupView.getAllLeaves(); +import { Controller, createWidget, pixFormat, shortcut, Widget } from "@/core"; + +@shortcut() +export class TreeExpanderPopup extends Widget { + static xtype = "bi.tree_expander.popup"; + + props() { + return { + baseCls: "bi-tree-expander-popup", + layer: 0, // 第几层级 + el: {}, + isLastNode: false, + showLine: true, + }; + } + + render() { + const self = this; + const { el, value, layer, showLine, isLastNode } = this.options; + const offset = BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2; + + this.popupView = createWidget({ + ...el, + value, + }, this); + + this.popupView.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); + }); + + if (showLine) { + this.popupView.element.css("margin-left", pixFormat(-offset * (layer + 1))); + this.element.css("margin-left", pixFormat(offset * (layer + 1))); } - }); - BI.shortcut("bi.tree_expander.popup", Widget); -}()); + return { + type: "bi.vertical", + cls: (showLine && !isLastNode) ? (BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? "line solid" : "line") : "", + scrolly: null, + items: [ + this.popupView + ], + }; + } + + setValue(v) { + this.popupView.setValue(v); + } + + getValue() { + return this.popupView.getValue(); + } + + populate(items) { + this.popupView.populate(items); + } + + getAllLeaves() { + return this.popupView && this.popupView.getAllLeaves(); + } +} diff --git a/src/case/ztree/1.asynctree.js b/src/case/ztree/asynctree.js similarity index 61% rename from src/case/ztree/1.asynctree.js rename to src/case/ztree/asynctree.js index ef44f50d3..d8d7028c6 100644 --- a/src/case/ztree/1.asynctree.js +++ b/src/case/ztree/asynctree.js @@ -1,77 +1,43 @@ -/** - * guy - * 异步树 - * @class BI.AsyncTree - * @extends BI.TreeView - */ -BI.AsyncTree = BI.inherit(BI.TreeView, { - _defaultConfig: function () { - return BI.extend(BI.AsyncTree.superclass._defaultConfig.apply(this, arguments), { +import { cjkEncodeDO, deepClone, each, extend, isEmpty, isNotNull, isNull, shortcut } from "@/core"; +import { TreeView } from "./treeview"; +import { TreeRenderPageService } from "./treerender.page.service"; + +@shortcut() +export class Asynctree extends TreeView { + static xtype = "bi.async_tree"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { showIcon: false, showLine: true, }); - }, - _init: function () { - BI.AsyncTree.superclass._init.apply(this, arguments); - var self = this; - this.service = new BI.TreeRenderPageService({ - subNodeListGetter: function (tId) { + } + + _init() { + super._init(...arguments); + const self = this; + this.service = new TreeRenderPageService({ + subNodeListGetter(tId) { // 获取待检测的子节点列表, ztree并没有获取节点列表dom的API, 此处使用BI.$获取 - return BI.$("#" + self.id + " #" + tId + "_ul"); - } + return BI.$(`#${self.id} #${tId}_ul`); + }, }); - }, + } // 配置属性 - _configSetting: function () { - var o = this.options; - var paras = this.options.paras; - var self = this; - var setting = { - async: { - enable: false, // 很明显这棵树把异步请求关掉了,所有的异步请求都是手动控制的 - otherParam: BI.cjkEncodeDO(paras) - }, - check: { - enable: true - }, - data: { - key: { - title: "title", - name: "text" - }, - simpleData: { - enable: true - } - }, - view: { - showIcon: o.showIcon, - expandSpeed: "", - nameIsHTML: true, - dblClickExpand: false, - showLine: o.showLine, - nodeClasses: function (treeId, treeNode) { - return { add: [treeNode.iconCls || ""] }; - } - }, - callback: { - beforeCheck: beforeCheck, - onCheck: onCheck, - beforeExpand: beforeExpand, - onExpand: onExpand, - onCollapse: onCollapse, - onClick: onClick, - } - }; + _configSetting() { + const o = this.options; + const paras = this.options.paras; + const self = this; function onClick(event, treeId, treeNode) { if (treeNode.disabled) { return false; } - var zTree = BI.$.fn.zTree.getZTreeObj(treeId); + const zTree = BI.$.fn.zTree.getZTreeObj(treeId); // 当前点击节点的状态是半选,且为true_part, 则将其改为false_part,使得点击半选后切换到的是全选 - var checked = treeNode.checked; - var status = treeNode.getCheckStatus(); + let checked = treeNode.checked; + const status = treeNode.getCheckStatus(); if (status.half === true && status.checked === true) { checked = false; } @@ -83,13 +49,13 @@ BI.AsyncTree = BI.inherit(BI.TreeView, { return false; } // 下面主动修改了node的halfCheck属性, 节点属性的判断依赖halfCheck,改之前就获取一下 - var status = treeNode.getCheckStatus(); + const status = treeNode.getCheckStatus(); treeNode.halfCheck = false; if (treeNode.checked === true) { // 将展开的节点halfCheck设为false,解决展开节点存在halfCheck=true的情况 guy // 所有的半选状态都需要取消halfCheck=true的情况 function track(children) { - BI.each(children, function (i, ch) { + each(children, (i, ch) => { ch.halfCheck = false; track(ch.children); }); @@ -97,9 +63,9 @@ BI.AsyncTree = BI.inherit(BI.TreeView, { track(treeNode.children); - var treeObj = BI.$.fn.zTree.getZTreeObj(treeId); - var nodes = treeObj.getSelectedNodes(); - BI.each(nodes, function (index, node) { + const treeObj = BI.$.fn.zTree.getZTreeObj(treeId); + const nodes = treeObj.getSelectedNodes(); + each(nodes, (index, node) => { node.halfCheck = false; }); } @@ -128,24 +94,59 @@ BI.AsyncTree = BI.inherit(BI.TreeView, { treeNode.halfCheck = false; } - return setting; - }, + return { + async: { + enable: false, // 很明显这棵树把异步请求关掉了,所有的异步请求都是手动控制的 + otherParam: cjkEncodeDO(paras), + }, + check: { + enable: true, + }, + data: { + key: { + title: "title", + name: "text", + }, + simpleData: { + enable: true, + }, + }, + view: { + showIcon: o.showIcon, + expandSpeed: "", + nameIsHTML: true, + dblClickExpand: false, + showLine: o.showLine, + nodeClasses(treeId, treeNode) { + return { add: [treeNode.iconCls || ""] }; + }, + }, + callback: { + beforeCheck, + onCheck, + beforeExpand, + onExpand, + onCollapse, + onClick, + }, + }; + } // 用来更新this.options.paras.selectedValues, 和ztree内部无关 - _selectTreeNode: function (treeId, treeNode) { - var self = this, o = this.options; - var parentValues = BI.deepClone(treeNode.parentValues || self._getParentValues(treeNode)); - var name = this._getNodeValue(treeNode); + _selectTreeNode(treeId, treeNode) { + const self = this; + let parentValues = deepClone(treeNode.parentValues || self._getParentValues(treeNode)); + let name = this._getNodeValue(treeNode); // var values = parentValues.concat([name]); if (treeNode.checked === true) { this._addTreeNode(this.options.paras.selectedValues, parentValues, name, {}); } else { - var tNode = treeNode; - var pNode = this._getTree(this.options.paras.selectedValues, parentValues); - if (BI.isNotNull(pNode[name])) { + let tNode = treeNode; + let pNode = this._getTree(this.options.paras.selectedValues, parentValues); + if (isNotNull(pNode[name])) { delete pNode[name]; } - while (tNode != null && BI.isEmpty(pNode)) { + while (tNode != null && isEmpty(pNode)) { parentValues = parentValues.slice(0, parentValues.length - 1); tNode = tNode.getParentNode(); if (tNode != null) { @@ -156,14 +157,15 @@ BI.AsyncTree = BI.inherit(BI.TreeView, { } this.options.paras.selectedValues = this._getJoinValue(); } - BI.AsyncTree.superclass._selectTreeNode.apply(self, arguments); - }, + super._selectTreeNode(...arguments); + } // 展开节点 - _beforeExpandNode: function (treeId, treeNode) { - var self = this, o = this.options; - var complete = function (d) { - var nodes = d.items || []; + _beforeExpandNode(treeId, treeNode) { + const self = this, o = this.options; + + function complete(d) { + const nodes = d.items || []; if (nodes.length > 0) { callback(self._dealWidthNodes(nodes), !!d.hasNext); } @@ -176,49 +178,48 @@ BI.AsyncTree = BI.inherit(BI.TreeView, { } else { self.service.removeNodeList(treeNode.tId); } - } function getNodes(options) { // console.log(times); options = options || {}; - var parentValues = treeNode.parentValues || self._getParentValues(treeNode); - var op = BI.extend({}, o.paras, { + const parentValues = treeNode.parentValues || self._getParentValues(treeNode); + const op = extend({}, o.paras, { id: treeNode.id, times: options.times, parentValues: parentValues.concat(self._getNodeValue(treeNode)), - checkState: treeNode.getCheckStatus() + checkState: treeNode.getCheckStatus(), }, options); o.itemsCreator(op, complete); } // 展开节点会将halfCheck置为false以开启自动计算半选, 所以第一次展开节点的时候需要在置为false之前获取配置 - var checkState = treeNode.getCheckStatus(); + const checkState = treeNode.getCheckStatus(); if (!treeNode.children && !treeNode.requested) { treeNode.requested = true; - setTimeout(function () { + setTimeout(() => { getNodes({ times: 1, - checkState: checkState + checkState, }); }, 17); } - }, + } // a,b 两棵树 // a->b b->a 做两次校验, 构造一个校验后的map // e.g. 以a为基准,如果b没有此节点,则在map中添加。 如b有,且是全选的, 则在map中构造全选(为什么不添加a的值呢? 因为这次是取并集), 如果b中也有和a一样的存值,就递归 - _join: function (valueA, valueB) { - var self = this; - var map = {}; + _join(valueA, valueB) { + const self = this; + const map = {}; track([], valueA, valueB); track([], valueB, valueA); function track(parent, node, compare) { - BI.each(node, function (n, item) { - if (BI.isNull(compare[n])) { + each(node, (n, item) => { + if (isNull(compare[n])) { self._addTreeNode(map, parent, n, item); - } else if (BI.isEmpty(compare[n])) { + } else if (isEmpty(compare[n])) { self._addTreeNode(map, parent, n, item); } else { track(parent.concat([n]), node[n], compare[n]); @@ -227,38 +228,37 @@ BI.AsyncTree = BI.inherit(BI.TreeView, { } return map; - }, + } - hasChecked: function () { - return !BI.isEmpty(this.options.paras.selectedValues) || BI.AsyncTree.superclass.hasChecked.apply(this, arguments); - }, + hasChecked() { + return !isEmpty(this.options.paras.selectedValues) || super.hasChecked(...arguments); + } - _getJoinValue: function () { + _getJoinValue() { if (!this.nodes) { return this.options.paras.selectedValues || {}; } - var checkedValues = this._getSelectedValues(); - if (BI.isEmpty(checkedValues)) { - return BI.deepClone(this.options.paras.selectedValues); + const checkedValues = this._getSelectedValues(); + if (isEmpty(checkedValues)) { + return deepClone(this.options.paras.selectedValues); } - if (BI.isEmpty(this.options.paras.selectedValues)) { + if (isEmpty(this.options.paras.selectedValues)) { return checkedValues; } + return this._join(checkedValues, this.options.paras.selectedValues); - }, + } - getValue: function () { + getValue() { return this._getJoinValue(); - }, + } // 生成树方法 - stroke: function (config) { + stroke(config) { delete this.options.keyword; this.service.clear(); - BI.extend(this.options.paras, config); - var setting = this._configSetting(); + extend(this.options.paras, config); + const setting = this._configSetting(); this._initTree(setting); } -}); - -BI.shortcut("bi.async_tree", BI.AsyncTree); +} diff --git a/src/case/ztree/index.js b/src/case/ztree/index.js new file mode 100644 index 000000000..d5cbfc63a --- /dev/null +++ b/src/case/ztree/index.js @@ -0,0 +1,14 @@ +import "./jquery.ztree.core-3.5"; +import "./jquery.ztree.excheck-3.5"; + +export * from "./treeview"; +export * from "./asynctree"; +export * from "./parttree"; +export * from "./tree.display"; +export * from "./tree.list.display"; +export * from "./tree.simple"; +export * from "./treerender.scroll.service"; +export * from "./treerender.page.service"; +export * from "./list/listtreeview"; +export * from "./list/listasynctree"; +export * from "./list/listparttree"; diff --git a/src/case/ztree/jquery.ztree.core-3.5.js b/src/case/ztree/jquery.ztree.core-3.5.js index 875f33e67..f4e899044 100644 --- a/src/case/ztree/jquery.ztree.core-3.5.js +++ b/src/case/ztree/jquery.ztree.core-3.5.js @@ -1,3 +1,4 @@ +/* eslint-disable */ /* * JQuery zTree core * v3.5.48 diff --git a/src/case/ztree/jquery.ztree.excheck-3.5.js b/src/case/ztree/jquery.ztree.excheck-3.5.js index e28915a6f..ea1f6a945 100644 --- a/src/case/ztree/jquery.ztree.excheck-3.5.js +++ b/src/case/ztree/jquery.ztree.excheck-3.5.js @@ -1,3 +1,4 @@ +/* eslint-disable */ /* * JQuery zTree excheck v3.5.18 * http://zTree.me/ @@ -10,602 +11,606 @@ * email: hunter.z@263.net * Date: 2015-06-18 */ -(function($){ +(function ($) { //default consts of excheck var _consts = { - event: { - CHECK: "ztree_check" + event: { + CHECK: "ztree_check" + }, + id: { + CHECK: "_check" + }, + checkbox: { + STYLE: "checkbox", + DEFAULT: "chk", + DISABLED: "disable", + FALSE: "false", + TRUE: "true", + FULL: "full", + PART: "part", + FOCUS: "focus" + }, + radio: { + STYLE: "radio", + TYPE_ALL: "all", + TYPE_LEVEL: "level" + } }, - id: { - CHECK: "_check" + //default setting of excheck + _setting = { + check: { + enable: false, + autoCheckTrigger: false, + chkStyle: _consts.checkbox.STYLE, + nocheckInherit: false, + chkDisabledInherit: false, + radioType: _consts.radio.TYPE_LEVEL, + chkboxType: { + "Y": "ps", + "N": "ps" + } + }, + data: { + key: { + checked: "checked" + } + }, + callback: { + beforeCheck: null, + onCheck: null + } }, - checkbox: { - STYLE: "checkbox", - DEFAULT: "chk", - DISABLED: "disable", - FALSE: "false", - TRUE: "true", - FULL: "full", - PART: "part", - FOCUS: "focus" + //default root of excheck + _initRoot = function (setting) { + var r = data.getRoot(setting); + r.radioCheckedList = []; }, - radio: { - STYLE: "radio", - TYPE_ALL: "all", - TYPE_LEVEL: "level" - } - }, - //default setting of excheck - _setting = { - check: { - enable: false, - autoCheckTrigger: false, - chkStyle: _consts.checkbox.STYLE, - nocheckInherit: false, - chkDisabledInherit: false, - radioType: _consts.radio.TYPE_LEVEL, - chkboxType: { - "Y": "ps", - "N": "ps" - } + //default cache of excheck + _initCache = function (treeId) { }, - data: { - key: { - checked: "checked" - } + //default bind event of excheck + _bindEvent = function (setting) { + var o = setting.treeObj, + c = consts.event; + o.bind(c.CHECK, function (event, srcEvent, treeId, node) { + event.srcEvent = srcEvent; + tools.apply(setting.callback.onCheck, [event, treeId, node]); + }); }, - callback: { - beforeCheck:null, - onCheck:null - } - }, - //default root of excheck - _initRoot = function (setting) { - var r = data.getRoot(setting); - r.radioCheckedList = []; - }, - //default cache of excheck - _initCache = function(treeId) {}, - //default bind event of excheck - _bindEvent = function(setting) { - var o = setting.treeObj, - c = consts.event; - o.bind(c.CHECK, function (event, srcEvent, treeId, node) { - event.srcEvent = srcEvent; - tools.apply(setting.callback.onCheck, [event, treeId, node]); - }); - }, - _unbindEvent = function(setting) { - var o = setting.treeObj, - c = consts.event; - o.unbind(c.CHECK); - }, - //default event proxy of excheck - _eventProxy = function(e) { - var target = e.target, - setting = data.getSetting(e.data.treeId), - tId = "", node = null, - nodeEventType = "", treeEventType = "", - nodeEventCallback = null, treeEventCallback = null; + _unbindEvent = function (setting) { + var o = setting.treeObj, + c = consts.event; + o.unbind(c.CHECK); + }, + //default event proxy of excheck + _eventProxy = function (e) { + var target = e.target, + setting = data.getSetting(e.data.treeId), + tId = "", node = null, + nodeEventType = "", treeEventType = "", + nodeEventCallback = null, treeEventCallback = null; - if (tools.eqs(e.type, "mouseover")) { - if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { - tId = tools.getNodeMainDom(target).id; - nodeEventType = "mouseoverCheck"; - } - } else if (tools.eqs(e.type, "mouseout")) { - if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { - tId = tools.getNodeMainDom(target).id; - nodeEventType = "mouseoutCheck"; - } - } else if (tools.eqs(e.type, "click")) { - if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { - tId = tools.getNodeMainDom(target).id; - nodeEventType = "checkNode"; + if (tools.eqs(e.type, "mouseover")) { + if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode" + consts.id.CHECK) !== null) { + tId = tools.getNodeMainDom(target).id; + nodeEventType = "mouseoverCheck"; + } + } else if (tools.eqs(e.type, "mouseout")) { + if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode" + consts.id.CHECK) !== null) { + tId = tools.getNodeMainDom(target).id; + nodeEventType = "mouseoutCheck"; + } + } else if (tools.eqs(e.type, "click")) { + if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode" + consts.id.CHECK) !== null) { + tId = tools.getNodeMainDom(target).id; + nodeEventType = "checkNode"; + } } - } - if (tId.length>0) { - node = data.getNodeCache(setting, tId); - switch (nodeEventType) { - case "checkNode" : - nodeEventCallback = _handler.onCheckNode; - break; - case "mouseoverCheck" : - nodeEventCallback = _handler.onMouseoverCheck; - break; - case "mouseoutCheck" : - nodeEventCallback = _handler.onMouseoutCheck; - break; + if (tId.length > 0) { + node = data.getNodeCache(setting, tId); + switch (nodeEventType) { + case "checkNode" : + nodeEventCallback = _handler.onCheckNode; + break; + case "mouseoverCheck" : + nodeEventCallback = _handler.onMouseoverCheck; + break; + case "mouseoutCheck" : + nodeEventCallback = _handler.onMouseoutCheck; + break; + } } - } - var proxyResult = { - stop: nodeEventType === "checkNode", - node: node, - nodeEventType: nodeEventType, - nodeEventCallback: nodeEventCallback, - treeEventType: treeEventType, - treeEventCallback: treeEventCallback - }; - return proxyResult - }, - //default init node of excheck - _initNode = function(setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { - if (!n) return; - var checkedKey = setting.data.key.checked; - if (typeof n[checkedKey] == "string") n[checkedKey] = tools.eqs(n[checkedKey], "true"); - n[checkedKey] = !!n[checkedKey]; - n.checkedOld = n[checkedKey]; - if (typeof n.nocheck == "string") n.nocheck = tools.eqs(n.nocheck, "true"); - n.nocheck = !!n.nocheck || (setting.check.nocheckInherit && parentNode && !!parentNode.nocheck); - if (typeof n.chkDisabled == "string") n.chkDisabled = tools.eqs(n.chkDisabled, "true"); - n.chkDisabled = !!n.chkDisabled || (setting.check.chkDisabledInherit && parentNode && !!parentNode.chkDisabled); - if (typeof n.halfCheck == "string") n.halfCheck = tools.eqs(n.halfCheck, "true"); - n.halfCheck = !!n.halfCheck; - n.check_Child_State = -1; - n.check_Focus = false; - n.getCheckStatus = function() {return data.getCheckStatus(setting, n);}; + var proxyResult = { + stop: nodeEventType === "checkNode", + node: node, + nodeEventType: nodeEventType, + nodeEventCallback: nodeEventCallback, + treeEventType: treeEventType, + treeEventCallback: treeEventCallback + }; + return proxyResult; + }, + //default init node of excheck + _initNode = function (setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { + if (!n) return; + var checkedKey = setting.data.key.checked; + if (typeof n[checkedKey] == "string") n[checkedKey] = tools.eqs(n[checkedKey], "true"); + n[checkedKey] = !!n[checkedKey]; + n.checkedOld = n[checkedKey]; + if (typeof n.nocheck == "string") n.nocheck = tools.eqs(n.nocheck, "true"); + n.nocheck = !!n.nocheck || (setting.check.nocheckInherit && parentNode && !!parentNode.nocheck); + if (typeof n.chkDisabled == "string") n.chkDisabled = tools.eqs(n.chkDisabled, "true"); + n.chkDisabled = !!n.chkDisabled || (setting.check.chkDisabledInherit && parentNode && !!parentNode.chkDisabled); + if (typeof n.halfCheck == "string") n.halfCheck = tools.eqs(n.halfCheck, "true"); + n.halfCheck = !!n.halfCheck; + n.check_Child_State = -1; + n.check_Focus = false; + n.getCheckStatus = function () { + return data.getCheckStatus(setting, n); + }; - if (setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL && n[checkedKey] ) { - var r = data.getRoot(setting); - r.radioCheckedList.push(n); - } - }, - //add dom for check - _beforeA = function(setting, node, html) { - var checkedKey = setting.data.key.checked; - if (setting.check.enable) { - data.makeChkFlag(setting, node); - html.push(""); - } - }, - //update zTreeObj, add method of check - _zTreeTools = function(setting, zTreeTools) { - zTreeTools.checkNode = function(node, checked, checkTypeFlag, callbackFlag) { - var checkedKey = this.setting.data.key.checked; - if (node.chkDisabled === true) return; - if (checked !== true && checked !== false) { - checked = !node[checkedKey]; + if (setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL && n[checkedKey]) { + var r = data.getRoot(setting); + r.radioCheckedList.push(n); } - callbackFlag = !!callbackFlag; - - if (node[checkedKey] === checked && !checkTypeFlag) { - return; - } else if (callbackFlag && tools.apply(this.setting.callback.beforeCheck, [this.setting.treeId, node], true) == false) { - return; + }, + //add dom for check + _beforeA = function (setting, node, html) { + var checkedKey = setting.data.key.checked; + if (setting.check.enable) { + data.makeChkFlag(setting, node); + html.push(""); } - if (tools.uCanDo(this.setting) && this.setting.check.enable && node.nocheck !== true) { - node[checkedKey] = checked; - var checkObj = $$(node, consts.id.CHECK, this.setting); - if (checkTypeFlag || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); - view.setChkClass(this.setting, checkObj, node); - view.repairParentChkClassWithSelf(this.setting, node); - if (callbackFlag) { - this.setting.treeObj.trigger(consts.event.CHECK, [null, this.setting.treeId, node]); + }, + //update zTreeObj, add method of check + _zTreeTools = function (setting, zTreeTools) { + zTreeTools.checkNode = function (node, checked, checkTypeFlag, callbackFlag) { + var checkedKey = this.setting.data.key.checked; + if (node.chkDisabled === true) return; + if (checked !== true && checked !== false) { + checked = !node[checkedKey]; } - } - } + callbackFlag = !!callbackFlag; - zTreeTools.checkAllNodes = function(checked) { - view.repairAllChk(this.setting, !!checked); - } + if (node[checkedKey] === checked && !checkTypeFlag) { + return; + } else if (callbackFlag && tools.apply(this.setting.callback.beforeCheck, [this.setting.treeId, node], true) == false) { + return; + } + if (tools.uCanDo(this.setting) && this.setting.check.enable && node.nocheck !== true) { + node[checkedKey] = checked; + var checkObj = $$(node, consts.id.CHECK, this.setting); + if (checkTypeFlag || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); + view.setChkClass(this.setting, checkObj, node); + view.repairParentChkClassWithSelf(this.setting, node); + if (callbackFlag) { + this.setting.treeObj.trigger(consts.event.CHECK, [null, this.setting.treeId, node]); + } + } + }; - zTreeTools.getCheckedNodes = function(checked) { - var childKey = this.setting.data.key.children; - checked = (checked !== false); - return data.getTreeCheckedNodes(this.setting, data.getRoot(this.setting)[childKey], checked); - } + zTreeTools.checkAllNodes = function (checked) { + view.repairAllChk(this.setting, !!checked); + }; - zTreeTools.getChangeCheckedNodes = function() { - var childKey = this.setting.data.key.children; - return data.getTreeChangeCheckedNodes(this.setting, data.getRoot(this.setting)[childKey]); - } + zTreeTools.getCheckedNodes = function (checked) { + var childKey = this.setting.data.key.children; + checked = (checked !== false); + return data.getTreeCheckedNodes(this.setting, data.getRoot(this.setting)[childKey], checked); + }; - zTreeTools.setChkDisabled = function(node, disabled, inheritParent, inheritChildren) { - disabled = !!disabled; - inheritParent = !!inheritParent; - inheritChildren = !!inheritChildren; - view.repairSonChkDisabled(this.setting, node, disabled, inheritChildren); - view.repairParentChkDisabled(this.setting, node.getParentNode(), disabled, inheritParent); - } + zTreeTools.getChangeCheckedNodes = function () { + var childKey = this.setting.data.key.children; + return data.getTreeChangeCheckedNodes(this.setting, data.getRoot(this.setting)[childKey]); + }; - var _updateNode = zTreeTools.updateNode; - zTreeTools.updateNode = function(node, checkTypeFlag) { - if (_updateNode) _updateNode.apply(zTreeTools, arguments); - if (!node || !this.setting.check.enable) return; - var nObj = $$(node, this.setting); - if (nObj.get(0) && tools.uCanDo(this.setting)) { - var checkObj = $$(node, consts.id.CHECK, this.setting); - if (checkTypeFlag == true || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); - view.setChkClass(this.setting, checkObj, node); - view.repairParentChkClassWithSelf(this.setting, node); - } - } - }, - //method of operate data - _data = { - getRadioCheckedList: function(setting) { - var checkedList = data.getRoot(setting).radioCheckedList; - for (var i=0, j=checkedList.length; i -1 && node.check_Child_State < 2) : (node.check_Child_State > 0))) }; - return r; }, - getTreeCheckedNodes: function(setting, nodes, checked, results) { - if (!nodes) return []; - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - onlyOne = (checked && setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL); - results = !results ? [] : results; - for (var i = 0, l = nodes.length; i < l; i++) { - if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] == checked) { - results.push(nodes[i]); - if(onlyOne) { - break; + //method of operate data + _data = { + getRadioCheckedList: function (setting) { + var checkedList = data.getRoot(setting).radioCheckedList; + for (var i = 0, j = checkedList.length; i < j; i++) { + if (!data.getNodeCache(setting, checkedList[i].tId)) { + checkedList.splice(i, 1); + i--; + j--; } } - data.getTreeCheckedNodes(setting, nodes[i][childKey], checked, results); - if(onlyOne && results.length > 0) { - break; + return checkedList; + }, + getCheckStatus: function (setting, node) { + if (!setting.check.enable || node.nocheck || node.chkDisabled) return null; + var checkedKey = setting.data.key.checked, + r = { + checked: node[checkedKey], + half: node.halfCheck ? node.halfCheck : (setting.check.chkStyle == consts.radio.STYLE ? (node.check_Child_State === 2) : (node[checkedKey] ? (node.check_Child_State > -1 && node.check_Child_State < 2) : (node.check_Child_State > 0))) + }; + return r; + }, + getTreeCheckedNodes: function (setting, nodes, checked, results) { + if (!nodes) return []; + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + onlyOne = (checked && setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL); + results = !results ? [] : results; + for (var i = 0, l = nodes.length; i < l; i++) { + if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] == checked) { + results.push(nodes[i]); + if (onlyOne) { + break; + } + } + data.getTreeCheckedNodes(setting, nodes[i][childKey], checked, results); + if (onlyOne && results.length > 0) { + break; + } } - } - return results; - }, - getTreeChangeCheckedNodes: function(setting, nodes, results) { - if (!nodes) return []; - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked; - results = !results ? [] : results; - for (var i = 0, l = nodes.length; i < l; i++) { - if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] != nodes[i].checkedOld) { - results.push(nodes[i]); + return results; + }, + getTreeChangeCheckedNodes: function (setting, nodes, results) { + if (!nodes) return []; + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked; + results = !results ? [] : results; + for (var i = 0, l = nodes.length; i < l; i++) { + if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] != nodes[i].checkedOld) { + results.push(nodes[i]); + } + data.getTreeChangeCheckedNodes(setting, nodes[i][childKey], results); } - data.getTreeChangeCheckedNodes(setting, nodes[i][childKey], results); - } - return results; - }, - makeChkFlag: function(setting, node) { - if (!node) return; - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - chkFlag = -1; - if (node[childKey]) { - for (var i = 0, l = node[childKey].length; i < l; i++) { - var cNode = node[childKey][i]; - var tmp = -1; - if (setting.check.chkStyle == consts.radio.STYLE) { - if (cNode.nocheck === true || cNode.chkDisabled === true) { - tmp = cNode.check_Child_State; - } else if (cNode.halfCheck === true) { - tmp = 2; - } else if (cNode[checkedKey]) { - tmp = 2; - } else { - tmp = cNode.check_Child_State > 0 ? 2:0; - } - if (tmp == 2) { - chkFlag = 2; break; - } else if (tmp == 0){ - chkFlag = 0; - } - } else if (setting.check.chkStyle == consts.checkbox.STYLE) { - if (cNode.nocheck === true || cNode.chkDisabled === true) { - tmp = cNode.check_Child_State; - } else if (cNode.halfCheck === true) { - tmp = 1; - } else if (cNode[checkedKey] ) { - tmp = (cNode.check_Child_State === -1 || cNode.check_Child_State === 2) ? 2 : 1; - } else { - tmp = (cNode.check_Child_State > 0) ? 1 : 0; - } - if (tmp === 1) { - chkFlag = 1; break; - } else if (tmp === 2 && chkFlag > -1 && i > 0 && tmp !== chkFlag) { - chkFlag = 1; break; - } else if (chkFlag === 2 && tmp > -1 && tmp < 2) { - chkFlag = 1; break; - } else if (tmp > -1) { - chkFlag = tmp; + return results; + }, + makeChkFlag: function (setting, node) { + if (!node) return; + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + chkFlag = -1; + if (node[childKey]) { + for (var i = 0, l = node[childKey].length; i < l; i++) { + var cNode = node[childKey][i]; + var tmp = -1; + if (setting.check.chkStyle == consts.radio.STYLE) { + if (cNode.nocheck === true || cNode.chkDisabled === true) { + tmp = cNode.check_Child_State; + } else if (cNode.halfCheck === true) { + tmp = 2; + } else if (cNode[checkedKey]) { + tmp = 2; + } else { + tmp = cNode.check_Child_State > 0 ? 2 : 0; + } + if (tmp == 2) { + chkFlag = 2; + break; + } else if (tmp == 0) { + chkFlag = 0; + } + } else if (setting.check.chkStyle == consts.checkbox.STYLE) { + if (cNode.nocheck === true || cNode.chkDisabled === true) { + tmp = cNode.check_Child_State; + } else if (cNode.halfCheck === true) { + tmp = 1; + } else if (cNode[checkedKey]) { + tmp = (cNode.check_Child_State === -1 || cNode.check_Child_State === 2) ? 2 : 1; + } else { + tmp = (cNode.check_Child_State > 0) ? 1 : 0; + } + if (tmp === 1) { + chkFlag = 1; + break; + } else if (tmp === 2 && chkFlag > -1 && i > 0 && tmp !== chkFlag) { + chkFlag = 1; + break; + } else if (chkFlag === 2 && tmp > -1 && tmp < 2) { + chkFlag = 1; + break; + } else if (tmp > -1) { + chkFlag = tmp; + } } } } + node.check_Child_State = chkFlag; } - node.check_Child_State = chkFlag; - } - }, - //method of event proxy - _event = { - - }, - //method of event handler - _handler = { - onCheckNode: function (event, node) { - if (node.chkDisabled === true) return false; - var setting = data.getSetting(event.data.treeId), - checkedKey = setting.data.key.checked; - if (tools.apply(setting.callback.beforeCheck, [setting.treeId, node], true) == false) return true; - node[checkedKey] = !node[checkedKey]; - view.checkNodeRelation(setting, node); - var checkObj = $$(node, consts.id.CHECK, setting); - view.setChkClass(setting, checkObj, node); - view.repairParentChkClassWithSelf(setting, node); - setting.treeObj.trigger(consts.event.CHECK, [event, setting.treeId, node]); - return true; }, - onMouseoverCheck: function(event, node) { - if (node.chkDisabled === true) return false; - var setting = data.getSetting(event.data.treeId), - checkObj = $$(node, consts.id.CHECK, setting); - node.check_Focus = true; - view.setChkClass(setting, checkObj, node); - return true; + //method of event proxy + _event = {}, + //method of event handler + _handler = { + onCheckNode: function (event, node) { + if (node.chkDisabled === true) return false; + var setting = data.getSetting(event.data.treeId), + checkedKey = setting.data.key.checked; + if (tools.apply(setting.callback.beforeCheck, [setting.treeId, node], true) == false) return true; + node[checkedKey] = !node[checkedKey]; + view.checkNodeRelation(setting, node); + var checkObj = $$(node, consts.id.CHECK, setting); + view.setChkClass(setting, checkObj, node); + view.repairParentChkClassWithSelf(setting, node); + setting.treeObj.trigger(consts.event.CHECK, [event, setting.treeId, node]); + return true; + }, + onMouseoverCheck: function (event, node) { + if (node.chkDisabled === true) return false; + var setting = data.getSetting(event.data.treeId), + checkObj = $$(node, consts.id.CHECK, setting); + node.check_Focus = true; + view.setChkClass(setting, checkObj, node); + return true; + }, + onMouseoutCheck: function (event, node) { + if (node.chkDisabled === true) return false; + var setting = data.getSetting(event.data.treeId), + checkObj = $$(node, consts.id.CHECK, setting); + node.check_Focus = false; + view.setChkClass(setting, checkObj, node); + return true; + } }, - onMouseoutCheck: function(event, node) { - if (node.chkDisabled === true) return false; - var setting = data.getSetting(event.data.treeId), - checkObj = $$(node, consts.id.CHECK, setting); - node.check_Focus = false; - view.setChkClass(setting, checkObj, node); - return true; - } - }, - //method of tools for zTree - _tools = { - - }, - //method of operate ztree dom - _view = { - checkNodeRelation: function(setting, node) { - var pNode, i, l, - childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - r = consts.radio; - if (setting.check.chkStyle == r.STYLE) { - var checkedList = data.getRadioCheckedList(setting); - if (node[checkedKey]) { - if (setting.check.radioType == r.TYPE_ALL) { - for (i = checkedList.length-1; i >= 0; i--) { - pNode = checkedList[i]; - if (pNode[checkedKey] && pNode != node) { - pNode[checkedKey] = false; - checkedList.splice(i, 1); + //method of tools for zTree + _tools = {}, + //method of operate ztree dom + _view = { + checkNodeRelation: function (setting, node) { + var pNode, i, l, + childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + r = consts.radio; + if (setting.check.chkStyle == r.STYLE) { + var checkedList = data.getRadioCheckedList(setting); + if (node[checkedKey]) { + if (setting.check.radioType == r.TYPE_ALL) { + for (i = checkedList.length - 1; i >= 0; i--) { + pNode = checkedList[i]; + if (pNode[checkedKey] && pNode != node) { + pNode[checkedKey] = false; + checkedList.splice(i, 1); - view.setChkClass(setting, $$(pNode, consts.id.CHECK, setting), pNode); - if (pNode.parentTId != node.parentTId) { - view.repairParentChkClassWithSelf(setting, pNode); + view.setChkClass(setting, $$(pNode, consts.id.CHECK, setting), pNode); + if (pNode.parentTId != node.parentTId) { + view.repairParentChkClassWithSelf(setting, pNode); + } + } + } + checkedList.push(node); + } else { + var parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(setting); + for (i = 0, l = parentNode[childKey].length; i < l; i++) { + pNode = parentNode[childKey][i]; + if (pNode[checkedKey] && pNode != node) { + pNode[checkedKey] = false; + view.setChkClass(setting, $$(pNode, consts.id.CHECK, setting), pNode); } } } - checkedList.push(node); - } else { - var parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(setting); - for (i = 0, l = parentNode[childKey].length; i < l; i++) { - pNode = parentNode[childKey][i]; - if (pNode[checkedKey] && pNode != node) { - pNode[checkedKey] = false; - view.setChkClass(setting, $$(pNode, consts.id.CHECK, setting), pNode); + } else if (setting.check.radioType == r.TYPE_ALL) { + for (i = 0, l = checkedList.length; i < l; i++) { + if (node == checkedList[i]) { + checkedList.splice(i, 1); + break; } } } - } else if (setting.check.radioType == r.TYPE_ALL) { - for (i = 0, l = checkedList.length; i < l; i++) { - if (node == checkedList[i]) { - checkedList.splice(i, 1); - break; - } + + } else { + if (node[checkedKey] && (!node[childKey] || node[childKey].length == 0 || setting.check.chkboxType.Y.indexOf("s") > -1)) { + view.setSonNodeCheckBox(setting, node, true); + } + if (!node[checkedKey] && (!node[childKey] || node[childKey].length == 0 || setting.check.chkboxType.N.indexOf("s") > -1)) { + view.setSonNodeCheckBox(setting, node, false); + } + if (node[checkedKey] && setting.check.chkboxType.Y.indexOf("p") > -1) { + view.setParentNodeCheckBox(setting, node, true); + } + if (!node[checkedKey] && setting.check.chkboxType.N.indexOf("p") > -1) { + view.setParentNodeCheckBox(setting, node, false); } } - - } else { - if (node[checkedKey] && (!node[childKey] || node[childKey].length==0 || setting.check.chkboxType.Y.indexOf("s") > -1)) { - view.setSonNodeCheckBox(setting, node, true); + }, + makeChkClass: function (setting, node) { + var checkedKey = setting.data.key.checked, + c = consts.checkbox, r = consts.radio, + checkboxType = setting.check.chkboxType; + var notEffectByOtherNode = (checkboxType.Y === "" && checkboxType.N === ""); + fullStyle = ""; + if (node.chkDisabled === true) { + fullStyle = c.DISABLED; + } else if (node.halfCheck) { + fullStyle = c.PART; + } else if (setting.check.chkStyle == r.STYLE) { + fullStyle = (node.check_Child_State < 1) ? c.FULL : c.PART; + } else { + fullStyle = node[checkedKey] ? ((node.check_Child_State === 2 || node.check_Child_State === -1) || notEffectByOtherNode ? c.FULL : c.PART) : ((node.check_Child_State < 1 || notEffectByOtherNode) ? c.FULL : c.PART); } - if (!node[checkedKey] && (!node[childKey] || node[childKey].length==0 || setting.check.chkboxType.N.indexOf("s") > -1)) { - view.setSonNodeCheckBox(setting, node, false); + var chkName = setting.check.chkStyle + "_" + (node[checkedKey] ? c.TRUE : c.FALSE) + "_" + fullStyle; + chkName = (node.check_Focus && node.chkDisabled !== true) ? chkName + "_" + c.FOCUS : chkName; + var chClass = consts.className.BUTTON + " " + c.DEFAULT + " " + chkName; + switch (chkName) { + case 'checkbox_true_part': + case 'checkbox_true_part_focus': + chClass += ' bi-half-button bi-high-light-border'; + break; + case 'checkbox_true_full': + case 'checkbox_true_full_focus': + chClass += ' bi-checkbox checkbox-content bi-high-light-background active'; + break; + case 'checkbox_false_full': + case 'checkbox_false_full_focus': + default: + chClass += ' bi-checkbox checkbox-content'; + break; } - if (node[checkedKey] && setting.check.chkboxType.Y.indexOf("p") > -1) { - view.setParentNodeCheckBox(setting, node, true); + return chClass + (node.disabled ? " disabled" : ""); + }, + repairAllChk: function (setting, checked) { + if (setting.check.enable && setting.check.chkStyle === consts.checkbox.STYLE) { + var checkedKey = setting.data.key.checked, + childKey = setting.data.key.children, + root = data.getRoot(setting); + for (var i = 0, l = root[childKey].length; i < l; i++) { + var node = root[childKey][i]; + if (node.nocheck !== true && node.chkDisabled !== true) { + node[checkedKey] = checked; + } + view.setSonNodeCheckBox(setting, node, checked); + } } - if (!node[checkedKey] && setting.check.chkboxType.N.indexOf("p") > -1) { - view.setParentNodeCheckBox(setting, node, false); + }, + repairChkClass: function (setting, node) { + if (!node) return; + data.makeChkFlag(setting, node); + if (node.nocheck !== true) { + var checkObj = $$(node, consts.id.CHECK, setting); + view.setChkClass(setting, checkObj, node); } - } - }, - makeChkClass: function(setting, node) { - var checkedKey = setting.data.key.checked, - c = consts.checkbox, r = consts.radio, - checkboxType = setting.check.chkboxType; - var notEffectByOtherNode = (checkboxType.Y === "" && checkboxType.N === ""); - fullStyle = ""; - if (node.chkDisabled === true) { - fullStyle = c.DISABLED; - } else if (node.halfCheck) { - fullStyle = c.PART; - } else if (setting.check.chkStyle == r.STYLE) { - fullStyle = (node.check_Child_State < 1)? c.FULL:c.PART; - } else { - fullStyle = node[checkedKey] ? ((node.check_Child_State === 2 || node.check_Child_State === -1) || notEffectByOtherNode ? c.FULL:c.PART) : ((node.check_Child_State < 1 || notEffectByOtherNode)? c.FULL:c.PART); - } - var chkName = setting.check.chkStyle + "_" + (node[checkedKey] ? c.TRUE : c.FALSE) + "_" + fullStyle; - chkName = (node.check_Focus && node.chkDisabled !== true) ? chkName + "_" + c.FOCUS : chkName; - var chClass = consts.className.BUTTON + " " + c.DEFAULT + " " + chkName; - switch (chkName) { - case 'checkbox_true_part': - case 'checkbox_true_part_focus': - chClass += ' bi-half-button bi-high-light-border'; - break; - case 'checkbox_true_full': - case 'checkbox_true_full_focus': - chClass += ' bi-checkbox checkbox-content bi-high-light-background active'; - break; - case 'checkbox_false_full': - case 'checkbox_false_full_focus': - default: - chClass += ' bi-checkbox checkbox-content'; - break; - } - return chClass + (node.disabled ? " disabled" : ""); - }, - repairAllChk: function(setting, checked) { - if (setting.check.enable && setting.check.chkStyle === consts.checkbox.STYLE) { - var checkedKey = setting.data.key.checked, - childKey = setting.data.key.children, - root = data.getRoot(setting); - for (var i = 0, l = root[childKey].length; i 0) { + view.repairParentChkClass(setting, node[childKey][0]); + } else { + view.repairParentChkClass(setting, node); + } + }, + repairSonChkDisabled: function (setting, node, chkDisabled, inherit) { + if (!node) return; + var childKey = setting.data.key.children; + if (node.chkDisabled != chkDisabled) { + node.chkDisabled = chkDisabled; + } + view.repairChkClass(setting, node); + if (node[childKey] && inherit) { + for (var i = 0, l = node[childKey].length; i < l; i++) { + var sNode = node[childKey][i]; + view.repairSonChkDisabled(setting, sNode, chkDisabled, inherit); } - view.setSonNodeCheckBox(setting, node, checked); } - } - }, - repairChkClass: function(setting, node) { - if (!node) return; - data.makeChkFlag(setting, node); - if (node.nocheck !== true) { - var checkObj = $$(node, consts.id.CHECK, setting); - view.setChkClass(setting, checkObj, node); - } - }, - repairParentChkClass: function(setting, node) { - if (!node || !node.parentTId) return; - var pNode = node.getParentNode(); - view.repairChkClass(setting, pNode); - view.repairParentChkClass(setting, pNode); - }, - repairParentChkClassWithSelf: function(setting, node) { - if (!node) return; - var childKey = setting.data.key.children; - if (node[childKey] && node[childKey].length > 0) { - view.repairParentChkClass(setting, node[childKey][0]); - } else { - view.repairParentChkClass(setting, node); - } - }, - repairSonChkDisabled: function(setting, node, chkDisabled, inherit) { - if (!node) return; - var childKey = setting.data.key.children; - if (node.chkDisabled != chkDisabled) { - node.chkDisabled = chkDisabled; - } - view.repairChkClass(setting, node); - if (node[childKey] && inherit) { - for (var i = 0, l = node[childKey].length; i < l; i++) { - var sNode = node[childKey][i]; - view.repairSonChkDisabled(setting, sNode, chkDisabled, inherit); + }, + repairParentChkDisabled: function (setting, node, chkDisabled, inherit) { + if (!node) return; + if (node.chkDisabled != chkDisabled && inherit) { + node.chkDisabled = chkDisabled; } - } - }, - repairParentChkDisabled: function(setting, node, chkDisabled, inherit) { - if (!node) return; - if (node.chkDisabled != chkDisabled && inherit) { - node.chkDisabled = chkDisabled; - } - view.repairChkClass(setting, node); - view.repairParentChkDisabled(setting, node.getParentNode(), chkDisabled, inherit); - }, - setChkClass: function(setting, obj, node) { - if (!obj) return; - if (node.nocheck === true) { - obj.hide(); - } else { - obj.show(); - } - obj.attr('class', view.makeChkClass(setting, node)); - }, - setParentNodeCheckBox: function(setting, node, value, srcNode) { - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - checkObj = $$(node, consts.id.CHECK, setting); - if (!srcNode) srcNode = node; - data.makeChkFlag(setting, node); - if (node.nocheck !== true && node.chkDisabled !== true) { - node[checkedKey] = value; - view.setChkClass(setting, checkObj, node); - if (setting.check.autoCheckTrigger && node != srcNode) { - setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); + view.repairChkClass(setting, node); + view.repairParentChkDisabled(setting, node.getParentNode(), chkDisabled, inherit); + }, + setChkClass: function (setting, obj, node) { + if (!obj) return; + if (node.nocheck === true) { + obj.hide(); + } else { + obj.show(); } - } - if (node.parentTId) { - var pSign = true; - if (!value) { - var pNodes = node.getParentNode()[childKey]; - for (var i = 0, l = pNodes.length; i < l; i++) { - if ((pNodes[i].nocheck !== true && pNodes[i].chkDisabled !== true && pNodes[i][checkedKey]) - || ((pNodes[i].nocheck === true || pNodes[i].chkDisabled === true) && pNodes[i].check_Child_State > 0)) { - pSign = false; - break; - } + obj.attr('class', view.makeChkClass(setting, node)); + }, + setParentNodeCheckBox: function (setting, node, value, srcNode) { + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + checkObj = $$(node, consts.id.CHECK, setting); + if (!srcNode) srcNode = node; + data.makeChkFlag(setting, node); + if (node.nocheck !== true && node.chkDisabled !== true) { + node[checkedKey] = value; + view.setChkClass(setting, checkObj, node); + if (setting.check.autoCheckTrigger && node != srcNode) { + setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); } } - if (pSign) { - view.setParentNodeCheckBox(setting, node.getParentNode(), value, srcNode); + if (node.parentTId) { + var pSign = true; + if (!value) { + var pNodes = node.getParentNode()[childKey]; + for (var i = 0, l = pNodes.length; i < l; i++) { + if ((pNodes[i].nocheck !== true && pNodes[i].chkDisabled !== true && pNodes[i][checkedKey]) + || ((pNodes[i].nocheck === true || pNodes[i].chkDisabled === true) && pNodes[i].check_Child_State > 0)) { + pSign = false; + break; + } + } + } + if (pSign) { + view.setParentNodeCheckBox(setting, node.getParentNode(), value, srcNode); + } } - } - }, - setSonNodeCheckBox: function(setting, node, value, srcNode) { - if (!node) return; - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - checkObj = $$(node, consts.id.CHECK, setting); - if (!srcNode) srcNode = node; + }, + setSonNodeCheckBox: function (setting, node, value, srcNode) { + if (!node) return; + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + checkObj = $$(node, consts.id.CHECK, setting); + if (!srcNode) srcNode = node; - var hasDisable = false; - if (node[childKey]) { - for (var i = 0, l = node[childKey].length; i < l && node.chkDisabled !== true; i++) { - var sNode = node[childKey][i]; - view.setSonNodeCheckBox(setting, sNode, value, srcNode); - if (sNode.chkDisabled === true) hasDisable = true; + var hasDisable = false; + if (node[childKey]) { + for (var i = 0, l = node[childKey].length; i < l && node.chkDisabled !== true; i++) { + var sNode = node[childKey][i]; + view.setSonNodeCheckBox(setting, sNode, value, srcNode); + if (sNode.chkDisabled === true) hasDisable = true; + } } - } - if (node != data.getRoot(setting) && node.chkDisabled !== true) { - if (hasDisable && node.nocheck !== true) { - data.makeChkFlag(setting, node); - } - if (node.nocheck !== true && node.chkDisabled !== true) { - node[checkedKey] = value; - if (!hasDisable) node.check_Child_State = (node[childKey] && node[childKey].length > 0) ? (value ? 2 : 0) : -1; - } else { - node.check_Child_State = -1; - } - view.setChkClass(setting, checkObj, node); - if (setting.check.autoCheckTrigger && node != srcNode && node.nocheck !== true && node.chkDisabled !== true) { - setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); + if (node != data.getRoot(setting) && node.chkDisabled !== true) { + if (hasDisable && node.nocheck !== true) { + data.makeChkFlag(setting, node); + } + if (node.nocheck !== true && node.chkDisabled !== true) { + node[checkedKey] = value; + if (!hasDisable) node.check_Child_State = (node[childKey] && node[childKey].length > 0) ? (value ? 2 : 0) : -1; + } else { + node.check_Child_State = -1; + } + view.setChkClass(setting, checkObj, node); + if (setting.check.autoCheckTrigger && node != srcNode && node.nocheck !== true && node.chkDisabled !== true) { + setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); + } } - } - } - }, + } + }, - _z = { - tools: _tools, - view: _view, - event: _event, - data: _data - }; + _z = { + tools: _tools, + view: _view, + event: _event, + data: _data + }; $.extend(true, $.fn.zTree.consts, _consts); $.extend(true, $.fn.zTree._z, _z); var zt = $.fn.zTree, - tools = zt._z.tools, - consts = zt.consts, - view = zt._z.view, - data = zt._z.data, - event = zt._z.event, - $$ = tools.$; + tools = zt._z.tools, + consts = zt.consts, + view = zt._z.view, + data = zt._z.data, + event = zt._z.event, + $$ = tools.$; data.exSetting(_setting); data.addInitBind(_bindEvent); @@ -618,22 +623,22 @@ data.addZTreeTools(_zTreeTools); var _createNodes = view.createNodes; - view.createNodes = function(setting, level, nodes, parentNode) { + view.createNodes = function (setting, level, nodes, parentNode) { if (_createNodes) _createNodes.apply(view, arguments); if (!nodes) return; view.repairParentChkClassWithSelf(setting, parentNode); - } + }; var _removeNode = view.removeNode; - view.removeNode = function(setting, node) { + view.removeNode = function (setting, node) { var parentNode = node.getParentNode(); if (_removeNode) _removeNode.apply(view, arguments); if (!node || !parentNode) return; view.repairChkClass(setting, parentNode); view.repairParentChkClass(setting, parentNode); - } + }; var _appendNodes = view.appendNodes; - view.appendNodes = function(setting, level, nodes, parentNode, initFlag, openFlag) { + view.appendNodes = function (setting, level, nodes, parentNode, initFlag, openFlag) { var html = ""; if (_appendNodes) { html = _appendNodes.apply(view, arguments); @@ -642,5 +647,5 @@ data.makeChkFlag(setting, parentNode); } return html; - } -})(BI.jQuery); \ No newline at end of file + }; +})(BI.jQuery); diff --git a/src/case/ztree/list/0.listtreeview.js b/src/case/ztree/list/0.listtreeview.js deleted file mode 100644 index dd9a1f8c8..000000000 --- a/src/case/ztree/list/0.listtreeview.js +++ /dev/null @@ -1,118 +0,0 @@ -/** - * author: windy - * 继承自treeView, 此树的父子节点的勾选状态互不影响, 此树不会有半选节点 - * 返回value格式为[["A"], ["A", "a"]]表示勾选了A且勾选了a - * @class BI.ListTreeView - * @extends BI.TreeView - */ -BI.ListTreeView = BI.inherit(BI.TreeView, { - - _constants: { - SPLIT: "<|>" - }, - - _defaultConfig: function () { - return BI.extend(BI.ListTreeView.superclass._defaultConfig.apply(this, arguments), { - value: {} - }); - }, - _init: function () { - BI.ListTreeView.superclass._init.apply(this, arguments); - var o = this.options; - if(BI.isNotNull(o.value)) { - this.setSelectedValue(o.value); - } - }, - - // 配置属性 - _configSetting: function () { - var paras = this.options.paras; - var self = this; - var setting = { - async: { - enable: false - }, - check: { - enable: true, - chkboxType: {Y: "", N: ""} - }, - data: { - key: { - title: "title", - name: "text" - }, - simpleData: { - enable: true - } - }, - view: { - showIcon: false, - expandSpeed: "", - nameIsHTML: true, - dblClickExpand: false - }, - callback: { - onCheck: onCheck, - onClick: onClick - } - }; - - function onClick (event, treeId, treeNode) { - var zTree = BI.$.fn.zTree.getZTreeObj(treeId); - var checked = treeNode.checked; - self._checkValue(treeNode, !checked); - zTree.checkNode(treeNode, !checked, true, true); - } - - function onCheck (event, treeId, treeNode) { - self._selectTreeNode(treeId, treeNode); - } - - return setting; - }, - - _selectTreeNode: function (treeId, treeNode) { - this._checkValue(treeNode, treeNode.checked); - BI.ListTreeView.superclass._selectTreeNode.apply(this, arguments); - }, - - _transArrayToMap: function (treeArrays) { - var self = this; - var map = {}; - BI.each(treeArrays, function (idx, array) { - var key = array.join(self._constants.SPLIT); - map[key] = true; - }); - return map; - }, - - _transMapToArray: function (treeMap) { - var self = this; - var array = []; - BI.each(treeMap, function (key) { - var item = key.split(self._constants.SPLIT); - array.push(item); - }); - return array; - }, - - _checkValue: function (treeNode, checked) { - var key = BI.concat(this._getParentValues(treeNode), this._getNodeValue(treeNode)).join(this._constants.SPLIT); - if(checked) { - this.storeValue[key] = true; - } else { - delete this.storeValue[key]; - } - }, - - setSelectedValue: function (value) { - this.options.paras.selectedValues = value || []; - this.storeValue = this._transArrayToMap(value); - }, - - getValue: function () { - return this._transMapToArray(this.storeValue); - } -}); - -BI.shortcut("bi.list_tree_view", BI.ListTreeView); \ No newline at end of file diff --git a/src/case/ztree/list/1.listasynctree.js b/src/case/ztree/list/1.listasynctree.js deleted file mode 100644 index 7e1f25b10..000000000 --- a/src/case/ztree/list/1.listasynctree.js +++ /dev/null @@ -1,123 +0,0 @@ -/** - * author: windy - * 继承自treeView, 此树的父子节点的勾选状态互不影响, 此树不会有半选节点 - * 返回value格式为["A", ["A", "a"]]表示勾选了A且勾选了a - * @class BI.ListListAsyncTree - * @extends BI.TreeView - */ -BI.ListAsyncTree = BI.inherit(BI.ListTreeView, { - _defaultConfig: function () { - return BI.extend(BI.ListAsyncTree.superclass._defaultConfig.apply(this, arguments), {}); - }, - _init: function () { - BI.ListAsyncTree.superclass._init.apply(this, arguments); - }, - - // 配置属性 - _configSetting: function () { - var paras = this.options.paras; - var self = this; - var setting = { - async: { - enable: false, // 很明显这棵树把异步请求关掉了,所有的异步请求都是手动控制的 - otherParam: BI.cjkEncodeDO(paras) - }, - check: { - enable: true, - chkboxType: {Y: "", N: ""} - }, - data: { - key: { - title: "title", - name: "text" - }, - simpleData: { - enable: true - } - }, - view: { - showIcon: false, - expandSpeed: "", - nameIsHTML: true, - dblClickExpand: false - }, - callback: { - onCheck: onCheck, - beforeExpand: beforeExpand, - beforeCheck: beforeCheck, - onClick: onClick - } - }; - - function beforeCheck (treeId, treeNode) { - treeNode.half = false; - } - - function onClick (event, treeId, treeNode) { - var zTree = BI.$.fn.zTree.getZTreeObj(treeId); - var checked = treeNode.checked; - self._checkValue(treeNode, !checked); - zTree.checkNode(treeNode, !checked, true, true); - } - - function beforeExpand (treeId, treeNode) { - self._beforeExpandNode(treeId, treeNode); - } - - function onCheck (event, treeId, treeNode) { - self._selectTreeNode(treeId, treeNode); - } - - return setting; - }, - - // 展开节点 - _beforeExpandNode: function (treeId, treeNode) { - var self = this, o = this.options; - var parentValues = treeNode.parentValues || self._getParentValues(treeNode); - var op = BI.extend({}, o.paras, { - id: treeNode.id, - times: 1, - parentValues: parentValues.concat(this._getNodeValue(treeNode)) - }); - var complete = function (d) { - var nodes = d.items || []; - if (nodes.length > 0) { - callback(self._dealWidthNodes(nodes), !!d.hasNext); - } - }; - var times = 1; - - function callback (nodes, hasNext) { - self.nodes.addNodes(treeNode, nodes); - // 展开节点是没有分页的 - if (hasNext === true) { - BI.delay(function () { - times++; - op.times = times; - o.itemsCreator(op, complete); - }, 100); - } - } - - if (!treeNode.children) { - setTimeout(function () { - o.itemsCreator(op, complete); - }, 17); - } - }, - - hasChecked: function () { - return !BI.isEmpty(this.options.paras.selectedValues) || BI.ListAsyncTree.superclass.hasChecked.apply(this, arguments); - }, - - // 生成树方法 - stroke: function (config) { - delete this.options.keyword; - BI.extend(this.options.paras, config); - var setting = this._configSetting(); - this._initTree(setting); - } -}); - -BI.shortcut("bi.list_async_tree", BI.ListAsyncTree); \ No newline at end of file diff --git a/src/case/ztree/list/listasynctree.js b/src/case/ztree/list/listasynctree.js new file mode 100644 index 000000000..019e7f4be --- /dev/null +++ b/src/case/ztree/list/listasynctree.js @@ -0,0 +1,122 @@ +/** + * author: windy + * 继承自treeView, 此树的父子节点的勾选状态互不影响, 此树不会有半选节点 + * 返回value格式为["A", ["A", "a"]]表示勾选了A且勾选了a + * @class ListListAsyncTree + * @extends TreeView + */ + +import { Listtreeview } from "./listtreeview"; +import { cjkEncodeDO, delay, isEmpty, shortcut, extend } from "@/core"; + +@shortcut() +export class Listasynctree extends Listtreeview { + static xtype = "bi.list_async_tree"; + + // 配置属性 + _configSetting() { + const paras = this.options.paras; + const self = this; + + function beforeCheck(treeId, treeNode) { + treeNode.half = false; + } + + function onClick(event, treeId, treeNode) { + const zTree = BI.$.fn.zTree.getZTreeObj(treeId); + const checked = treeNode.checked; + self._checkValue(treeNode, !checked); + zTree.checkNode(treeNode, !checked, true, true); + } + + function beforeExpand(treeId, treeNode) { + self._beforeExpandNode(treeId, treeNode); + } + + function onCheck(event, treeId, treeNode) { + self._selectTreeNode(treeId, treeNode); + } + + return { + async: { + enable: false, // 很明显这棵树把异步请求关掉了,所有的异步请求都是手动控制的 + otherParam: cjkEncodeDO(paras), + }, + check: { + enable: true, + chkboxType: { Y: "", N: "" }, + }, + data: { + key: { + title: "title", + name: "text", + }, + simpleData: { + enable: true, + }, + }, + view: { + showIcon: false, + expandSpeed: "", + nameIsHTML: true, + dblClickExpand: false, + }, + callback: { + onCheck, + beforeExpand, + beforeCheck, + onClick, + }, + }; + } + + // 展开节点 + _beforeExpandNode(treeId, treeNode) { + const self = this, o = this.options; + const parentValues = treeNode.parentValues || self._getParentValues(treeNode); + const op = extend({}, o.paras, { + id: treeNode.id, + times: 1, + parentValues: parentValues.concat(this._getNodeValue(treeNode)), + }); + + function complete(d) { + const nodes = d.items || []; + if (nodes.length > 0) { + callback(self._dealWidthNodes(nodes), !!d.hasNext); + } + }; + let times = 1; + + function callback(nodes, hasNext) { + self.nodes.addNodes(treeNode, nodes); + // 展开节点是没有分页的 + if (hasNext === true) { + delay(() => { + times++; + op.times = times; + o.itemsCreator(op, complete); + }, 100); + } + } + + if (!treeNode.children) { + setTimeout(() => { + o.itemsCreator(op, complete); + }, 17); + } + } + + hasChecked() { + return !isEmpty(this.options.paras.selectedValues) || super.hasChecked(...arguments); + } + + // 生成树方法 + stroke(config) { + delete this.options.keyword; + extend(this.options.paras, config); + const setting = this._configSetting(); + this._initTree(setting); + } +} + diff --git a/src/case/ztree/list/listparttree.js b/src/case/ztree/list/listparttree.js index cc4462166..dd908c36f 100644 --- a/src/case/ztree/list/listparttree.js +++ b/src/case/ztree/list/listparttree.js @@ -1,27 +1,28 @@ /** * guy * 局部树,两个请求树, 第一个请求构造树,第二个请求获取节点 - * @class BI.ListPartTree - * @extends BI.AsyncTree + * @class ListPartTree + * @extends Asynctree */ -BI.ListPartTree = BI.inherit(BI.ListAsyncTree, { - _defaultConfig: function () { - return BI.extend(BI.ListPartTree.superclass._defaultConfig.apply(this, arguments), {}); - }, - _init: function () { - BI.ListPartTree.superclass._init.apply(this, arguments); - }, - _loadMore: function () { - var self = this, o = this.options; - var op = BI.extend({}, o.paras, { - type: BI.TreeView.REQ_TYPE_INIT_DATA, - times: ++this.times +import { Listasynctree } from "./listasynctree"; +import { shortcut, extend, Events, delay } from "@/core"; +import { TreeView } from "../treeview"; + +@shortcut() +export class ListPartTree extends Listasynctree { + static xtype = "bi.list_part_tree"; + + _loadMore() { + const self = this, o = this.options; + const op = extend({}, o.paras, { + type: TreeView.REQ_TYPE_INIT_DATA, + times: ++this.times, }); this.tip.setLoading(); - o.itemsCreator(op, function (d) { - var hasNext = !!d.hasNext, nodes = d.items || []; + o.itemsCreator(op, d => { + const hasNext = !!d.hasNext, nodes = d.items || []; o.paras.lastSearchValue = d.lastSearchValue; if (self._stop === true) { return; @@ -35,24 +36,25 @@ BI.ListPartTree = BI.inherit(BI.ListAsyncTree, { self.nodes.addNodes(null, self._dealWidthNodes(nodes)); } }); - }, + } - _initTree: function (setting, keyword) { - var self = this, o = this.options; + _initTree(setting, keyword) { + const self = this, o = this.options; this.times = 1; - var tree = this.tree; + const tree = this.tree; tree.empty(); self.tip.setVisible(false); this.loading(); - var op = BI.extend({}, o.paras, { - type: BI.TreeView.REQ_TYPE_INIT_DATA, - times: this.times + const op = extend({}, o.paras, { + type: TreeView.REQ_TYPE_INIT_DATA, + times: this.times, }); - var complete = function (d) { - if (self._stop === true || keyword != o.paras.keyword) { + + function complete(d) { + if (self._stop === true || keyword !== o.paras.keyword) { return; } - var hasNext = !!d.hasNext, nodes = d.items || []; + const hasNext = !!d.hasNext, nodes = d.items || []; o.paras.lastSearchValue = d.lastSearchValue; // 没有请求到数据也要初始化空树, 如果不初始化, 树就是上一次构造的树, 节点信息都是过期的 callback(nodes.length > 0 ? self._dealWidthNodes(nodes) : []); @@ -63,30 +65,28 @@ BI.ListPartTree = BI.inherit(BI.ListAsyncTree, { } else { self.tip.setLoaded(); } - self.fireEvent(BI.Events.AFTERINIT); - }; + self.fireEvent(Events.AFTERINIT); + } - function callback (nodes) { + function callback(nodes) { if (self._stop === true) { return; } self.nodes = BI.$.fn.zTree.init(tree.element, setting, nodes); } - BI.delay(function () { + delay(() => { o.itemsCreator(op, complete); }, 100); - }, + } // 生成树方法 - stroke: function (config) { - var o = this.options; + stroke(config) { + const o = this.options; delete o.paras.keyword; - BI.extend(o.paras, config); + extend(o.paras, config); delete o.paras.lastSearchValue; - var setting = this._configSetting(); + const setting = this._configSetting(); this._initTree(setting, o.paras.keyword); } -}); - -BI.shortcut("bi.list_part_tree", BI.ListPartTree); \ No newline at end of file +} diff --git a/src/case/ztree/list/listtreeview.js b/src/case/ztree/list/listtreeview.js new file mode 100644 index 000000000..b31e93869 --- /dev/null +++ b/src/case/ztree/list/listtreeview.js @@ -0,0 +1,121 @@ +/** + * author: windy + * 继承自treeView, 此树的父子节点的勾选状态互不影响, 此树不会有半选节点 + * 返回value格式为[["A"], ["A", "a"]]表示勾选了A且勾选了a + * @class BI.ListTreeView + * @extends BI.TreeView + */ + +import { TreeView } from "../treeview"; +import { extend, isNotNull, concat, each, shortcut } from "@/core"; + +@shortcut() +export class Listtreeview extends TreeView { + static xtype = "bi.list_tree_view"; + + _constants = { + SPLIT: "<|>", + }; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { + value: {}, + }); + } + + _init() { + super._init(...arguments); + const o = this.options; + if (isNotNull(o.value)) { + this.setSelectedValue(o.value); + } + } + + // 配置属性 + _configSetting() { + const self = this; + + function onClick(event, treeId, treeNode) { + const zTree = BI.$.fn.zTree.getZTreeObj(treeId); + const checked = treeNode.checked; + self._checkValue(treeNode, !checked); + zTree.checkNode(treeNode, !checked, true, true); + } + + function onCheck(event, treeId, treeNode) { + self._selectTreeNode(treeId, treeNode); + } + + return { + async: { + enable: false, + }, + check: { + enable: true, + chkboxType: { Y: "", N: "" }, + }, + data: { + key: { + title: "title", + name: "text", + }, + simpleData: { + enable: true, + }, + }, + view: { + showIcon: false, + expandSpeed: "", + nameIsHTML: true, + dblClickExpand: false, + }, + callback: { + onCheck, + onClick, + }, + }; + } + + _selectTreeNode(treeId, treeNode) { + this._checkValue(treeNode, treeNode.checked); + super._selectTreeNode(...arguments); + } + + _transArrayToMap(treeArrays) { + const map = {}; + each(treeArrays, (idx, array) => { + const key = array.join(this._constants.SPLIT); + map[key] = true; + }); + + return map; + } + + _transMapToArray(treeMap) { + const array = []; + BI.each(treeMap, key => { + const item = key.split(this._constants.SPLIT); + array.push(item); + }); + + return array; + } + + _checkValue(treeNode, checked) { + const key = concat(this._getParentValues(treeNode), this._getNodeValue(treeNode)).join(this._constants.SPLIT); + if (checked) { + this.storeValue[key] = true; + } else { + delete this.storeValue[key]; + } + } + + setSelectedValue(value) { + this.options.paras.selectedValues = value || []; + this.storeValue = this._transArrayToMap(value); + } + + getValue() { + return this._transMapToArray(this.storeValue); + } +} diff --git a/src/case/ztree/parttree.js b/src/case/ztree/parttree.js index 8a347548a..f66c14920 100644 --- a/src/case/ztree/parttree.js +++ b/src/case/ztree/parttree.js @@ -4,20 +4,30 @@ * @class BI.PartTree * @extends BI.AsyncTree */ -BI.PartTree = BI.inherit(BI.AsyncTree, { - _defaultConfig: function () { - return BI.extend(BI.PartTree.superclass._defaultConfig.apply(this, arguments), {}); - }, - - _loadMore: function () { - var self = this, o = this.options; - var op = BI.extend({}, o.paras, { - type: BI.TreeView.REQ_TYPE_INIT_DATA, - times: ++this.times +import { isEmpty, shortcut, extend, deepClone, each, isNotEmptyArray, Events, delay, isNull } from "@/core"; +import { Asynctree } from "./asynctree"; +import { TreeView } from "./treeview"; + +@shortcut() +export class PartTree extends Asynctree { + static xtype = "bi.part_tree"; + + static EVENT_CLICK_TREE_NODE = "EVENT_CLICK_TREE_NODE"; + + constructor(...args) { + super(...args); + this.seMethos = super._selectTreeNode; + } + + _loadMore() { + const self = this, o = this.options; + const op = extend({}, o.paras, { + type: TreeView.REQ_TYPE_INIT_DATA, + times: ++this.times, }); this.tip.setLoading(); - o.itemsCreator(op, function (d) { - var hasNext = !!d.hasNext, nodes = d.items || []; + o.itemsCreator(op, d => { + const hasNext = !!d.hasNext, nodes = d.items || []; o.paras.lastSearchValue = d.lastSearchValue; if (self._stop === true) { return; @@ -31,71 +41,73 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { self.nodes.addNodes(null, self._dealWidthNodes(nodes)); } }); - }, + } - _selectTreeNode: function (treeId, treeNode) { - var self = this, o = this.options; - var parentValues = BI.deepClone(treeNode.parentValues || self._getParentValues(treeNode)); - var name = this._getNodeValue(treeNode); - this.fireEvent(BI.PartTree.EVENT_CLICK_TREE_NODE); + _selectTreeNode(...args) { + const self = this, o = this.options; + const [treeId, treeNode] = args; + const parentValues = deepClone(treeNode.parentValues || self._getParentValues(treeNode)); + const name = this._getNodeValue(treeNode); + this.fireEvent(PartTree.EVENT_CLICK_TREE_NODE); if (treeNode.checked === true) { this.options.paras.selectedValues = this._getUnionValue(); - // this._buildTree(self.options.paras.selectedValues, BI.concat(parentValues, name)); - o.itemsCreator(BI.extend({}, o.paras, { - type: BI.TreeView.REQ_TYPE_ADJUST_DATA, + // this._buildTree(self.options.paras.selectedValues, concat(parentValues, name)); + o.itemsCreator(extend({}, o.paras, { + type: TreeView.REQ_TYPE_ADJUST_DATA, curSelectedValue: name, - parentValues: parentValues + parentValues, }), function (res) { self.options.paras.selectedValues = res; - BI.AsyncTree.superclass._selectTreeNode.apply(self, arguments); + this.seMethos(...args); }); } else { // 如果选中的值中不存在该值不处理 // 因为反正是不选中,没必要管 - var t = this.options.paras.selectedValues; - var p = parentValues.concat(name); - for (var i = 0, len = p.length; i < len; i++) { + let t = this.options.paras.selectedValues; + const p = parentValues.concat(name); + for (let i = 0, len = p.length; i < len; i++) { t = t[p[i]]; if (t == null) { return; } // 选中中国-江苏, 搜索南京,取消勾选 - if (BI.isEmpty(t)) { + if (isEmpty(t)) { break; } } - o.itemsCreator(BI.extend({}, o.paras, { - type: BI.TreeView.REQ_TYPE_SELECT_DATA, + o.itemsCreator(extend({}, o.paras, { + type: TreeView.REQ_TYPE_SELECT_DATA, notSelectedValue: name, - parentValues: parentValues - }), function (new_values) { + parentValues, + }), new_values => { self.options.paras.selectedValues = new_values; - BI.AsyncTree.superclass._selectTreeNode.apply(self, arguments); + this.seMethos(...args); }); } - }, + } - _getSelectedValues: function () { - var self = this; - var hashMap = {}; - var rootNoots = this.nodes.getNodes(); - track(rootNoots); + _getSelectedValues() { + const self = this; + const hashMap = {}; + const rootNodes = this.nodes.getNodes(); + track(rootNodes); function track(nodes) { - BI.each(nodes, function (i, node) { - var checkState = node.getCheckStatus(); + each(nodes, (i, node) => { + const checkState = node.getCheckStatus(); if (checkState.checked === false) { return true; } - var parentValues = node.parentValues || self._getParentValues(node); + const parentValues = node.parentValues || self._getParentValues(node); // 把文字中的html去掉,其实就是把文字颜色去掉 - var values = parentValues.concat([self._getNodeValue(node)]); + const values = parentValues.concat([self._getNodeValue(node)]); self._buildTree(hashMap, values); // if(checkState.checked === true && checkState.half === false && nodes[i].flag === true){ // continue; // } - if (BI.isNotEmptyArray(node.children)) { + if (isNotEmptyArray(node.children)) { track(node.children); + return true; } if (checkState.half === true) { @@ -105,24 +117,25 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { } return hashMap; - }, + } - _initTree: function (setting, keyword) { - var self = this, o = this.options; + _initTree(setting, keyword) { + const self = this, o = this.options; this.times = 1; - var tree = this.tree; + const tree = this.tree; tree.empty(); self.tip.setVisible(false); this.loading(); - var op = BI.extend({}, o.paras, { - type: BI.TreeView.REQ_TYPE_INIT_DATA, - times: this.times + const op = extend({}, o.paras, { + type: TreeView.REQ_TYPE_INIT_DATA, + times: this.times, }); - var complete = function (d) { - if (self._stop === true || keyword != o.paras.keyword) { + + function complete(d) { + if (self._stop === true || keyword !== o.paras.keyword) { return; } - var hasNext = !!d.hasNext, nodes = d.items || []; + const hasNext = !!d.hasNext, nodes = d.items || []; o.paras.lastSearchValue = d.lastSearchValue; // 没有请求到数据也要初始化空树, 如果不初始化, 树就是上一次构造的树, 节点信息都是过期的 callback(nodes.length > 0 ? self._dealWidthNodes(nodes) : []); @@ -133,8 +146,8 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { } else { self.tip.setLoaded(); } - self.fireEvent(BI.Events.AFTERINIT); - }; + self.fireEvent(Events.AFTERINIT); + } function callback(nodes) { if (self._stop === true) { @@ -143,40 +156,41 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { self.nodes = BI.$.fn.zTree.init(tree.element, setting, nodes); } - BI.delay(function () { + delay(() => { o.itemsCreator(op, complete); }, 100); - }, + } - getValue: function () { - return BI.deepClone(this.options.paras.selectedValues || {}); - }, + getValue() { + return deepClone(this.options.paras.selectedValues || {}); + } - _getUnionValue: function () { + _getUnionValue() { if (!this.nodes) { return {}; } - var checkedValues = this._getSelectedValues(); - if (BI.isEmpty(checkedValues)) { - return BI.deepClone(this.options.paras.selectedValues); + const checkedValues = this._getSelectedValues(); + if (isEmpty(checkedValues)) { + return deepClone(this.options.paras.selectedValues); } - if (BI.isEmpty(this.options.paras.selectedValues)) { + if (isEmpty(this.options.paras.selectedValues)) { return checkedValues; } + return this._union(checkedValues, this.options.paras.selectedValues); - }, + } - _union: function (valueA, valueB) { - var self = this; - var map = {}; + _union(valueA, valueB) { + const self = this; + const map = {}; track([], valueA, valueB); track([], valueB, valueA); function track(parent, node, compare) { - BI.each(node, function (n, item) { - if (BI.isNull(compare[n])) { + each(node, (n, item) => { + if (isNull(compare[n])) { self._addTreeNode(map, parent, n, item); - } else if (BI.isEmpty(compare[n])) { + } else if (isEmpty(compare[n])) { self._addTreeNode(map, parent, n, {}); } else { track(parent.concat([n]), node[n], compare[n]); @@ -185,18 +199,15 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { } return map; - }, + } // 生成树方法 - stroke: function (config) { - var o = this.options; + stroke(config) { + const o = this.options; delete o.paras.keyword; - BI.extend(o.paras, config); + extend(o.paras, config); delete o.paras.lastSearchValue; - var setting = this._configSetting(); + const setting = this._configSetting(); this._initTree(setting, o.paras.keyword); } -}); - -BI.PartTree.EVENT_CLICK_TREE_NODE = "EVENT_CLICK_TREE_NODE"; -BI.shortcut("bi.part_tree", BI.PartTree); +} diff --git a/src/case/ztree/tree.display.js b/src/case/ztree/tree.display.js index 4c0135675..a385d58c6 100644 --- a/src/case/ztree/tree.display.js +++ b/src/case/ztree/tree.display.js @@ -4,63 +4,64 @@ * @class BI.DisplayTree * @extends BI.TreeView */ -BI.DisplayTree = BI.inherit(BI.TreeView, { - _defaultConfig: function () { - return BI.extend(BI.DisplayTree.superclass._defaultConfig.apply(this, arguments), { - extraCls: "bi-display-tree" + +import { extend } from "@/core"; +import { TreeView } from "./treeview"; + +export class DisplayTree extends TreeView { + static xtype = "bi.display_tree"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { + extraCls: "bi-display-tree", }); - }, + } // 配置属性 - _configSetting: function () { - var setting = { + _configSetting() { + function beforeCollapse(treeId, treeNode) { + return false; + } + + return { view: { selectedMulti: false, dblClickExpand: false, showIcon: false, nameIsHTML: true, - showTitle: false + showTitle: false, }, data: { key: { title: "title", - name: "text" + name: "text", }, simpleData: { - enable: true - } + enable: true, + }, }, callback: { - beforeCollapse: beforeCollapse - } + beforeCollapse, + }, }; + } - function beforeCollapse(treeId, treeNode) { - return false; - } - - return setting; - }, - - _dealWidthNodes: function (nodes) { - nodes = BI.DisplayTree.superclass._dealWidthNodes.apply(this, arguments); - var self = this, o = this.options; - BI.each(nodes, function (i, node) { + _dealWidthNodes(nodes) { + nodes = super._dealWidthNodes(...arguments); + BI.each(nodes, (i, node) => { node.isParent = node.isParent || node.parent; if (node.text == null) { if (node.count > 0) { - node.text = node.value + "(" + BI.i18nText("BI-Basic_Altogether") + node.count + BI.i18nText("BI-Basic_Count") + ")"; + node.text = `${node.value}(${BI.i18nText("BI-Basic_Altogether")}${node.count}${BI.i18nText("BI-Basic_Count")})`; } } }); - return nodes; - }, - initTree: function (nodes, setting) { - var setting = setting || this._configSetting(); - this.nodes = BI.$.fn.zTree.init(this.tree.element, setting, nodes); + return nodes; } -}); -BI.DisplayTree.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.display_tree", BI.DisplayTree); + initTree(nodes, setting) { + this.nodes = BI.$.fn.zTree.init(this.tree.element, setting || this._configSetting(), nodes); + } +} diff --git a/src/case/ztree/tree.list.display.js b/src/case/ztree/tree.list.display.js index 60ce5574d..a3769e898 100644 --- a/src/case/ztree/tree.list.display.js +++ b/src/case/ztree/tree.list.display.js @@ -4,75 +4,69 @@ * @class BI.ListListDisplayTree * @extends BI.TreeView */ -BI.ListDisplayTree = BI.inherit(BI.ListTreeView, { - _defaultConfig: function () { - return BI.extend(BI.ListDisplayTree.superclass._defaultConfig.apply(this, arguments), { - extraCls: "bi-list-display-tree" - }); - }, - _init: function () { - BI.ListDisplayTree.superclass._init.apply(this, arguments); - }, +import { Listtreeview } from "./list/listtreeview"; +import { each, shortcut } from "@/core"; + +@shortcut() +export class ListDisplayTree extends Listtreeview { + static xtype = "bi.list_display_tree"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + props() { + return { + extraCls: "bi-list-display-tree", + }; + } // 配置属性 - _configSetting: function () { - var setting = { + _configSetting() { + function beforeCollapse(treeId, treeNode) { + return false; + } + + function getFont(treeId, node) { + return node.isLeaf ? {} : { color: "#999999" }; + } + + return { view: { selectedMulti: false, dblClickExpand: false, showIcon: false, nameIsHTML: true, showTitle: false, - fontCss: getFont + fontCss: getFont, }, data: { key: { title: "title", - name: "text" + name: "text", }, simpleData: { - enable: true - } + enable: true, + }, }, callback: { - beforeCollapse: beforeCollapse - } + beforeCollapse, + }, }; + } - function beforeCollapse(treeId, treeNode) { - return false; - } - - function getFont(treeId, node) { - return node.isLeaf ? {} : {color: "#999999"}; - } - - return setting; - }, - - _dealWidthNodes: function (nodes) { - nodes = BI.ListDisplayTree.superclass._dealWidthNodes.apply(this, arguments); - var self = this, o = this.options; - BI.each(nodes, function (i, node) { + _dealWidthNodes(nodes) { + nodes = super._dealWidthNodes(...arguments); + each(nodes, (i, node) => { node.isParent = node.isParent || node.parent; if (node.text == null) { if (node.count > 0) { - node.text = node.value + "(" + BI.i18nText("BI-Basic_Altogether") + node.count + BI.i18nText("BI-Basic_Count") + ")"; + node.text = `${node.value}(${BI.i18nText("BI-Basic_Altogether")}${node.count}${BI.i18nText("BI-Basic_Count")})`; } } }); - return nodes; - }, - initTree: function (nodes, setting) { - var setting = setting || this._configSetting(); - this.nodes = BI.$.fn.zTree.init(this.tree.element, setting, nodes); - }, - - destroy: function () { - BI.ListDisplayTree.superclass.destroy.apply(this, arguments); + return nodes; } -}); -BI.ListDisplayTree.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.list_display_tree", BI.ListDisplayTree); \ No newline at end of file + initTree(nodes, setting) { + this.nodes = BI.$.fn.zTree.init(this.tree.element, setting || this._configSetting(), nodes); + } +} diff --git a/src/case/ztree/tree.simple.js b/src/case/ztree/tree.simple.js index 690a445a7..1483a27a7 100644 --- a/src/case/ztree/tree.simple.js +++ b/src/case/ztree/tree.simple.js @@ -2,66 +2,86 @@ * 简单的多选树 * * Created by GUY on 2016/2/16. - * @class BI.SimpleTreeView - * @extends BI.Widget + * @class SimpleTreeView + * @extends Widget */ -BI.SimpleTreeView = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.SimpleTreeView.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + Widget, + Tree, + createWidget, + emptyFn, + isNotNull, + isNotEmptyArray, + each, + makeObject, + isEmpty +} from "@/core"; +import { TreeView } from "./treeview"; + +@shortcut() +export class SimpleTreeView extends Widget { + static xtype = "bi.simple_tree"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + props() { + return { baseCls: "bi-simple-tree", - itemsCreator: BI.emptyFn, - items: null - }); - }, - _init: function () { - BI.SimpleTreeView.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.structure = new BI.Tree(); - this.tree = BI.createWidget({ - type: "bi.tree_view", + itemsCreator: emptyFn, + items: null, + }; + } + + _init() { + super._init(...arguments); + const self = this, o = this.options; + this.structure = new Tree(); + this.tree = createWidget({ + type: TreeView.xtype, element: this, - itemsCreator: function (op, callback) { - var fn = function (items) { + itemsCreator(op, callback) { + function fn(items) { callback({ - items: items + items, }); - self.structure.initTree(BI.Tree.transformToTreeFormat(items)); + self.structure.initTree(Tree.transformToTreeFormat(items)); }; - if (BI.isNotNull(o.items)) { + if (isNotNull(o.items)) { fn(o.items); } else { o.itemsCreator(op, fn); } - } + }, }); - this.tree.on(BI.TreeView.EVENT_CHANGE, function () { - self.fireEvent(BI.SimpleTreeView.EVENT_CHANGE, arguments); + this.tree.on(TreeView.EVENT_CHANGE, function () { + self.fireEvent(SimpleTreeView.EVENT_CHANGE, arguments); }); - if (BI.isNotEmptyArray(o.items)) { + if (isNotEmptyArray(o.items)) { this.populate(); } - if (BI.isNotNull(o.value)) { + if (isNotNull(o.value)) { this.setValue(o.value); } - }, + } - populate: function (items, keyword) { + populate(items, keyword) { if (items) { this.options.items = items; } this.tree.stroke({ - keyword: keyword + keyword, }); - }, + } - _digest: function (v) { + _digest(v) { v || (v = []); - var self = this, map = {}; - var selected = []; - BI.each(v, function (i, val) { - var node = self.structure.search(val, "value"); + const self = this, map = {}; + const selected = []; + each(v, (i, val) => { + const node = self.structure.search(val, "value"); if (node) { - var p = node; + let p = node; p = p.getParent(); if (p) { if (!map[p.value]) { @@ -82,18 +102,20 @@ BI.SimpleTreeView = BI.inherit(BI.Widget, { } } }); - return BI.makeObject(v.concat(selected)); - }, - setValue: function (v) { + return makeObject(v.concat(selected)); + } + + setValue(v) { this.tree.setValue(this._digest(v)); - }, + } + + _getValue() { + const result = [], val = this.tree.getValue(); - _getValue: function () { - var self = this, result = [], val = this.tree.getValue(); - var track = function (nodes) { - BI.each(nodes, function (key, node) { - if (BI.isEmpty(node)) { + function track(nodes) { + each(nodes, (key, node) => { + if (isEmpty(node)) { result.push(key); } else { track(node); @@ -101,27 +123,27 @@ BI.SimpleTreeView = BI.inherit(BI.Widget, { }); }; track(val); + return result; - }, + } - empty: function () { + empty() { this.tree.empty(); - }, + } - getValue: function () { - var self = this, result = [], val = this._getValue(); - BI.each(val, function (i, key) { - var target = self.structure.search(key, "value"); + getValue() { + const self = this, result = [], val = this._getValue(); + each(val, (i, key) => { + const target = self.structure.search(key, "value"); if (target) { - self.structure._traverse(target, function (node) { + self.structure._traverse(target, node => { if (node.isLeaf()) { result.push(node.value); } }); } }); + return result; } -}); -BI.SimpleTreeView.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.simple_tree", BI.SimpleTreeView); +} diff --git a/src/case/ztree/treerender.page.service.js b/src/case/ztree/treerender.page.service.js new file mode 100644 index 000000000..5bb8be327 --- /dev/null +++ b/src/case/ztree/treerender.page.service.js @@ -0,0 +1,72 @@ +/** + * @author windy + * @version 2.0 + * Created by windy on 2020/1/8 + * 提供节点分页加载方式 + */ + +import { createWidget, debounce, has, OB, size, each } from "@/core"; + +export class TreeRenderPageService extends OB { + nodeLists = {}; + + _getLoadingBar(tId) { + const tip = createWidget({ + type: "bi.loading_bar", + height: 25, + handler: () => { + this.refreshNodes(tId); + }, + }); + tip.setLoaded(); + + return tip; + } + + pushNodeList(tId, populate) { + const o = this.options; + const tip = this._getLoadingBar(tId); + if (!has(this.nodeLists, tId)) { + this.nodeLists[tId] = { + populate: debounce(populate, 0), + options: { + times: 1, + }, + loadWidget: tip, + }; + } else { + this.nodeLists[tId].loadWidget.destroy(); + this.nodeLists[tId].loadWidget = tip; + } + createWidget({ + type: "bi.vertical", + element: o.subNodeListGetter(tId), + items: [tip], + }); + } + + refreshNodes(tId) { + const nodeList = this.nodeLists[tId]; + nodeList.options.times++; + nodeList.loadWidget.setLoading(); + nodeList.populate({ + times: nodeList.options.times, + }); + } + + removeNodeList(tId) { + this.nodeLists[tId] && this.nodeLists[tId].loadWidget.destroy(); + this.nodeLists[tId] && (this.nodeLists[tId].loadWidget = null); + delete this.nodeLists[tId]; + if (size(this.nodeLists) === 0) { + this.clear(); + } + } + + clear() { + each(this.nodeLists, tId => { + this.removeNodeList(tId); + }); + this.nodeLists = {}; + } +} diff --git a/src/case/ztree/treerender.scroll.service.js b/src/case/ztree/treerender.scroll.service.js index a2d019c46..ffd5ea289 100644 --- a/src/case/ztree/treerender.scroll.service.js +++ b/src/case/ztree/treerender.scroll.service.js @@ -5,120 +5,121 @@ * 提供节点滚动加载方式 */ -!(function () { - BI.TreeRenderScrollService = BI.inherit(BI.OB, { - _init: function () { - this.nodeLists = {}; +import { debounce, each, has, isNotNull, OB, size } from "@/core"; - this.id = this.options.id; - // renderService是否已经注册了滚动 - this.hasBinded = false; +export class TreeRenderScrollService extends OB { + _init() { + this.nodeLists = {}; - this.container = this.options.container; - }, + this.id = this.options.id; + // renderService是否已经注册了滚动 + this.hasBinded = false; - _getNodeListBounds: function (tId) { - var nodeList = this.options.subNodeListGetter(tId)[0]; + this.container = this.options.container; + } + + _getNodeListBounds(tId) { + const nodeList = this.options.subNodeListGetter(tId)[0]; + + return { + top: nodeList.offsetTop, + left: nodeList.offsetLeft, + width: nodeList.offsetWidth, + height: nodeList.offsetHeight, + }; + } + + _getTreeContainerBounds() { + const nodeList = this.container[0]; + if (isNotNull(nodeList)) { return { - top: nodeList.offsetTop, - left: nodeList.offsetLeft, + top: nodeList.offsetTop + nodeList.scrollTop, + left: nodeList.offsetLeft + nodeList.scrollLeft, width: nodeList.offsetWidth, - height: nodeList.offsetHeight - } - }, - - _getTreeContainerBounds: function () { - var nodeList = this.container[0]; - if (BI.isNotNull(nodeList)) { - return { - top: nodeList.offsetTop + nodeList.scrollTop, - left: nodeList.offsetLeft + nodeList.scrollLeft, - width: nodeList.offsetWidth, - height: nodeList.offsetHeight - }; - } - return {}; - }, - - _canNodePopulate: function (tId) { - if (this.nodeLists[tId].locked) { - return false; - } - // 获取ul, 即子节点列表的bounds - // 是否需要继续加载,只需要看子节点列表的下边界与container是否无交集 - var bounds = this._getNodeListBounds(tId); - var containerBounds = this._getTreeContainerBounds(tId); - // ul底部是不是漏出来了 - if (bounds.top + bounds.height < containerBounds.top + containerBounds.height) { - return true; - } + height: nodeList.offsetHeight, + }; + } + + return {}; + } + + _canNodePopulate(tId) { + if (this.nodeLists[tId].locked) { return false; - }, - - _isNodeInVisible: function (tId) { - var nodeList = this.options.subNodeListGetter(tId); - return nodeList.length === 0 || nodeList.css("display") === "none"; - }, - - pushNodeList: function (tId, populate) { - var self = this; - if (!BI.has(this.nodeLists, tId)) { - this.nodeLists[tId] = { - populate: BI.debounce(populate, 0), - options: { - times: 1 - }, - // 在上一次请求返回前, 通过滚动再次触发加载的时候, 不应该认为是下一次分页, 需要等待上次请求返回 - // 以保证顺序和请求次数的完整 - locked: false - }; - } else { - this.nodeLists[tId].locked = false; - } - if(!this.hasBinded) { - // console.log("绑定事件"); - this.hasBinded = true; - this.container && this.container.on("scroll", BI.debounce(function () { - self.refreshAllNodes(); - }, 30)); - } - }, - - refreshAllNodes: function () { - var self = this; - BI.each(this.nodeLists, function (tId) { - // 不展开的节点就不看了 - !self._isNodeInVisible(tId) && self.refreshNodes(tId); - }); - }, - - refreshNodes: function (tId) { - if (this._canNodePopulate(tId)) { - var nodeList = this.nodeLists[tId]; - nodeList.options.times++; - nodeList.locked = true; - nodeList.populate({ - times: nodeList.options.times - }); - } - }, - - removeNodeList: function (tId) { - delete this.nodeLists[tId]; - if (BI.size(this.nodeLists) === 0) { - this.clear(); - } - }, - - clear: function () { - var self = this; - BI.each(this.nodeLists, function (tId) { - self.removeNodeList(tId); + } + // 获取ul, 即子节点列表的bounds + // 是否需要继续加载,只需要看子节点列表的下边界与container是否无交集 + const bounds = this._getNodeListBounds(tId); + const containerBounds = this._getTreeContainerBounds(tId); + + // ul底部是不是漏出来了 + return bounds.top + bounds.height < containerBounds.top + containerBounds.height; + } + + _isNodeInVisible(tId) { + const nodeList = this.options.subNodeListGetter(tId); + + return nodeList.length === 0 || nodeList.css("display") === "none"; + } + + pushNodeList(tId, populate) { + const self = this; + if (!has(this.nodeLists, tId)) { + this.nodeLists[tId] = { + populate: debounce(populate, 0), + options: { + times: 1, + }, + // 在上一次请求返回前, 通过滚动再次触发加载的时候, 不应该认为是下一次分页, 需要等待上次请求返回 + // 以保证顺序和请求次数的完整 + locked: false, + }; + } else { + this.nodeLists[tId].locked = false; + } + if (!this.hasBinded) { + // console.log("绑定事件"); + this.hasBinded = true; + this.container && this.container.on("scroll", debounce(() => { + self.refreshAllNodes(); + }, 30)); + } + } + + refreshAllNodes() { + const self = this; + each(this.nodeLists, tId => { + // 不展开的节点就不看了 + !self._isNodeInVisible(tId) && self.refreshNodes(tId); + }); + } + + refreshNodes(tId) { + if (this._canNodePopulate(tId)) { + const nodeList = this.nodeLists[tId]; + nodeList.options.times++; + nodeList.locked = true; + nodeList.populate({ + times: nodeList.options.times, }); - this.nodeLists = {}; - // console.log("解绑事件"); - this.container.off("scroll"); - this.hasBinded = false; } - }); -})(); \ No newline at end of file + } + + removeNodeList(tId) { + delete this.nodeLists[tId]; + if (size(this.nodeLists) === 0) { + this.clear(); + } + } + + clear() { + const self = this; + each(this.nodeLists, tId => { + self.removeNodeList(tId); + }); + this.nodeLists = {}; + // console.log("解绑事件"); + this.container.off("scroll"); + this.hasBinded = false; + } +} diff --git a/src/case/ztree/treetrender.page.service.js b/src/case/ztree/treetrender.page.service.js deleted file mode 100644 index e1d7edb81..000000000 --- a/src/case/ztree/treetrender.page.service.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * @author windy - * @version 2.0 - * Created by windy on 2020/1/8 - * 提供节点分页加载方式 - */ - -!(function () { - BI.TreeRenderPageService = BI.inherit(BI.OB, { - _init: function () { - this.nodeLists = {}; - }, - - _getLoadingBar: function(tId) { - var self = this; - var tip = BI.createWidget({ - type: "bi.loading_bar", - height: 25, - handler: function () { - self.refreshNodes(tId); - } - }); - tip.setLoaded(); - return tip; - }, - - pushNodeList: function (tId, populate) { - var self = this, o = this.options; - var tip = this._getLoadingBar(tId); - if (!BI.has(this.nodeLists, tId)) { - this.nodeLists[tId] = { - populate: BI.debounce(populate, 0), - options: { - times: 1 - }, - loadWidget: tip - }; - } else { - this.nodeLists[tId].loadWidget.destroy(); - this.nodeLists[tId].loadWidget = tip; - } - BI.createWidget({ - type: "bi.vertical", - element: o.subNodeListGetter(tId), - items: [tip] - }); - }, - - refreshNodes: function (tId) { - var nodeList = this.nodeLists[tId]; - nodeList.options.times++; - nodeList.loadWidget.setLoading(); - nodeList.populate({ - times: nodeList.options.times - }); - }, - - removeNodeList: function (tId) { - this.nodeLists[tId] && this.nodeLists[tId].loadWidget.destroy(); - this.nodeLists[tId] && (this.nodeLists[tId].loadWidget = null); - delete this.nodeLists[tId]; - if (BI.size(this.nodeLists) === 0) { - this.clear(); - } - }, - - clear: function () { - var self = this; - BI.each(this.nodeLists, function (tId) { - self.removeNodeList(tId); - }); - this.nodeLists = {}; - } - }); - -})(); \ No newline at end of file diff --git a/src/case/ztree/0.treeview.js b/src/case/ztree/treeview.js similarity index 58% rename from src/case/ztree/0.treeview.js rename to src/case/ztree/treeview.js index 41166220d..a58fd4709 100644 --- a/src/case/ztree/0.treeview.js +++ b/src/case/ztree/treeview.js @@ -1,119 +1,137 @@ -/** - * guy - * 异步树 - * @class BI.TreeView - * @extends BI.Pane - */ -BI.TreeView = BI.inherit(BI.Pane, { - _defaultConfig: function () { - return BI.extend(BI.TreeView.superclass._defaultConfig.apply(this, arguments), { +import { + cjkEncodeDO, + Controller, + createWidget, + emptyFn, + Events, + extend, + UUID, + isNotNull, + jsonEncode, + delay, each, replaceAll, + isUndefined, isNotEmptyArray, deepClone, map, Tree, + isNull, shortcut +} from "@/core"; +import { Msg, Pane } from "@/base"; + +@shortcut() +export class TreeView extends Pane { + static xtype = "bi.tree_view"; + static REQ_TYPE_INIT_DATA = 1; + static REQ_TYPE_ADJUST_DATA = 2; + static REQ_TYPE_SELECT_DATA = 3; + static REQ_TYPE_GET_SELECTED_DATA = 4; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_INIT = Events.INIT; + static EVENT_AFTERINIT = Events.AFTERINIT; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { _baseCls: "bi-tree", paras: { - selectedValues: {} + selectedValues: {}, }, - itemsCreator: BI.emptyFn, - showLine: true + itemsCreator: emptyFn, + showLine: true, }); - }, - _init: function () { - BI.TreeView.superclass._init.apply(this, arguments); - var o = this.options; + } + + _init() { + super._init(...arguments); + const o = this.options; this._stop = false; this._createTree(); - this.tip = BI.createWidget({ + this.tip = createWidget({ type: "bi.loading_bar", invisible: true, - handler: BI.bind(this._loadMore, this) + handler: () => this._loadMore(), }); - BI.createWidget({ + createWidget({ type: "bi.vertical", scrollable: true, scrolly: false, element: this, - items: [this.tip] + items: [this.tip], }); - if (BI.isNotNull(o.value)) { + if (isNotNull(o.value)) { this.setSelectedValue(o.value); } - if (BI.isIE9Below && BI.isIE9Below()) { - this.element.addClass("hack"); - } - }, + } - _createTree: function () { - this.id = "bi-tree" + BI.UUID(); + _createTree() { + this.id = `bi-tree${UUID()}`; if (this.nodes) { this.nodes.destroy(); } if (this.tree) { this.tree.destroy(); } - this.tree = BI.createWidget({ + this.tree = createWidget({ type: "bi.layout", - element: "" + element: ``, }); - BI.createWidget({ + createWidget({ type: "bi.default", element: this, - items: [this.tree] + items: [this.tree], }); - }, + } // 选择节点触发方法 - _selectTreeNode: function (treeId, treeNode) { - this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.CLICK, treeNode, this); - this.fireEvent(BI.TreeView.EVENT_CHANGE, treeNode, this); - }, + _selectTreeNode(treeId, treeNode) { + this.fireEvent(Controller.EVENT_CHANGE, Events.CLICK, treeNode, this); + this.fireEvent(TreeView.EVENT_CHANGE, treeNode, this); + } // 配置属性 - _configSetting: function () { - var paras = this.options.paras; - var self = this; - var o = this.options; - var setting = { + _configSetting() { + const paras = this.options.paras; + const self = this; + const o = this.options; + const setting = { async: { enable: true, url: getUrl, - autoParam: ["id", "name"], // 节点展开异步请求自动提交id和name - otherParam: BI.cjkEncodeDO(paras) // 静态参数 + autoParam: ["id", "name"], // 节点展开异步请求自动提交id和name + otherParam: cjkEncodeDO(paras), // 静态参数 }, check: { - enable: true + enable: true, }, data: { key: { title: "title", - name: "text" // 节点的name属性替换成text + name: "text", // 节点的name属性替换成text }, simpleData: { - enable: true // 可以穿id,pid属性的对象数组 - } + enable: true, // 可以穿id,pid属性的对象数组 + }, }, view: { showIcon: false, expandSpeed: "", - nameIsHTML: true, // 节点可以用html标签代替 + nameIsHTML: true, // 节点可以用html标签代替 dblClickExpand: false, showLine: o.showLine, }, callback: { - beforeExpand: beforeExpand, - onAsyncSuccess: onAsyncSuccess, - onAsyncError: onAsyncError, - beforeCheck: beforeCheck, - onCheck: onCheck, - onExpand: onExpand, - onCollapse: onCollapse, - onClick: onClick - } + beforeExpand, + onAsyncSuccess, + onAsyncError, + beforeCheck, + onCheck, + onExpand, + onCollapse, + onClick, + }, }; - var className = "dark", perTime = 100; + const className = "dark", perTime = 100; function onClick(event, treeId, treeNode) { // 当前点击节点的状态是半选,且为true_part, 则将其改为false_part,使得点击半选后切换到的是全选 - var checked = treeNode.checked; - var status = treeNode.getCheckStatus(); + let checked = treeNode.checked; + const status = treeNode.getCheckStatus(); if (status.half === true && status.checked === true) { checked = false; } @@ -122,14 +140,14 @@ BI.TreeView = BI.inherit(BI.Pane, { } function getUrl(treeId, treeNode) { - var parentNode = self._getParentValues(treeNode); + const parentNode = self._getParentValues(treeNode); treeNode.times = treeNode.times || 1; - var param = "id=" + treeNode.id - + "×=" + (treeNode.times++) - + "&parentValues= " + _global.encodeURIComponent(BI.jsonEncode(parentNode)) - + "&checkState=" + _global.encodeURIComponent(BI.jsonEncode(treeNode.getCheckStatus())); + const param = `id=${treeNode.id + }×=${treeNode.times++ + }&parentValues= ${_global.encodeURIComponent(jsonEncode(parentNode)) + }&checkState=${_global.encodeURIComponent(jsonEncode(treeNode.getCheckStatus()))}`; - return "&" + param; + return `&${param}`; } function beforeExpand(treeId, treeNode) { @@ -138,13 +156,14 @@ BI.TreeView = BI.inherit(BI.Pane, { treeNode.times = 1; ajaxGetNodes(treeNode, "refresh"); } + return true; } - BI.Msg.toast("Please Wait。", { - level: "warning" + Msg.toast("Please Wait。", { + level: "warning", }); // 不展开节点,也不触发onExpand事件 - return false; + return false; } function onAsyncSuccess(event, treeId, treeNode, msg) { @@ -152,14 +171,14 @@ BI.TreeView = BI.inherit(BI.Pane, { if (!msg || msg.length === 0 || /^[\s,\S]*<\/html>$/gi.test(msg) || self._stop) { return; } - var zTree = self.nodes; - var totalCount = treeNode.count || 0; + const zTree = self.nodes; + const totalCount = treeNode.count || 0; // 尝试去获取下一组节点,若获取值为空数组,表示获取完成 // TODO by GUY if (treeNode.children.length > totalCount) { treeNode.count = treeNode.children.length; - BI.delay(function () { + delay(() => { ajaxGetNodes(treeNode); }, perTime); } else { @@ -171,15 +190,15 @@ BI.TreeView = BI.inherit(BI.Pane, { } function onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) { - var zTree = self.nodes; - BI.Msg.toast("Error!", "warning"); + const zTree = self.nodes; + Msg.toast("Error!", "warning"); // treeNode.icon = ""; // zTree.updateNode(treeNode); } function ajaxGetNodes(treeNode, reloadType) { - var zTree = self.nodes; - if (reloadType == "refresh") { + const zTree = self.nodes; + if (reloadType === "refresh") { zTree.updateNode(treeNode); // 刷新一下当前节点,如果treeNode.xxx被改了的话 } zTree.reAsyncChildNodes(treeNode, reloadType, true); // 强制加载子节点,reloadType === refresh为先清空再加载,否则为追加到现有子节点之后 @@ -190,13 +209,13 @@ BI.TreeView = BI.inherit(BI.Pane, { return false; } // 下面主动修改了node的halfCheck属性, 节点属性的判断依赖halfCheck,改之前就获取一下 - var status = treeNode.getCheckStatus(); + const status = treeNode.getCheckStatus(); treeNode.halfCheck = false; if (treeNode.checked === true) { // 将展开的节点halfCheck设为false,解决展开节点存在halfCheck=true的情况 guy // 所有的半选状态都需要取消halfCheck=true的情况 function track(children) { - BI.each(children, function (i, ch) { + each(children, (i, ch) => { if (ch.halfCheck === true) { ch.halfCheck = false; track(ch.children); @@ -205,9 +224,9 @@ BI.TreeView = BI.inherit(BI.Pane, { } track(treeNode.children); - var treeObj = self.nodes; - var nodes = treeObj.getSelectedNodes(); - BI.$.each(nodes, function (index, node) { + const treeObj = self.nodes; + const nodes = treeObj.getSelectedNodes(); + BI.$.each(nodes, (index, node) => { node.halfCheck = false; }); } @@ -232,102 +251,106 @@ BI.TreeView = BI.inherit(BI.Pane, { } return setting; - }, + } - _getParentValues: function (treeNode) { + _getParentValues(treeNode) { if (!treeNode.getParentNode()) { return []; } - var parentNode = treeNode.getParentNode(); - var result = this._getParentValues(parentNode); + const parentNode = treeNode.getParentNode(); + let result = this._getParentValues(parentNode); result = result.concat([this._getNodeValue(parentNode)]); + return result; - }, + } - _getNodeValue: function (node) { + _getNodeValue(node) { // 去除标红 - return BI.isUndefined(node.value) ? BI.replaceAll(node.text.replace(/<[^>]+>/g, ""), " ", " ") : node.value; - }, + return isUndefined(node.value) ? replaceAll(node.text.replace(/<[^>]+>/g, ""), " ", " ") : node.value; + } // 获取半选框值 - _getHalfSelectedValues: function (map, node) { - var self = this; - var checkState = node.getCheckStatus(); + _getHalfSelectedValues(map, node) { + const self = this; + const checkState = node.getCheckStatus(); // 将未选的去掉 if (checkState.checked === false && checkState.half === false) { return; } // 如果节点已展开,并且是半选 - if (BI.isNotEmptyArray(node.children) && checkState.half === true) { - var children = node.children; - BI.each(children, function (i, ch) { + if (isNotEmptyArray(node.children) && checkState.half === true) { + const children = node.children; + each(children, (i, ch) => { self._getHalfSelectedValues(map, ch); }); + return; } - var parent = node.parentValues || self._getParentValues(node); - var path = parent.concat(this._getNodeValue(node)); + const parent = node.parentValues || self._getParentValues(node); + const path = parent.concat(this._getNodeValue(node)); // 当前节点是全选的,因为上面的判断已经排除了不选和半选 - if (BI.isNotEmptyArray(node.children) || checkState.half === false) { + if (isNotEmptyArray(node.children) || checkState.half === false) { this._buildTree(map, path); + return; } // 剩下的就是半选不展开的节点,因为不知道里面是什么情况,所以借助selectedValues(这个是完整的选中情况) - var storeValues = BI.deepClone(this.options.paras.selectedValues); - var treeNode = this._getTree(storeValues, path); + const storeValues = deepClone(this.options.paras.selectedValues); + const treeNode = this._getTree(storeValues, path); this._addTreeNode(map, parent, this._getNodeValue(node), treeNode); - }, + } // 获取的是以values最后一个节点为根的子树 - _getTree: function (map, values) { - var cur = map; - BI.any(values, function (i, value) { + _getTree(map, values) { + let cur = map; + some(values, (i, value) => { if (cur[value] == null) { return true; } cur = cur[value]; }); + return cur; - }, + } // 以values为path一路向里补充map, 并在末尾节点添加key: value节点 - _addTreeNode: function (map, values, key, value) { - var cur = map; - BI.each(values, function (i, value) { + _addTreeNode(map, values, key, value) { + let cur = map; + each(values, (i, value) => { if (cur[value] == null) { cur[value] = {}; } cur = cur[value]; }); cur[key] = value; - }, + } // 构造树节点 - _buildTree: function (map, values) { - var cur = map; - BI.each(values, function (i, value) { + _buildTree(map, values) { + let cur = map; + each(values, (i, value) => { if (cur[value] == null) { cur[value] = {}; } cur = cur[value]; }); - }, + } // 获取选中的值 - _getSelectedValues: function () { - var self = this; - var hashMap = {}; - var rootNoots = this.nodes.getNodes(); + _getSelectedValues() { + const self = this; + const hashMap = {}; + const rootNoots = this.nodes.getNodes(); track(rootNoots); // 可以看到这个方法没有递归调用,所以在_getHalfSelectedValues中需要关心全选的节点 function track(nodes) { - BI.each(nodes, function (i, node) { - var checkState = node.getCheckStatus(); + each(nodes, (i, node) => { + const checkState = node.getCheckStatus(); if (checkState.checked === true || checkState.half === true) { if (checkState.half === true) { self._getHalfSelectedValues(hashMap, node); } else { - var parentValues = node.parentValues || self._getParentValues(node); - var values = parentValues.concat([self._getNodeValue(node)]); + const parentValues = node.parentValues || self._getParentValues(node); + const values = parentValues.concat([self._getNodeValue(node)]); self._buildTree(hashMap, values); } } @@ -335,27 +358,28 @@ BI.TreeView = BI.inherit(BI.Pane, { } return hashMap; - }, + } // 处理节点 - _dealWidthNodes: function (nodes) { - var self = this, o = this.options; - var ns = BI.Tree.arrayFormat(nodes); - return BI.map(ns, function (i, n) { - var newNode = BI.extend({}, n); + _dealWidthNodes(nodes) { + const self = this, o = this.options; + const ns = Tree.arrayFormat(nodes); + + return map(ns, (i, n) => { + const newNode = extend({}, n); newNode.isParent = newNode.isParent || newNode.parent; // n.value = BI.isUndefined(n.value) ? n.text : n.value; // n.text = BI.isUndefined(n.text) ? n.value : n.text; // if (n.text === null) { // n.text = ""; // } - if (BI.isNull(newNode.title)) { + if (isNull(newNode.title)) { newNode.title = newNode.text; } if (newNode.disabled) { newNode.title = newNode.warningTitle || newNode.title; } - var text = BI.createWidget(BI.extend({ + const text = createWidget(extend({ cls: "tree-node-text", tagName: "span", whiteSpace: "nowrap", @@ -363,9 +387,9 @@ BI.TreeView = BI.inherit(BI.Pane, { keyword: o.paras.keyword, }, newNode, { type: "bi.text", - text: BI.replaceAll(newNode.text, "\n", " ") + text: replaceAll(newNode.text, "\n", " "), })); - var fragment = BI.Widget._renderEngine.createElement("
"); + const fragment = BI.Widget._renderEngine.createElement("
"); fragment.append(text.element[0]); newNode.text = fragment.html(); // // 处理标红 @@ -376,21 +400,22 @@ BI.TreeView = BI.inherit(BI.Pane, { // n.text = BI.htmlEncode(BI.Text.formatText(n.text + "")); // } // } + return newNode; }); - }, + } - _loadMore: function () { - var self = this, o = this.options; + _loadMore() { + const self = this, o = this.options; this.tip.setLoading(); - var op = BI.extend({}, o.paras, { - times: ++this.times + const op = extend({}, o.paras, { + times: ++this.times, }); - o.itemsCreator(op, function (res) { + o.itemsCreator(op, res => { if (self._stop === true) { return; } - var hasNext = !!res.hasNext, nodes = res.items || []; + const hasNext = !!res.hasNext, nodes = res.items || []; if (!hasNext) { self.tip.setEnd(); @@ -401,32 +426,34 @@ BI.TreeView = BI.inherit(BI.Pane, { self.nodes.addNodes(null, self._dealWidthNodes(nodes)); } }); - }, + } // 生成树内部方法 - _initTree: function (setting) { - var self = this, o = this.options; - self.fireEvent(BI.Events.INIT); + _initTree(setting) { + const self = this, o = this.options; + self.fireEvent(Events.INIT); this.times = 1; - var tree = this.tree; + const tree = this.tree; tree.empty(); this.loading(); this.tip.setVisible(false); - var callback = function (nodes) { + + function callback(nodes) { if (self._stop === true) { return; } self.nodes = BI.$.fn.zTree.init(tree.element, setting, nodes); - }; - var op = BI.extend({}, o.paras, { - times: 1 + } + + const op = extend({}, o.paras, { + times: 1, }); - o.itemsCreator(op, function (res) { + o.itemsCreator(op, res => { if (self._stop === true) { return; } - var hasNext = !!res.hasNext, nodes = res.items || []; + const hasNext = !!res.hasNext, nodes = res.items || []; if (nodes.length > 0) { callback(self._dealWidthNodes(nodes)); } @@ -437,68 +464,69 @@ BI.TreeView = BI.inherit(BI.Pane, { } else { self.tip.setLoaded(); } - op.times === 1 && self.fireEvent(BI.Events.AFTERINIT); + op.times === 1 && self.fireEvent(Events.AFTERINIT); }); - }, + } // 构造树结构, - initTree: function (nodes, setting) { - var setting = setting || { + initTree(nodes, setting) { + const defaultSetting = { async: { - enable: false + enable: false, }, check: { - enable: false + enable: false, }, data: { key: { title: "title", - name: "text" + name: "text", }, simpleData: { - enable: true - } + enable: true, + }, }, view: { showIcon: false, expandSpeed: "", - nameIsHTML: true + nameIsHTML: true, }, - callback: {} + callback: {}, }; - this.nodes = BI.$.fn.zTree.init(this.tree.element, setting, nodes); - }, + this.nodes = BI.$.fn.zTree.init(this.tree.element, setting || defaultSetting, nodes); + } - start: function () { + start() { this._stop = false; - }, + } - stop: function () { + stop() { this._stop = true; - }, + } // 生成树方法 - stroke: function (config) { + stroke(config) { delete this.options.keyword; - BI.extend(this.options.paras, config); - var setting = this._configSetting(); + extend(this.options.paras, config); + const setting = this._configSetting(); this._createTree(); this.start(); this._initTree(setting); - }, + } + + populate() { + this.stroke(...arguments); + } - populate: function () { - this.stroke.apply(this, arguments); - }, + hasChecked() { + const treeObj = this.nodes; - hasChecked: function () { - var treeObj = this.nodes; return treeObj.getCheckedNodes(true).length > 0; - }, + } - checkAll: function (checked) { + checkAll(checked) { function setNode(children) { - BI.each(children, function (i, child) { + each(children, (i, child) => { child.halfCheck = false; setNode(child.children); }); @@ -508,68 +536,58 @@ BI.TreeView = BI.inherit(BI.Pane, { return; } - BI.each(this.nodes.getNodes(), function (i, node) { + each(this.nodes.getNodes(), (i, node) => { node.halfCheck = false; setNode(node.children); }); this.nodes.checkAllNodes(checked); - }, + } - expandAll: function (flag) { + expandAll(flag) { this.nodes && this.nodes.expandAll(flag); - }, + } // 设置树节点的状态 - setValue: function (value, param) { + setValue(value, param) { this.checkAll(false); this.updateValue(value, param); this.refresh(); - }, + } - setSelectedValue: function (value) { - this.options.paras.selectedValues = BI.deepClone(value || {}); - }, + setSelectedValue(value) { + this.options.paras.selectedValues = deepClone(value || {}); + } - updateValue: function (values, param) { + updateValue(values, param) { if (!this.nodes) { return; } param || (param = "value"); - var treeObj = this.nodes; - BI.each(values, function (v, op) { - var nodes = treeObj.getNodesByParam(param, v, null); - BI.each(nodes, function (j, node) { - BI.extend(node, { checked: true }, op); + const treeObj = this.nodes; + each(values, (v, op) => { + const nodes = treeObj.getNodesByParam(param, v, null); + each(nodes, (j, node) => { + extend(node, { checked: true }, op); treeObj.updateNode(node); }); }); - }, + } - refresh: function () { + refresh() { this.nodes && this.nodes.refresh(); - }, + } - getValue: function () { + getValue() { if (!this.nodes) { return null; } + return this._getSelectedValues(); - }, + } - destroyed: function () { + destroyed() { this.stop(); this.nodes && this.nodes.destroy(); } -}); -BI.extend(BI.TreeView, { - REQ_TYPE_INIT_DATA: 1, - REQ_TYPE_ADJUST_DATA: 2, - REQ_TYPE_SELECT_DATA: 3, - REQ_TYPE_GET_SELECTED_DATA: 4 -}); - -BI.TreeView.EVENT_CHANGE = "EVENT_CHANGE"; -BI.TreeView.EVENT_INIT = BI.Events.INIT; -BI.TreeView.EVENT_AFTERINIT = BI.Events.AFTERINIT; - -BI.shortcut("bi.tree_view", BI.TreeView); +} + diff --git a/src/core/platform/web/jquery/jquery.mousewheel.js b/src/core/platform/web/jquery/jquery.mousewheel.js index 557fe35e4..576658a56 100644 --- a/src/core/platform/web/jquery/jquery.mousewheel.js +++ b/src/core/platform/web/jquery/jquery.mousewheel.js @@ -1,3 +1,4 @@ +/* eslint-disable */ /* ! * jQuery Mousewheel 3.1.13 * @@ -21,15 +22,15 @@ // } }(function ($) { - var toFix = ["wheel", "mousewheel", "DOMMouseScroll", "MozMousePixelScroll"], - toBind = ( "onwheel" in document || document.documentMode >= 9 ) ? + var toFix = ["wheel", "mousewheel", "DOMMouseScroll", "MozMousePixelScroll"], + toBind = ("onwheel" in document || document.documentMode >= 9) ? ["wheel"] : ["mousewheel", "DomMouseScroll", "MozMousePixelScroll"], - slice = Array.prototype.slice, + slice = Array.prototype.slice, nullLowestDeltaTimeout, lowestDelta; - if ( $.event.fixHooks ) { - for ( var i = toFix.length; i; ) { - $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks; + if ($.event.fixHooks) { + for (var i = toFix.length; i;) { + $.event.fixHooks[toFix[--i]] = $.event.mouseHooks; } } @@ -37,9 +38,9 @@ version: "3.1.12", setup: function () { - if ( this.addEventListener ) { - for ( var i = toBind.length; i; ) { - this.addEventListener( toBind[--i], handler, false ); + if (this.addEventListener) { + for (var i = toBind.length; i;) { + this.addEventListener(toBind[--i], handler, false); } } else { this.onmousewheel = handler; @@ -47,9 +48,9 @@ }, teardown: function () { - if ( this.removeEventListener ) { - for ( var i = toBind.length; i; ) { - this.removeEventListener( toBind[--i], handler, false ); + if (this.removeEventListener) { + for (var i = toBind.length; i;) { + this.removeEventListener(toBind[--i], handler, false); } } else { this.onmousewheel = null; @@ -73,26 +74,34 @@ }); - function handler (event) { - var orgEvent = event || _global.event, - args = slice.call(arguments, 1), - delta = 0, - deltaX = 0, - deltaY = 0, - absDelta = 0, - offsetX = 0, - offsetY = 0; + function handler(event) { + var orgEvent = event || _global.event, + args = slice.call(arguments, 1), + delta = 0, + deltaX = 0, + deltaY = 0, + absDelta = 0, + offsetX = 0, + offsetY = 0; event = $.event.fix(orgEvent); event.type = "mousewheel"; // Old school scrollwheel delta - if ( "detail" in orgEvent ) { deltaY = orgEvent.detail * -1; } - if ( "wheelDelta" in orgEvent ) { deltaY = orgEvent.wheelDelta; } - if ( "wheelDeltaY" in orgEvent ) { deltaY = orgEvent.wheelDeltaY; } - if ( "wheelDeltaX" in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; } + if ("detail" in orgEvent) { + deltaY = orgEvent.detail * -1; + } + if ("wheelDelta" in orgEvent) { + deltaY = orgEvent.wheelDelta; + } + if ("wheelDeltaY" in orgEvent) { + deltaY = orgEvent.wheelDeltaY; + } + if ("wheelDeltaX" in orgEvent) { + deltaX = orgEvent.wheelDeltaX * -1; + } // Firefox < 17 horizontal scrolling related to DOMMouseScroll event - if ( "axis" in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { + if ("axis" in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS) { deltaX = deltaY * -1; deltaY = 0; } @@ -101,62 +110,66 @@ delta = deltaY === 0 ? deltaX : deltaY; // New school wheel delta (wheel event) - if ( "deltaY" in orgEvent ) { + if ("deltaY" in orgEvent) { deltaY = orgEvent.deltaY * -1; - delta = deltaY; + delta = deltaY; } - if ( "deltaX" in orgEvent ) { + if ("deltaX" in orgEvent) { deltaX = orgEvent.deltaX; - if ( deltaY === 0 ) { delta = deltaX * -1; } + if (deltaY === 0) { + delta = deltaX * -1; + } } // No change actually happened, no reason to go any further - if ( deltaY === 0 && deltaX === 0 ) { return; } + if (deltaY === 0 && deltaX === 0) { + return; + } // Need to convert lines and pages to pixels if we aren't already in pixels // There are three delta modes: // * deltaMode 0 is by pixels, nothing to do // * deltaMode 1 is by lines // * deltaMode 2 is by pages - if ( orgEvent.deltaMode === 1 ) { + if (orgEvent.deltaMode === 1) { var lineHeight = 40; - delta *= lineHeight; + delta *= lineHeight; deltaY *= lineHeight; deltaX *= lineHeight; - } else if ( orgEvent.deltaMode === 2 ) { + } else if (orgEvent.deltaMode === 2) { var pageHeight = 800; - delta *= pageHeight; + delta *= pageHeight; deltaY *= pageHeight; deltaX *= pageHeight; } // Store lowest absolute delta to normalize the delta values - absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) ); + absDelta = Math.max(Math.abs(deltaY), Math.abs(deltaX)); - if ( !lowestDelta || absDelta < lowestDelta ) { + if (!lowestDelta || absDelta < lowestDelta) { lowestDelta = absDelta; // Adjust older deltas if necessary - if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) { + if (shouldAdjustOldDeltas(orgEvent, absDelta)) { lowestDelta /= 40; } } // Adjust older deltas if necessary - if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) { + if (shouldAdjustOldDeltas(orgEvent, absDelta)) { // Divide all the things by 40! - delta /= 40; + delta /= 40; deltaX /= 40; deltaY /= 40; } // Get a whole, normalized value for the deltas - delta = Math[ delta >= 1 ? "floor" : "ceil" ](delta / lowestDelta); - deltaX = Math[ deltaX >= 1 ? "floor" : "ceil" ](deltaX / lowestDelta); - deltaY = Math[ deltaY >= 1 ? "floor" : "ceil" ](deltaY / lowestDelta); + delta = Math[delta >= 1 ? "floor" : "ceil"](delta / lowestDelta); + deltaX = Math[deltaX >= 1 ? "floor" : "ceil"](deltaX / lowestDelta); + deltaY = Math[deltaY >= 1 ? "floor" : "ceil"](deltaY / lowestDelta); // Normalise offsetX and offsetY properties - if ( special.settings.normalizeOffset && this.getBoundingClientRect ) { + if (special.settings.normalizeOffset && this.getBoundingClientRect) { var boundingRect = this.getBoundingClientRect(); offsetX = event.clientX - boundingRect.left; offsetY = event.clientY - boundingRect.top; @@ -180,17 +193,19 @@ // handle multiple device types that give different // a different lowestDelta // Ex: trackpad = 3 and mouse wheel = 120 - if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); } + if (nullLowestDeltaTimeout) { + clearTimeout(nullLowestDeltaTimeout); + } nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200); return ($.event.dispatch || $.event.handle).apply(this, args); } - function nullLowestDelta () { + function nullLowestDelta() { lowestDelta = null; } - function shouldAdjustOldDeltas (orgEvent, absDelta) { + function shouldAdjustOldDeltas(orgEvent, absDelta) { // If this is an older event and the delta is divisable by 120, // then we are assuming that the browser is treating this as an // older mouse wheel event and that we should divide the deltas @@ -201,4 +216,4 @@ return special.settings.adjustOldDeltas && orgEvent.type === "mousewheel" && absDelta % 120 === 0; } -})); \ No newline at end of file +})); From aa6fcad0bf9508b9ccb51e7e5e6fc16c98a642ed Mon Sep 17 00:00:00 2001 From: zsmj Date: Wed, 11 Jan 2023 15:40:42 +0800 Subject: [PATCH 071/300] =?UTF-8?q?KERNEL-14066=20feat:=20case/tree?= =?UTF-8?q?=E5=92=8Ccase/ztree?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/platform/web/index.js | 1 - src/core/utils/color.js | 406 ++++++++++++------------ src/core/{platform/web => utils}/dom.js | 368 ++++++++++----------- src/core/utils/index.js | 10 +- 4 files changed, 397 insertions(+), 388 deletions(-) rename src/core/{platform/web => utils}/dom.js (73%) diff --git a/src/core/platform/web/index.js b/src/core/platform/web/index.js index db216134b..054b6dede 100644 --- a/src/core/platform/web/index.js +++ b/src/core/platform/web/index.js @@ -1,4 +1,3 @@ -export * as DOM from "./dom"; export * from "./detectElementResize"; export * from "./function"; export * from "./load"; diff --git a/src/core/utils/color.js b/src/core/utils/color.js index a219a4f7d..718a9e74b 100644 --- a/src/core/utils/color.js +++ b/src/core/utils/color.js @@ -1,204 +1,206 @@ import { parseInt, parseFloat, isNull, isKey } from "../2.base"; -import * as DOMUtils from "../platform/web/dom"; - -export const DOM = { - isColor(color) { - return color && (this.isRGBColor(color) || this.isHexColor(color)); - }, - - isRGBColor(color) { - if (!color) { - return false; - } - - return color.substr(0, 3) === "rgb"; - }, - - isHexColor(color) { - if (!color) { - return false; - } - - return color[0] === "#" && color.length === 7; - }, - - isDarkColor(hex) { - if (!hex || !this.isHexColor(hex)) { - return false; - } - const rgb = this.rgb2json(this.hex2rgb(hex)); - const grayLevel = Math.round(rgb.r * 0.299 + rgb.g * 0.587 + rgb.b * 0.114); - if (grayLevel < 192/** 网上给的是140**/) { - return true; - } - + +export function isColor(color) { + return color && (isRGBColor(color) || isHexColor(color)); +} + +export function isRGBColor(color) { + if (!color) { + return false; + } + + return color.substr(0, 3) === "rgb"; +} + +export function isHexColor(color) { + if (!color) { return false; - }, - - // 获取对比颜色 - getContrastColor(color) { - if (!color || !this.isColor(color)) { - return ""; - } - if (this.isDarkColor(color)) { - return "#FFFFFF"; - } - - return "#3D4D66"; - }, - - rgb2hex(rgbColour) { - if (!rgbColour || rgbColour.substr(0, 3) !== "rgb") { - return ""; - } - const rgbValues = rgbColour.match(/\d+(\.\d+)?/g); - const red = parseInt(rgbValues[0]); - const green = parseInt(rgbValues[1]); - const blue = parseInt(rgbValues[2]); - - const hexColour = `#${this.int2hex(red)}${this.int2hex(green)}${this.int2hex(blue)}`; - - return hexColour; - }, - - _hue2rgb(m1, m2, h) { - h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h); - if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; - if (h * 2 < 1) return m2; - if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6; - - return m1; - }, - - hsl2rgb(hsl) { - const h = hsl[0], s = hsl[1], l = hsl[2]; - const m2 = (l <= 0.5) ? l * (s + 1) : l + s - l * s; - const m1 = l * 2 - m2; - - return [this._hue2rgb(m1, m2, h + 0.33333), - this._hue2rgb(m1, m2, h), - this._hue2rgb(m1, m2, h - 0.33333)]; - }, - - rgb2hsl(rgb) { - let h, s; - const r = rgb[0], g = rgb[1], b = rgb[2]; - const min = Math.min(r, Math.min(g, b)); - const max = Math.max(r, Math.max(g, b)); - const delta = max - min; - const l = (min + max) / 2; - s = 0; - if (l > 0 && l < 1) { - s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l)); - } - h = 0; - if (delta > 0) { - if (max === r && max !== g) h += (g - b) / delta; - if (max === g && max !== b) h += (2 + (b - r) / delta); - if (max === b && max !== r) h += (4 + (r - g) / delta); - h /= 6; - } - - return [h, s, l]; - }, - - rgb2json(rgbColour) { - if (!rgbColour) { - return {}; - } - if (!this.isRGBColor(rgbColour)) { - return {}; - } - const rgbValues = rgbColour.match(/\d+(\.\d+)?/g); - - return { - r: parseInt(rgbValues[0]), - g: parseInt(rgbValues[1]), - b: parseInt(rgbValues[2]), - }; - }, - - rgba2json(rgbColour) { - if (!rgbColour) { - return {}; - } - const rgbValues = rgbColour.match(/\d+(\.\d+)?/g); - - return { - r: parseInt(rgbValues[0]), - g: parseInt(rgbValues[1]), - b: parseInt(rgbValues[2]), - a: parseFloat(rgbValues[3]), - }; - }, - - json2rgb(rgb) { - if (!isKey(rgb.r) || !isKey(rgb.g) || !isKey(rgb.b)) { - return ""; - } - - return `rgb(${rgb.r},${rgb.g},${rgb.b})`; - }, - - json2rgba(rgba) { - if (!isKey(rgba.r) || !isKey(rgba.g) || !isKey(rgba.b)) { - return ""; - } - - return `rgba(${rgba.r},${rgba.g},${rgba.b},${rgba.a})`; - }, - - int2hex(strNum) { - const hexdig = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; - - return `${hexdig[strNum >>> 4]}${hexdig[strNum & 15]}`; - }, - - hex2rgb(color) { - if (!color) { - return ""; - } - if (!this.isHexColor(color)) { - return color; - } - let tempValue = "rgb(", colorArray; - - if (color.length === 7) { - colorArray = [parseInt(`0x${color.substring(1, 3)}`), - parseInt(`0x${color.substring(3, 5)}`), - parseInt(`0x${color.substring(5, 7)}`)]; - } else if (color.length === 4) { - colorArray = [parseInt(`0x${color.substring(1, 2)}`), - parseInt(`0x${color.substring(2, 3)}`), - parseInt(`0x${color.substring(3, 4)}`)]; - } - tempValue += `${colorArray[0]},`; - tempValue += `${colorArray[1]},`; - tempValue += `${colorArray[2]})`; - - return tempValue; - }, - - rgba2rgb(rgbColor, bgColor) { - if (isNull(bgColor)) { - bgColor = 1; - } - if (rgbColor.substr(0, 4) !== "rgba") { - return ""; - } - const rgbValues = rgbColor.match(/\d+(\.\d+)?/g); - if (rgbValues.length < 4) { - return ""; - } - const R = parseFloat(rgbValues[0]); - const G = parseFloat(rgbValues[1]); - const B = parseFloat(rgbValues[2]); - const A = parseFloat(rgbValues[3]); - - return `rgb(${Math.floor(255 * (bgColor * (1 - A)) + R * A)},${ - Math.floor(255 * (bgColor * (1 - A)) + G * A)},${ - Math.floor(255 * (bgColor * (1 - A)) + B * A)})`; - }, - - ...DOMUtils, -}; + } + + return color[0] === "#" && color.length === 7; +} + +export function isDarkColor(hex) { + if (!hex || !isHexColor(hex)) { + return false; + } + const rgb = rgb2json(hex2rgb(hex)); + const grayLevel = Math.round(rgb.r * 0.299 + rgb.g * 0.587 + rgb.b * 0.114); + if (grayLevel < 192/** 网上给的是140**/) { + return true; + } + + return false; +} + +// 获取对比颜色 +export function getContrastColor(color) { + if (!color || !isColor(color)) { + return ""; + } + if (isDarkColor(color)) { + return "#FFFFFF"; + } + + return "#3D4D66"; +} + +export function rgb2hex(rgbColour) { + if (!rgbColour || rgbColour.substr(0, 3) !== "rgb") { + return ""; + } + const rgbValues = rgbColour.match(/\d+(\.\d+)?/g); + const red = parseInt(rgbValues[0]); + const green = parseInt(rgbValues[1]); + const blue = parseInt(rgbValues[2]); + + const hexColour = `#${int2hex(red)}${int2hex(green)}${int2hex(blue)}`; + + return hexColour; +} + +function _hue2rgb(m1, m2, h) { + h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h); + if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; + if (h * 2 < 1) return m2; + if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6; + + return m1; +} + +export function hsl2rgb(hsl) { + const h = hsl[0], s = hsl[1], l = hsl[2]; + const m2 = (l <= 0.5) ? l * (s + 1) : l + s - l * s; + const m1 = l * 2 - m2; + + return [ + _hue2rgb(m1, m2, h + 0.33333), + _hue2rgb(m1, m2, h), + _hue2rgb(m1, m2, h - 0.33333) + ]; +} + +export function rgb2hsl(rgb) { + let h, s; + const r = rgb[0], g = rgb[1], b = rgb[2]; + const min = Math.min(r, Math.min(g, b)); + const max = Math.max(r, Math.max(g, b)); + const delta = max - min; + const l = (min + max) / 2; + s = 0; + if (l > 0 && l < 1) { + s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l)); + } + h = 0; + if (delta > 0) { + if (max === r && max !== g) h += (g - b) / delta; + if (max === g && max !== b) h += (2 + (b - r) / delta); + if (max === b && max !== r) h += (4 + (r - g) / delta); + h /= 6; + } + + return [h, s, l]; +} + +export function rgb2json(rgbColour) { + if (!rgbColour) { + return {}; + } + if (!isRGBColor(rgbColour)) { + return {}; + } + const rgbValues = rgbColour.match(/\d+(\.\d+)?/g); + + return { + r: parseInt(rgbValues[0]), + g: parseInt(rgbValues[1]), + b: parseInt(rgbValues[2]), + }; +} + +export function rgba2json(rgbColour) { + if (!rgbColour) { + return {}; + } + const rgbValues = rgbColour.match(/\d+(\.\d+)?/g); + + return { + r: parseInt(rgbValues[0]), + g: parseInt(rgbValues[1]), + b: parseInt(rgbValues[2]), + a: parseFloat(rgbValues[3]), + }; +} + +export function json2rgb(rgb) { + if (!isKey(rgb.r) || !isKey(rgb.g) || !isKey(rgb.b)) { + return ""; + } + + return `rgb(${rgb.r},${rgb.g},${rgb.b})`; +} + +export function json2rgba(rgba) { + if (!isKey(rgba.r) || !isKey(rgba.g) || !isKey(rgba.b)) { + return ""; + } + + return `rgba(${rgba.r},${rgba.g},${rgba.b},${rgba.a})`; +} + +export function int2hex(strNum) { + const hexdig = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; + + return `${hexdig[strNum >>> 4]}${hexdig[strNum & 15]}`; +} + +export function hex2rgb(color) { + if (!color) { + return ""; + } + if (!isHexColor(color)) { + return color; + } + let tempValue = "rgb(", colorArray; + + if (color.length === 7) { + colorArray = [ + parseInt(`0x${color.substring(1, 3)}`), + parseInt(`0x${color.substring(3, 5)}`), + parseInt(`0x${color.substring(5, 7)}`) + ]; + } else if (color.length === 4) { + colorArray = [ + parseInt(`0x${color.substring(1, 2)}`), + parseInt(`0x${color.substring(2, 3)}`), + parseInt(`0x${color.substring(3, 4)}`) + ]; + } + tempValue += `${colorArray[0]},`; + tempValue += `${colorArray[1]},`; + tempValue += `${colorArray[2]})`; + + return tempValue; +} + +export function rgba2rgb(rgbColor, bgColor) { + if (isNull(bgColor)) { + bgColor = 1; + } + if (rgbColor.substr(0, 4) !== "rgba") { + return ""; + } + const rgbValues = rgbColor.match(/\d+(\.\d+)?/g); + if (rgbValues.length < 4) { + return ""; + } + const R = parseFloat(rgbValues[0]); + const G = parseFloat(rgbValues[1]); + const B = parseFloat(rgbValues[2]); + const A = parseFloat(rgbValues[3]); + + return `rgb(${Math.floor(255 * (bgColor * (1 - A)) + R * A)},${ + Math.floor(255 * (bgColor * (1 - A)) + G * A)},${ + Math.floor(255 * (bgColor * (1 - A)) + B * A)})`; +} + diff --git a/src/core/platform/web/dom.js b/src/core/utils/dom.js similarity index 73% rename from src/core/platform/web/dom.js rename to src/core/utils/dom.js index 1fca2871b..c356b9b50 100644 --- a/src/core/platform/web/dom.js +++ b/src/core/utils/dom.js @@ -1,7 +1,7 @@ /** * 对DOM操作的通用函数 */ -import { each, isEmpty, isNull } from "../../2.base"; +import { each, isEmpty, isNull } from "../2.base"; export function ready(fn) { BI.Widget._renderEngine.createElement(document).ready(fn); @@ -502,208 +502,208 @@ export function getComboPositionByDirections(combo, popup, extraWidth, extraHeig for (i = 0; i < directions.length; i++) { direct = directions[i]; switch (direct) { - case "left": - leftRight.push(direct); - break; - case "right": - leftRight.push(direct); - break; - case "top": - topBottom.push(direct); - break; - case "bottom": - topBottom.push(direct); - break; - case "innerLeft": - innerLeftRight.push(direct); - break; - case "innerRight": - innerLeftRight.push(direct); - break; - default: - break; + case "left": + leftRight.push(direct); + break; + case "right": + leftRight.push(direct); + break; + case "top": + topBottom.push(direct); + break; + case "bottom": + topBottom.push(direct); + break; + case "innerLeft": + innerLeftRight.push(direct); + break; + case "innerRight": + innerLeftRight.push(direct); + break; + default: + break; } } for (i = 0; i < directions.length; i++) { let tW, tH; direct = directions[i]; switch (direct) { - case "left": - if (!isNeedAdaptHeight) { - tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? 0 : extraHeight; - if (isLeftSpaceEnough(combo, popup, tW)) { - left = getLeftPosition(combo, popup, tW, container).left; - if (topBottom[0] === "bottom") { - pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight, container); - } else { - pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight, container); + case "left": + if (!isNeedAdaptHeight) { + tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? 0 : extraHeight; + if (isLeftSpaceEnough(combo, popup, tW)) { + left = getLeftPosition(combo, popup, tW, container).left; + if (topBottom[0] === "bottom") { + pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight, container); + } else { + pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight, container); + } + pos.dir = `left,${pos.dir}`; + if (tbFirst) { + pos.change = "left"; + } + pos.left = left; + + return pos; } - pos.dir = `left,${pos.dir}`; - if (tbFirst) { - pos.change = "left"; + } + lrFirst = true; + break; + case "right": + if (!isNeedAdaptHeight) { + tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? extraWidth : extraHeight; + if (isRightSpaceEnough(combo, popup, tW)) { + left = getRightPosition(combo, popup, tW, container).left; + if (topBottom[0] === "bottom") { + pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight, container); + } else { + pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight, container); + } + pos.dir = `right,${pos.dir}`; + if (tbFirst) { + pos.change = "right"; + } + pos.left = left; + + return pos; } - pos.left = left; - - return pos; } - } - lrFirst = true; - break; - case "right": - if (!isNeedAdaptHeight) { - tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? extraWidth : extraHeight; - if (isRightSpaceEnough(combo, popup, tW)) { - left = getRightPosition(combo, popup, tW, container).left; - if (topBottom[0] === "bottom") { - pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight, container); + lrFirst = true; + break; + case "top": + tW = lrFirst ? extraHeight : extraWidth, tH = lrFirst ? extraWidth : extraHeight; + if (isTopSpaceEnough(combo, popup, tH)) { + top = getTopPosition(combo, popup, tH, container).top; + if (leftRight[0] === "right") { + pos = getLeftAlignPosition(combo, popup, tW, container); } else { - pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight, container); + pos = getRightAlignPosition(combo, popup, tW, container); } - pos.dir = `right,${pos.dir}`; - if (tbFirst) { - pos.change = "right"; + pos.dir = `top,${pos.dir}`; + if (lrFirst) { + pos.change = "top"; } - pos.left = left; + pos.top = top; return pos; } - } - lrFirst = true; - break; - case "top": - tW = lrFirst ? extraHeight : extraWidth, tH = lrFirst ? extraWidth : extraHeight; - if (isTopSpaceEnough(combo, popup, tH)) { - top = getTopPosition(combo, popup, tH, container).top; - if (leftRight[0] === "right") { - pos = getLeftAlignPosition(combo, popup, tW, container); - } else { - pos = getRightAlignPosition(combo, popup, tW, container); - } - pos.dir = `top,${pos.dir}`; - if (lrFirst) { - pos.change = "top"; + if (needAdaptHeight) { + isNeedAdaptHeight = true; } - pos.top = top; - - return pos; - } - if (needAdaptHeight) { - isNeedAdaptHeight = true; - } - tbFirst = true; - break; - case "bottom": - tW = lrFirst ? extraHeight : extraWidth, tH = lrFirst ? extraWidth : extraHeight; - if (isBottomSpaceEnough(combo, popup, tH)) { - top = getBottomPosition(combo, popup, tH, container).top; - if (leftRight[0] === "right") { - pos = getLeftAlignPosition(combo, popup, tW, container); - } else { - pos = getRightAlignPosition(combo, popup, tW, container); - } - pos.dir = `bottom,${pos.dir}`; - if (lrFirst) { - pos.change = "bottom"; - } - pos.top = top; - - return pos; - } - if (needAdaptHeight) { - isNeedAdaptHeight = true; - } - tbFirst = true; - break; - case "innerLeft": - if (!isNeedAdaptHeight) { - tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? 0 : extraHeight; - if (isInnerLeftSpaceEnough(combo, popup, tW)) { - left = getInnerLeftPosition(combo, popup, tW).left; - if (topBottom[0] === "bottom") { - pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight); + tbFirst = true; + break; + case "bottom": + tW = lrFirst ? extraHeight : extraWidth, tH = lrFirst ? extraWidth : extraHeight; + if (isBottomSpaceEnough(combo, popup, tH)) { + top = getBottomPosition(combo, popup, tH, container).top; + if (leftRight[0] === "right") { + pos = getLeftAlignPosition(combo, popup, tW, container); } else { - pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight); + pos = getRightAlignPosition(combo, popup, tW, container); } - pos.dir = `innerLeft,${pos.dir}`; - if (tbFirst) { - pos.change = "innerLeft"; + pos.dir = `bottom,${pos.dir}`; + if (lrFirst) { + pos.change = "bottom"; } - pos.left = left; + pos.top = top; return pos; } - } - lrFirst = true; - break; - case "innerRight": - if (!isNeedAdaptHeight) { - tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? extraWidth : extraHeight; - if (isInnerRightSpaceEnough(combo, popup, tW)) { - left = getInnerRightPosition(combo, popup, tW).left; - if (topBottom[0] === "bottom") { - pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight); - } else { - pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight); + if (needAdaptHeight) { + isNeedAdaptHeight = true; + } + tbFirst = true; + break; + case "innerLeft": + if (!isNeedAdaptHeight) { + tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? 0 : extraHeight; + if (isInnerLeftSpaceEnough(combo, popup, tW)) { + left = getInnerLeftPosition(combo, popup, tW).left; + if (topBottom[0] === "bottom") { + pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight); + } else { + pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight); + } + pos.dir = `innerLeft,${pos.dir}`; + if (tbFirst) { + pos.change = "innerLeft"; + } + pos.left = left; + + return pos; } - pos.dir = `innerLeft,${pos.dir}`; - if (tbFirst) { - pos.change = "innerRight"; + } + lrFirst = true; + break; + case "innerRight": + if (!isNeedAdaptHeight) { + tW = tbFirst ? extraHeight : extraWidth, tH = tbFirst ? extraWidth : extraHeight; + if (isInnerRightSpaceEnough(combo, popup, tW)) { + left = getInnerRightPosition(combo, popup, tW).left; + if (topBottom[0] === "bottom") { + pos = getTopAlignPosition(combo, popup, tH, needAdaptHeight); + } else { + pos = getBottomAlignPosition(combo, popup, tH, needAdaptHeight); + } + pos.dir = `innerLeft,${pos.dir}`; + if (tbFirst) { + pos.change = "innerRight"; + } + pos.left = left; + + return pos; } - pos.left = left; - - return pos; } - } - break; - default: - break; + break; + default: + break; } } // 此处为四个方向放不下时挑空间最大的方向去放置, 也就是说我设置了弹出方向为"bottom,left", // 最后发现实际弹出方向可能是"top,left",那么此时外界获取popup的方向应该是"top,left" switch (directions[0]) { - case "left": - case "right": - if (isRightSpaceLarger(combo)) { - left = getRightAdaptPosition(combo, popup, extraWidth, container).left; - firstDir = "right"; - } else { - left = getLeftAdaptPosition(combo, popup, extraWidth, container).left; - firstDir = "left"; - } - if (topBottom[0] === "bottom") { - pos = getTopAlignPosition(combo, popup, extraHeight, needAdaptHeight); + case "left": + case "right": + if (isRightSpaceLarger(combo)) { + left = getRightAdaptPosition(combo, popup, extraWidth, container).left; + firstDir = "right"; + } else { + left = getLeftAdaptPosition(combo, popup, extraWidth, container).left; + firstDir = "left"; + } + if (topBottom[0] === "bottom") { + pos = getTopAlignPosition(combo, popup, extraHeight, needAdaptHeight); + pos.left = left; + pos.dir = `${firstDir},${pos.dir}`; + + return pos; + } + pos = getBottomAlignPosition(combo, popup, extraHeight, needAdaptHeight); pos.left = left; pos.dir = `${firstDir},${pos.dir}`; return pos; - } - pos = getBottomAlignPosition(combo, popup, extraHeight, needAdaptHeight); - pos.left = left; - pos.dir = `${firstDir},${pos.dir}`; - - return pos; - default : - if (isBottomSpaceLarger(combo)) { - top = getBottomAdaptPosition(combo, popup, extraHeight, needAdaptHeight, container).top; - firstDir = "bottom"; - } else { - top = getTopAdaptPosition(combo, popup, extraHeight, needAdaptHeight, container).top; - firstDir = "top"; - } - if (leftRight[0] === "right") { - pos = getLeftAlignPosition(combo, popup, extraWidth, container); + default : + if (isBottomSpaceLarger(combo)) { + top = getBottomAdaptPosition(combo, popup, extraHeight, needAdaptHeight, container).top; + firstDir = "bottom"; + } else { + top = getTopAdaptPosition(combo, popup, extraHeight, needAdaptHeight, container).top; + firstDir = "top"; + } + if (leftRight[0] === "right") { + pos = getLeftAlignPosition(combo, popup, extraWidth, container); + pos.top = top; + pos.dir = `${firstDir},${pos.dir}`; + + return pos; + } + pos = getRightAlignPosition(combo, popup, extraWidth, container); pos.top = top; pos.dir = `${firstDir},${pos.dir}`; return pos; - } - pos = getRightAlignPosition(combo, popup, extraWidth, container); - pos.top = top; - pos.dir = `${firstDir},${pos.dir}`; - - return pos; } } @@ -716,26 +716,26 @@ export function getComboPosition(combo, popup, extraWidth, extraHeight, needAdap popup.resetHeight && popup.resetHeight(maxHeight); const position = getComboPositionByDirections(combo, popup, extraWidth, extraHeight, needAdaptHeight, directions || ["bottom", "top", "right", "left"], positionRelativeElement); switch (offsetStyle) { - case "center": - if (position.change) { - const p = getMiddleAdaptPosition(combo, popup, positionRelativeElement); - position.top = p.top; - } else { - const p = getCenterAdaptPosition(combo, popup, positionRelativeElement); - position.left = p.left; - } - break; - case "middle": - if (position.change) { - const p = getCenterAdaptPosition(combo, popup, positionRelativeElement); - position.left = p.left; - } else { - const p = getMiddleAdaptPosition(combo, popup, positionRelativeElement); - position.top = p.top; - } - break; - default: - break; + case "center": + if (position.change) { + const p = getMiddleAdaptPosition(combo, popup, positionRelativeElement); + position.top = p.top; + } else { + const p = getCenterAdaptPosition(combo, popup, positionRelativeElement); + position.left = p.left; + } + break; + case "middle": + if (position.change) { + const p = getCenterAdaptPosition(combo, popup, positionRelativeElement); + position.left = p.left; + } else { + const p = getMiddleAdaptPosition(combo, popup, positionRelativeElement); + position.top = p.top; + } + break; + default: + break; } if (needAdaptHeight === true) { popup.resetHeight && popup.resetHeight(Math.min(viewportBounds.height - position.top - (positionRelativeElement ? positionRelativeElement.getBoundingClientRect().top : 0), maxHeight)); diff --git a/src/core/utils/index.js b/src/core/utils/index.js index 059be17e4..0937fcd71 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -1,4 +1,12 @@ export * from "./events"; export * from "./i18n"; export { makeFirstPY } from "./chinesePY"; -export { DOM } from "./color"; + +import * as platformDom from "./dom"; +import * as colorDom from "./color"; + + +export const DOM = { + ...platformDom, + ...colorDom +}; From 9ea65567ca81e47db5dc26b95d4c4811340cd469 Mon Sep 17 00:00:00 2001 From: zsmj Date: Wed, 11 Jan 2023 16:02:39 +0800 Subject: [PATCH 072/300] =?UTF-8?q?KERNEL-14066=20feat:=20case/tree?= =?UTF-8?q?=E5=92=8Ccase/ztree?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/single/bar/bar.loading.js | 32 +++++++++---------- src/base/single/index.js | 1 + src/case/tree/tree.level.js | 31 +++++++++++++----- src/case/tree/treeexpander/tree.expander.js | 6 ++-- .../tree/treeexpander/tree.expander.popup.js | 4 +-- src/case/ztree/treerender.page.service.js | 7 ++-- src/case/ztree/treeview.js | 14 ++++---- src/core/wrapper/index.js | 2 +- 8 files changed, 57 insertions(+), 40 deletions(-) diff --git a/src/base/single/bar/bar.loading.js b/src/base/single/bar/bar.loading.js index f8bd97970..a4ab85a46 100644 --- a/src/base/single/bar/bar.loading.js +++ b/src/base/single/bar/bar.loading.js @@ -1,12 +1,8 @@ -import { shortcut, emptyFn } from "../../../core" -/** - * guy - * 加载条 - * @type {*|void|Object} - */ -@shortcut() -class LoadingBar extends BI.Single { +import { shortcut, emptyFn } from "@/core"; +import { Single } from "../0.single"; +@shortcut() +class LoadingBar extends Single { static xtype = "bi.loading_bar"; _defaultConfig() { @@ -14,10 +10,10 @@ class LoadingBar extends BI.Single { return { ...conf, - baseCls: (conf.baseCls || "") + " bi-loading-bar bi-tips", + baseCls: `${conf.baseCls || ""} bi-loading-bar bi-tips`, height: 30, handler: emptyFn, - } + }; } render() { @@ -49,13 +45,15 @@ class LoadingBar extends BI.Single { this.cardLayout = BI.createWidget({ type: "bi.card", element: this, - items: [{ - el: loaded, - cardName: "loaded", - }, { - el: loading, - cardName: "loading", - }], + items: [ + { + el: loaded, + cardName: "loaded", + }, { + el: loading, + cardName: "loading", + } + ], }); this.invisible(); } diff --git a/src/base/single/index.js b/src/base/single/index.js index 4ace50599..1d0bf1a61 100644 --- a/src/base/single/index.js +++ b/src/base/single/index.js @@ -9,6 +9,7 @@ export { Link } from "./link/link"; export { Instruction } from "./instruction/instruction"; export { Img } from "./img/img"; export { Trigger } from "./trigger/trigger"; +export { LoadingBar } from "./bar/bar.loading"; export * from "./tip"; export * from "./label"; export * from "./input"; diff --git a/src/case/tree/tree.level.js b/src/case/tree/tree.level.js index bd522ce3a..23a2c4473 100644 --- a/src/case/tree/tree.level.js +++ b/src/case/tree/tree.level.js @@ -1,4 +1,19 @@ -import { shortcut, Widget, extend, isKey, each, UUID, defaults, isNotEmptyArray, Tree, createWidget } from "@/core"; +import { + shortcut, + Widget, + extend, + isKey, + each, + UUID, + defaults, + isNotEmptyArray, + Tree, + createWidget, + VerticalLayout +} from "@/core"; +import { ButtonTree, CustomTree } from "@/base"; +import { TreeExpander } from "./treeexpander/tree.expander"; +import { BasicTreeItem, BasicTreeNode } from "@/case"; @shortcut() export class LevelTree extends Widget { @@ -36,13 +51,13 @@ export class LevelTree extends Widget { } extend.pNode = pNode; if (node.isParent === true || node.parent === true || isNotEmptyArray(node.children)) { - extend.type = "bi.tree_node"; + extend.type = BasicTreeNode.xtype; extend.selectable = false; defaults(node, extend); self._formatItems(node.children, layer + 1, node); } else { - extend.type = "bi.tree_item"; + extend.type = BasicTreeItem.xtype; defaults(node, extend); } }); @@ -63,26 +78,26 @@ export class LevelTree extends Widget { this.empty(); this._assertId(nodes); this.tree = createWidget({ - type: "bi.custom_tree", + type: CustomTree.xtype, element: this, expander: extend({ - type: "bi.tree_expander", + type: TreeExpander.xtype, el: {}, isDefaultInit: false, selectable: false, popup: { - type: "bi.custom_tree", + type: CustomTree.xtype, }, }, o.expander), items: this._formatItems(Tree.transformToTreeFormat(nodes), 0), value: o.value, el: extend({ - type: "bi.button_tree", + type: ButtonTree.xtype, chooseType: 0, layouts: [ { - type: "bi.vertical", + type: VerticalLayout.xtype, } ], }, o.el), diff --git a/src/case/tree/treeexpander/tree.expander.js b/src/case/tree/treeexpander/tree.expander.js index c9e8185f5..32f35a081 100644 --- a/src/case/tree/treeexpander/tree.expander.js +++ b/src/case/tree/treeexpander/tree.expander.js @@ -1,4 +1,6 @@ import { contains, Controller, createWidget, isArray, shortcut, Widget } from "@/core"; +import { Expander } from "@/base"; +import { TreeExpanderPopup } from "./tree.expander.popup"; @shortcut() export class TreeExpander extends Widget { @@ -25,7 +27,7 @@ export class TreeExpander extends Widget { }); return { - type: "bi.expander", + type: Expander.xtype, ref(_ref) { self.expander = _ref; }, @@ -33,7 +35,7 @@ export class TreeExpander extends Widget { el: this.trigger, isDefaultInit: o.isDefaultInit, popup: { - type: "bi.tree_expander.popup", + type: TreeExpanderPopup.xtype, layer: o.layer || o.el.layer, isLastNode: o.isLastNode || o.el.isLastNode, isFirstNode: o.isFirstNode || o.el.isFirstNode, diff --git a/src/case/tree/treeexpander/tree.expander.popup.js b/src/case/tree/treeexpander/tree.expander.popup.js index ac12b708c..d00c790f7 100644 --- a/src/case/tree/treeexpander/tree.expander.popup.js +++ b/src/case/tree/treeexpander/tree.expander.popup.js @@ -1,4 +1,4 @@ -import { Controller, createWidget, pixFormat, shortcut, Widget } from "@/core"; +import { Controller, createWidget, pixFormat, shortcut, VerticalLayout, Widget } from "@/core"; @shortcut() export class TreeExpanderPopup extends Widget { @@ -34,7 +34,7 @@ export class TreeExpanderPopup extends Widget { } return { - type: "bi.vertical", + type: VerticalLayout.xtype, cls: (showLine && !isLastNode) ? (BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? "line solid" : "line") : "", scrolly: null, items: [ diff --git a/src/case/ztree/treerender.page.service.js b/src/case/ztree/treerender.page.service.js index 5bb8be327..56112c217 100644 --- a/src/case/ztree/treerender.page.service.js +++ b/src/case/ztree/treerender.page.service.js @@ -5,14 +5,15 @@ * 提供节点分页加载方式 */ -import { createWidget, debounce, has, OB, size, each } from "@/core"; +import { createWidget, debounce, has, OB, size, each, VerticalLayout } from "@/core"; +import { LoadingBar } from "@/base"; export class TreeRenderPageService extends OB { nodeLists = {}; _getLoadingBar(tId) { const tip = createWidget({ - type: "bi.loading_bar", + type: LoadingBar.xtype, height: 25, handler: () => { this.refreshNodes(tId); @@ -39,7 +40,7 @@ export class TreeRenderPageService extends OB { this.nodeLists[tId].loadWidget = tip; } createWidget({ - type: "bi.vertical", + type: VerticalLayout.xtype, element: o.subNodeListGetter(tId), items: [tip], }); diff --git a/src/case/ztree/treeview.js b/src/case/ztree/treeview.js index a58fd4709..33ee57363 100644 --- a/src/case/ztree/treeview.js +++ b/src/case/ztree/treeview.js @@ -10,9 +10,9 @@ import { jsonEncode, delay, each, replaceAll, isUndefined, isNotEmptyArray, deepClone, map, Tree, - isNull, shortcut + isNull, shortcut, VerticalLayout, Layout, DefaultLayout } from "@/core"; -import { Msg, Pane } from "@/base"; +import { Msg, Pane, LoadingBar, Text } from "@/base"; @shortcut() export class TreeView extends Pane { @@ -43,12 +43,12 @@ export class TreeView extends Pane { this._createTree(); this.tip = createWidget({ - type: "bi.loading_bar", + type: LoadingBar.xtype, invisible: true, handler: () => this._loadMore(), }); createWidget({ - type: "bi.vertical", + type: VerticalLayout.xtype, scrollable: true, scrolly: false, element: this, @@ -68,11 +68,11 @@ export class TreeView extends Pane { this.tree.destroy(); } this.tree = createWidget({ - type: "bi.layout", + type: Layout.xtype, element: ``, }); createWidget({ - type: "bi.default", + type: DefaultLayout.xtype, element: this, items: [this.tree], }); @@ -386,7 +386,7 @@ export class TreeView extends Pane { root: true, keyword: o.paras.keyword, }, newNode, { - type: "bi.text", + type: Text.xtype, text: replaceAll(newNode.text, "\n", " "), })); const fragment = BI.Widget._renderEngine.createElement("
"); diff --git a/src/core/wrapper/index.js b/src/core/wrapper/index.js index c32c3e3bf..0e7310cd2 100644 --- a/src/core/wrapper/index.js +++ b/src/core/wrapper/index.js @@ -1,2 +1,2 @@ -export { Layout } from "./layout"; +export { Layout } from "./layout.js"; export * from "./layout/index"; From 8979ae1743f4c9eac3f77909909b347efd5524f5 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Wed, 11 Jan 2023 16:15:07 +0800 Subject: [PATCH 073/300] =?UTF-8?q?KERNEL-14085=20refactor:=20widget/calen?= =?UTF-8?q?der=E3=80=81date?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/combination/navigation.js | 14 +- src/core/utils/dom.js | 8 +- src/core/wrapper/layout/layout.card.js | 2 +- src/widget/collapse/collapse.js | 114 +++++---- src/widget/date/calendar/combo.month.date.js | 77 +++--- src/widget/date/calendar/combo.year.date.js | 85 ++++--- src/widget/date/calendar/index.js | 8 + src/widget/date/calendar/picker.date.js | 240 +++++++++--------- src/widget/date/calendar/picker.year.js | 138 +++++----- .../date/calendar/popup.calendar.date.js | 146 ++++++----- src/widget/date/calendar/popup.month.js | 113 +++++---- src/widget/date/calendar/popup.year.js | 129 +++++----- .../date/calendar/trigger.triangle.date.js | 69 ++--- src/widget/index.js | 12 + 14 files changed, 611 insertions(+), 544 deletions(-) create mode 100644 src/widget/date/calendar/index.js create mode 100644 src/widget/index.js diff --git a/src/base/combination/navigation.js b/src/base/combination/navigation.js index da12b1174..546cb4ff3 100644 --- a/src/base/combination/navigation.js +++ b/src/base/combination/navigation.js @@ -18,9 +18,7 @@ export class Navigation extends Widget { single: false, showIndex: false, tab: false, - cardCreator: (v) => { - return createWidget(); - }, + cardCreator: v => createWidget(), afterCardCreated: BI.emptyFn, afterCardShow: BI.emptyFn, @@ -45,13 +43,12 @@ export class Navigation extends Widget { new ShowListener({ eventObj: this.tab, cardLayout: this.layout, - cardNameCreator: (v) => { - return this.showIndex + v; - }, - cardCreator: (v) => { + cardNameCreator: v => this.showIndex + v, + cardCreator: v => { Widget.execWithContext(this, () => { this.cardMap[v] = cardCreator(v); }); + return this.cardMap[v]; }, afterCardCreated: bind(this.afterCardCreated, this), @@ -76,7 +73,7 @@ export class Navigation extends Widget { const { single } = this.options; if (single === true) { each(this.cardMap, (name, card) => { - if (name !== (currCardName + "")) { + if (name !== (`${currCardName}`)) { this.layout.deleteCardByName(name); delete this.cardMap[name]; } @@ -170,6 +167,5 @@ export class Navigation extends Widget { destroy() { super.destroy(arguments); } - } diff --git a/src/core/utils/dom.js b/src/core/utils/dom.js index c356b9b50..4b5096a8f 100644 --- a/src/core/utils/dom.js +++ b/src/core/utils/dom.js @@ -265,12 +265,12 @@ export function _getLeftAlignPosition(combo, popup, extraWidth, container) { } export function getLeftAlignPosition(combo, popup, extraWidth, container) { - let left = this._getLeftAlignPosition(combo, popup, extraWidth, container); + let left = _getLeftAlignPosition(combo, popup, extraWidth, container); let dir = ""; // 如果放不下,优先使用RightAlign, 如果RightAlign也放不下, 再使用left=0 const containerRect = container ? container.getBoundingClientRect() : { left: 0 }; if (left + containerRect.left < 0) { - left = this._getRightAlignPosition(combo, popup, extraWidth); + left = _getRightAlignPosition(combo, popup, extraWidth); dir = "left"; } if (left + containerRect.left < 0) { @@ -302,11 +302,11 @@ export function _getRightAlignPosition(combo, popup, extraWidth, container) { } export function getRightAlignPosition(combo, popup, extraWidth, container) { - let left = this._getRightAlignPosition(combo, popup, extraWidth, container); + let left = _getRightAlignPosition(combo, popup, extraWidth, container); let dir = ""; // 如果放不下,优先使用LeftAlign, 如果LeftAlign也放不下, 再使用left=0 if (left < 0) { - left = this._getLeftAlignPosition(combo, popup, extraWidth, container); + left = _getLeftAlignPosition(combo, popup, extraWidth, container); dir = "right"; } if (left < 0) { diff --git a/src/core/wrapper/layout/layout.card.js b/src/core/wrapper/layout/layout.card.js index 4b2fbad2a..6a7ebaadc 100644 --- a/src/core/wrapper/layout/layout.card.js +++ b/src/core/wrapper/layout/layout.card.js @@ -83,7 +83,7 @@ export class CardLayout extends Layout { } isCardExisted(cardName) { - return some(this.options.items, (i, item) => item.cardName === cardName && item.el); + return some(this.options.items, (i, item) => item.cardName == cardName && item.el); } getCardByName(cardName) { diff --git a/src/widget/collapse/collapse.js b/src/widget/collapse/collapse.js index f899c3588..4111a23ce 100644 --- a/src/widget/collapse/collapse.js +++ b/src/widget/collapse/collapse.js @@ -1,6 +1,13 @@ -BI.Collapse = BI.inherit(BI.Widget, { +import { shortcut, Widget, map, extend, isFunction, contains, each, isKey, isNotEmptyArray } from "@/core"; +import { Expander } from "@/base"; - props: { +@shortcut() +export class Collapse extends Widget { + static xtype = "bi.collapse" + + static EVENT_EXPAND = "EVENT_EXPAND" + + props = { baseCls: "bi-collapse", items: [], value: [], @@ -11,98 +18,95 @@ BI.Collapse = BI.inherit(BI.Widget, { isDefaultInit: false, openMotion: { animation: "bi-slide-up", - animationDuring: 200 - } - }, + animationDuring: 200, + }, + }; - render: function () { - var o = this.options; + render() { + const o = this.options; - var collapseCls = o.ghost ? "" : "bi-background " + (o.bordered ? "bi-border bi-border-radius" : ""); + const collapseCls = o.ghost ? "" : `bi-background ${o.bordered ? "bi-border bi-border-radius" : ""}`; this.expanders = {}; return { type: "bi.vertical", cls: collapseCls, - items: this._getItems(this.options.items) + items: this._getItems(this.options.items), }; - }, + } - _getItems: function (items) { - var self = this, o = this.options; + _getItems(items) { + const o = this.options; - return BI.map(items, function (index, item) { - var isActive = BI.contains(self._getCurrentValue(o.value), item.value); - var cls = o.ghost || index === 0 ? "" : "bi-border-top"; + return map(items, (index, item) => { + const isActive = contains(this._getCurrentValue(o.value), item.value); + const cls = o.ghost || index === 0 ? "" : "bi-border-top"; - var el = BI.extend({ + const el = extend({ type: "bi.arrow_group_node", height: 30, text: item.text, value: item.value, - open: isActive + open: isActive, }, item.el); - var popup = BI.extend({ + const popup = extend({ animation: o.openMotion.animation, - animationDuring: o.openMotion.animationDuring + animationDuring: o.openMotion.animationDuring, }, item.popup); - - return BI.extend({ + + return extend({ type: "bi.expander", - cls: cls, + cls, isDefaultInit: o.isDefaultInit, trigger: o.trigger, listeners: [{ - eventName: BI.Expander.EVENT_EXPAND, - action: function () { - self._hideOtherExpander(item.value); - self.fireEvent(BI.Collapse.EVENT_EXPAND, item.value); - } - }] + eventName: Expander.EVENT_EXPAND, + action: () => { + this._hideOtherExpander(item.value); + this.fireEvent(Collapse.EVENT_EXPAND, item.value); + }, + }], }, item, { - el: el, - popup: popup, - ref: function (_ref) { - BI.isFunction(item.ref) && item.ref(_ref); - self.expanders[item.value] = _ref; - } + el, + popup, + ref: _ref => { + isFunction(item.ref) && item.ref(_ref); + this.expanders[item.value] = _ref; + }, }); }); - }, + } - _hideOtherExpander: function (expandKey) { + _hideOtherExpander(expandKey) { if (this.options.accordion) { - BI.each(this.expanders, function (key, expander) { - key !== (expandKey + "") && expander.hideView(); + each(this.expanders, (key, expander) => { + key !== (`${expandKey}`) && expander.hideView(); }); } - }, + } + + _getCurrentValue(v) { + const values = isNotEmptyArray(v) ? v : isKey(v) ? [v] : []; - _getCurrentValue: function (v) { - var values = BI.isNotEmptyArray(v) ? v : BI.isKey(v) ? [v] : []; - return this.options.accordion ? values.slice(0, 1) : values; - }, + } - getValue: function () { - var value = []; - BI.each(this.expanders, function (key, expander) { + getValue() { + const value = []; + each(this.expanders, (key, expander) => { expander.isExpanded() && value.push(key); }); return value; - }, + } - setValue: function (v) { - var values = BI.map(this._getCurrentValue(v), function (idx, value) {return value + "";}); - BI.each(this.expanders, function (key, expander) { - BI.contains(values, key) ? expander.showView() : expander.hideView(); + setValue(v) { + const values = map(this._getCurrentValue(v), (idx, value) => `${value}`); + each(this.expanders, (key, expander) => { + contains(values, key) ? expander.showView() : expander.hideView(); }); } -}); - -BI.Collapse.EVENT_EXPAND = "EVENT_EXPAND"; -BI.shortcut("bi.collapse", BI.Collapse); +} diff --git a/src/widget/date/calendar/combo.month.date.js b/src/widget/date/calendar/combo.month.date.js index aac5a7fc0..565745c4e 100644 --- a/src/widget/date/calendar/combo.month.date.js +++ b/src/widget/date/calendar/combo.month.date.js @@ -1,40 +1,49 @@ +import { shortcut, extend, createWidget } from "@/core"; +import { Trigger, Combo } from "@/base"; +import { MonthPopup } from "./popup.month"; + /** * 日期控件中的月份下拉框 * * Created by GUY on 2015/9/7. - * @class BI.MonthDateCombo - * @extends BI.Trigger + * @class MonthDateCombo + * @extends Trigger */ -BI.MonthDateCombo = BI.inherit(BI.Trigger, { - _defaultConfig: function () { - return BI.extend( BI.MonthDateCombo.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class MonthDateCombo extends Trigger { + static xtype = "bi.month_date_combo" + + static EVENT_CHANGE = "EVENT_CHANGE" + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-month-combo", height: 24, - container: null + container: null, }); - }, - _init: function () { - BI.MonthDateCombo.superclass._init.apply(this, arguments); - var self = this, o = this.options; + } + + _init() { + super._init(...arguments); + const o = this.options; - this.trigger = BI.createWidget({ - type: "bi.date_triangle_trigger" + this.trigger = createWidget({ + type: "bi.date_triangle_trigger", }); - this.popup = BI.createWidget({ + this.popup = createWidget({ type: "bi.month_popup", allowMonths: o.allowMonths, - behaviors: o.behaviors + behaviors: o.behaviors, }); - this.popup.on(BI.MonthPopup.EVENT_CHANGE, function () { - self.setValue(self.popup.getValue()); - self.combo.hideView(); - self.fireEvent(BI.MonthDateCombo.EVENT_CHANGE); + this.popup.on(MonthPopup.EVENT_CHANGE, () => { + this.setValue(this.popup.getValue()); + this.combo.hideView(); + this.fireEvent(MonthDateCombo.EVENT_CHANGE); }); - - this.combo = BI.createWidget({ + this.combo = createWidget({ type: "bi.combo", offsetStyle: "center", container: o.container, @@ -49,28 +58,26 @@ BI.MonthDateCombo = BI.inherit(BI.Trigger, { type: "bi.vertical", hgap: 6, vgap: 5, - items: [this.popup] - } - } + items: [this.popup], + }, + }, }); - this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { - self.doBehavior(); + this.combo.on(Combo.EVENT_BEFORE_POPUPVIEW, () => { + this.doBehavior(); }); - }, + } - populate: function () { - this.popup.populate.apply(this.popup, arguments); - }, + populate() { + this.popup.populate(...arguments); + } - setValue: function (v) { + setValue(v) { this.trigger.setValue(v); this.popup.setValue(v); - }, + } - getValue: function () { + getValue() { return this.popup.getValue(); } -}); -BI.MonthDateCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.month_date_combo", BI.MonthDateCombo); \ No newline at end of file +} diff --git a/src/widget/date/calendar/combo.year.date.js b/src/widget/date/calendar/combo.year.date.js index c8e72580b..b3f883b12 100644 --- a/src/widget/date/calendar/combo.year.date.js +++ b/src/widget/date/calendar/combo.year.date.js @@ -1,45 +1,55 @@ +import { shortcut, extend, createWidget } from "@/core"; +import { Trigger, Combo } from "@/base"; +import { YearPopup } from "./popup.year"; + /** * 年份下拉框 * * Created by GUY on 2015/9/7. - * @class BI.YearDateCombo - * @extends BI.Trigger + * @class YearDateCombo + * @extends Trigger */ -BI.YearDateCombo = BI.inherit(BI.Trigger, { - _defaultConfig: function () { - return BI.extend( BI.YearDateCombo.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class YearDateCombo extends Trigger { + static xtype = "bi.year_date_combo" + + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW" + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-year-combo", min: "1900-01-01", // 最小日期 max: "2099-12-31", // 最大日期 behaviors: {}, height: 24, - container: null + container: null, }); - }, - _init: function () { - BI.YearDateCombo.superclass._init.apply(this, arguments); - var self = this, o = this.options; + } + + _init() { + super._init(...arguments); + const o = this.options; - this.trigger = BI.createWidget({ - type: "bi.date_triangle_trigger" + this.trigger = createWidget({ + type: "bi.date_triangle_trigger", }); - this.popup = BI.createWidget({ + this.popup = createWidget({ type: "bi.year_popup", behaviors: o.behaviors, min: o.min, max: o.max, - width: 122 + width: 122, }); - this.popup.on(BI.YearPopup.EVENT_CHANGE, function () { - self.setValue(self.popup.getValue()); - self.combo.hideView(); - self.fireEvent(BI.YearDateCombo.EVENT_CHANGE); + this.popup.on(YearPopup.EVENT_CHANGE, () => { + this.setValue(this.popup.getValue()); + this.combo.hideView(); + this.fireEvent(YearDateCombo.EVENT_CHANGE); }); - - this.combo = BI.createWidget({ + this.combo = createWidget({ type: "bi.combo", offsetStyle: "center", element: this, @@ -50,36 +60,33 @@ BI.YearDateCombo = BI.inherit(BI.Trigger, { popup: { minWidth: 100, stopPropagation: false, - el: this.popup - } + el: this.popup, + }, }); - this.combo.on(BI.Combo.EVENT_CHANGE, function () { - self.fireEvent(BI.YearDateCombo.EVENT_CHANGE); + this.combo.on(Combo.EVENT_CHANGE, () => { + this.fireEvent(YearDateCombo.EVENT_CHANGE); }); // BI-22551 popup未初始化传入的behavior无效 - this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { - self.doBehavior(); - self.fireEvent(BI.YearDateCombo.EVENT_BEFORE_POPUPVIEW); + this.combo.on(Combo.EVENT_BEFORE_POPUPVIEW, () => { + this.doBehavior(); + this.fireEvent(YearDateCombo.EVENT_BEFORE_POPUPVIEW); }); - }, + } - setMinDate: function (minDate) { + setMinDate(minDate) { this.popup.setMinDate(minDate); - }, + } - setMaxDate: function (maxDate) { + setMaxDate(maxDate) { this.popup.setMaxDate(maxDate); - }, + } - setValue: function (v) { + setValue(v) { this.trigger.setValue(v); this.popup.setValue(v); - }, + } - getValue: function () { + getValue() { return this.popup.getValue(); } -}); -BI.YearDateCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.YearDateCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut("bi.year_date_combo", BI.YearDateCombo); +} diff --git a/src/widget/date/calendar/index.js b/src/widget/date/calendar/index.js new file mode 100644 index 000000000..26a397d24 --- /dev/null +++ b/src/widget/date/calendar/index.js @@ -0,0 +1,8 @@ +export { MonthDateCombo } from "./combo.month.date"; +export { YearDateCombo } from "./combo.year.date"; +export { DatePicker } from "./picker.date"; +export { YearPicker } from "./picker.year"; +export { DateCalendarPopup } from "./popup.calendar.date"; +export { MonthPopup } from "./popup.month"; +export { YearPopup } from "./popup.year"; +export { DateTriangleTrigger } from "./trigger.triangle.date"; diff --git a/src/widget/date/calendar/picker.date.js b/src/widget/date/calendar/picker.date.js index 369982dfa..a5a23ae11 100644 --- a/src/widget/date/calendar/picker.date.js +++ b/src/widget/date/calendar/picker.date.js @@ -1,222 +1,226 @@ +import { shortcut, Widget, extend, createWidget, contains, isNull, getDate, filter, range, checkDateVoid, parseDateTime, parseInt, print } from "@/core"; +import { IconButton } from "@/base"; +import { YearDateCombo } from "./combo.year.date"; +import { MonthDateCombo } from "./combo.month.date"; + /** * Created by GUY on 2015/9/7. - * @class BI.DatePicker - * @extends BI.Widget + * @class DatePicker + * @extends Widget */ -BI.DatePicker = BI.inherit(BI.Widget, { - _defaultConfig: function () { - var conf = BI.DatePicker.superclass._defaultConfig.apply(this, arguments); +@shortcut() +export class DatePicker extends Widget { + static xtype = "bi.date_picker" + + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW" + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); - return BI.extend(conf, { + return extend(conf, { baseCls: "bi-date-picker", height: 40, min: "1900-01-01", // 最小日期 - max: "2099-12-31" // 最大日期 + max: "2099-12-31", // 最大日期 }); - }, - - _init: function () { - BI.DatePicker.superclass._init.apply(this, arguments); - var self = this; - var o = this.options; - this._year = BI.getDate().getFullYear(); - this._month = BI.getDate().getMonth() + 1; - this.left = BI.createWidget({ + } + + _init() { + super._init(...arguments); + const o = this.options; + this._year = getDate().getFullYear(); + this._month = getDate().getMonth() + 1; + this.left = createWidget({ type: "bi.icon_button", cls: "pre-page-h-font", width: 24, - height: 24 + height: 24, }); - this.left.on(BI.IconButton.EVENT_CHANGE, function () { - if (self._month === 1) { - self.setValue({ - year: (self.year.getValue() - 1) || (BI.getDate().getFullYear() - 1), - month: 12 + this.left.on(IconButton.EVENT_CHANGE, () => { + if (this._month === 1) { + this.setValue({ + year: (this.year.getValue() - 1) || (getDate().getFullYear() - 1), + month: 12, }); } else { - self.setValue({ - year: self.year.getValue() || BI.getDate().getFullYear(), - month: (self.month.getValue() - 1) || BI.getDate().getMonth() + this.setValue({ + year: this.year.getValue() || getDate().getFullYear(), + month: (this.month.getValue() - 1) || getDate().getMonth(), }); } - self.fireEvent(BI.DatePicker.EVENT_CHANGE); - // self._checkLeftValid(); - // self._checkRightValid(); + this.fireEvent(DatePicker.EVENT_CHANGE); + // this._checkLeftValid(); + // this._checkRightValid(); }); - this.right = BI.createWidget({ + this.right = createWidget({ type: "bi.icon_button", cls: "next-page-h-font", width: 24, - height: 24 + height: 24, }); - this.right.on(BI.IconButton.EVENT_CHANGE, function () { - if (self._month === 12) { - self.setValue({ - year: (self.year.getValue() + 1) || (BI.getDate().getFullYear() + 1), - month: 1 + this.right.on(IconButton.EVENT_CHANGE, () => { + if (this._month === 12) { + this.setValue({ + year: (this.year.getValue() + 1) || (getDate().getFullYear() + 1), + month: 1, }); } else { - self.setValue({ - year: self.year.getValue() || BI.getDate().getFullYear(), - month: (self.month.getValue() + 1) || (BI.getDate().getMonth() + 2) + this.setValue({ + year: this.year.getValue() || getDate().getFullYear(), + month: (this.month.getValue() + 1) || (getDate().getMonth() + 2), }); } - self.fireEvent(BI.DatePicker.EVENT_CHANGE); - // self._checkLeftValid(); - // self._checkRightValid(); + this.fireEvent(DatePicker.EVENT_CHANGE); + // this._checkLeftValid(); + // this._checkRightValid(); }); - this.year = BI.createWidget({ + this.year = createWidget({ type: "bi.year_date_combo", behaviors: o.behaviors, min: o.min, - max: o.max + max: o.max, }); - this.year.on(BI.YearDateCombo.EVENT_CHANGE, function () { - self.setValue({ - year: self.year.getValue(), - month: self._refreshMonth() + this.year.on(YearDateCombo.EVENT_CHANGE, () => { + this.setValue({ + year: this.year.getValue(), + month: this._refreshMonth(), }); - self.fireEvent(BI.DatePicker.EVENT_CHANGE); + this.fireEvent(DatePicker.EVENT_CHANGE); }); - this.year.on(BI.YearDateCombo.EVENT_BEFORE_POPUPVIEW, function () { - self.fireEvent(BI.DatePicker.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); + this.year.on(YearDateCombo.EVENT_BEFORE_POPUPVIEW, () => { + this.fireEvent(DatePicker.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); }); - this.month = BI.createWidget({ + this.month = createWidget({ type: "bi.month_date_combo", behaviors: o.behaviors, - allowMonths: this._getAllowMonths() + allowMonths: this._getAllowMonths(), }); - this.month.on(BI.MonthDateCombo.EVENT_CHANGE, function () { - self.setValue({ - year: self.year.getValue() || self._year, - month: self.month.getValue() + this.month.on(MonthDateCombo.EVENT_CHANGE, () => { + this.setValue({ + year: this.year.getValue() || this._year, + month: this.month.getValue(), }); - self.fireEvent(BI.DatePicker.EVENT_CHANGE); + this.fireEvent(DatePicker.EVENT_CHANGE); }); - this.month.on(BI.YearDateCombo.EVENT_BEFORE_POPUPVIEW, function () { - self.fireEvent(BI.DatePicker.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); + this.month.on(YearDateCombo.EVENT_BEFORE_POPUPVIEW, () => { + this.fireEvent(DatePicker.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); }); - BI.createWidget({ + createWidget({ type: "bi.htape", element: this, items: [{ el: { type: "bi.center_adapt", - items: [this.left] + items: [this.left], }, - width: 24 + width: 24, }, { el: { type: "bi.center_adapt", hgap: 10, - items: [this.year, this.month] - } + items: [this.year, this.month], + }, }, { el: { type: "bi.center_adapt", - items: [this.right] + items: [this.right], }, - width: 24 - }] + width: 24, + }], }); this.setValue({ year: this._year, - month: this._month + month: this._month, }); - }, + } - _refreshMonth: function (defaultMonth) { - var month = this.month.getValue(); + _refreshMonth(defaultMonth) { + let month = this.month.getValue(); this.month.populate(this._getAllowMonths()); - var allowMonth = this._getAllowMonths(); - if (!BI.contains(allowMonth, month)) { + const allowMonth = this._getAllowMonths(); + if (!contains(allowMonth, month)) { month = defaultMonth || allowMonth[0]; } this.month.setValue(month); + return month; - }, + } - _getAllowMonths: function () { - var obj = this._getCheckMinMaxDate(); - var year = this.year.getValue() || this._year; + _getAllowMonths() { + const obj = this._getCheckMinMaxDate(); + const year = this.year.getValue() || this._year; - return BI.filter(BI.range(1, 13), function (idx, v) { - return !BI.checkDateVoid(year, v, 1, obj.min, obj.max)[0]; - }); - }, - - // 上一年月不合法则灰化 - _checkLeftValid: function () { - var obj = this._getCheckMinMaxDate(); - var year = this._month === 1 ? this._year - 1 : this._year; - var month = this._month === 1 ? 12 : this._month - 1; - var valid = BI.isNull(BI.checkDateVoid(year, month, 1, obj.min, obj.max)[0]); + return filter(range(1, 13), (idx, v) => !checkDateVoid(year, v, 1, obj.min, obj.max)[0]); + } + + _checkLeftValid() { + const obj = this._getCheckMinMaxDate(); + const year = this._month === 1 ? this._year - 1 : this._year; + const month = this._month === 1 ? 12 : this._month - 1; + const valid = isNull(checkDateVoid(year, month, 1, obj.min, obj.max)[0]); this.left.setEnable(valid); return valid; - }, - - // 下一年月不合法则灰化 - _checkRightValid: function () { - var obj = this._getCheckMinMaxDate(); - var year = this._month === 12 ? this._year + 1 : this._year; - var month = this._month === 12 ? 1 : this._month + 1; - var valid = BI.isNull(BI.checkDateVoid(year, month, 1, obj.min, obj.max)[0]); + } + + _checkRightValid() { + const obj = this._getCheckMinMaxDate(); + const year = this._month === 12 ? this._year + 1 : this._year; + const month = this._month === 12 ? 1 : this._month + 1; + const valid = isNull(checkDateVoid(year, month, 1, obj.min, obj.max)[0]); this.right.setEnable(valid); return valid; - }, + } - _getCheckMinMaxDate: function () { - var o = this.options; - var minDate = BI.parseDateTime(o.min, "%Y-%X-%d"); - var maxDate = BI.parseDateTime(o.max, "%Y-%X-%d"); + _getCheckMinMaxDate() { + const o = this.options; + const minDate = parseDateTime(o.min, "%Y-%X-%d"); + const maxDate = parseDateTime(o.max, "%Y-%X-%d"); minDate.setDate(1); maxDate.setDate(1); return { - min: BI.print(minDate, "%Y-%X-%d"), - max: BI.print(maxDate, "%Y-%X-%d") + min: print(minDate, "%Y-%X-%d"), + max: print(maxDate, "%Y-%X-%d"), }; - }, + } - setMinDate: function (minDate) { + setMinDate(minDate) { this.options.min = minDate; this.year.setMinDate(minDate); this._refreshMonth(this._month); // this._checkLeftValid(); // this._checkRightValid(); - }, + } - setMaxDate: function (maxDate) { + setMaxDate(maxDate) { this.options.max = maxDate; this.year.setMaxDate(maxDate); this._refreshMonth(this._month); // this._checkLeftValid(); // this._checkRightValid(); - }, + } - setValue: function (ob) { - this._year = BI.parseInt(ob.year); - this._month = BI.parseInt(ob.month); + setValue(ob) { + this._year = parseInt(ob.year); + this._month = parseInt(ob.month); this.year.setValue(ob.year); this._refreshMonth(this._month); this.month.setValue(ob.month); // this._checkLeftValid(); // this._checkRightValid(); - }, + } - getValue: function () { + getValue() { return { year: this.year.getValue(), - month: this.month.getValue() + month: this.month.getValue(), }; } -}); -BI.DatePicker.EVENT_CHANGE = "EVENT_CHANGE"; -BI.DatePicker.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW"; -BI.shortcut("bi.date_picker", BI.DatePicker); +} diff --git a/src/widget/date/calendar/picker.year.js b/src/widget/date/calendar/picker.year.js index ac94ecd2b..cced43639 100644 --- a/src/widget/date/calendar/picker.year.js +++ b/src/widget/date/calendar/picker.year.js @@ -1,131 +1,135 @@ -/** - * Created by GUY on 2015/9/7. - * @class BI.YearPicker - * @extends BI.Widget - */ -BI.YearPicker = BI.inherit(BI.Widget, { - _defaultConfig: function () { - var conf = BI.YearPicker.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { +import { shortcut, Widget, extend, createWidget, getDate, parseDateTime } from "@/core"; +import { IconButton } from "@/base"; +import { YearDateCombo } from "./combo.year.date"; + +@shortcut() +export class YearPicker extends Widget { + static xtype = "bi.year_picker" + + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW" + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { baseCls: "bi-year-picker", behaviors: {}, height: 40, min: "1900-01-01", // 最小日期 - max: "2099-12-31" // 最大日期 + max: "2099-12-31", // 最大日期 }); - }, + } - _init: function () { - BI.YearPicker.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this._year = BI.getDate().getFullYear(); - this.left = BI.createWidget({ - type: "bi.icon_button", + _init() { + super._init(...arguments); + const o = this.options; + this._year = getDate().getFullYear(); + this.left = createWidget({ + type: IconButton.xtype, cls: "pre-page-h-font", width: 25, - height: 25 + height: 25, }); - this.left.on(BI.IconButton.EVENT_CHANGE, function () { - self.setValue(self.year.getValue() - 1); - self.fireEvent(BI.YearPicker.EVENT_CHANGE); - // self._checkLeftValid(); - // self._checkRightValid(); + this.left.on(IconButton.EVENT_CHANGE, () => { + this.setValue(this.year.getValue() - 1); + this.fireEvent(YearPicker.EVENT_CHANGE); + // this._checkLeftValid(); + // this._checkRightValid(); }); - this.right = BI.createWidget({ - type: "bi.icon_button", + this.right = createWidget({ + type: IconButton.xtype, cls: "next-page-h-font", width: 25, - height: 25 + height: 25, }); - this.right.on(BI.IconButton.EVENT_CHANGE, function () { - self.setValue(self.year.getValue() + 1); - self.fireEvent(BI.YearPicker.EVENT_CHANGE); - // self._checkLeftValid(); - // self._checkRightValid(); + this.right.on(IconButton.EVENT_CHANGE, () => { + this.setValue(this.year.getValue() + 1); + this.fireEvent(YearPicker.EVENT_CHANGE); + // this._checkLeftValid(); + // this._checkRightValid(); }); - this.year = BI.createWidget({ + this.year = createWidget({ type: "bi.year_date_combo", min: o.min, behaviors: o.behaviors, max: o.max, - width: 50 + width: 50, }); - this.year.on(BI.YearDateCombo.EVENT_CHANGE, function () { - self.setValue(self.year.getValue()); - self.fireEvent(BI.YearPicker.EVENT_CHANGE); + this.year.on(YearDateCombo.EVENT_CHANGE, () => { + this.setValue(this.year.getValue()); + this.fireEvent(YearPicker.EVENT_CHANGE); }); - this.year.on(BI.YearDateCombo.EVENT_BEFORE_POPUPVIEW, function () { - self.fireEvent(BI.YearPicker.EVENT_BEFORE_POPUPVIEW); + this.year.on(YearDateCombo.EVENT_BEFORE_POPUPVIEW, () => { + this.fireEvent(YearPicker.EVENT_BEFORE_POPUPVIEW); }); - BI.createWidget({ + createWidget({ type: "bi.htape", element: this, items: [{ el: { type: "bi.center_adapt", - items: [this.left] + items: [this.left], }, - width: 25 + width: 25, }, { type: "bi.center_adapt", items: [{ - el: this.year - }] + el: this.year, + }], }, { el: { type: "bi.center_adapt", - items: [this.right] + items: [this.right], }, - width: 25 - }] + width: 25, + }], }); this.setValue(this._year); - }, + } - _checkLeftValid: function () { - var o = this.options; - var valid = this._year > BI.parseDateTime(o.min, "%Y-%X-%d").getFullYear(); + _checkLeftValid() { + const o = this.options; + const valid = this._year > parseDateTime(o.min, "%Y-%X-%d").getFullYear(); this.left.setEnable(valid); + return valid; - }, + } - _checkRightValid: function () { - var o = this.options; - var valid = this._year < BI.parseDateTime(o.max, "%Y-%X-%d").getFullYear(); + _checkRightValid() { + const o = this.options; + const valid = this._year < parseDateTime(o.max, "%Y-%X-%d").getFullYear(); this.right.setEnable(valid); + return valid; - }, + } - setMinDate: function (minDate) { + setMinDate(minDate) { this.options.min = minDate; this.year.setMinDate(minDate); // this._checkLeftValid(); // this._checkRightValid(); - }, + } - setMaxDate: function (maxDate) { + setMaxDate(maxDate) { this.options.max = maxDate; this.year.setMaxDate(maxDate); // this._checkLeftValid(); // this._checkRightValid(); - }, - + } - setValue: function (v) { + setValue(v) { this._year = v; this.year.setValue(v); // this._checkLeftValid(); // this._checkRightValid(); - }, + } - getValue: function () { + getValue() { return this.year.getValue(); } -}); -BI.YearPicker.EVENT_CHANGE = "EVENT_CHANGE"; -BI.YearPicker.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut("bi.year_picker", BI.YearPicker); +} diff --git a/src/widget/date/calendar/popup.calendar.date.js b/src/widget/date/calendar/popup.calendar.date.js index ce2892f55..a3180e334 100644 --- a/src/widget/date/calendar/popup.calendar.date.js +++ b/src/widget/date/calendar/popup.calendar.date.js @@ -1,38 +1,49 @@ +import { shortcut, Widget, createWidget, bind, getDate, each, isNotEmptyString } from "@/core"; +import { Navigation } from "@/base"; +import { Calendar } from "@/case"; +import { DatePicker } from "./picker.date"; + /** * Created by GUY on 2015/9/7. - * @class BI.DateCalendarPopup - * @extends BI.Widget + * @class DateCalendarPopup + * @extends Widget */ -BI.DateCalendarPopup = BI.inherit(BI.Widget, { +@shortcut() +export class DateCalendarPopup extends Widget { + static xtype = "bi.date_calendar_popup" - props: { + props = { baseCls: "bi-date-calendar-popup", - min: "1900-01-01", // 最小日期 - max: "2099-12-31", // 最大日期 - selectedTime: null - }, - - _createNav: function (v) { - var date = BI.Calendar.getDateJSONByPage(v); - var calendar = BI.createWidget({ + min: "1900-01-01", + max: "2099-12-31", + selectedTime: null, + }; + + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW" + + + _createNav(v) { + const date = Calendar.getDateJSONByPage(v); + const calendar = createWidget({ type: "bi.calendar", logic: { - dynamic: true + dynamic: true, }, min: this.options.min, max: this.options.max, year: date.year, month: date.month, // BI-45616 此处为确定当前应该展示哪个年月对应的Calendar, day不是关键数据, 给1号就可 - day: 1 + day: 1, }); + return calendar; - }, + } - render: function () { - var self = this, - o = this.options; - this.today = BI.getDate(); + render() { + const o = this.options; + this.today = getDate(); this._year = this.today.getFullYear(); this._month = this.today.getMonth() + 1; this._day = this.today.getDate(); @@ -40,47 +51,47 @@ BI.DateCalendarPopup = BI.inherit(BI.Widget, { this.selectedTime = o.selectedTime || { year: this._year, month: this._month, - day: this._day + day: this._day, }; - this.datePicker = BI.createWidget({ + this.datePicker = createWidget({ type: "bi.date_picker", behaviors: o.behaviors, min: o.min, - max: o.max + max: o.max, }); - this.calendar = BI.createWidget({ + this.calendar = createWidget({ direction: "top", logic: { - dynamic: true + dynamic: true, }, type: "bi.navigation", tab: this.datePicker, - cardCreator: BI.bind(this._createNav, this), + cardCreator: bind(this._createNav, this), - afterCardCreated: function () { + afterCardCreated () { }, - afterCardShow: function () { - this.setValue(self.selectedTime); - } + afterCardShow: () => { + this.calendar.setValue(this.selectedTime); + }, }); - this.datePicker.on(BI.DatePicker.EVENT_CHANGE, function () { - self.selectedTime = self.datePicker.getValue(); - self.selectedTime.day = 1; - self.calendar.setSelect(BI.Calendar.getPageByDateJSON(self.selectedTime)); + this.datePicker.on(DatePicker.EVENT_CHANGE, () => { + this.selectedTime = this.datePicker.getValue(); + this.selectedTime.day = 1; + this.calendar.setSelect(Calendar.getPageByDateJSON(this.selectedTime)); }); - this.datePicker.on(BI.DatePicker.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW, function () { - self.fireEvent(BI.DateCalendarPopup.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); + this.datePicker.on(DatePicker.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW, () => { + this.fireEvent(DateCalendarPopup.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); }); - this.calendar.on(BI.Navigation.EVENT_CHANGE, function () { - self.selectedTime = self.calendar.getValue(); - self.setValue(self.selectedTime); - self.fireEvent(BI.DateCalendarPopup.EVENT_CHANGE); + this.calendar.on(Navigation.EVENT_CHANGE, () => { + this.selectedTime = this.calendar.getValue(); + this.setValue(this.selectedTime); + this.fireEvent(DateCalendarPopup.EVENT_CHANGE); }); return [{ @@ -88,64 +99,61 @@ BI.DateCalendarPopup = BI.inherit(BI.Widget, { items: [{ el: this.calendar, hgap: 12, - bgap: 7 - }] + bgap: 7, + }], }, { type: "bi.absolute", items: [{ el: { type: "bi.layout", - cls: "bi-split-top" + cls: "bi-split-top", }, height: 1, top: 40, left: 0, - right: 0 - }] - }] - }, - - _checkMin: function () { - var o = this.options; - BI.each(this.calendar.getAllCard(), function (idx, calendar) { + right: 0, + }], + }]; + } + + _checkMin() { + const o = this.options; + each(this.calendar.getAllCard(), (idx, calendar) => { calendar.setMinDate(o.min); }); - }, + } - _checkMax: function () { - var o = this.options; - BI.each(this.calendar.getAllCard(), function (idx, calendar) { + _checkMax() { + const o = this.options; + each(this.calendar.getAllCard(), (idx, calendar) => { calendar.setMaxDate(o.max); }); - }, + } - setMinDate: function (minDate) { - if (BI.isNotEmptyString(this.options.min)) { + setMinDate(minDate) { + if (isNotEmptyString(this.options.min)) { this.options.min = minDate; this.datePicker.setMinDate(minDate); this._checkMin(); } - }, + } - setMaxDate: function (maxDate) { - if (BI.isNotEmptyString(this.options.max)) { + setMaxDate(maxDate) { + if (isNotEmptyString(this.options.max)) { this.options.max = maxDate; this.datePicker.setMaxDate(maxDate); this._checkMax(); } - }, + } - setValue: function (timeOb) { + setValue(timeOb) { this.datePicker.setValue(timeOb); - this.calendar.setSelect(BI.Calendar.getPageByDateJSON(timeOb)); + this.calendar.setSelect(Calendar.getPageByDateJSON(timeOb)); this.calendar.setValue(timeOb); this.selectedTime = timeOb; - }, + } - getValue: function () { + getValue() { return this.selectedTime; } -}); -BI.DateCalendarPopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.DateCalendarPopup.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW"; -BI.shortcut("bi.date_calendar_popup", BI.DateCalendarPopup); +} diff --git a/src/widget/date/calendar/popup.month.js b/src/widget/date/calendar/popup.month.js index 402c6ffc2..2c859c660 100644 --- a/src/widget/date/calendar/popup.month.js +++ b/src/widget/date/calendar/popup.month.js @@ -1,99 +1,102 @@ +import { shortcut, Widget, extend, Controller, createWidget, Events, createItems, toPix, map, contains, getDate, LogicFactory, parseInt } from "@/core"; + /** * 月份展示面板 * * Created by GUY on 2015/9/2. - * @class BI.MonthPopup - * @extends BI.Trigger + * @class MonthPopup + * @extends Widget */ -BI.MonthPopup = BI.inherit(BI.Widget, { +@shortcut() +export class MonthPopup extends Widget { + static xtype = "bi.month_popup" + + static EVENT_CHANGE = "EVENT_CHANGE" - _defaultConfig: function () { - return BI.extend(BI.MonthPopup.superclass._defaultConfig.apply(this, arguments), { + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-month-popup", - behaviors: {} + behaviors: {}, }); - }, + } - _init: function () { - BI.MonthPopup.superclass._init.apply(this, arguments); - var self = this, o = this.options; + _init() { + super._init(...arguments); + const o = this.options; - this.selectedMonth = BI.getDate().getMonth() + 1; + this.selectedMonth = getDate().getMonth() + 1; - this.month = BI.createWidget({ + this.month = createWidget({ type: "bi.button_group", element: this, behaviors: o.behaviors, - items: BI.createItems(this._getItems(o.allowMonths), {}), - layouts: [BI.LogicFactory.createLogic("table", BI.extend({ - dynamic: true + items: createItems(this._getItems(o.allowMonths), {}), + layouts: [LogicFactory.createLogic("table", extend({ + dynamic: true, }, { columns: 2, rows: 6, columnSize: [1 / 2, 1 / 2], - rowSize: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + 1 + rowSize: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + 1, })), { type: "bi.center_adapt", vgap: 2, }], - value: o.value + value: o.value, }); - this.month.on(BI.Controller.EVENT_CHANGE, function (type, value) { - self.selectedMonth = value; - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if (type === BI.Events.CLICK) { - self.fireEvent(BI.MonthPopup.EVENT_CHANGE); + this.month.on(Controller.EVENT_CHANGE, (...args) => { + const [type, value] = args; + this.selectedMonth = value; + this.fireEvent(Controller.EVENT_CHANGE, ...args); + if (type === Events.CLICK) { + this.fireEvent(MonthPopup.EVENT_CHANGE); } }); - }, + } - _getItems: function(m) { - BI.Widget.pushContext(this); + _getItems(m) { + Widget.pushContext(this); // 纵向排列月 - var month = [1, 7, 2, 8, 3, 9, 4, 10, 5, 11, 6, 12]; - var items = []; + const month = [1, 7, 2, 8, 3, 9, 4, 10, 5, 11, 6, 12]; + let items = []; items.push(month.slice(0, 2)); items.push(month.slice(2, 4)); items.push(month.slice(4, 6)); items.push(month.slice(6, 8)); items.push(month.slice(8, 10)); items.push(month.slice(10, 12)); - items = BI.map(items, function (i, item) { - return BI.map(item, function (j, td) { - return { - type: "bi.text_item", - cls: "bi-border-radius bi-list-item-select", - textAlign: "center", - whiteSpace: "nowrap", - once: false, - forceSelected: true, - height: BI.toPix(BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, 1), - width: 30, - value: td, - text: td, - disabled: !BI.contains(m, td) - }; - }); - }); - BI.Widget.popContext(); + items = map(items, (i, item) => map(item, (j, td) => { + return { + type: "bi.text_item", + cls: "bi-border-radius bi-list-item-select", + textAlign: "center", + whiteSpace: "nowrap", + once: false, + forceSelected: true, + height: toPix(BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, 1), + width: 30, + value: td, + text: td, + disabled: !contains(m, td), + }; + })); + Widget.popContext(); return items; - }, + } - populate: function(months) { + populate(months) { this.month.populate(this._getItems(months)); - }, + } - getValue: function () { + getValue() { return this.selectedMonth; - }, + } - setValue: function (v) { - v = BI.parseInt(v); + setValue(v) { + v = parseInt(v); this.selectedMonth = v; this.month.setValue([v]); } -}); -BI.MonthPopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.month_popup", BI.MonthPopup); +} diff --git a/src/widget/date/calendar/popup.year.js b/src/widget/date/calendar/popup.year.js index 8c6c4d614..c7b8f0491 100644 --- a/src/widget/date/calendar/popup.year.js +++ b/src/widget/date/calendar/popup.year.js @@ -1,136 +1,143 @@ +import { shortcut, Widget, extend, createWidget, isKey, Controller, bind, isNotNull, isNotEmptyString, getDate, parseInt } from "@/core"; +import { Navigation } from "@/base"; +import { YearCalendar } from "@/case"; + /** * 年份展示面板 * * Created by GUY on 2015/9/2. - * @class BI.YearPopup - * @extends BI.Trigger + * @class YearPopup + * @extends Widget */ -BI.YearPopup = BI.inherit(BI.Widget, { +@shortcut() +export class YearPopup extends Widget { + static xtype = "bi.year_popup" + + static EVENT_CHANGE = "EVENT_CHANGE" - _defaultConfig: function () { - return BI.extend(BI.YearPopup.superclass._defaultConfig.apply(this, arguments), { + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-year-popup", behaviors: {}, min: "1900-01-01", // 最小日期 - max: "2099-12-31" // 最大日期 + max: "2099-12-31", // 最大日期 }); - }, + } - _createYearCalendar: function (v) { - var o = this.options, y = this._year; + _createYearCalendar(v) { + const o = this.options, + y = this._year; - var calendar = BI.createWidget({ + const calendar = createWidget({ type: "bi.year_calendar", behaviors: o.behaviors, min: o.min, max: o.max, logic: { - dynamic: true + dynamic: true, }, - year: y + v * 12 + year: y + v * 12, }); calendar.setValue(this._year); + return calendar; - }, + } - _init: function () { - BI.YearPopup.superclass._init.apply(this, arguments); - var self = this, o = this.options; + _init() { + super._init(...arguments); + const o = this.options; - this.selectedYear = this._year = BI.getDate().getFullYear(); + this.selectedYear = this._year = getDate().getFullYear(); - this.backBtn = BI.createWidget({ + this.backBtn = createWidget({ type: "bi.icon_button", cls: "pre-page-h-font", width: 24, height: 24, - value: -1 + value: -1, }); - this.preBtn = BI.createWidget({ + this.preBtn = createWidget({ type: "bi.icon_button", cls: "next-page-h-font", width: 24, height: 24, - value: 1 + value: 1, }); - this.navigation = BI.createWidget({ + this.navigation = createWidget({ type: "bi.navigation", element: this, single: true, logic: { - dynamic: true + dynamic: true, }, tab: { cls: "year-popup-navigation bi-high-light bi-split-top", height: 24, - items: [this.backBtn, this.preBtn] + items: [this.backBtn, this.preBtn], + }, + cardCreator: bind(this._createYearCalendar, this), + afterCardCreated: () => { + this.setValue(this.selectedYear); }, - cardCreator: BI.bind(this._createYearCalendar, this), - afterCardCreated: function () { - this.setValue(self.selectedYear); - } }); - this.navigation.on(BI.Navigation.EVENT_CHANGE, function () { - self.selectedYear = this.getValue(); - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - self.fireEvent(BI.YearPopup.EVENT_CHANGE, self.selectedYear); + this.navigation.on(Navigation.EVENT_CHANGE, (...args) => { + this.selectedYear = this.navigation.getValue(); + this.fireEvent(Controller.EVENT_CHANGE, ...args); + this.fireEvent(YearPopup.EVENT_CHANGE, this.selectedYear); }); - if(BI.isKey(o.value)){ + if (isKey(o.value)) { this.setValue(o.value); } - }, + } - _checkMin: function () { - var calendar = this.navigation.getSelectedCard(); - if (BI.isNotNull(calendar)) { + _checkMin() { + const calendar = this.navigation.getSelectedCard(); + if (isNotNull(calendar)) { calendar.setMinDate(this.options.min); } - }, + } - _checkMax: function () { - var calendar = this.navigation.getSelectedCard(); - if (BI.isNotNull(calendar)) { + _checkMax() { + const calendar = this.navigation.getSelectedCard(); + if (isNotNull(calendar)) { calendar.setMaxDate(this.options.max); } - }, + } - setMinDate: function (minDate) { - if (BI.isNotEmptyString(this.options.min)) { + setMinDate(minDate) { + if (isNotEmptyString(this.options.min)) { this.options.min = minDate; this._checkMin(); } - }, + } - setMaxDate: function (maxDate) { - if (BI.isNotEmptyString(this.options.max)) { + setMaxDate(maxDate) { + if (isNotEmptyString(this.options.max)) { this.options.max = maxDate; this._checkMax(); } - }, + } - getValue: function () { + getValue() { return this.selectedYear; - }, + } - setValue: function (v) { - var o = this.options; - v = BI.parseInt(v); + setValue(v) { + v = parseInt(v); // 切换年不受范围限制 // 对于年控件来说,只要传入的minDate和maxDate的year区间包含v就是合法的 - // var startDate = BI.parseDateTime(o.min, "%Y-%X-%d"); - // var endDate = BI.parseDateTime(o.max, "%Y-%X-%d"); - // if (BI.checkDateVoid(v, 1, 1, BI.print(BI.getDate(startDate.getFullYear(), 0, 1), "%Y-%X-%d"), BI.print(BI.getDate(endDate.getFullYear(), 0, 1), "%Y-%X-%d"))[0]) { - // v = BI.getDate().getFullYear(); + // var startDate = parseDateTime(o.min, "%Y-%X-%d"); + // var endDate = parseDateTime(o.max, "%Y-%X-%d"); + // if (checkDateVoid(v, 1, 1, print(getDate(startDate.getFullYear(), 0, 1), "%Y-%X-%d"), print(getDate(endDate.getFullYear(), 0, 1), "%Y-%X-%d"))[0]) { + // v = getDate().getFullYear(); // } this.selectedYear = v; - this.navigation.setSelect(BI.YearCalendar.getPageByYear(v)); + this.navigation.setSelect(YearCalendar.getPageByYear(v)); this.navigation.setValue(v); } -}); -BI.YearPopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.year_popup", BI.YearPopup); \ No newline at end of file +} diff --git a/src/widget/date/calendar/trigger.triangle.date.js b/src/widget/date/calendar/trigger.triangle.date.js index 32c61dc1f..d79b0e431 100644 --- a/src/widget/date/calendar/trigger.triangle.date.js +++ b/src/widget/date/calendar/trigger.triangle.date.js @@ -1,66 +1,73 @@ +import { shortcut, extend, createWidget } from "@/core"; +import { Trigger } from "@/base"; + /** * 日期控件中的年份或月份trigger * * Created by GUY on 2015/9/7. - * @class BI.DateTriangleTrigger - * @extends BI.Trigger + * @class DateTriangleTrigger + * @extends Trigger */ -BI.DateTriangleTrigger = BI.inherit(BI.Trigger, { - _const: { +@shortcut() +export class DateTriangleTrigger extends Trigger { + static xtype = "bi.date_triangle_trigger" + + _const = { height: 24, iconWidth: 12, - iconHeight: 12 - }, + iconHeight: 12, + }; - _defaultConfig: function () { - return BI.extend( BI.DateTriangleTrigger.superclass._defaultConfig.apply(this, arguments), { + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-date-triangle-trigger solid-triangle-bottom-font cursor-pointer", - height: 24 + height: 24, }); - }, - _init: function () { - BI.DateTriangleTrigger.superclass._init.apply(this, arguments); - var o = this.options, c = this._const; - this.text = BI.createWidget({ + } + + _init() { + super._init(...arguments); + const o = this.options, + c = this._const; + this.text = createWidget({ type: "bi.label", cls: "list-item-text", textAlign: "right", text: o.text, value: o.value, - height: c.height + height: c.height, }); - BI.createWidget({ + createWidget({ type: "bi.vertical_adapt", element: this, items: [{ el: this.text, - rgap: 5 + rgap: 5, }, { type: "bi.icon_label", - width: 16 - }] + width: 16, + }], }); - }, + } - setValue: function (v) { + setValue(v) { this.text.setValue(v); - }, + } - getValue: function () { + getValue() { return this.text.getValue(); - }, + } - setText: function (v) { + setText(v) { this.text.setText(v); - }, + } - getText: function () { + getText() { return this.item.getText(); - }, + } - getKey: function () { + getKey() { } -}); -BI.shortcut("bi.date_triangle_trigger", BI.DateTriangleTrigger); \ No newline at end of file +} diff --git a/src/widget/index.js b/src/widget/index.js new file mode 100644 index 000000000..9e92a96ba --- /dev/null +++ b/src/widget/index.js @@ -0,0 +1,12 @@ +import { Collapse } from "./collapse/collapse"; +import * as calendar from "./date/calendar"; + +Object.assign(BI, { + Collapse, + ...calendar, +}); + +export * from "./date/calendar"; +export { + Collapse +}; From dd9db4d1fbf93b042e9129c3d28c4554aee7afa8 Mon Sep 17 00:00:00 2001 From: Treecat Date: Wed, 11 Jan 2023 16:16:21 +0800 Subject: [PATCH 074/300] =?UTF-8?q?KERNEL-14076=20feat:=E8=84=9A=E6=9C=AC?= =?UTF-8?q?=E5=8F=AF=E4=BB=A5=E8=87=AA=E5=8A=A8=E5=A4=84=E7=90=86=E4=BE=9D?= =?UTF-8?q?=E8=B5=96=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.js | 153 +++++++++++++++++++++++++++++++++------------------ es6.xtype.js | 128 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 228 insertions(+), 53 deletions(-) create mode 100644 es6.xtype.js diff --git a/es6.js b/es6.js index 7b7734593..2f92decf7 100644 --- a/es6.js +++ b/es6.js @@ -2,6 +2,7 @@ const fs = require("fs"); const path = require("path"); const prettier = require("prettier"); const { exec } = require("child_process"); +const { search, initDepts } = require("./es6.xtype"); async function fix(path) { new Promise(res => { @@ -11,7 +12,65 @@ async function fix(path) { }); } +// 加载模块 +const loader = { + G: { "@/core": { shortcut: true } }, + async load(srcName, module) { + const G = loader.G; + const target = [ + "isNull", + "toPix", + "isKey", + "isObject", + "map", + "extend", + "isFunction", + "isEmptyArray", + "isArray", + "Controller", + "createWidget", + "Events", + "emptyFn", + "nextTick", + "bind", + "i18nText", + "isNotNull", + "isString", + "isNumber", + "isEmpty", + "isEmptyString", + "any", + "deepContains", + "isNotEmptyString", + "each", + "contains", + "remove", + "createItems", + "makeArrayByArray", + ]; + console.log(module); + if (target.indexOf(module) >= 0) { + G["@/core"][module] = true; + + return true; + } + + const key = search(srcName, module); + if (key) { + if (!G[key]) { + G[key] = {}; + } + G[key][module] = true; + } + + return !!key; + }, +}; + + async function handleFile(srcName) { + const G = loader.G; + const sourceCode = fs.readFileSync(srcName).toString(); const result = /BI\.(.*?)\s\=\sBI\.inherit\(/.exec(sourceCode); @@ -24,6 +83,8 @@ async function handleFile(srcName) { const superName = /inherit\(BI\.(.*?),/.exec(sourceCode)[1]; + + // const xtype = /BI.shortcut\(\"(.*?)\"/.exec(sourceCode)[1]; const collection = { @@ -31,6 +92,7 @@ async function handleFile(srcName) { attr: {}, }; + // eslint-disable-next-line no-unused-vars const BI = { inherit(_, options) { collection.methods = Object.keys(options) @@ -49,6 +111,7 @@ async function handleFile(srcName) { }, }; + // eslint-disable-next-line no-eval eval(sourceCode); let M = ""; @@ -56,13 +119,7 @@ async function handleFile(srcName) { let I = ""; let A = ""; - const coreImport = { - shortcut: true, - }; - - if (superName === "Widget") { - coreImport.Widget = true; - } + loader.load(srcName, superName); Object.keys(collection.attr).forEach(key => { A = `${key} = ${JSON.stringify(collection.attr[key])};`; @@ -81,67 +138,52 @@ async function handleFile(srcName) { f = f.replace(`BI.${clzName}.superclass`, "super"); // 换 super._defaultConfig f = f.replace( - `super\._defaultConfig\.apply\(this\,\sarguments\)`, + /super\._defaultConfig\.apply\(this,\sarguments\)/g, "super._defaultConfig(arguments)" ); // 换 super.xxx.apply - f = f.replace(/super\.(.*?)\.apply\(this\,\sarguments\)/, a => { - const f = /super\.(.*?)\.apply\(this\,\sarguments\)/.exec(a); + f = f.replace(/super\.(.*?)\.apply\(this,\sarguments\)/, a => { + const f = /super\.(.*?)\.apply\(this,\sarguments\)/.exec(a); return `super.${f[1]}(...arguments)`; }); - const target = [ - "isNull", - "toPix", - "isKey", - "isObject", - "map", - "extend", - "isFunction", - "isEmptyArray", - "isArray", - "Controller", - clzName, - "createWidget", - "Events", - "emptyFn", - "nextTick", - "bind", - "i18nText", - "isNotNull", - "isString", - "isNumber", - "isEmpty", - "isEmptyString", - "any", - "deepContains", - "isNotEmptyString", - "each", - "contains", - "remove", - "createItems", - "makeArrayByArray", - ]; - - target.forEach(t => { - const arr = f.split(`BI.${t}`); - // nodejs 低版本没有 replaceAll - if (arr.length > 1) { - if (t !== clzName) coreImport[t] = true; - f = arr.join(t); + // 尝试换掉所有的 BI.xxx. BI.xxx( BI.xxx[空白] + f = f.replace(/BI\.(.*?)(\.|\(|\s|,)/g, matchedSentence => { + const match = /BI\.(.*?)(\.|\(|\s|,)/.exec(matchedSentence); + const target = match[1]; + const end = match[2]; + // 尝试加载 target + const loadSuccess = loader.load(srcName, target); + if (loadSuccess) { + return target + end; + } else { + console.log(`加载 ${target}失败`); + + return matchedSentence; } }); M += `${f}\n`; }); - Object.keys(coreImport).forEach(el => { - I += `${el},`; + + + + Object.keys(G).forEach(moduleKey => { + if (moduleKey === path.basename(srcName).replace(/.js$/g, "")) { + return; + } + let i = ""; + Object.keys(G[moduleKey]).forEach(key => { + i += `${key}, `; + }); + I += `import {${i}} from '${moduleKey}'\n`; }); + const outputCode = ` -import {${I}} from "@/core" +${I} @shortcut() export class ${clzName} extends ${superName} { @@ -187,4 +229,9 @@ async function traverse(srcName) { } const srcName = process.argv[2]; -traverse(srcName); + +initDepts().then(() => { + traverse(srcName); +}); + + diff --git a/es6.xtype.js b/es6.xtype.js new file mode 100644 index 000000000..70b4d3db7 --- /dev/null +++ b/es6.xtype.js @@ -0,0 +1,128 @@ +const fs = require("fs"); +const path = require("path"); + +const depts = {}; + +async function handle(filename) { + // 找clzName + const code = fs.readFileSync(filename); + const inheritRegResult = /BI\.(.*?)\s=\sBI\.inherit\(/.exec(code); + let clzName; + if (inheritRegResult) { + clzName = inheritRegResult[1]; + } else { + const clzRegResult = /export\sclass\s(.*?)\sextend/.exec(code); + if (clzRegResult) { + clzName = clzRegResult[1]; + } + } + depts[clzName] = filename; +} + +function isExist(filePath) { + return fs.existsSync(filePath); +} + +async function bfs(filename) { + const stat = fs.statSync(filename); + const isDir = stat.isDirectory(); + if (isDir) { + const files = fs.readdirSync(filename); + for (let i = 0; i < files.length; i++) { + const file = files[i]; + await bfs(path.resolve(filename, file)); + } + } else { + await handle(filename); + } +} + +async function initDepts() { + // dfs 构建依赖关系 + await bfs(path.resolve("src")); +} + + +function search(src, clzName) { + if (!depts[clzName]) { + return ""; + } + + const dstName = path.basename(depts[clzName]).replace(/.js$/g, ""); + const dstPath = path.normalize(depts[clzName]).split("src")[1].split("\\").join("/").split("/"); + const srcPath = path.normalize(src).split("src")[1].split("\\").join("/").split("/"); + + // console.log("src", src); + // console.log("dst", depts[clzName]); + + dstPath.shift(); + dstPath.pop(); + srcPath.shift(); + srcPath.pop(); + + const findDstIndexPath = (dstArr, startIndex) => { + let i = startIndex; + + while (!isExist(path.resolve("src", dstArr.slice(0, i + 1).join("/"), "index.js"))) { + i++; + } + if (i < dstArr.length) { + return dstArr.slice(startIndex, i + 1).join("/"); + } else { + return `${dstArr.slice(startIndex).join("/")}/${dstName}`; + } + }; + + // 不同包 + if (dstPath[0] !== srcPath[0]) { + return `@/${dstPath[0]}`; + } + + // 同包 + let i = 0; + while (dstPath[i] === srcPath[i] && i < dstPath.length && i < srcPath.length) { + i++; + } + + if (i < srcPath.length) { + let result = ""; + const rawI = i; + + // 回溯 + for (let j = 0; j < srcPath.length - rawI; j++) { + result += "../"; + i--; + } + i++; + // dstPath 也没有了 + if (i < dstPath.length) { + return result + findDstIndexPath(dstPath, i); + // 还有好多没有匹配完 + // while (i < srcPath) { + // // exists(srcPath.slice(0, i).join()) + // result += srcPath[i]; + // i++; + // } + } else if (i === dstPath.length) { + return `${result}${dstName}`; + } + } else if (i === srcPath.length) { + if (i === dstPath.length) { + return dstName; + } else if (i < dstPath.length) { + return findDstIndexPath(dstPath, i); + } + } +} + +// search(process.argv[2], "Text").then(res => { +// console.log(res); +// }); + +exports.initDepts = initDepts; +exports.search = search; + + + + + From aa3d0eb03570b0ddc775f693db4cc8bd1407870e Mon Sep 17 00:00:00 2001 From: zsmj Date: Wed, 11 Jan 2023 16:27:53 +0800 Subject: [PATCH 075/300] update --- src/case/button/node/treenode.js | 17 +++++++++-------- src/case/button/treeitem/treeitem.js | 12 ++++++------ 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/src/case/button/node/treenode.js b/src/case/button/node/treenode.js index e0a931e7d..f6ef4c5bc 100644 --- a/src/case/button/node/treenode.js +++ b/src/case/button/node/treenode.js @@ -1,13 +1,14 @@ -import { NodeButton } from "../../../base/single/button/button.node"; -import { shortcut, extend } from "../../../core"; +import { Label, NodeButton } from "@/base"; +import { shortcut, extend, VerticalAdaptLayout } from "@/core"; +import { TreeNodeSwitcher } from "@/case"; @shortcut() export class BasicTreeNode extends NodeButton { static xtype = "bi.tree_node"; - + _defaultConfig(props) { const conf = super._defaultConfig.apply(this, arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-tree-node ${props.selectable ? "bi-list-item-active" : "bi-list-item"}`, id: "", @@ -27,7 +28,7 @@ export class BasicTreeNode extends NodeButton { const o = this.options; const checkbox = { - type: "bi.tree_node_switcher", + type: TreeNodeSwitcher.xtype, ref: _ref => { this.switcher = _ref; }, @@ -39,7 +40,7 @@ export class BasicTreeNode extends NodeButton { layer: o.layer, ...o.switcherIcon, stopPropagation: o.selectable, - mounted () { + mounted() { this.setEnable(true); }, listeners: [ @@ -55,7 +56,7 @@ export class BasicTreeNode extends NodeButton { }; return { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, columnSize: [o.iconWrapperWidth || o.height, "fill"], items: [ { @@ -63,7 +64,7 @@ export class BasicTreeNode extends NodeButton { lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, // 偏移公式为每一层的偏移量为节点高度的一半 }, { el: { - type: "bi.label", + type: Label.xtype, ref: _ref => { this.text = _ref; }, diff --git a/src/case/button/treeitem/treeitem.js b/src/case/button/treeitem/treeitem.js index 85777dd5c..64ae3ffdc 100644 --- a/src/case/button/treeitem/treeitem.js +++ b/src/case/button/treeitem/treeitem.js @@ -1,5 +1,5 @@ -import { NodeButton } from "../../../base/single/button/button.node"; -import { shortcut, extend } from "../../../core"; +import { shortcut, extend, VerticalAdaptLayout, Layout } from "@/core"; +import { NodeButton, Label } from "@/base"; @shortcut() export class BasicTreeItem extends NodeButton { @@ -7,7 +7,7 @@ export class BasicTreeItem extends NodeButton { _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-tree-item bi-list-item-active`, id: "", @@ -23,12 +23,12 @@ export class BasicTreeItem extends NodeButton { const o = this.options; return { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, columnSize: ["", "fill"], items: [ { el: { - type: "bi.layout", + type: Layout.xtype, height: o.height, width: o.height, cls: this.getLineCls(), @@ -37,7 +37,7 @@ export class BasicTreeItem extends NodeButton { }, { el: { - type: "bi.label", + type: Label.xtype, ref: _ref => { this.text = _ref; }, From 175bbf178b98dc54273487b40febd91ff6fd91b2 Mon Sep 17 00:00:00 2001 From: Treecat Date: Wed, 11 Jan 2023 16:58:20 +0800 Subject: [PATCH 076/300] =?UTF-8?q?KERNEL-14076=20feat:=E6=8A=8A=20base=20?= =?UTF-8?q?=E9=87=8C=E9=9D=A2=E7=9A=84=E5=87=BD=E6=95=B0=E9=83=BD=E5=8A=A0?= =?UTF-8?q?=E8=BF=9B=E6=9D=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.js | 102 ++++++++++++++++++++++++++++++--------------------------- 1 file changed, 54 insertions(+), 48 deletions(-) diff --git a/es6.js b/es6.js index 560f26f7d..c1f9d79ad 100644 --- a/es6.js +++ b/es6.js @@ -12,49 +12,49 @@ async function fix(path) { }); } +const target = [ + "isNull", + "toPix", + "isKey", + "isObject", + "map", + "extend", + "isFunction", + "isEmptyArray", + "isArray", + "Controller", + "createWidget", + "Events", + "emptyFn", + "nextTick", + "bind", + "i18nText", + "isNotNull", + "isString", + "isNumber", + "isEmpty", + "isEmptyString", + "any", + "deepContains", + "isNotEmptyString", + "each", + "contains", + "remove", + "createItems", + "makeArrayByArray", +]; + // 加载模块 const loader = { G: { "@/core": { shortcut: true } }, async load(srcName, module) { const G = loader.G; - const target = [ - "isNull", - "toPix", - "isKey", - "isObject", - "map", - "extend", - "isFunction", - "isEmptyArray", - "isArray", - "Controller", - "createWidget", - "Events", - "emptyFn", - "nextTick", - "bind", - "i18nText", - "isNotNull", - "isString", - "isNumber", - "isEmpty", - "isEmptyString", - "any", - "deepContains", - "isNotEmptyString", - "each", - "contains", - "remove", - "createItems", - "makeArrayByArray", - ]; - console.log(module); if (target.indexOf(module) >= 0) { G["@/core"][module] = true; - + return true; } - + const key = search(srcName, module); if (key) { if (!G[key]) { @@ -67,7 +67,6 @@ const loader = { }, }; - async function handleFile(srcName) { const G = loader.G; @@ -83,8 +82,6 @@ async function handleFile(srcName) { const superName = /inherit\(BI\.(.*?),/.exec(sourceCode)[1]; - - // const xtype = /BI.shortcut\(\"(.*?)\"/.exec(sourceCode)[1]; const collection = { @@ -134,15 +131,17 @@ async function handleFile(srcName) { collection.methods.forEach(el => { let f = `${el.toString().replace(/^function/, el.name)}\n`; - // 换 BI.Button.superclass - f = f.replace(`BI.${clzName}.superclass`, "super"); + // 换 BI.Button.superclass,就说能不能跑吧 + for (let i = 0; i < 100; i++) { + f = f.replace(`BI.${clzName}.superclass`, "super"); + } // 换 super._defaultConfig f = f.replace( /super\._defaultConfig\.apply\(this,\sarguments\)/g, - "super._defaultConfig(arguments)" + "super._defaultConfig(...arguments)" ); // 换 super.xxx.apply - f = f.replace(/super\.(.*?)\.apply\(this,\sarguments\)/, a => { + f = f.replace(/super\.(.*?)\.apply\(this,\sarguments\)/g, a => { const f = /super\.(.*?)\.apply\(this,\sarguments\)/.exec(a); return `super.${f[1]}(...arguments)`; @@ -159,7 +158,7 @@ async function handleFile(srcName) { return target + end; } else { console.log(`加载 ${target}失败`); - + return matchedSentence; } }); @@ -167,9 +166,6 @@ async function handleFile(srcName) { M += `${f}\n`; }); - - - Object.keys(G).forEach(moduleKey => { if (moduleKey === path.basename(srcName).replace(/.js$/g, "")) { return; @@ -181,7 +177,6 @@ async function handleFile(srcName) { I += `import {${i}} from '${moduleKey}'\n`; }); - const outputCode = ` ${I} @@ -233,7 +228,18 @@ async function traverse(srcName) { const srcName = process.argv[2]; initDepts().then(() => { + const content = fs.readFileSync("src/core/2.base.js").toString(); + + let result = content.match(/export function (.*?)\(/g); + target.push( + ...result.map(el => + el.replace("export function ", "").replace("(", "") + ) + ); + result = content.match(/export const (.*?) =/g); + target.push( + ...result.map(el => el.replace("export const ", "").replace(" =", "")) + ); + traverse(srcName); }); - - From ddd233adcb8ad7e180dc2584197ab8b9ef521481 Mon Sep 17 00:00:00 2001 From: Treecat Date: Wed, 11 Jan 2023 17:13:25 +0800 Subject: [PATCH 077/300] =?UTF-8?q?KERNEL-14076=20fix:=E8=A7=A3=E5=86=B3?= =?UTF-8?q?=E6=AD=BB=E5=BE=AA=E7=8E=AF=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.xtype.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/es6.xtype.js b/es6.xtype.js index 70b4d3db7..854728add 100644 --- a/es6.xtype.js +++ b/es6.xtype.js @@ -60,12 +60,15 @@ function search(src, clzName) { srcPath.shift(); srcPath.pop(); + + const findDstIndexPath = (dstArr, startIndex) => { let i = startIndex; - while (!isExist(path.resolve("src", dstArr.slice(0, i + 1).join("/"), "index.js"))) { + while (!isExist(path.resolve("src", dstArr.slice(0, i + 1).join("/"), "index.js")) && i < dstArr.length) { i++; } + if (i < dstArr.length) { return dstArr.slice(startIndex, i + 1).join("/"); } else { From 065e44cf0cc555da677c532416b9b17a92a9c661 Mon Sep 17 00:00:00 2001 From: Treecat Date: Wed, 11 Jan 2023 19:24:33 +0800 Subject: [PATCH 078/300] =?UTF-8?q?KERNEL-14076=20feat:es6=E8=84=9A?= =?UTF-8?q?=E6=9C=AC=E8=87=AA=E5=8A=A8=E4=BF=AE=E5=A4=8Dxtype?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.js | 67 +++++++++++++++++++++++++++++++++++++++++++--------- es6.xtype.js | 37 ++++++++++++++++++++--------- 2 files changed, 82 insertions(+), 22 deletions(-) diff --git a/es6.js b/es6.js index c1f9d79ad..7c8f87934 100644 --- a/es6.js +++ b/es6.js @@ -2,7 +2,7 @@ const fs = require("fs"); const path = require("path"); const prettier = require("prettier"); const { exec } = require("child_process"); -const { search, initDepts } = require("./es6.xtype"); +const { search, initDepts, depts } = require("./es6.xtype"); async function fix(path) { new Promise(res => { @@ -42,28 +42,42 @@ const target = [ "remove", "createItems", "makeArrayByArray", + "VerticalAlign", + "transformItems", ]; // 加载模块 const loader = { G: { "@/core": { shortcut: true } }, - async load(srcName, module) { + load(srcName, module) { const G = loader.G; if (target.indexOf(module) >= 0) { G["@/core"][module] = true; return true; } + if (module.startsWith('"bi.')) { + const key = search(srcName, module); + if (key) { + if (!G[key]) { + G[key] = {}; + } + const clzName = depts[module].clzName; + G[key][clzName] = true; + } - const key = search(srcName, module); - if (key) { - if (!G[key]) { - G[key] = {}; + return !!key; + } else { + const key = search(srcName, module); + if (key) { + if (!G[key]) { + G[key] = {}; + } + G[key][module] = true; } - G[key][module] = true; - } - return !!key; + return !!key; + } }, }; @@ -74,7 +88,24 @@ async function handleFile(srcName) { const result = /BI\.(.*?)\s\=\sBI\.inherit\(/.exec(sourceCode); if (!result) { - console.log(`可能是已经es6过了 ${srcName}`); + console.log(`可能是已经es6过了 ${srcName}, 尝试替换 xtype`); + // 处理 xtype + + // 尝试对 xtype 进行替换 + const noXtypeCode = sourceCode.replace(/"bi\.(.*?)"/g, matchedSentence => { + const loadSuccess = loader.load(srcName, matchedSentence); + if (loadSuccess) { + const clzName = depts[matchedSentence].clzName; + + return `${clzName}.xtype`; + } else { + console.log(`加载 ${matchedSentence}失败`); + + return matchedSentence; + } + }); + + fs.writeFileSync(srcName, noXtypeCode); return; } @@ -157,7 +188,21 @@ async function handleFile(srcName) { if (loadSuccess) { return target + end; } else { - console.log(`加载 ${target}失败`); + console.log(`BI.xxx 加载 ${target}失败`); + + return matchedSentence; + } + }); + + // 尝试对 xtype 进行替换 + f = f.replace(/"bi\.(.*?)"/g, matchedSentence => { + const loadSuccess = loader.load(srcName, matchedSentence); + if (loadSuccess) { + const clzName = depts[matchedSentence].clzName; + + return `${clzName}.xtype`; + } else { + console.log(`加载 ${matchedSentence}失败`); return matchedSentence; } diff --git a/es6.xtype.js b/es6.xtype.js index 854728add..dd9bec56c 100644 --- a/es6.xtype.js +++ b/es6.xtype.js @@ -10,10 +10,24 @@ async function handle(filename) { let clzName; if (inheritRegResult) { clzName = inheritRegResult[1]; + // 把 } else { const clzRegResult = /export\sclass\s(.*?)\sextend/.exec(code); + if (clzRegResult) { clzName = clzRegResult[1]; + } else { + return; + } + const xtypeResult = /static xtype = (.*?)(;|\s)/.exec(code); + // 找一下 xtype + if (xtypeResult) { + depts[xtypeResult[1]] = { + clzName, + clzPath: filename, + }; + } else { + // console.log(`${filename} 没有 xtype`); } } depts[clzName] = filename; @@ -43,13 +57,21 @@ async function initDepts() { } -function search(src, clzName) { +function search(src, module) { + let clzName = module; + let clzPath = depts[module]; + if (!depts[clzName]) { return ""; } - const dstName = path.basename(depts[clzName]).replace(/.js$/g, ""); - const dstPath = path.normalize(depts[clzName]).split("src")[1].split("\\").join("/").split("/"); + if (clzName.indexOf("\"") >= 0) { + clzName = depts[module].clzName; + clzPath = depts[module].clzPath; + } + + const dstName = path.basename(clzPath).replace(/.js$/g, ""); + const dstPath = path.normalize(clzPath).split("src")[1].split("\\").join("/").split("/"); const srcPath = path.normalize(src).split("src")[1].split("\\").join("/").split("/"); // console.log("src", src); @@ -60,8 +82,6 @@ function search(src, clzName) { srcPath.shift(); srcPath.pop(); - - const findDstIndexPath = (dstArr, startIndex) => { let i = startIndex; @@ -100,12 +120,6 @@ function search(src, clzName) { // dstPath 也没有了 if (i < dstPath.length) { return result + findDstIndexPath(dstPath, i); - // 还有好多没有匹配完 - // while (i < srcPath) { - // // exists(srcPath.slice(0, i).join()) - // result += srcPath[i]; - // i++; - // } } else if (i === dstPath.length) { return `${result}${dstName}`; } @@ -124,6 +138,7 @@ function search(src, clzName) { exports.initDepts = initDepts; exports.search = search; +exports.depts = depts; From 1c1b262c9e168bace4fdeb570ee308e55805b60a Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Wed, 11 Jan 2023 20:27:06 +0800 Subject: [PATCH 079/300] =?UTF-8?q?KERNEL-14087=20refactor:=20widget/dynam?= =?UTF-8?q?icdate=E3=80=81datepane=E3=80=81datetime=E3=80=81datetimepane?= =?UTF-8?q?=E3=80=81dynamicdatetime?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.js | 1 + src/case/linearsegment/linear.segment.js | 6 +- src/widget/datepane/card.static.datepane.js | 212 +++---- src/widget/datepane/datepane.js | 326 +++++------ src/widget/datepane/index.js | 2 + src/widget/datetime/datetime.combo.js | 124 ++-- src/widget/datetime/datetime.popup.js | 114 ++-- src/widget/datetime/datetime.trigger.js | 92 +-- src/widget/datetime/index.js | 3 + .../datetimepane/card.static.datetimepane.js | 195 ++++--- src/widget/datetimepane/datetimepane.js | 319 ++++++----- src/widget/datetimepane/index.js | 2 + .../dynamicdate/dynamicdate.caculate.js | 206 +++---- src/widget/dynamicdate/dynamicdate.card.js | 535 ++++++++--------- src/widget/dynamicdate/dynamicdate.combo.js | 406 ++++++------- .../dynamicdate/dynamicdate.param.item.js | 153 ++--- src/widget/dynamicdate/dynamicdate.popup.js | 388 +++++++------ src/widget/dynamicdate/dynamicdate.trigger.js | 449 ++++++++------- src/widget/dynamicdate/index.js | 6 + .../dynamicdatetime/dynamicdatetime.combo.js | 409 +++++++------ .../dynamicdatetime/dynamicdatetime.popup.js | 417 +++++++------- .../dynamicdatetime.timeselect.js | 269 ++++----- .../dynamicdatetime.trigger.js | 536 +++++++++--------- src/widget/dynamicdatetime/index.js | 4 + src/widget/index.js | 15 + 25 files changed, 2688 insertions(+), 2501 deletions(-) create mode 100644 src/widget/datepane/index.js create mode 100644 src/widget/datetime/index.js create mode 100644 src/widget/datetimepane/index.js create mode 100644 src/widget/dynamicdate/index.js create mode 100644 src/widget/dynamicdatetime/index.js diff --git a/es6.js b/es6.js index 7c8f87934..c93a368fc 100644 --- a/es6.js +++ b/es6.js @@ -44,6 +44,7 @@ const target = [ "makeArrayByArray", "VerticalAlign", "transformItems", + "print", ]; // 加载模块 diff --git a/src/case/linearsegment/linear.segment.js b/src/case/linearsegment/linear.segment.js index b34771c3b..c44265704 100644 --- a/src/case/linearsegment/linear.segment.js +++ b/src/case/linearsegment/linear.segment.js @@ -25,12 +25,12 @@ export class LinearSegment extends Widget { value: o.value, listeners: [{ eventName: "__EVENT_CHANGE__", - action () { - this.fireEvent("__EVENT_CHANGE__", arguments); + action: (...args) => { + this.fireEvent("__EVENT_CHANGE__", ...args); }, }, { eventName: "EVENT_CHANGE", - action () { + action: () => { this.fireEvent("EVENT_CHANGE"); }, }], diff --git a/src/widget/datepane/card.static.datepane.js b/src/widget/datepane/card.static.datepane.js index 34ed5ac14..a6a469437 100644 --- a/src/widget/datepane/card.static.datepane.js +++ b/src/widget/datepane/card.static.datepane.js @@ -1,185 +1,207 @@ -/** - * Created by zcf on 2017/2/20. - */ -BI.StaticDatePaneCard = BI.inherit(BI.Widget, { - _defaultConfig: function () { - var conf = BI.StaticDatePaneCard.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { +import { shortcut, Widget, extend, createWidget, bind, isNull, each, isNotEmptyString, getDate, getMonthDays } from "@/core"; +import { DatePicker, DateCalendarPopup } from "../date/calendar"; +import { Calendar } from "@/case"; +import { Navigation } from "@/base"; + +@shortcut() +export class StaticDatePaneCard extends Widget { + static xtype = "bi.static_date_pane_card"; + + static EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = + "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { baseCls: "bi-date-pane", min: "1900-01-01", // 最小日期 max: "2099-12-31", // 最大日期 - selectedTime: null + selectedTime: null, }); - }, - _init: function () { - BI.StaticDatePaneCard.superclass._init.apply(this, arguments); - var self = this, o = this.options; + } + + _init() { + super._init(...arguments); + const o = this.options; - this.today = BI.getDate(); + this.today = getDate(); this._year = this.today.getFullYear(); this._month = this.today.getMonth() + 1; this.selectedTime = o.selectedTime || { year: this._year, - month: this._month + month: this._month, }; - this.datePicker = BI.createWidget({ + this.datePicker = createWidget({ type: "bi.date_picker", behaviors: o.behaviors, min: o.min, - max: o.max + max: o.max, }); - this.datePicker.on(BI.DatePicker.EVENT_CHANGE, function () { - var value = self.datePicker.getValue(); - var monthDay = BI.getMonthDays(BI.getDate(value.year, value.month - 1, 1)); - var day = self.selectedTime.day || 0; + this.datePicker.on(DatePicker.EVENT_CHANGE, () => { + const value = this.datePicker.getValue(); + const monthDay = getMonthDays( + getDate(value.year, value.month - 1, 1) + ); + let day = this.selectedTime.day || 0; if (day > monthDay) { day = monthDay; } - self.selectedTime = { + this.selectedTime = { year: value.year, - month: value.month + month: value.month, }; - day !== 0 && (self.selectedTime.day = day); - self.calendar.setSelect(BI.Calendar.getPageByDateJSON(self.selectedTime)); - self.calendar.setValue(self.selectedTime); - day !== 0 && self.fireEvent(BI.DateCalendarPopup.EVENT_CHANGE); - }); - this.datePicker.on(BI.DatePicker.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW, function () { - self.fireEvent(BI.StaticDatePaneCard.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); + day !== 0 && (this.selectedTime.day = day); + this.calendar.setSelect( + Calendar.getPageByDateJSON(this.selectedTime) + ); + this.calendar.setValue(this.selectedTime); + day !== 0 && this.fireEvent(DateCalendarPopup.EVENT_CHANGE); }); + this.datePicker.on( + DatePicker.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW, + () => { + this.fireEvent( + StaticDatePaneCard.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW + ); + } + ); - this.calendar = BI.createWidget({ + this.calendar = createWidget({ direction: "custom", // logic: { // dynamic: false // }, type: "bi.navigation", tab: this.datePicker, - cardCreator: BI.bind(this._createNav, this) + cardCreator: bind(this._createNav, this), }); - this.calendar.on(BI.Navigation.EVENT_CHANGE, function () { - self.selectedTime = self.calendar.getValue(); - self.calendar.empty(); - self.setValue(self.selectedTime); - self.fireEvent(BI.DateCalendarPopup.EVENT_CHANGE); + this.calendar.on(Navigation.EVENT_CHANGE, () => { + this.selectedTime = this.calendar.getValue(); + this.calendar.empty(); + this.setValue(this.selectedTime); + this.fireEvent(DateCalendarPopup.EVENT_CHANGE); }); this.setValue(o.selectedTime); - BI.createWidget({ + createWidget({ type: "bi.vtape", element: this, - items: [{ - el: this.datePicker, - height: 40 - }, this.calendar], - hgap: 10 + items: [ + { + el: this.datePicker, + height: 40, + }, + this.calendar + ], + hgap: 10, }); - BI.createWidget({ + createWidget({ type: "bi.absolute", element: this, - items: [{ - el: { - type: "bi.layout", - cls: "bi-split-top" - }, - height: 1, - top: 40, - left: 0, - right: 0 - }] + items: [ + { + el: { + type: "bi.layout", + cls: "bi-split-top", + }, + height: 1, + top: 40, + left: 0, + right: 0, + } + ], }); + } - }, - - _createNav: function (v) { - var date = BI.Calendar.getDateJSONByPage(v); - var calendar = BI.createWidget({ + _createNav(v) { + const date = Calendar.getDateJSONByPage(v); + const calendar = createWidget({ type: "bi.calendar", logic: { - dynamic: false + dynamic: false, }, min: this.options.min, max: this.options.max, year: date.year, month: date.month, - day: this.selectedTime.day + day: this.selectedTime.day, }); + return calendar; - }, + } - _getNewCurrentDate: function () { - var today = BI.getDate(); + _getNewCurrentDate() { + const today = getDate(); + return { year: today.getFullYear(), - month: today.getMonth() + 1 + month: today.getMonth() + 1, }; - }, + } - _setCalenderValue: function (date) { - this.calendar.setSelect(BI.Calendar.getPageByDateJSON(date)); + _setCalenderValue(date) { + this.calendar.setSelect(Calendar.getPageByDateJSON(date)); this.calendar.setValue(date); this.selectedTime = date; - }, + } - _setDatePicker: function (timeOb) { - if (BI.isNull(timeOb) || BI.isNull(timeOb.year) || BI.isNull(timeOb.month)) { + _setDatePicker(timeOb) { + if (isNull(timeOb) || isNull(timeOb.year) || isNull(timeOb.month)) { this.datePicker.setValue(this._getNewCurrentDate()); } else { this.datePicker.setValue(timeOb); } - }, + } - _setCalendar: function (timeOb) { - if (BI.isNull(timeOb) || BI.isNull(timeOb.day)) { + _setCalendar(timeOb) { + if (isNull(timeOb) || isNull(timeOb.day)) { this.calendar.empty(); this._setCalenderValue(this._getNewCurrentDate()); } else { this._setCalenderValue(timeOb); } - }, + } - _checkMin: function () { - var o = this.options; - BI.each(this.calendar.getAllCard(), function (idx, calendar) { + _checkMin() { + const o = this.options; + each(this.calendar.getAllCard(), (idx, calendar) => { calendar.setMinDate(o.min); }); - }, + } - _checkMax: function () { - var o = this.options; - BI.each(this.calendar.getAllCard(), function (idx, calendar) { + _checkMax() { + const o = this.options; + each(this.calendar.getAllCard(), (idx, calendar) => { calendar.setMaxDate(o.max); }); - }, + } - setMinDate: function (minDate) { - if (BI.isNotEmptyString(this.options.min)) { + setMinDate(minDate) { + if (isNotEmptyString(this.options.min)) { this.options.min = minDate; this.datePicker.setMinDate(minDate); this._checkMin(); } - }, + } - setMaxDate: function (maxDate) { - if (BI.isNotEmptyString(this.options.max)) { + setMaxDate(maxDate) { + if (isNotEmptyString(this.options.max)) { this.options.max = maxDate; this.datePicker.setMaxDate(maxDate); this._checkMax(); } - }, + } - setValue: function (timeOb) { + setValue(timeOb) { this._setDatePicker(timeOb); this._setCalendar(timeOb); - }, + } - getValue: function () { + getValue() { return this.selectedTime; } - -}); -BI.StaticDatePaneCard.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW" -BI.shortcut("bi.static_date_pane_card", BI.StaticDatePaneCard); \ No newline at end of file +} diff --git a/src/widget/datepane/datepane.js b/src/widget/datepane/datepane.js index 3537797c3..e3bc64684 100644 --- a/src/widget/datepane/datepane.js +++ b/src/widget/datepane/datepane.js @@ -1,14 +1,26 @@ -BI.DynamicDatePane = BI.inherit(BI.Widget, { +import { shortcut, Widget, createItems, i18nText, isEmptyObject, isNull, isEmptyString, isNotEmptyObject, getDate } from "@/core"; +import { ButtonGroup, TextButton } from "@/base"; +import { DynamicDateHelper, DynamicDateCombo, DynamicDatePopup } from "../dynamicdate"; - props: { +@shortcut() +export class DynamicDatePane extends Widget { + static xtype = "bi.dynamic_date_pane"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW"; + static Static = 1; + static Dynamic = 2; + + props = { baseCls: "bi-dynamic-date-pane", minDate: "1900-01-01", maxDate: "2099-12-31", - supportDynamic: true - }, + supportDynamic: true, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; + return { type: "bi.vtape", items: [{ @@ -17,201 +29,193 @@ BI.DynamicDatePane = BI.inherit(BI.Widget, { invisible: !o.supportDynamic, cls: "bi-split-bottom", height: 30, - items: BI.createItems([{ - text: BI.i18nText("BI-Multi_Date_YMD"), - value: BI.DynamicDatePane.Static + items: createItems([{ + text: i18nText("BI-Multi_Date_YMD"), + value: DynamicDatePane.Static, }, { - text: BI.i18nText("BI-Basic_Dynamic_Title"), - value: BI.DynamicDatePane.Dynamic + text: i18nText("BI-Basic_Dynamic_Title"), + value: DynamicDatePane.Dynamic, }], { - textAlign: "center" + textAlign: "center", }), listeners: [{ - eventName: BI.ButtonGroup.EVENT_CHANGE, - action: function () { - var value = this.getValue()[0]; - self.dateTab.setSelect(value); + eventName: ButtonGroup.EVENT_CHANGE, + action: () => { + let date; + const value = this.switcher.getValue()[0]; + this.dateTab.setSelect(value); switch (value) { - case BI.DynamicDatePane.Static: - var date = BI.DynamicDateHelper.getCalculation(self.dynamicPane.getValue()); - self.ymd.setValue({ - year: date.getFullYear(), - month: date.getMonth() + 1, - day: date.getDate() - }); - break; - case BI.DynamicDatePane.Dynamic: - self.dynamicPane.setValue({ - year: 0 - }); - break; - default: - break; + case DynamicDatePane.Static: + date = DynamicDateHelper.getCalculation(this.dynamicPane.getValue()); + this.ymd.setValue({ + year: date.getFullYear(), + month: date.getMonth() + 1, + day: date.getDate(), + }); + break; + case DynamicDatePane.Dynamic: + this.dynamicPane.setValue({ + year: 0, + }); + break; + default: + break; } - self.fireEvent(BI.DynamicDatePane.EVENT_CHANGE); - } + this.fireEvent(DynamicDatePane.EVENT_CHANGE); + }, }], - ref: function () { - self.switcher = this; - } + ref: _ref => { + this.switcher = _ref; + }, }, - height: o.supportDynamic ? 30 : 0 + height: o.supportDynamic ? 30 : 0, }, { type: "bi.tab", - ref: function () { - self.dateTab = this; + ref: _ref => { + this.dateTab = _ref; }, - showIndex: BI.DynamicDatePane.Static, - cardCreator: function (v) { + showIndex: DynamicDatePane.Static, + cardCreator: v => { switch (v) { - case BI.DynamicDatePane.Static: - return { - type: "bi.static_date_pane_card", + case DynamicDatePane.Static: + return { + type: "bi.static_date_pane_card", + min: o.minDate, + max: o.maxDate, + behaviors: o.behaviors, + listeners: [{ + eventName: "EVENT_CHANGE", + action: () => { + this.fireEvent(DynamicDatePane.EVENT_CHANGE); + }, + }, { + eventName: "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW", + action: () => { + this.fireEvent(DynamicDatePane.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); + }, + }], + ref: _ref => { + this.ymd = _ref; + }, + }; + case DynamicDatePane.Dynamic: + default: + return { + type: "bi.vtape", + items: [{ + type: "bi.dynamic_date_card", min: o.minDate, max: o.maxDate, - behaviors: o.behaviors, - listeners: [{ - eventName: "EVENT_CHANGE", - action: function () { - self.fireEvent(BI.DynamicDatePane.EVENT_CHANGE); - } - }, { - eventName: "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW", - action: function () { - self.fireEvent(BI.DynamicDatePane.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); - } - }], - ref: function () { - self.ymd = this; - } - }; - case BI.DynamicDatePane.Dynamic: - default: - return { - type: "bi.vtape", - items: [{ - type: "bi.dynamic_date_card", - min: o.minDate, - max: o.maxDate, - ref: function () { - self.dynamicPane = this; - } - }, { - el: { - type: "bi.center", - items: [{ - type: "bi.text_button", - cls: "bi-high-light bi-border-top", - shadow: true, - text: BI.i18nText("BI-Basic_Clear"), - textHeight: 23, - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - self.setValue(); - self.fireEvent(BI.DynamicDatePane.EVENT_CHANGE); + ref: _ref => { + this.dynamicPane = _ref; + }, + }, { + el: { + type: "bi.center", + items: [{ + type: "bi.text_button", + cls: "bi-high-light bi-border-top", + shadow: true, + text: i18nText("BI-Basic_Clear"), + textHeight: 23, + listeners: [{ + eventName: TextButton.EVENT_CHANGE, + action: () => { + this.setValue(); + this.fireEvent(DynamicDatePane.EVENT_CHANGE); + }, + }], + }, { + type: "bi.text_button", + cls: "bi-border-left bi-high-light bi-border-top", + textHeight: 23, + shadow: true, + text: i18nText("BI-Basic_OK"), + listeners: [{ + eventName: TextButton.EVENT_CHANGE, + action: () => { + const type = this.dateTab.getSelect(); + if (type === DynamicDateCombo.Dynamic) { + this.dynamicPane.checkValidation(true) && this.fireEvent(DynamicDatePopup.EVENT_CHANGE); + } else { + this.fireEvent(DynamicDatePane.EVENT_CHANGE); } - }] - }, { - type: "bi.text_button", - cls: "bi-border-left bi-high-light bi-border-top", - textHeight: 23, - shadow: true, - text: BI.i18nText("BI-Basic_OK"), - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - var type = self.dateTab.getSelect(); - if (type === BI.DynamicDateCombo.Dynamic) { - self.dynamicPane.checkValidation(true) && self.fireEvent(BI.DynamicDatePopup.EVENT_CHANGE); - } else { - self.fireEvent(BI.DynamicDatePane.EVENT_CHANGE); - } - } - }] - }] - }, - height: 24 - }] - }; + }, + }], + }], + }, + height: 24, + }], + }; } - } - }] + }, + }], }; - }, + } - created: function () { + created() { this.setValue(this.options.value); - }, + } - _checkValueValid: function (value) { - return BI.isNull(value) || BI.isEmptyObject(value) || BI.isEmptyString(value); - }, + _checkValueValid(value) { + return isNull(value) || isEmptyObject(value) || isEmptyString(value); + } - _checkValue: function (v) { + _checkValue(v) { switch (v.type) { - case BI.DynamicDateCombo.Dynamic: - return BI.isNotEmptyObject(v.value); - case BI.DynamicDateCombo.Static: - default: - return true; + case DynamicDateCombo.Dynamic: + return isNotEmptyObject(v.value); + case DynamicDateCombo.Static: + default: + return true; } - }, + } - setMinDate: function (minDate) { + setMinDate(minDate) { if (this.options.minDate !== minDate) { this.options.minDate = minDate; this.ymd.setMinDate(minDate); } - }, + } - setMaxDate: function (maxDate) { + setMaxDate(maxDate) { if (this.options.maxDate !== maxDate) { this.options.maxDate = maxDate; this.ymd.setMaxDate(maxDate); } - }, + } - setValue: function (v) { + setValue(v) { v = v || {}; - var type = v.type || BI.DynamicDateCombo.Static; - var value = v.value || v; + const type = v.type || DynamicDateCombo.Static; + const value = v.value || v; this.switcher.setValue(type); this.dateTab.setSelect(type); switch (type) { - case BI.DynamicDateCombo.Dynamic: - this.dynamicPane.setValue(value); - break; - case BI.DynamicDateCombo.Static: - default: - if (this._checkValueValid(value)) { - var date = BI.getDate(); - this.ymd.setValue({ - year: date.getFullYear(), - month: date.getMonth() + 1 - }); - } else { - this.ymd.setValue(value); - } - break; + case DynamicDateCombo.Dynamic: + this.dynamicPane.setValue(value); + break; + case DynamicDateCombo.Static: + default: + if (this._checkValueValid(value)) { + const date = getDate(); + this.ymd.setValue({ + year: date.getFullYear(), + month: date.getMonth() + 1, + }); + } else { + this.ymd.setValue(value); + } + break; } - }, + } - getValue: function () { - var type = this.dateTab.getSelect(); + getValue() { + const type = this.dateTab.getSelect(); + return { - type: type, - value: type === BI.DynamicDatePane.Static ? this.dateTab.getValue() : this.dynamicPane.getValue() + type, + value: type === DynamicDatePane.Static ? this.dateTab.getValue() : this.dynamicPane.getValue(), }; } -}); - -BI.DynamicDatePane.EVENT_CHANGE = "EVENT_CHANGE"; -BI.DynamicDatePane.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW"; - -BI.shortcut("bi.dynamic_date_pane", BI.DynamicDatePane); - -BI.extend(BI.DynamicDatePane, { - Static: 1, - Dynamic: 2 -}); +} diff --git a/src/widget/datepane/index.js b/src/widget/datepane/index.js new file mode 100644 index 000000000..240c9dd1a --- /dev/null +++ b/src/widget/datepane/index.js @@ -0,0 +1,2 @@ +export { StaticDatePaneCard } from "./card.static.datepane"; +export { DynamicDatePane } from "./datepane"; diff --git a/src/widget/datetime/datetime.combo.js b/src/widget/datetime/datetime.combo.js index 28037bb69..1d279cb39 100644 --- a/src/widget/datetime/datetime.combo.js +++ b/src/widget/datetime/datetime.combo.js @@ -1,64 +1,75 @@ -/** - * Created by Urthur on 2017/7/14. - */ -BI.DateTimeCombo = BI.inherit(BI.Single, { - constants: { +import { shortcut, extend, getDate, isNotNull, createWidget } from "@/core"; +import { Single, Combo, IconButton } from "@/base"; +import { DateTimePopup } from "./datetime.popup"; + +@shortcut() +export class DateTimeCombo extends Single { + static xtype = "bi.date_time_combo" + + constants = { popupHeight: 290, popupWidth: 270, comboAdjustHeight: 1, border: 1, - iconWidth: 24 - }, - _defaultConfig: function (conf) { - return BI.extend(BI.DateTimeCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: "bi-date-time-combo bi-focus-shadow " + (conf.simple ? "bi-border-bottom" : "bi-border bi-border-radius"), + iconWidth: 24, + }; + + static EVENT_CANCEL = "EVENT_CANCEL" + static EVENT_CONFIRM = "EVENT_CONFIRM" + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW" + + _defaultConfig(conf) { + return extend(super._defaultConfig(...arguments), { + baseCls: `bi-date-time-combo bi-focus-shadow ${conf.simple ? "bi-border-bottom" : "bi-border bi-border-radius"}`, width: 200, height: 24, minDate: "1900-01-01", - maxDate: "2099-12-31" + maxDate: "2099-12-31", }); - }, - _init: function () { - BI.DateTimeCombo.superclass._init.apply(this, arguments); - var self = this, opts = this.options; - var date = BI.getDate(); - this.storeValue = BI.isNotNull(opts.value) ? opts.value : { + } + + _init() { + super._init(...arguments); + const opts = this.options; + const date = getDate(); + this.storeValue = isNotNull(opts.value) ? opts.value : { year: date.getFullYear(), month: date.getMonth() + 1, day: date.getDate(), hour: date.getHours(), minute: date.getMinutes(), - second: date.getSeconds() + second: date.getSeconds(), }; - this.trigger = BI.createWidget({ + this.trigger = createWidget({ type: "bi.date_time_trigger", height: opts.height, min: opts.minDate, max: opts.maxDate, - value: opts.value + value: opts.value, }); - this.popup = BI.createWidget({ + this.popup = createWidget({ type: "bi.date_time_popup", behaviors: opts.behaviors, min: opts.minDate, max: opts.maxDate, - value: opts.value + value: opts.value, }); - self.setValue(this.storeValue); + this.setValue(this.storeValue); - this.popup.on(BI.DateTimePopup.BUTTON_CANCEL_EVENT_CHANGE, function () { - self.setValue(self.storeValue); - self.hidePopupView(); - self.fireEvent(BI.DateTimeCombo.EVENT_CANCEL); + this.popup.on(DateTimePopup.BUTTON_CANCEL_EVENT_CHANGE, () => { + this.setValue(this.storeValue); + this.hidePopupView(); + this.fireEvent(DateTimeCombo.EVENT_CANCEL); }); - this.popup.on(BI.DateTimePopup.BUTTON_OK_EVENT_CHANGE, function () { - self.storeValue = self.popup.getValue(); - self.setValue(self.storeValue); - self.hidePopupView(); - self.fireEvent(BI.DateTimeCombo.EVENT_CONFIRM); + this.popup.on(DateTimePopup.BUTTON_OK_EVENT_CHANGE, () => { + this.storeValue = this.popup.getValue(); + this.setValue(this.storeValue); + this.hidePopupView(); + this.fireEvent(DateTimeCombo.EVENT_CONFIRM); }); - this.combo = BI.createWidget({ + this.combo = createWidget({ type: "bi.combo", container: opts.container, toggle: false, @@ -69,56 +80,51 @@ BI.DateTimeCombo = BI.inherit(BI.Single, { popup: { el: this.popup, width: this.constants.popupWidth, - stopPropagation: false + stopPropagation: false, }, // DEC-4250 和复选下拉一样,点击不收起 - hideChecker: function (e) { + hideChecker (e) { return triggerBtn.element.find(e.target).length === 0; - } + }, }); - this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { - self.popup.setValue(self.storeValue); - self.fireEvent(BI.DateTimeCombo.EVENT_BEFORE_POPUPVIEW); + this.combo.on(Combo.EVENT_BEFORE_POPUPVIEW, () => { + this.popup.setValue(this.storeValue); + this.fireEvent(DateTimeCombo.EVENT_BEFORE_POPUPVIEW); }); - var triggerBtn = BI.createWidget({ + const triggerBtn = createWidget({ type: "bi.icon_button", cls: "bi-trigger-icon-button date-font", width: this.constants.iconWidth, height: opts.height, }); - triggerBtn.on(BI.IconButton.EVENT_CHANGE, function () { - if (self.combo.isViewVisible()) { - // self.combo.hideView(); + triggerBtn.on(IconButton.EVENT_CHANGE, () => { + if (this.combo.isViewVisible()) { + // this.combo.hideView(); } else { - self.combo.showView(); + this.combo.showView(); } }); - BI.createWidget({ + createWidget({ type: "bi.htape", columnSize: ["", this.constants.iconWidth], element: this, - items: [this.combo, triggerBtn] + items: [this.combo, triggerBtn], }); - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v; this.popup.setValue(v); this.trigger.setValue(v); - }, - getValue: function () { + } + + getValue() { return this.storeValue; - }, + } - hidePopupView: function () { + hidePopupView() { this.combo.hideView(); } -}); - -BI.DateTimeCombo.EVENT_CANCEL = "EVENT_CANCEL"; -BI.DateTimeCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.DateTimeCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.DateTimeCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut("bi.date_time_combo", BI.DateTimeCombo); +} diff --git a/src/widget/datetime/datetime.popup.js b/src/widget/datetime/datetime.popup.js index 7102fbc41..bafe42b11 100644 --- a/src/widget/datetime/datetime.popup.js +++ b/src/widget/datetime/datetime.popup.js @@ -1,113 +1,121 @@ -/** - * Created by Urthur on 2017/7/14. - */ -BI.DateTimePopup = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.DateTimePopup.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, Widget, extend, createWidget, i18nText, isNull, getDate } from "@/core"; +import { TextButton } from "@/base"; +import { DateCalendarPopup } from "../date/calendar"; + +@shortcut() +export class DateTimePopup extends Widget { + static xtype = "bi.date_time_popup" + + static BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE" + static BUTTON_CANCEL_EVENT_CHANGE = "BUTTON_CANCEL_EVENT_CHANGE" + static CALENDAR_EVENT_CHANGE = "CALENDAR_EVENT_CHANGE" + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-date-time-popup", width: 268, - height: 374 + height: 374, }); - }, - _init: function () { - BI.DateTimePopup.superclass._init.apply(this, arguments); - var self = this, opts = this.options; - this.cancelButton = BI.createWidget({ + } + + _init() { + super._init(...arguments); + const opts = this.options; + this.cancelButton = createWidget({ type: "bi.text_button", cls: "multidate-popup-button bi-border-top bi-border-right", shadow: true, - text: BI.i18nText("BI-Basic_Cancel") + text: i18nText("BI-Basic_Cancel"), }); - this.cancelButton.on(BI.TextButton.EVENT_CHANGE, function () { - self.fireEvent(BI.DateTimePopup.BUTTON_CANCEL_EVENT_CHANGE); + this.cancelButton.on(TextButton.EVENT_CHANGE, () => { + this.fireEvent(DateTimePopup.BUTTON_CANCEL_EVENT_CHANGE); }); - this.okButton = BI.createWidget({ + this.okButton = createWidget({ type: "bi.text_button", cls: "multidate-popup-button bi-border-top", shadow: true, - text: BI.i18nText("BI-Basic_OK") + text: i18nText("BI-Basic_OK"), }); - this.okButton.on(BI.TextButton.EVENT_CHANGE, function () { - self.fireEvent(BI.DateTimePopup.BUTTON_OK_EVENT_CHANGE); + this.okButton.on(TextButton.EVENT_CHANGE, () => { + this.fireEvent(DateTimePopup.BUTTON_OK_EVENT_CHANGE); }); - this.dateCombo = BI.createWidget({ + this.dateCombo = createWidget({ type: "bi.date_calendar_popup", behaviors: opts.behaviors, - min: self.options.min, - max: self.options.max + min: this.options.min, + max: this.options.max, }); - self.dateCombo.on(BI.DateCalendarPopup.EVENT_CHANGE, function () { - self.fireEvent(BI.DateTimePopup.CALENDAR_EVENT_CHANGE); + this.dateCombo.on(DateCalendarPopup.EVENT_CHANGE, () => { + this.fireEvent(DateTimePopup.CALENDAR_EVENT_CHANGE); }); - this.dateButton = BI.createWidget({ + this.dateButton = createWidget({ type: "bi.grid", - items: [[this.cancelButton, this.okButton]] + items: [ + [this.cancelButton, this.okButton] + ], }); - BI.createWidget({ + createWidget({ element: this, type: "bi.vtape", items: [{ - el: this.dateCombo + el: this.dateCombo, }, { el: { type: "bi.center_adapt", cls: "bi-split-top", items: [{ type: "bi.dynamic_date_time_select", - ref: function (_ref) { - self.timeSelect = _ref; - } - }] + ref: _ref => { + this.timeSelect = _ref; + }, + }], }, - height: 50 + height: 50, }, { el: this.dateButton, - height: 30 - }] + height: 30, + }], }); this.setValue(opts.value); - }, + } - setValue: function (v) { - var value = v, date; - if (BI.isNull(value)) { - date = BI.getDate(); + setValue(v) { + const value = v; + let date; + if (isNull(value)) { + date = getDate(); this.dateCombo.setValue({ year: date.getFullYear(), month: date.getMonth() + 1, - day: date.getDate() + day: date.getDate(), }); this.timeSelect.setValue({ hour: date.getHours(), minute: date.getMinutes(), - second: date.getSeconds() + second: date.getSeconds(), }); } else { this.dateCombo.setValue({ year: value.year, month: value.month, - day: value.day + day: value.day, }); this.timeSelect.setValue({ hour: value.hour, minute: value.minute, - second: value.second + second: value.second, }); } - }, + } - getValue: function () { - return BI.extend({ + getValue() { + return extend({ year: this.dateCombo.getValue().year, month: this.dateCombo.getValue().month, - day: this.dateCombo.getValue().day + day: this.dateCombo.getValue().day, }, this.timeSelect.getValue()); } -}); -BI.DateTimePopup.BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE"; -BI.DateTimePopup.BUTTON_CANCEL_EVENT_CHANGE = "BUTTON_CANCEL_EVENT_CHANGE"; -BI.DateTimePopup.CALENDAR_EVENT_CHANGE = "CALENDAR_EVENT_CHANGE"; -BI.shortcut("bi.date_time_popup", BI.DateTimePopup); +} diff --git a/src/widget/datetime/datetime.trigger.js b/src/widget/datetime/datetime.trigger.js index d161585e6..c8ea49714 100644 --- a/src/widget/datetime/datetime.trigger.js +++ b/src/widget/datetime/datetime.trigger.js @@ -1,63 +1,75 @@ -/** - * Created by Urthur on 2017/7/14. - */ -BI.DateTimeTrigger = BI.inherit(BI.Trigger, { - _const: { +import { + shortcut, + extend, + createWidget, + isNull, + getDate, + print +} from "@/core"; +import { + Trigger +} from "@/base"; + + +@shortcut() +export class DateTimeTrigger extends Trigger { + static xtype = "bi.date_time_trigger" + + _const = { hgap: 4, - iconWidth:24 - }, + iconWidth: 24, + }; - _defaultConfig: function () { - return BI.extend(BI.DateTimeTrigger.superclass._defaultConfig.apply(this, arguments), { + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-date-time-trigger", min: "1900-01-01", // 最小日期 max: "2099-12-31", // 最大日期 height: 24, - width: 200 + width: 200, }); - }, - _init: function () { - BI.DateTimeTrigger.superclass._init.apply(this, arguments); - var self = this, o = this.options, c = this._const; - this.text = BI.createWidget({ + } + + _init() { + super._init(...arguments); + const o = this.options, + c = this._const; + this.text = createWidget({ type: "bi.label", textAlign: "left", height: o.height, width: o.width, - hgap: c.hgap + hgap: c.hgap, }); - BI.createWidget({ + createWidget({ type: "bi.htape", element: this, items: [{ - el: this.text - },{ - el: BI.createWidget(), - width: this._const.iconWidth - }] + el: this.text, + }, { + el: createWidget(), + width: this._const.iconWidth, + }], }); this.setValue(o.value); - }, - - _printTime: function (v) { - return v < 10 ? "0" + v : v; - }, - - setValue: function (v) { - var self = this; - var value = v, dateStr; - if(BI.isNull(value)) { - value = BI.getDate(); - dateStr = BI.print(value, "%Y-%X-%d %H:%M:%S"); - } else { - var date = BI.getDate(value.year, value.month - 1, value.day, value.hour, value.minute, value.second); - dateStr = BI.print(date, "%Y-%X-%d %H:%M:%S"); + } + + _printTime(v) { + return v < 10 ? `0${v}` : v; + } + setValue(v) { + let value = v, + dateStr; + if (isNull(value)) { + value = getDate(); + dateStr = print(value, "%Y-%X-%d %H:%M:%S"); + } else { + const date = getDate(value.year, value.month - 1, value.day, value.hour, value.minute, value.second); + dateStr = print(date, "%Y-%X-%d %H:%M:%S"); } this.text.setText(dateStr); this.text.setTitle(dateStr); } - -}); -BI.shortcut("bi.date_time_trigger", BI.DateTimeTrigger); +} diff --git a/src/widget/datetime/index.js b/src/widget/datetime/index.js new file mode 100644 index 000000000..3a292c518 --- /dev/null +++ b/src/widget/datetime/index.js @@ -0,0 +1,3 @@ +export { DateTimeCombo } from "./datetime.combo"; +export { DateTimePopup } from "./datetime.popup"; +export { DateTimeTrigger } from "./datetime.trigger"; diff --git a/src/widget/datetimepane/card.static.datetimepane.js b/src/widget/datetimepane/card.static.datetimepane.js index b63b83c9a..910ed91f8 100644 --- a/src/widget/datetimepane/card.static.datetimepane.js +++ b/src/widget/datetimepane/card.static.datetimepane.js @@ -1,205 +1,216 @@ -BI.StaticDateTimePaneCard = BI.inherit(BI.Widget, { - _defaultConfig: function () { - var conf = BI.StaticDateTimePaneCard.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { +import { shortcut, Widget, extend, getDate, createWidget, bind, isNull, each, isNotEmptyString, getMonthDays } from "@/core"; +import { DatePicker, DateCalendarPopup } from "../date/calendar"; +import { Calendar } from "@/case"; +import { Navigation } from "@/base"; +import { DynamicDateTimeSelect } from "../dynamicdatetime/dynamicdatetime.timeselect"; + +@shortcut() +export class StaticDateTimePaneCard extends Widget { + static xtype = "bi.static_date_time_pane_card" + + static EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW" + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { baseCls: "bi-date-time-pane", min: "1900-01-01", // 最小日期 max: "2099-12-31", // 最大日期 - selectedTime: null + selectedTime: null, }); - }, - _init: function () { - BI.StaticDateTimePaneCard.superclass._init.apply(this, arguments); - var self = this, o = this.options; + } + + _init() { + super._init(...arguments); + const o = this.options; - this.today = BI.getDate(); + this.today = getDate(); this._year = this.today.getFullYear(); this._month = this.today.getMonth() + 1; this.selectedTime = o.selectedTime || { year: this._year, - month: this._month + month: this._month, }; - this.datePicker = BI.createWidget({ + this.datePicker = createWidget({ type: "bi.date_picker", behaviors: o.behaviors, min: o.min, - max: o.max + max: o.max, }); - this.datePicker.on(BI.DatePicker.EVENT_CHANGE, function () { - var value = self.datePicker.getValue(); - var monthDay = BI.getMonthDays(BI.getDate(value.year, value.month - 1, 1)); - var day = self.selectedTime.day || 0; + this.datePicker.on(DatePicker.EVENT_CHANGE, () => { + const value = this.datePicker.getValue(); + const monthDay = getMonthDays(getDate(value.year, value.month - 1, 1)); + let day = this.selectedTime.day || 0; if (day > monthDay) { day = monthDay; } - self.selectedTime = BI.extend(self.selectedTime, { + this.selectedTime = extend(this.selectedTime, { year: value.year, - month: value.month + month: value.month, }); - day !== 0 && (self.selectedTime.day = day); - self.calendar.setSelect(BI.Calendar.getPageByDateJSON(self.selectedTime)); - self.calendar.setValue(self.selectedTime); - day !== 0 && self.fireEvent(BI.DateCalendarPopup.EVENT_CHANGE); + day !== 0 && (this.selectedTime.day = day); + this.calendar.setSelect(Calendar.getPageByDateJSON(this.selectedTime)); + this.calendar.setValue(this.selectedTime); + day !== 0 && this.fireEvent(DateCalendarPopup.EVENT_CHANGE); }); - this.datePicker.on(BI.DatePicker.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW, function () { - self.fireEvent(BI.StaticDateTimePaneCard.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); + this.datePicker.on(DatePicker.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW, () => { + this.fireEvent(StaticDateTimePaneCard.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); }); - this.calendar = BI.createWidget({ + this.calendar = createWidget({ direction: "custom", // logic: { // dynamic: false // }, type: "bi.navigation", tab: this.datePicker, - cardCreator: BI.bind(this._createNav, this) + cardCreator: bind(this._createNav, this), }); - this.calendar.on(BI.Navigation.EVENT_CHANGE, function () { - self.selectedTime = BI.extend(self.calendar.getValue(), self.timeSelect.getValue()); - self.calendar.empty(); - self.setValue(self.selectedTime); - self.fireEvent(BI.DateCalendarPopup.EVENT_CHANGE); + this.calendar.on(Navigation.EVENT_CHANGE, () => { + this.selectedTime = extend(this.calendar.getValue(), this.timeSelect.getValue()); + this.calendar.empty(); + this.setValue(this.selectedTime); + this.fireEvent(DateCalendarPopup.EVENT_CHANGE); }); - BI.createWidget({ + createWidget({ type: "bi.vtape", element: this, hgap: 10, items: [{ el: this.datePicker, - height: 40 + height: 40, }, this.calendar, { el: { type: "bi.dynamic_date_time_select", cls: "bi-split-top", - ref: function () { - self.timeSelect = this; + ref: _ref => { + this.timeSelect = _ref; }, listeners: [{ - eventName: BI.DynamicDateTimeSelect.EVENT_CONFIRM, - action: function () { - self.selectedTime = BI.extend(self.calendar.getValue(), self.timeSelect.getValue()); - self.fireEvent("EVENT_CHANGE"); - } - }] + eventName: DynamicDateTimeSelect.EVENT_CONFIRM, + action: () => { + this.selectedTime = extend(this.calendar.getValue(), this.timeSelect.getValue()); + this.fireEvent("EVENT_CHANGE"); + }, + }], }, - height: 40 - }] + height: 40, + }], }); - BI.createWidget({ + createWidget({ type: "bi.absolute", element: this, items: [{ el: { type: "bi.layout", - cls: "bi-split-top" + cls: "bi-split-top", }, height: 1, top: 40, left: 0, - right: 0 - }] + right: 0, + }], }); this.setValue(o.selectedTime); + } - }, - - _createNav: function (v) { - var date = BI.Calendar.getDateJSONByPage(v); - var calendar = BI.createWidget({ + _createNav(v) { + const date = Calendar.getDateJSONByPage(v); + const calendar = createWidget({ type: "bi.calendar", logic: { - dynamic: false + dynamic: false, }, min: this.options.min, max: this.options.max, year: date.year, month: date.month, - day: this.selectedTime.day + day: this.selectedTime.day, }); + return calendar; - }, + } - _getNewCurrentDate: function () { - var today = BI.getDate(); + _getNewCurrentDate() { + const today = getDate(); + return { year: today.getFullYear(), - month: today.getMonth() + 1 + month: today.getMonth() + 1, }; - }, + } - _setCalenderValue: function (date) { - this.calendar.setSelect(BI.Calendar.getPageByDateJSON(date)); + _setCalenderValue(date) { + this.calendar.setSelect(Calendar.getPageByDateJSON(date)); this.calendar.setValue(date); - this.selectedTime = BI.extend({}, this.timeSelect.getValue(), date); - }, + this.selectedTime = extend({}, this.timeSelect.getValue(), date); + } - _setDatePicker: function (timeOb) { - if (BI.isNull(timeOb) || BI.isNull(timeOb.year) || BI.isNull(timeOb.month)) { + _setDatePicker(timeOb) { + if (isNull(timeOb) || isNull(timeOb.year) || isNull(timeOb.month)) { this.datePicker.setValue(this._getNewCurrentDate()); } else { this.datePicker.setValue(timeOb); } - }, + } - _setCalendar: function (timeOb) { - if (BI.isNull(timeOb) || BI.isNull(timeOb.day)) { + _setCalendar(timeOb) { + if (isNull(timeOb) || isNull(timeOb.day)) { this.calendar.empty(); this._setCalenderValue(this._getNewCurrentDate()); } else { this._setCalenderValue(timeOb); } - }, + } - _checkMin: function () { - var o = this.options; - BI.each(this.calendar.getAllCard(), function (idx, calendar) { + _checkMin() { + const o = this.options; + each(this.calendar.getAllCard(), (idx, calendar) => { calendar.setMinDate(o.min); }); - }, + } - _checkMax: function () { - var o = this.options; - BI.each(this.calendar.getAllCard(), function (idx, calendar) { + _checkMax() { + const o = this.options; + each(this.calendar.getAllCard(), (idx, calendar) => { calendar.setMaxDate(o.max); }); - }, + } - setMinDate: function (minDate) { - if (BI.isNotEmptyString(this.options.min)) { + setMinDate(minDate) { + if (isNotEmptyString(this.options.min)) { this.options.min = minDate; this.datePicker.setMinDate(minDate); this._checkMin(); } - }, + } - setMaxDate: function (maxDate) { - if (BI.isNotEmptyString(this.options.max)) { + setMaxDate(maxDate) { + if (isNotEmptyString(this.options.max)) { this.options.max = maxDate; this.datePicker.setMaxDate(maxDate); this._checkMax(); } - }, + } - setValue: function (timeOb) { + setValue(timeOb) { timeOb = timeOb || {}; this._setDatePicker(timeOb); this._setCalendar(timeOb); this.timeSelect.setValue({ hour: timeOb.hour, minute: timeOb.minute, - second: timeOb.second + second: timeOb.second, }); - }, + } - getValue: function () { + getValue() { return this.selectedTime; } - -}); -BI.StaticDateTimePaneCard.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW"; -BI.shortcut("bi.static_date_time_pane_card", BI.StaticDateTimePaneCard); \ No newline at end of file +} diff --git a/src/widget/datetimepane/datetimepane.js b/src/widget/datetimepane/datetimepane.js index aaad8a0dd..f806b0f4d 100644 --- a/src/widget/datetimepane/datetimepane.js +++ b/src/widget/datetimepane/datetimepane.js @@ -1,14 +1,28 @@ -BI.DynamicDateTimePane = BI.inherit(BI.Widget, { +import { shortcut, Widget, createItems, i18nText, isNull, isEmptyObject, isEmptyString, isNotEmptyObject, getDate } from "@/core"; +import { ButtonGroup, TextButton } from "@/base"; +import { DynamicDatePane } from "../datepane"; +import { DynamicDateCombo, DynamicDateHelper } from "../dynamicdate"; - props: { +@shortcut() +export class DynamicDateTimePane extends Widget { + static xtype = "bi.dynamic_date_time_pane" + + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW" + + static Static = 1 + static Dynamic = 2 + + props = { baseCls: "bi-dynamic-date-pane", minDate: "1900-01-01", maxDate: "2099-12-31", supportDynamic: true, - }, + }; - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; + return { type: "bi.vtape", items: [{ @@ -17,198 +31,191 @@ BI.DynamicDateTimePane = BI.inherit(BI.Widget, { invisible: !o.supportDynamic, cls: "bi-split-bottom", height: 30, - items: BI.createItems([{ - text: BI.i18nText("BI-Multi_Date_YMD"), - value: BI.DynamicDateTimePane.Static + items: createItems([{ + text: i18nText("BI-Multi_Date_YMD"), + value: DynamicDateTimePane.Static, }, { - text: BI.i18nText("BI-Basic_Dynamic_Title"), - value: BI.DynamicDateTimePane.Dynamic + text: i18nText("BI-Basic_Dynamic_Title"), + value: DynamicDateTimePane.Dynamic, }], { - textAlign: "center" + textAlign: "center", }), listeners: [{ - eventName: BI.ButtonGroup.EVENT_CHANGE, - action: function () { - var value = this.getValue()[0]; - self.dateTab.setSelect(value); + eventName: ButtonGroup.EVENT_CHANGE, + action: () => { + const value = this.switcher.getValue()[0]; + let date; + this.dateTab.setSelect(value); switch (value) { - case BI.DynamicDateTimePane.Static: - var date = BI.DynamicDateHelper.getCalculation(self.dynamicPane.getValue()); - self.ymd.setValue({ - year: date.getFullYear(), - month: date.getMonth() + 1, - day: date.getDate() - }); - break; - case BI.DynamicDateTimePane.Dynamic: - self.dynamicPane.setValue({ - year: 0 - }); - break; - default: - break; + case DynamicDateTimePane.Static: + date = DynamicDateHelper.getCalculation(this.dynamicPane.getValue()); + this.ymd.setValue({ + year: date.getFullYear(), + month: date.getMonth() + 1, + day: date.getDate(), + }); + break; + case DynamicDateTimePane.Dynamic: + this.dynamicPane.setValue({ + year: 0, + }); + break; + default: + break; } - self.fireEvent(BI.DynamicDateTimePane.EVENT_CHANGE); - } + this.fireEvent(DynamicDateTimePane.EVENT_CHANGE); + }, }], - ref: function () { - self.switcher = this; - } + ref: _ref => { + this.switcher = _ref; + }, }, - height: o.supportDynamic ? 30 : 0 + height: o.supportDynamic ? 30 : 0, }, { type: "bi.tab", - ref: function () { - self.dateTab = this; + ref: _ref => { + this.dateTab = _ref; }, - showIndex: BI.DynamicDateTimePane.Static, - cardCreator: function (v) { + showIndex: DynamicDateTimePane.Static, + cardCreator: v => { switch (v) { - case BI.DynamicDateTimePane.Static: - return { - type: "bi.static_date_time_pane_card", + case DynamicDateTimePane.Static: + return { + type: "bi.static_date_time_pane_card", + min: o.minDate, + max: o.maxDate, + behaviors: o.behaviors, + listeners: [{ + eventName: "EVENT_CHANGE", + action: () => { + this.fireEvent(DynamicDateTimePane.EVENT_CHANGE); + }, + }, { + eventName: "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW", + action: () => { + this.fireEvent(DynamicDateTimePane.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); + }, + }], + ref: _ref => { + this.ymd = _ref; + }, + }; + case DynamicDateTimePane.Dynamic: + default: + return { + type: "bi.vtape", + items: [{ + type: "bi.dynamic_date_card", min: o.minDate, max: o.maxDate, - behaviors: o.behaviors, - listeners: [{ - eventName: "EVENT_CHANGE", - action: function () { - self.fireEvent(BI.DynamicDateTimePane.EVENT_CHANGE); - } - }, { - eventName: "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW", - action: function () { - self.fireEvent(BI.DynamicDateTimePane.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); - } - }], - ref: function () { - self.ymd = this; - } - }; - case BI.DynamicDateTimePane.Dynamic: - default: - return { - type: "bi.vtape", - items: [{ - type: "bi.dynamic_date_card", - min: o.minDate, - max: o.maxDate, - ref: function () { - self.dynamicPane = this; - } - }, { - el: { - type: "bi.center", - items: [{ - type: "bi.text_button", - cls: "bi-high-light bi-border-top", - shadow: true, - text: BI.i18nText("BI-Basic_Clear"), - textHeight: 23, - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - self.setValue(); - self.fireEvent(BI.DynamicDatePane.EVENT_CHANGE); + ref: _ref => { + this.dynamicPane = _ref; + }, + }, { + el: { + type: "bi.center", + items: [{ + type: "bi.text_button", + cls: "bi-high-light bi-border-top", + shadow: true, + text: i18nText("BI-Basic_Clear"), + textHeight: 23, + listeners: [{ + eventName: TextButton.EVENT_CHANGE, + action: () => { + this.setValue(); + this.fireEvent(DynamicDatePane.EVENT_CHANGE); + }, + }], + }, { + type: "bi.text_button", + cls: "bi-border-left bi-high-light bi-border-top", + textHeight: 23, + shadow: true, + text: i18nText("BI-Basic_OK"), + listeners: [{ + eventName: TextButton.EVENT_CHANGE, + action: () => { + const type = this.dateTab.getSelect(); + if (type === DynamicDateCombo.Dynamic) { + this.dynamicPane.checkValidation(true) && this.fireEvent(DynamicDatePane.EVENT_CHANGE); + } else { + this.fireEvent(DynamicDatePane.EVENT_CHANGE); } - }] - }, { - type: "bi.text_button", - cls: "bi-border-left bi-high-light bi-border-top", - textHeight: 23, - shadow: true, - text: BI.i18nText("BI-Basic_OK"), - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - var type = self.dateTab.getSelect(); - if (type === BI.DynamicDateCombo.Dynamic) { - self.dynamicPane.checkValidation(true) && self.fireEvent(BI.DynamicDatePane.EVENT_CHANGE); - } else { - self.fireEvent(BI.DynamicDatePane.EVENT_CHANGE); - } - } - }] - }] - }, - height: 24 - }] - }; + }, + }], + }], + }, + height: 24, + }], + }; } - } - }] + }, + }], }; - }, + } - created: function () { + created() { this.setValue(this.options.value); - }, + } - _checkValueValid: function (value) { - return BI.isNull(value) || BI.isEmptyObject(value) || BI.isEmptyString(value); - }, + _checkValueValid(value) { + return isNull(value) || isEmptyObject(value) || isEmptyString(value); + } - _checkValue: function (v) { + _checkValue(v) { switch (v.type) { - case BI.DynamicDateCombo.Dynamic: - return BI.isNotEmptyObject(v.value); - case BI.DynamicDateCombo.Static: - default: - return true; + case DynamicDateCombo.Dynamic: + return isNotEmptyObject(v.value); + case DynamicDateCombo.Static: + default: + return true; } - }, + } - setMinDate: function (minDate) { + setMinDate(minDate) { if (this.options.minDate !== minDate) { this.options.minDate = minDate; this.ymd.setMinDate(minDate); } - }, + } - setMaxDate: function (maxDate) { + setMaxDate(maxDate) { if (this.options.maxDate !== maxDate) { this.options.maxDate = maxDate; this.ymd.setMaxDate(maxDate); } - }, + } - setValue: function (v) { + setValue(v) { v = v || {}; - var type = v.type || BI.DynamicDateTimePane.Static; - var value = v.value || v; + const type = v.type || DynamicDateTimePane.Static; + const value = v.value || v; this.switcher.setValue(type); this.dateTab.setSelect(type); switch (type) { - case BI.DynamicDateTimePane.Dynamic: - this.dynamicPane.setValue(value); - break; - case BI.DynamicDateTimePane.Static: - default: - if (this._checkValueValid(value)) { - var date = BI.getDate(); - this.ymd.setValue({ - year: date.getFullYear(), - month: date.getMonth() + 1 - }); - } else { - this.ymd.setValue(value); - } - break; + case DynamicDateTimePane.Dynamic: + this.dynamicPane.setValue(value); + break; + case DynamicDateTimePane.Static: + default: + if (this._checkValueValid(value)) { + const date = getDate(); + this.ymd.setValue({ + year: date.getFullYear(), + month: date.getMonth() + 1, + }); + } else { + this.ymd.setValue(value); + } + break; } - }, + } - getValue: function () { + getValue() { return { type: this.dateTab.getSelect(), - value: this.dateTab.getValue() + value: this.dateTab.getValue(), }; } -}); -BI.DynamicDateTimePane.EVENT_CHANGE = "EVENT_CHANGE"; -BI.DynamicDateTimePane.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW"; -BI.shortcut("bi.dynamic_date_time_pane", BI.DynamicDateTimePane); - -BI.extend(BI.DynamicDateTimePane, { - Static: 1, - Dynamic: 2 -}); +} diff --git a/src/widget/datetimepane/index.js b/src/widget/datetimepane/index.js new file mode 100644 index 000000000..f70ff91e9 --- /dev/null +++ b/src/widget/datetimepane/index.js @@ -0,0 +1,2 @@ +export { StaticDateTimePaneCard } from "./card.static.datetimepane"; +export { DynamicDateTimePane } from "./datetimepane"; diff --git a/src/widget/dynamicdate/dynamicdate.caculate.js b/src/widget/dynamicdate/dynamicdate.caculate.js index 665661d9e..e94718d82 100644 --- a/src/widget/dynamicdate/dynamicdate.caculate.js +++ b/src/widget/dynamicdate/dynamicdate.caculate.js @@ -1,117 +1,119 @@ -!(function () { - BI.DynamicDateHelper = {}; - BI.extend(BI.DynamicDateHelper, { - getCalculation: function (obj) { - var date = BI.getDate(); +import { isNotNull, parseInt, getDate, i18nText, size, getOffsetQuarter, getOffsetMonth, getOffsetDate, getLastDateOfMonth, getWeekStartDate, getWeekEndDate, getQuarterStartDate, getQuarterEndDate, print } from "@/core"; +import { DynamicDateCard } from "./dynamicdate.card"; - return this.getCalculationByDate(date, obj); - }, +export const DynamicDateHelper = { + getCalculation (obj) { + const date = getDate(); - getDescription: function (obj) { - var value = ""; - var endText = ""; - if(BI.isNotNull(obj.year)) { - if(BI.parseInt(obj.year) !== 0) { - value += Math.abs(obj.year) + BI.i18nText("BI-Basic_Year") + (obj.year < 0 ? BI.i18nText("BI-Basic_Front") : BI.i18nText("BI-Basic_Behind")); - } - endText = getPositionText(BI.i18nText("BI-Basic_Year"), obj.position); - } - if(BI.isNotNull(obj.quarter)) { - if(BI.parseInt(obj.quarter) !== 0) { - value += Math.abs(obj.quarter) + BI.i18nText("BI-Basic_Single_Quarter") + (obj.quarter < 0 ? BI.i18nText("BI-Basic_Front") : BI.i18nText("BI-Basic_Behind")); - } - endText = getPositionText(BI.i18nText("BI-Basic_Single_Quarter"), obj.position); - } - if(BI.isNotNull(obj.month)) { - if(BI.parseInt(obj.month) !== 0) { - value += Math.abs(obj.month) + BI.i18nText("BI-Basic_Month") + (obj.month < 0 ? BI.i18nText("BI-Basic_Front") : BI.i18nText("BI-Basic_Behind")); - } - endText = getPositionText(BI.i18nText("BI-Basic_Month"), obj.position); + return this.getCalculationByDate(date, obj); + }, + + getDescription (obj) { + let value = ""; + let endText = ""; + if (isNotNull(obj.year)) { + if (parseInt(obj.year) !== 0) { + value += Math.abs(obj.year) + i18nText("BI-Basic_Year") + (obj.year < 0 ? i18nText("BI-Basic_Front") : i18nText("BI-Basic_Behind")); + } + endText = getPositionText(i18nText("BI-Basic_Year"), obj.position); + } + if (isNotNull(obj.quarter)) { + if (parseInt(obj.quarter) !== 0) { + value += Math.abs(obj.quarter) + i18nText("BI-Basic_Single_Quarter") + (obj.quarter < 0 ? i18nText("BI-Basic_Front") : i18nText("BI-Basic_Behind")); } - if(BI.isNotNull(obj.week)) { - if(BI.parseInt(obj.week) !== 0) { - value += Math.abs(obj.week) + BI.i18nText("BI-Basic_Week") + (obj.week < 0 ? BI.i18nText("BI-Basic_Front") : BI.i18nText("BI-Basic_Behind")); - } - endText = getPositionText(BI.i18nText("BI-Basic_Week"), obj.position); + endText = getPositionText(i18nText("BI-Basic_Single_Quarter"), obj.position); + } + if (isNotNull(obj.month)) { + if (parseInt(obj.month) !== 0) { + value += Math.abs(obj.month) + i18nText("BI-Basic_Month") + (obj.month < 0 ? i18nText("BI-Basic_Front") : i18nText("BI-Basic_Behind")); } - if(BI.isNotNull(obj.day)) { - if(BI.parseInt(obj.day) !== 0) { - value += Math.abs(obj.day) + BI.i18nText("BI-Basic_Day") + (obj.day < 0 ? BI.i18nText("BI-Basic_Front") : BI.i18nText("BI-Basic_Behind")); - } - endText = BI.size(obj) === 1 ? getPositionText(BI.i18nText("BI-Basic_Month"), obj.position) : ""; + endText = getPositionText(i18nText("BI-Basic_Month"), obj.position); + } + if (isNotNull(obj.week)) { + if (parseInt(obj.week) !== 0) { + value += Math.abs(obj.week) + i18nText("BI-Basic_Week") + (obj.week < 0 ? i18nText("BI-Basic_Front") : i18nText("BI-Basic_Behind")); } - if(BI.isNotNull(obj.workDay) && BI.parseInt(obj.workDay) !== 0) { - value += Math.abs(obj.workDay) + BI.i18nText("BI-Basic_Work_Day") + (obj.workDay < 0 ? BI.i18nText("BI-Basic_Front") : BI.i18nText("BI-Basic_Behind")); + endText = getPositionText(i18nText("BI-Basic_Week"), obj.position); + } + if (isNotNull(obj.day)) { + if (parseInt(obj.day) !== 0) { + value += Math.abs(obj.day) + i18nText("BI-Basic_Day") + (obj.day < 0 ? i18nText("BI-Basic_Front") : i18nText("BI-Basic_Behind")); } - return value + endText; + endText = size(obj) === 1 ? getPositionText(i18nText("BI-Basic_Month"), obj.position) : ""; + } + if (isNotNull(obj.workDay) && parseInt(obj.workDay) !== 0) { + value += Math.abs(obj.workDay) + i18nText("BI-Basic_Work_Day") + (obj.workDay < 0 ? i18nText("BI-Basic_Front") : i18nText("BI-Basic_Behind")); + } + + return value + endText; - function getPositionText (baseText, position) { - switch (position) { - case BI.DynamicDateCard.OFFSET.BEGIN: - return baseText + BI.i18nText("BI-Basic_Begin_Start"); - case BI.DynamicDateCard.OFFSET.END: - return baseText + BI.i18nText("BI-Basic_End_Stop"); - case BI.DynamicDateCard.OFFSET.CURRENT: - default: - return BI.i18nText("BI-Basic_Current_Day"); - } + function getPositionText (baseText, position) { + switch (position) { + case DynamicDateCard.OFFSET.BEGIN: + return baseText + i18nText("BI-Basic_Begin_Start"); + case DynamicDateCard.OFFSET.END: + return baseText + i18nText("BI-Basic_End_Stop"); + case DynamicDateCard.OFFSET.CURRENT: + default: + return i18nText("BI-Basic_Current_Day"); } - }, + } + }, - getCalculationByDate: function (date, obj) { - if (BI.isNotNull(obj.year)) { - date = BI.getDate((date.getFullYear() + BI.parseInt(obj.year)), date.getMonth(), date.getDate()); - } - if (BI.isNotNull(obj.quarter)) { - date = BI.getOffsetQuarter(date, BI.parseInt(obj.quarter)); - } - if (BI.isNotNull(obj.month)) { - date = BI.getOffsetMonth(date, BI.parseInt(obj.month)); - } - if (BI.isNotNull(obj.week)) { - date = BI.getOffsetDate(date, BI.parseInt(obj.week) * 7); - } - if (BI.isNotNull(obj.day)) { - date = BI.getOffsetDate(date, BI.parseInt(obj.day)); - } - if (BI.isNotNull(obj.workDay)) { - // 配置了节假日就按照节假日计算工作日偏移,否则按正常的天去算 - if(BI.isNotNull(BI.holidays)) { - var count = Math.abs(obj.workDay); - for (var i = 0; i < count; i++) { - date = BI.getOffsetDate(date, obj.workDay < 0 ? -1 : 1); - if(BI.isNotNull(BI.holidays[BI.print(date, "%Y-%X-%d")])) { - i--; - } + getCalculationByDate (date, obj) { + if (isNotNull(obj.year)) { + date = getDate((date.getFullYear() + parseInt(obj.year)), date.getMonth(), date.getDate()); + } + if (isNotNull(obj.quarter)) { + date = getOffsetQuarter(date, parseInt(obj.quarter)); + } + if (isNotNull(obj.month)) { + date = getOffsetMonth(date, parseInt(obj.month)); + } + if (isNotNull(obj.week)) { + date = getOffsetDate(date, parseInt(obj.week) * 7); + } + if (isNotNull(obj.day)) { + date = getOffsetDate(date, parseInt(obj.day)); + } + if (isNotNull(obj.workDay)) { + // 配置了节假日就按照节假日计算工作日偏移,否则按正常的天去算 + if (isNotNull(BI.holidays)) { + const count = Math.abs(obj.workDay); + for (let i = 0; i < count; i++) { + date = getOffsetDate(date, obj.workDay < 0 ? -1 : 1); + if (isNotNull(BI.holidays[print(date, "%Y-%X-%d")])) { + i--; } - } else { - date = BI.getOffsetDate(date, BI.parseInt(obj.workDay)); } + } else { + date = getOffsetDate(date, parseInt(obj.workDay)); } - if (BI.isNotNull(obj.position) && obj.position !== BI.DynamicDateCard.OFFSET.CURRENT) { - date = this.getBeginDate(date, obj); - } + } + if (isNotNull(obj.position) && obj.position !== DynamicDateCard.OFFSET.CURRENT) { + date = this.getBeginDate(date, obj); + } - return BI.getDate(date.getFullYear(), date.getMonth(), date.getDate()); - }, + return getDate(date.getFullYear(), date.getMonth(), date.getDate()); + }, - getBeginDate: function (date, obj) { - if (BI.isNotNull(obj.day)) { - return obj.position === BI.DynamicDateCard.OFFSET.BEGIN ? BI.getDate(date.getFullYear(), date.getMonth(), 1) : BI.getDate(date.getFullYear(), date.getMonth(), (BI.getLastDateOfMonth(date)).getDate()); - } - if (BI.isNotNull(obj.week)) { - return obj.position === BI.DynamicDateCard.OFFSET.BEGIN ? BI.getWeekStartDate(date) : BI.getWeekEndDate(date); - } - if (BI.isNotNull(obj.month)) { - return obj.position === BI.DynamicDateCard.OFFSET.BEGIN ? BI.getDate(date.getFullYear(), date.getMonth(), 1) : BI.getDate(date.getFullYear(), date.getMonth(), (BI.getLastDateOfMonth(date)).getDate()); - } - if (BI.isNotNull(obj.quarter)) { - return obj.position === BI.DynamicDateCard.OFFSET.BEGIN ? BI.getQuarterStartDate(date) : BI.getQuarterEndDate(date); - } - if (BI.isNotNull(obj.year)) { - return obj.position === BI.DynamicDateCard.OFFSET.BEGIN ? BI.getDate(date.getFullYear(), 0, 1) : BI.getDate(date.getFullYear(), 11, 31); - } - return date; + getBeginDate (date, obj) { + if (isNotNull(obj.day)) { + return obj.position === DynamicDateCard.OFFSET.BEGIN ? getDate(date.getFullYear(), date.getMonth(), 1) : getDate(date.getFullYear(), date.getMonth(), (getLastDateOfMonth(date)).getDate()); + } + if (isNotNull(obj.week)) { + return obj.position === DynamicDateCard.OFFSET.BEGIN ? getWeekStartDate(date) : getWeekEndDate(date); + } + if (isNotNull(obj.month)) { + return obj.position === DynamicDateCard.OFFSET.BEGIN ? getDate(date.getFullYear(), date.getMonth(), 1) : getDate(date.getFullYear(), date.getMonth(), (getLastDateOfMonth(date)).getDate()); + } + if (isNotNull(obj.quarter)) { + return obj.position === DynamicDateCard.OFFSET.BEGIN ? getQuarterStartDate(date) : getQuarterEndDate(date); + } + if (isNotNull(obj.year)) { + return obj.position === DynamicDateCard.OFFSET.BEGIN ? getDate(date.getFullYear(), 0, 1) : getDate(date.getFullYear(), 11, 31); } - }); -})(); + + return date; + }, +}; diff --git a/src/widget/dynamicdate/dynamicdate.card.js b/src/widget/dynamicdate/dynamicdate.card.js index ad347e97d..4b0ce2649 100644 --- a/src/widget/dynamicdate/dynamicdate.card.js +++ b/src/widget/dynamicdate/dynamicdate.card.js @@ -1,89 +1,111 @@ -BI.DynamicDateCard = BI.inherit(BI.Widget, { +import { shortcut, Widget, i18nText, createItems, each, isNotNull, map, has, bind, last, extend, checkDateVoid, isNull, isNotEmptyString, parseDateTime, any } from "@/core"; +import { ButtonGroup, Bubbles } from "@/base"; +import { MultiSelectItem } from "@/case"; +import { DynamicDateHelper } from "./dynamicdate.caculate"; - props: { - baseCls: "bi-dynamic-date-card" - }, +@shortcut() +export class DynamicDateCard extends Widget { + static xtype = "bi.dynamic_date_card"; + + static TYPE = { + YEAR: 1, + QUARTER: 2, + MONTH: 3, + WEEK: 4, + DAY: 5, + WORK_DAY: 6, + }; + static OFFSET = { + CURRENT: 1, + BEGIN: 2, + END: 3, + }; - render: function () { - var self = this; - this.position = BI.DynamicDateCard.OFFSET.CURRENT; + props = { + baseCls: "bi-dynamic-date-card", + }; + + render() { + this.position = DynamicDateCard.OFFSET.CURRENT; + return { type: "bi.vertical", items: [{ el: { type: "bi.label", - text: BI.i18nText("BI-Multi_Date_Relative_Current_Time"), + text: i18nText("BI-Multi_Date_Relative_Current_Time"), textAlign: "left", - lgap: 10 + lgap: 10, }, tgap: 10, - bgap: 5 + bgap: 5, }, { type: "bi.button_group", - ref: function () { - self.checkgroup = this; + ref: _ref => { + this.checkgroup = _ref; }, - chooseType: BI.ButtonGroup.CHOOSE_TYPE_MULTI, + chooseType: ButtonGroup.CHOOSE_TYPE_MULTI, lgap: 4, - value: [BI.DynamicDateCard.TYPE.YEAR], - items: BI.createItems([{ - text: BI.i18nText("BI-Basic_Year"), - value: BI.DynamicDateCard.TYPE.YEAR + value: [DynamicDateCard.TYPE.YEAR], + items: createItems([{ + text: i18nText("BI-Basic_Year"), + value: DynamicDateCard.TYPE.YEAR, }, { - text: BI.i18nText("BI-Basic_Single_Quarter"), - value: BI.DynamicDateCard.TYPE.QUARTER + text: i18nText("BI-Basic_Single_Quarter"), + value: DynamicDateCard.TYPE.QUARTER, }, { - text: BI.i18nText("BI-Basic_Month"), - value: BI.DynamicDateCard.TYPE.MONTH + text: i18nText("BI-Basic_Month"), + value: DynamicDateCard.TYPE.MONTH, }, { - text: BI.i18nText("BI-Basic_Week"), - value: BI.DynamicDateCard.TYPE.WEEK + text: i18nText("BI-Basic_Week"), + value: DynamicDateCard.TYPE.WEEK, }, { - text: BI.i18nText("BI-Basic_Day"), - value: BI.DynamicDateCard.TYPE.DAY + text: i18nText("BI-Basic_Day"), + value: DynamicDateCard.TYPE.DAY, }], { type: "bi.multi_select_item", logic: { - dynamic: true + dynamic: true, }, iconWrapperWidth: 26, }), layouts: [{ type: "bi.left", - rgap: 4 + rgap: 4, }], listeners: [{ - eventName: BI.ButtonGroup.EVENT_CHANGE, - action: function () { - var value = self.checkgroup.getValue(); - if(value.length !== 0) { - self.workDayBox.setSelected(false); + eventName: ButtonGroup.EVENT_CHANGE, + action: () => { + const value = this.checkgroup.getValue(); + if (value.length !== 0) { + this.workDayBox.setSelected(false); } - var plainValue = {}; - BI.each(self.resultPane.getAllButtons(), function (idx, button) { - var value = button.getValue(); - if(BI.isNotNull(value.dateType)) { + const plainValue = {}; + each(this.resultPane.getAllButtons(), (idx, button) => { + const value = button.getValue(); + if (isNotNull(value.dateType)) { plainValue[value.dateType] = { value: value.value, - offset: value.offset + offset: value.offset, }; } }); - self.resultPane.populate(self._getParamJson(BI.map(self.checkgroup.getValue(), function (idx, v) { - var obj = { - dateType: v + this.resultPane.populate(this._getParamJson(map(this.checkgroup.getValue(), (idx, v) => { + const obj = { + dateType: v, }; - if(BI.has(plainValue, v)) { + if (has(plainValue, v)) { obj.value = plainValue[v].value; obj.offset = plainValue[v].offset; } + return obj; }))); - self.position = BI.DynamicDateCard.OFFSET.CURRENT; - self.fireEvent("EVENT_CHANGE"); - } - }] + this.position = DynamicDateCard.OFFSET.CURRENT; + this.fireEvent("EVENT_CHANGE"); + }, + }], }, { type: "bi.vertical_adapt", lgap: 2, @@ -91,283 +113,287 @@ BI.DynamicDateCard = BI.inherit(BI.Widget, { el: { type: "bi.multi_select_item", iconWrapperWidth: 26, - ref: function () { - self.workDayBox = this; + ref: _ref => { + this.workDayBox = _ref; }, logic: { - dynamic: true + dynamic: true, }, - text: BI.i18nText("BI-Basic_Work_Day"), - value: BI.DynamicDateCard.TYPE.WORK_DAY, + text: i18nText("BI-Basic_Work_Day"), + value: DynamicDateCard.TYPE.WORK_DAY, listeners: [{ - eventName: BI.MultiSelectItem.EVENT_CHANGE, - action: function () { - if(this.isSelected()) { - self.checkgroup.setValue(); + eventName: MultiSelectItem.EVENT_CHANGE, + action: () => { + if (this.workDayBox.isSelected()) { + this.checkgroup.setValue(); } - self.resultPane.populate(this.isSelected() ? self._getParamJson([{ - dateType: BI.DynamicDateCard.TYPE.WORK_DAY + this.resultPane.populate(this.workDayBox.isSelected() ? this._getParamJson([{ + dateType: DynamicDateCard.TYPE.WORK_DAY, }]) : []); - self.position = BI.DynamicDateCard.OFFSET.CURRENT; - self.fireEvent("EVENT_CHANGE"); - } - }] - } + this.position = DynamicDateCard.OFFSET.CURRENT; + this.fireEvent("EVENT_CHANGE"); + }, + }], + }, }], - ref: function () { - self.workDay = this; - } + ref: _ref => { + this.workDay = _ref; + }, }, { type: "bi.button_group", items: this._getParamJson([{ - dateType: BI.DynamicDateCard.TYPE.YEAR + dateType: DynamicDateCard.TYPE.YEAR, }]), - ref: function () { - self.resultPane = this; + ref: _ref => { + this.resultPane = _ref; }, layouts: [{ type: "bi.vertical", bgap: 10, - hgap: 10 - }] - }] + hgap: 10, + }], + }], }; - }, + } - _getParamJson: function (values, positionValue) { - var self = this, o = this.options; - var items = BI.map(values, function (idx, value) { + _getParamJson(values, positionValue) { + const items = map(values, (idx, value) => { return { el: { type: "bi.dynamic_date_param_item", - validationChecker: BI.bind(self._checkDate, self), + validationChecker: bind(this._checkDate, this), dateType: value.dateType, value: value.value, offset: value.offset, listeners: [{ eventName: "EVENT_CHANGE", - action: function () { - self.fireEvent("EVENT_CHANGE"); - } + action: () => { + this.fireEvent("EVENT_CHANGE"); + }, }, { eventName: "EVENT_INPUT_CHANGE", - action: function () { - BI.Bubbles.hide("dynamic-date-error"); - } - }] + action () { + Bubbles.hide("dynamic-date-error"); + }, + }], }, - tgap: idx === 0 ? 5 : 0 + tgap: idx === 0 ? 5 : 0, }; }); - if(values.length === 1 && values[0].dateType === BI.DynamicDateCard.TYPE.DAY) { - var comboItems = this._getText(BI.DynamicDateCard.TYPE.MONTH); - comboItems[0].text = BI.i18nText("BI-Basic_Empty"); + if (values.length === 1 && values[0].dateType === DynamicDateCard.TYPE.DAY) { + const comboItems = this._getText(DynamicDateCard.TYPE.MONTH); + comboItems[0].text = i18nText("BI-Basic_Empty"); items.push({ type: "bi.text_value_combo", height: BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, items: comboItems, container: null, - value: positionValue || BI.DynamicDateCard.OFFSET.CURRENT, + value: positionValue || DynamicDateCard.OFFSET.CURRENT, + ref: _ref => { + this.textValueCombo = _ref; + }, listeners: [{ eventName: "EVENT_CHANGE", - action: function () { - self.position = this.getValue()[0]; - this.setValue(self.position); - self.fireEvent("EVENT_CHANGE"); - } - }] + action: () => { + this.position = this.textValueCombo.getValue()[0]; + this.textValueCombo.setValue(this.position); + this.fireEvent("EVENT_CHANGE"); + }, + }], }); - }else{ - if(values.length !== 0 && BI.last(values).dateType !== BI.DynamicDateCard.TYPE.DAY && BI.last(values).dateType !== BI.DynamicDateCard.TYPE.WORK_DAY) { + } else { + if (values.length !== 0 && last(values).dateType !== DynamicDateCard.TYPE.DAY && last(values).dateType !== DynamicDateCard.TYPE.WORK_DAY) { items.push({ type: "bi.text_value_combo", height: BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, container: null, - items: this._getText(BI.last(values).dateType), - value: positionValue || BI.DynamicDateCard.OFFSET.CURRENT, + items: this._getText(last(values).dateType), + value: positionValue || DynamicDateCard.OFFSET.CURRENT, + ref: _ref => { + this.textValueCombo = _ref; + }, listeners: [{ eventName: "EVENT_CHANGE", - action: function () { - self.position = this.getValue()[0]; - this.setValue(self.position); - self.fireEvent("EVENT_CHANGE"); - } - }] + action: () => { + this.position = this.textValueCombo.getValue()[0]; + this.textValueCombo.setValue(this.position); + this.fireEvent("EVENT_CHANGE"); + }, + }], }); - } } return items; - }, + } - _checkDate: function (obj) { - var o = this.options; - var date = BI.DynamicDateHelper.getCalculation(BI.extend(this._getValue(), this._digestDateTypeValue(obj))); + _checkDate(obj) { + const o = this.options; + const date = DynamicDateHelper.getCalculation(extend(this._getValue(), this._digestDateTypeValue(obj))); - return !BI.checkDateVoid(date.getFullYear(), date.getMonth() + 1, date.getDate(), o.min, o.max)[0]; - }, + return !checkDateVoid(date.getFullYear(), date.getMonth() + 1, date.getDate(), o.min, o.max)[0]; + } - _getText: function (lastValue) { + _getText(lastValue) { switch (lastValue) { - case BI.DynamicDateCard.TYPE.YEAR: - return [{ - text: BI.i18nText("BI-Basic_Current_Day"), - value: BI.DynamicDateCard.OFFSET.CURRENT - }, { - text: BI.i18nText("BI-Basic_Year_Begin"), - value: BI.DynamicDateCard.OFFSET.BEGIN - }, { - text: BI.i18nText("BI-Basic_Year_End"), - value: BI.DynamicDateCard.OFFSET.END - }]; - case BI.DynamicDateCard.TYPE.QUARTER: - return [{ - text: BI.i18nText("BI-Basic_Current_Day"), - value: BI.DynamicDateCard.OFFSET.CURRENT - }, { - text: BI.i18nText("BI-Basic_Quarter_Begin"), - value: BI.DynamicDateCard.OFFSET.BEGIN - }, { - text: BI.i18nText("BI-Basic_Quarter_End"), - value: BI.DynamicDateCard.OFFSET.END - }]; - case BI.DynamicDateCard.TYPE.MONTH: - return [{ - text: BI.i18nText("BI-Basic_Current_Day"), - value: BI.DynamicDateCard.OFFSET.CURRENT - }, { - text: BI.i18nText("BI-Basic_Month_Begin"), - value: BI.DynamicDateCard.OFFSET.BEGIN - }, { - text: BI.i18nText("BI-Basic_Month_End"), - value: BI.DynamicDateCard.OFFSET.END - }]; - case BI.DynamicDateCard.TYPE.WEEK: - default: - return [{ - text: BI.i18nText("BI-Basic_Current_Day"), - value: BI.DynamicDateCard.OFFSET.CURRENT - }, { - text: BI.i18nText("BI-Basic_Week_Begin"), - value: BI.DynamicDateCard.OFFSET.BEGIN - }, { - text: BI.i18nText("BI-Basic_Week_End"), - value: BI.DynamicDateCard.OFFSET.END - }]; + case DynamicDateCard.TYPE.YEAR: + return [{ + text: i18nText("BI-Basic_Current_Day"), + value: DynamicDateCard.OFFSET.CURRENT, + }, { + text: i18nText("BI-Basic_Year_Begin"), + value: DynamicDateCard.OFFSET.BEGIN, + }, { + text: i18nText("BI-Basic_Year_End"), + value: DynamicDateCard.OFFSET.END, + }]; + case DynamicDateCard.TYPE.QUARTER: + return [{ + text: i18nText("BI-Basic_Current_Day"), + value: DynamicDateCard.OFFSET.CURRENT, + }, { + text: i18nText("BI-Basic_Quarter_Begin"), + value: DynamicDateCard.OFFSET.BEGIN, + }, { + text: i18nText("BI-Basic_Quarter_End"), + value: DynamicDateCard.OFFSET.END, + }]; + case DynamicDateCard.TYPE.MONTH: + return [{ + text: i18nText("BI-Basic_Current_Day"), + value: DynamicDateCard.OFFSET.CURRENT, + }, { + text: i18nText("BI-Basic_Month_Begin"), + value: DynamicDateCard.OFFSET.BEGIN, + }, { + text: i18nText("BI-Basic_Month_End"), + value: DynamicDateCard.OFFSET.END, + }]; + case DynamicDateCard.TYPE.WEEK: + default: + return [{ + text: i18nText("BI-Basic_Current_Day"), + value: DynamicDateCard.OFFSET.CURRENT, + }, { + text: i18nText("BI-Basic_Week_Begin"), + value: DynamicDateCard.OFFSET.BEGIN, + }, { + text: i18nText("BI-Basic_Week_End"), + value: DynamicDateCard.OFFSET.END, + }]; } - }, + } - _createValue: function (type, v) { + _createValue(type, v) { return { dateType: type, value: Math.abs(v), - offset: v > 0 ? 1 : 0 + offset: v > 0 ? 1 : 0, }; - }, + } - _digestDateTypeValue: function (value) { - var valueMap = {}; + _digestDateTypeValue(value) { + const valueMap = {}; switch (value.dateType) { - case BI.DynamicDateCard.TYPE.YEAR: - valueMap.year = (value.offset === 0 ? -value.value : +value.value); - break; - case BI.DynamicDateCard.TYPE.QUARTER: - valueMap.quarter = (value.offset === 0 ? -value.value : +value.value); - break; - case BI.DynamicDateCard.TYPE.MONTH: - valueMap.month = (value.offset === 0 ? -value.value : +value.value); - break; - case BI.DynamicDateCard.TYPE.WEEK: - valueMap.week = (value.offset === 0 ? -value.value : +value.value); - break; - case BI.DynamicDateCard.TYPE.DAY: - valueMap.day = (value.offset === 0 ? -value.value : +value.value); - break; - case BI.DynamicDateCard.TYPE.WORK_DAY: - valueMap.workDay = (value.offset === 0 ? -value.value : +value.value); - break; - default: - break; + case DynamicDateCard.TYPE.YEAR: + valueMap.year = (value.offset === 0 ? -value.value : +value.value); + break; + case DynamicDateCard.TYPE.QUARTER: + valueMap.quarter = (value.offset === 0 ? -value.value : +value.value); + break; + case DynamicDateCard.TYPE.MONTH: + valueMap.month = (value.offset === 0 ? -value.value : +value.value); + break; + case DynamicDateCard.TYPE.WEEK: + valueMap.week = (value.offset === 0 ? -value.value : +value.value); + break; + case DynamicDateCard.TYPE.DAY: + valueMap.day = (value.offset === 0 ? -value.value : +value.value); + break; + case DynamicDateCard.TYPE.WORK_DAY: + valueMap.workDay = (value.offset === 0 ? -value.value : +value.value); + break; + default: + break; } - if (BI.isNull(value.dateType)) { - valueMap.position = this.position || BI.DynamicDateCard.OFFSET.CURRENT; + if (isNull(value.dateType)) { + valueMap.position = this.position || DynamicDateCard.OFFSET.CURRENT; } + return valueMap; - }, + } - setMinDate: function(minDate) { - if (BI.isNotEmptyString(this.options.min)) { + setMinDate(minDate) { + if (isNotEmptyString(this.options.min)) { this.options.min = minDate; } - }, + } - setMaxDate: function (maxDate) { - if (BI.isNotEmptyString(this.options.max)) { + setMaxDate(maxDate) { + if (isNotEmptyString(this.options.max)) { this.options.max = maxDate; } - }, + } - setValue: function (v) { + setValue(v) { v = v || {}; - this.position = v.position || BI.DynamicDateCard.OFFSET.CURRENT; - var values = []; - var valuesItems = []; - if(BI.isNotNull(v.year)) { - values.push(BI.DynamicDateCard.TYPE.YEAR); - valuesItems.push(this._createValue(BI.DynamicDateCard.TYPE.YEAR, v.year)); + this.position = v.position || DynamicDateCard.OFFSET.CURRENT; + const values = []; + const valuesItems = []; + if (isNotNull(v.year)) { + values.push(DynamicDateCard.TYPE.YEAR); + valuesItems.push(this._createValue(DynamicDateCard.TYPE.YEAR, v.year)); } - if(BI.isNotNull(v.quarter)) { - values.push(BI.DynamicDateCard.TYPE.QUARTER); - valuesItems.push(this._createValue(BI.DynamicDateCard.TYPE.QUARTER, v.quarter)); + if (isNotNull(v.quarter)) { + values.push(DynamicDateCard.TYPE.QUARTER); + valuesItems.push(this._createValue(DynamicDateCard.TYPE.QUARTER, v.quarter)); } - if(BI.isNotNull(v.month)) { - values.push(BI.DynamicDateCard.TYPE.MONTH); - valuesItems.push(this._createValue(BI.DynamicDateCard.TYPE.MONTH, v.month)); + if (isNotNull(v.month)) { + values.push(DynamicDateCard.TYPE.MONTH); + valuesItems.push(this._createValue(DynamicDateCard.TYPE.MONTH, v.month)); } - if(BI.isNotNull(v.week)) { - values.push(BI.DynamicDateCard.TYPE.WEEK); - valuesItems.push(this._createValue(BI.DynamicDateCard.TYPE.WEEK, v.week)); + if (isNotNull(v.week)) { + values.push(DynamicDateCard.TYPE.WEEK); + valuesItems.push(this._createValue(DynamicDateCard.TYPE.WEEK, v.week)); } - if(BI.isNotNull(v.day)) { - values.push(BI.DynamicDateCard.TYPE.DAY); - valuesItems.push(this._createValue(BI.DynamicDateCard.TYPE.DAY, v.day)); + if (isNotNull(v.day)) { + values.push(DynamicDateCard.TYPE.DAY); + valuesItems.push(this._createValue(DynamicDateCard.TYPE.DAY, v.day)); } - if(BI.isNotNull(v.workDay)) { - values.push(BI.DynamicDateCard.TYPE.WORK_DAY); - valuesItems.push(this._createValue(BI.DynamicDateCard.TYPE.WORK_DAY, v.workDay)); + if (isNotNull(v.workDay)) { + values.push(DynamicDateCard.TYPE.WORK_DAY); + valuesItems.push(this._createValue(DynamicDateCard.TYPE.WORK_DAY, v.workDay)); } this.checkgroup.setValue(values); - this.workDayBox.setSelected(BI.isNotNull(v.workDay)); + this.workDayBox.setSelected(isNotNull(v.workDay)); this.resultPane.populate(this._getParamJson(valuesItems, v.position)); - }, + } - _getValue: function () { - var self = this; - var valueMap = {}; - var selectValues = this.checkgroup.getValue(); - var buttons = this.resultPane.getAllButtons(); - if(selectValues.length !== 0) { - BI.each(buttons, function (idx, button) { - var value = button.getValue(); - BI.extend(valueMap, self._digestDateTypeValue(value)); + _getValue() { + const valueMap = {}; + const selectValues = this.checkgroup.getValue(); + const buttons = this.resultPane.getAllButtons(); + if (selectValues.length !== 0) { + each(buttons, (idx, button) => { + const value = button.getValue(); + extend(valueMap, this._digestDateTypeValue(value)); }); } - if(this.workDayBox.isSelected()) { - var value = buttons[0].getValue(); + if (this.workDayBox.isSelected()) { + const value = buttons[0].getValue(); valueMap.workDay = (value.offset === 0 ? -value.value : +value.value); } return valueMap; - }, + } - _getErrorText: function () { - var o = this.options; - var start = BI.parseDateTime(o.min, "%Y-%X-%d"); - var end = BI.parseDateTime(o.max, "%Y-%X-%d"); + _getErrorText() { + const o = this.options; + const start = parseDateTime(o.min, "%Y-%X-%d"); + const end = parseDateTime(o.max, "%Y-%X-%d"); - return BI.i18nText("BI-Basic_Date_Range_Error", + return i18nText("BI-Basic_Date_Range_Error", start.getFullYear(), start.getMonth() + 1, start.getDate(), @@ -375,49 +401,28 @@ BI.DynamicDateCard = BI.inherit(BI.Widget, { end.getMonth() + 1, end.getDate() ); - }, + } - getValue: function () { + getValue() { return this.checkValidation() ? this._getValue() : {}; - }, + } - getInputValue: function () { + getInputValue() { return this._getValue(); - }, + } - checkValidation: function (show) { - var buttons = this.resultPane.getAllButtons(); - var errorText; - var invalid = BI.any(buttons, function (idx, button) { - return button.checkValidation && !button.checkValidation(); - }); + checkValidation(show) { + const buttons = this.resultPane.getAllButtons(); + let errorText; + let invalid = any(buttons, (idx, button) => button.checkValidation && !button.checkValidation()); if (invalid) { - errorText = BI.i18nText("BI-Please_Input_Natural_Number"); + errorText = i18nText("BI-Please_Input_Natural_Number"); } else { invalid = !this._checkDate(this._getValue()); errorText = this._getErrorText(); } - invalid && show && BI.Bubbles.show("dynamic-date-error", errorText, this.resultPane); + invalid && show && Bubbles.show("dynamic-date-error", errorText, this.resultPane); return !invalid; - }, - -}); -BI.shortcut("bi.dynamic_date_card", BI.DynamicDateCard); - -BI.extend(BI.DynamicDateCard, { - TYPE: { - YEAR: 1, - QUARTER: 2, - MONTH: 3, - WEEK: 4, - DAY: 5, - WORK_DAY: 6 - }, - OFFSET: { - CURRENT: 1, - BEGIN: 2, - END: 3 } - -}); \ No newline at end of file +} diff --git a/src/widget/dynamicdate/dynamicdate.combo.js b/src/widget/dynamicdate/dynamicdate.combo.js index 3219fb298..7cb7165dc 100644 --- a/src/widget/dynamicdate/dynamicdate.combo.js +++ b/src/widget/dynamicdate/dynamicdate.combo.js @@ -1,13 +1,13 @@ -BI.DynamicDateCombo = BI.inherit(BI.Single, { - constants: { - popupHeight: 259, - popupWidth: 270, - comboAdjustHeight: 1, - border: 1, - iconWidth: 24 - }, +import { shortcut, getDate, toPix, isEqual, isNotEmptyString, isEmptyString, isNotNull, isNotEmptyObject, checkDateVoid } from "@/core"; +import { Single, Combo } from "@/base"; +import { DynamicDateTrigger } from "./dynamicdate.trigger"; +import { DynamicDatePopup } from "./dynamicdate.popup"; - props: { +@shortcut() +export class DynamicDateCombo extends Single { + static xtype = "bi.dynamic_date_combo" + + props = { baseCls: "bi-dynamic-date-combo", height: 24, minDate: "1900-01-01", @@ -16,32 +16,46 @@ BI.DynamicDateCombo = BI.inherit(BI.Single, { allowEdit: true, supportDynamic: true, attributes: { - tabIndex: -1 + tabIndex: -1, }, isNeedAdjustHeight: false, - isNeedAdjustWidth: false - }, + isNeedAdjustWidth: false, + }; + + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" + static EVENT_CONFIRM = "EVENT_CONFIRM" + static EVENT_FOCUS = "EVENT_FOCUS" + static EVENT_BLUR = "EVENT_BLUR" + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_VALID = "EVENT_VALID" + static EVENT_ERROR = "EVENT_ERROR" + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW" + static EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW" + static EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW" - _init: function () { - BI.DynamicDateCombo.superclass._init.apply(this, arguments); - }, + static Static = 1; + static Dynamic = 2; + + _init() { + super._init(...arguments); + } - render: function () { - var self = this, opts = this.options; + render() { + const opts = this.options; this.storeTriggerValue = ""; - var date = BI.getDate(); + const date = getDate(); this.storeValue = opts.value; - var border = opts.simple ? 1 : 2; + const border = opts.simple ? 1 : 2; return { type: "bi.absolute", items: [{ el: { type: "bi.combo", - cls: (opts.simple ? "bi-border-bottom" : "bi-border bi-border-radius") + " bi-focus-shadow", + cls: `${opts.simple ? "bi-border-bottom" : "bi-border bi-border-radius"} bi-focus-shadow`, container: opts.container, - ref: function () { - self.combo = this; + ref: _ref => { + this.combo = _ref; }, toggle: false, isNeedAdjustHeight: opts.isNeedAdjustHeight, @@ -50,16 +64,16 @@ BI.DynamicDateCombo = BI.inherit(BI.Single, { el: { type: "bi.horizontal_fill", columnSize: [this.constants.iconWidth, "fill"], - height: BI.toPix(opts.height, border), + height: toPix(opts.height, border), items: [{ el: { type: "bi.icon_button", cls: "bi-trigger-icon-button date-change-h-font", - width: BI.toPix(opts.height, border), - height: BI.toPix(opts.height, border), - ref: function () { - self.changeIcon = this; - } + width: toPix(opts.height, border), + height: toPix(opts.height, border), + ref: _ref => { + this.changeIcon = _ref; + }, }, }, { type: "bi.dynamic_date_trigger", @@ -69,86 +83,86 @@ BI.DynamicDateCombo = BI.inherit(BI.Single, { format: opts.format, allowEdit: opts.allowEdit, watermark: opts.watermark, - iconWidth: BI.toPix(opts.height, border), - height: BI.toPix(opts.height, border), + iconWidth: toPix(opts.height, border), + height: toPix(opts.height, border), value: opts.value, - ref: function () { - self.trigger = this; + ref: _ref => { + this.trigger = _ref; }, listeners: [{ - eventName: BI.DynamicDateTrigger.EVENT_KEY_DOWN, - action: function () { - if (self.combo.isViewVisible()) { - self.combo.hideView(); + eventName: DynamicDateTrigger.EVENT_KEY_DOWN, + action: (...args) => { + if (this.combo.isViewVisible()) { + this.combo.hideView(); } - self.fireEvent(BI.DynamicDateCombo.EVENT_KEY_DOWN, arguments); - } + this.fireEvent(DynamicDateCombo.EVENT_KEY_DOWN, ...args); + }, }, { - eventName: BI.DynamicDateTrigger.EVENT_STOP, - action: function () { - if (!self.combo.isViewVisible()) { - self.combo.showView(); + eventName: DynamicDateTrigger.EVENT_STOP, + action: () => { + if (!this.combo.isViewVisible()) { + this.combo.showView(); } - } + }, }, { - eventName: BI.DynamicDateTrigger.EVENT_FOCUS, - action: function () { - self.storeTriggerValue = self.trigger.getKey(); - if (!self.combo.isViewVisible()) { - self.combo.showView(); + eventName: DynamicDateTrigger.EVENT_FOCUS, + action: () => { + this.storeTriggerValue = this.trigger.getKey(); + if (!this.combo.isViewVisible()) { + this.combo.showView(); } - self.fireEvent(BI.DynamicDateCombo.EVENT_FOCUS); - } + this.fireEvent(DynamicDateCombo.EVENT_FOCUS); + }, }, { - eventName: BI.DynamicDateTrigger.EVENT_BLUR, - action: function () { - self.fireEvent(BI.DynamicDateCombo.EVENT_BLUR); - } + eventName: DynamicDateTrigger.EVENT_BLUR, + action: () => { + this.fireEvent(DynamicDateCombo.EVENT_BLUR); + }, }, { - eventName: BI.DynamicDateTrigger.EVENT_ERROR, - action: function () { - self.storeValue = { - type: BI.DynamicDateCombo.Static, + eventName: DynamicDateTrigger.EVENT_ERROR, + action: () => { + this.storeValue = { + type: DynamicDateCombo.Static, value: { year: date.getFullYear(), - month: date.getMonth() + 1 - } + month: date.getMonth() + 1, + }, }; - self.combo.element.addClass("error"); - self.fireEvent(BI.DynamicDateCombo.EVENT_ERROR); - } + this.combo.element.addClass("error"); + this.fireEvent(DynamicDateCombo.EVENT_ERROR); + }, }, { - eventName: BI.DynamicDateTrigger.EVENT_VALID, - action: function () { - self.storeValue = self.trigger.getValue(); - self.combo.element.removeClass("error"); - self.fireEvent(BI.DynamicDateCombo.EVENT_VALID); - } + eventName: DynamicDateTrigger.EVENT_VALID, + action: () => { + this.storeValue = this.trigger.getValue(); + this.combo.element.removeClass("error"); + this.fireEvent(DynamicDateCombo.EVENT_VALID); + }, }, { - eventName: BI.DynamicDateTrigger.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.DynamicDateCombo.EVENT_CHANGE); - } + eventName: DynamicDateTrigger.EVENT_CHANGE, + action: () => { + this.fireEvent(DynamicDateCombo.EVENT_CHANGE); + }, }, { - eventName: BI.DynamicDateTrigger.EVENT_CONFIRM, - action: function () { - var dateStore = self.storeTriggerValue; - var dateObj = self.trigger.getKey(); - if (self.combo.isViewVisible() || BI.isEqual(dateObj, dateStore)) { + eventName: DynamicDateTrigger.EVENT_CONFIRM, + action: () => { + const dateStore = this.storeTriggerValue; + const dateObj = this.trigger.getKey(); + if (this.combo.isViewVisible() || isEqual(dateObj, dateStore)) { return; } - if (BI.isNotEmptyString(dateObj) && !BI.isEqual(dateObj, dateStore)) { - self.storeValue = self.trigger.getValue(); - self.setValue(self.trigger.getValue()); - } else if (BI.isEmptyString(dateObj)) { - self.storeValue = null; - self.trigger.setValue(); + if (isNotEmptyString(dateObj) && !isEqual(dateObj, dateStore)) { + this.storeValue = this.trigger.getValue(); + this.setValue(this.trigger.getValue()); + } else if (isEmptyString(dateObj)) { + this.storeValue = null; + this.trigger.setValue(); } - self._checkDynamicValue(self.storeValue); - self.fireEvent(BI.DynamicDateCombo.EVENT_CONFIRM); - } - }] - }] + this._checkDynamicValue(this.storeValue); + this.fireEvent(DynamicDateCombo.EVENT_CONFIRM); + }, + }], + }], }, adjustLength: this.constants.comboAdjustHeight, popup: { @@ -159,54 +173,54 @@ BI.DynamicDateCombo = BI.inherit(BI.Single, { behaviors: opts.behaviors, min: opts.minDate, max: opts.maxDate, - ref: function () { - self.popup = this; + ref: _ref => { + this.popup = _ref; }, listeners: [{ - eventName: BI.DynamicDatePopup.BUTTON_CLEAR_EVENT_CHANGE, - action: function () { - self.setValue(); - self.combo.hideView(); - self.fireEvent(BI.DynamicDateCombo.EVENT_CONFIRM); - } + eventName: DynamicDatePopup.BUTTON_CLEAR_EVENT_CHANGE, + action: () => { + this.setValue(); + this.combo.hideView(); + this.fireEvent(DynamicDateCombo.EVENT_CONFIRM); + }, }, { - eventName: BI.DynamicDatePopup.BUTTON_lABEL_EVENT_CHANGE, - action: function () { - var date = BI.getDate(); - self.setValue({ - type: BI.DynamicDateCombo.Static, + eventName: DynamicDatePopup.BUTTON_lABEL_EVENT_CHANGE, + action: () => { + const date = getDate(); + this.setValue({ + type: DynamicDateCombo.Static, value: { year: date.getFullYear(), month: date.getMonth() + 1, - day: date.getDate() - } + day: date.getDate(), + }, }); - self.combo.hideView(); - self.fireEvent(BI.DynamicDateCombo.EVENT_CONFIRM); - } + this.combo.hideView(); + this.fireEvent(DynamicDateCombo.EVENT_CONFIRM); + }, }, { - eventName: BI.DynamicDatePopup.BUTTON_OK_EVENT_CHANGE, - action: function () { - var value = self.popup.getValue(); - if (self._checkValue(value)) { - self.setValue(value); + eventName: DynamicDatePopup.BUTTON_OK_EVENT_CHANGE, + action: () => { + const value = this.popup.getValue(); + if (this._checkValue(value)) { + this.setValue(value); } - self.combo.hideView(); - self.fireEvent(BI.DynamicDateCombo.EVENT_CONFIRM); - } + this.combo.hideView(); + this.fireEvent(DynamicDateCombo.EVENT_CONFIRM); + }, }, { - eventName: BI.DynamicDatePopup.EVENT_CHANGE, - action: function () { - self.setValue(self.popup.getValue()); - self.combo.hideView(); - self.fireEvent(BI.DynamicDateCombo.EVENT_CONFIRM); - } + eventName: DynamicDatePopup.EVENT_CHANGE, + action: () => { + this.setValue(this.popup.getValue()); + this.combo.hideView(); + this.fireEvent(DynamicDateCombo.EVENT_CONFIRM); + }, }, { - eventName: BI.DynamicDatePopup.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW, - action: function () { - self.fireEvent(BI.DynamicDateCombo.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); - } - }] + eventName: DynamicDatePopup.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW, + action: () => { + this.fireEvent(DynamicDateCombo.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); + }, + }], }, }, // // DEC-4250 和复选下拉一样,点击triggerBtn不默认收起 @@ -214,120 +228,106 @@ BI.DynamicDateCombo = BI.inherit(BI.Single, { // return self.triggerBtn.element.find(e.target).length === 0; // }, listeners: [{ - eventName: BI.Combo.EVENT_BEFORE_POPUPVIEW, - action: function () { - self.popup.setMinDate(opts.minDate); - self.popup.setMaxDate(opts.maxDate); - self.popup.setValue(self.storeValue); - self.fireEvent(BI.DynamicDateCombo.EVENT_BEFORE_POPUPVIEW); - } - }] + eventName: Combo.EVENT_BEFORE_POPUPVIEW, + action: () => { + this.popup.setMinDate(opts.minDate); + this.popup.setMaxDate(opts.maxDate); + this.popup.setValue(this.storeValue); + this.fireEvent(DynamicDateCombo.EVENT_BEFORE_POPUPVIEW); + }, + }], }, top: 0, left: 0, right: 0, - bottom: 0 - }] + bottom: 0, + }], }; - }, + } - created: function () { + created() { this._checkDynamicValue(this.storeValue); - }, + } - _checkDynamicValue: function (v) { - var o = this.options; - var type = null; - if (BI.isNotNull(v)) { + _checkDynamicValue(v) { + let type = null; + if (isNotNull(v)) { type = v.type; } switch (type) { - case BI.DynamicDateCombo.Dynamic: - this.changeIcon.setVisible(true); - // this.comboWrapper.attr("items")[0].width = o.height - this.options.simple ? 1 : 2; - // this.comboWrapper.resize(); - break; - default: - // this.comboWrapper.attr("items")[0].width = 0; - // this.comboWrapper.resize(); - this.changeIcon.setVisible(false); - break; + case DynamicDateCombo.Dynamic: + this.changeIcon.setVisible(true); + // this.comboWrapper.attr("items")[0].width = o.height - this.options.simple ? 1 : 2; + // this.comboWrapper.resize(); + break; + default: + // this.comboWrapper.attr("items")[0].width = 0; + // this.comboWrapper.resize(); + this.changeIcon.setVisible(false); + break; } - }, + } - _checkValue: function (v) { - var o = this.options; + _checkValue(v) { + const o = this.options; + let value; switch (v.type) { - case BI.DynamicDateCombo.Dynamic: - return BI.isNotEmptyObject(v.value); - case BI.DynamicDateCombo.Static: - var value = v.value || {}; + case DynamicDateCombo.Dynamic: + return isNotEmptyObject(v.value); + case DynamicDateCombo.Static: + value = v.value || {}; - return !BI.checkDateVoid(value.year, value.month, value.day, o.minDate, o.maxDate)[0]; - default: - return true; + return !checkDateVoid(value.year, value.month, value.day, o.minDate, o.maxDate)[0]; + default: + return true; } - }, + } - _defaultState: function () { + _defaultState() { - }, + } - setMinDate: function (minDate) { - var o = this.options; + setMinDate(minDate) { + const o = this.options; o.minDate = minDate; this.trigger.setMinDate(minDate); this.popup && this.popup.setMinDate(minDate); - }, + } - setMaxDate: function (maxDate) { - var o = this.options; + setMaxDate(maxDate) { + const o = this.options; o.maxDate = maxDate; this.trigger.setMaxDate(maxDate); this.popup && this.popup.setMaxDate(maxDate); - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v; this.trigger.setValue(v); this._checkDynamicValue(v); - }, - getValue: function () { + } + + getValue() { return this.storeValue; - }, - getKey: function () { + } + + getKey() { return this.trigger.getKey(); - }, - hidePopupView: function () { + } + + hidePopupView() { this.combo.hideView(); - }, + } - focus: function () { + focus() { this.trigger.focus(); - }, + } - blur: function () { + blur() { this.trigger.blur(); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.trigger.setWaterMark(v); } -}); - -BI.DynamicDateCombo.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.DynamicDateCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.DynamicDateCombo.EVENT_FOCUS = "EVENT_FOCUS"; -BI.DynamicDateCombo.EVENT_BLUR = "EVENT_BLUR"; -BI.DynamicDateCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.DynamicDateCombo.EVENT_VALID = "EVENT_VALID"; -BI.DynamicDateCombo.EVENT_ERROR = "EVENT_ERROR"; -BI.DynamicDateCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.DynamicDateCombo.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW"; - -BI.shortcut("bi.dynamic_date_combo", BI.DynamicDateCombo); - -BI.extend(BI.DynamicDateCombo, { - Static: 1, - Dynamic: 2 -}); +} diff --git a/src/widget/dynamicdate/dynamicdate.param.item.js b/src/widget/dynamicdate/dynamicdate.param.item.js index ed8c4dea0..7a2a9691a 100644 --- a/src/widget/dynamicdate/dynamicdate.param.item.js +++ b/src/widget/dynamicdate/dynamicdate.param.item.js @@ -1,130 +1,137 @@ -BI.DynamicDateParamItem = BI.inherit(BI.Widget, { +import { shortcut, Widget, toPix, isNaturalNumber, i18nText } from "@/core"; +import { DynamicDateCard } from "./dynamicdate.card"; +import { SignEditor, TextValueCombo } from "@/case"; - props: function() { +@shortcut() +export class DynamicDateParamItem extends Widget { + static xtype = "bi.dynamic_date_param_item" + + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_INPUT_CHANGE = "EVENT_INPUT_CHANGE" + + props() { return { baseCls: "bi-dynamic-date-param-item", - dateType: BI.DynamicDateCard.TYPE.YEAR, - validationChecker: function() { + dateType: DynamicDateCard.TYPE.YEAR, + validationChecker () { return true; }, value: 0, offset: 0, height: BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, - } - }, + }; + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; + return { type: "bi.htape", items: [{ el: { type: "bi.sign_editor", cls: "bi-border bi-focus-shadow bi-border-radius", - height: BI.toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 2), - validationChecker: function (v) { - return BI.isNaturalNumber(v); + height: toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 2), + validationChecker (v) { + return isNaturalNumber(v); }, value: o.value, - ref: function () { - self.editor = this; + ref: _ref => { + this.editor = _ref; }, - errorText: function () { - return BI.i18nText("BI-Please_Input_Natural_Number"); + errorText () { + return i18nText("BI-Please_Input_Natural_Number"); }, allowBlank: false, listeners: [{ - eventName: BI.SignEditor.EVENT_CONFIRM, - action: function () { - self.fireEvent(BI.DynamicDateParamItem.EVENT_CHANGE); - } + eventName: SignEditor.EVENT_CONFIRM, + action: () => { + this.fireEvent(DynamicDateParamItem.EVENT_CHANGE); + }, }, { - eventName: BI.SignEditor.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.DynamicDateParamItem.EVENT_INPUT_CHANGE); - } - }] + eventName: SignEditor.EVENT_CHANGE, + action: () => { + this.fireEvent(DynamicDateParamItem.EVENT_INPUT_CHANGE); + }, + }], }, - width: 60 + width: 60, }, { el: { type: "bi.label", height: BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, - text: this._getText() + text: this._getText(), }, - width: o.dateType === BI.DynamicDateCard.TYPE.WORK_DAY ? 60 : 20 + width: o.dateType === DynamicDateCard.TYPE.WORK_DAY ? 60 : 20, }, { type: "bi.text_value_combo", height: BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, items: [{ - text: BI.i18nText("BI-Basic_Front"), - value: 0 + text: i18nText("BI-Basic_Front"), + value: 0, }, { - text: BI.i18nText("BI-Basic_Behind"), - value: 1 + text: i18nText("BI-Basic_Behind"), + value: 1, }], - ref: function () { - self.offsetCombo = this; + ref: _ref => { + this.offsetCombo = _ref; }, container: null, value: o.offset, listeners: [{ eventName: BI.TextValueCombo.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.DynamicDateParamItem.EVENT_CHANGE); - } - }] - }] + action: () => { + this.fireEvent(DynamicDateParamItem.EVENT_CHANGE); + }, + }], + }], }; - }, + } - _getText: function () { - var text = ""; + _getText() { + let text = ""; switch (this.options.dateType) { - case BI.DynamicDateCard.TYPE.YEAR: - text = BI.i18nText("BI-Basic_Year"); - break; - case BI.DynamicDateCard.TYPE.QUARTER: - text = BI.i18nText("BI-Basic_Single_Quarter"); - break; - case BI.DynamicDateCard.TYPE.MONTH: - text = BI.i18nText("BI-Basic_Month"); - break; - case BI.DynamicDateCard.TYPE.WEEK: - text = BI.i18nText("BI-Basic_Week"); - break; - case BI.DynamicDateCard.TYPE.DAY: - text = BI.i18nText("BI-Basic_Day"); - break; - case BI.DynamicDateCard.TYPE.WORK_DAY: - default: - text = BI.i18nText("BI-Basic_Work_Day"); - break; + case DynamicDateCard.TYPE.YEAR: + text = i18nText("BI-Basic_Year"); + break; + case DynamicDateCard.TYPE.QUARTER: + text = i18nText("BI-Basic_Single_Quarter"); + break; + case DynamicDateCard.TYPE.MONTH: + text = i18nText("BI-Basic_Month"); + break; + case DynamicDateCard.TYPE.WEEK: + text = i18nText("BI-Basic_Week"); + break; + case DynamicDateCard.TYPE.DAY: + text = i18nText("BI-Basic_Day"); + break; + case DynamicDateCard.TYPE.WORK_DAY: + default: + text = i18nText("BI-Basic_Work_Day"); + break; } + return text; - }, + } - checkValidation: function () { - return BI.isNaturalNumber(this.editor.getValue()); - }, + checkValidation() { + return isNaturalNumber(this.editor.getValue()); + } - setValue: function (v) { + setValue(v) { v = v || {}; v.value = v.value || 0; v.offset = v.offset || 0; this.editor.setValue(v.value); this.offsetCombo.setValue(v.offset); - }, + } - getValue: function () { + getValue() { return { dateType: this.options.dateType, value: this.editor.getValue(), - offset: this.offsetCombo.getValue()[0] + offset: this.offsetCombo.getValue()[0], }; } - -}); -BI.DynamicDateParamItem.EVENT_CHANGE = "EVENT_CHANGE"; -BI.DynamicDateParamItem.EVENT_INPUT_CHANGE = "EVENT_INPUT_CHANGE"; -BI.shortcut("bi.dynamic_date_param_item", BI.DynamicDateParamItem); +} diff --git a/src/widget/dynamicdate/dynamicdate.popup.js b/src/widget/dynamicdate/dynamicdate.popup.js index 1f0967e58..f241f9597 100644 --- a/src/widget/dynamicdate/dynamicdate.popup.js +++ b/src/widget/dynamicdate/dynamicdate.popup.js @@ -1,257 +1,267 @@ -BI.DynamicDatePopup = BI.inherit(BI.Widget, { - constants: { - tabHeight: 40, - }, +import { shortcut, Widget, createWidget, i18nText, toPix, createItems, isNull, isEmptyObject, isEmptyString, getDate, checkDateVoid, print } from "@/core"; +import { DynamicDateCombo } from "./dynamicdate.combo"; +import { TextButton, Tab } from "@/base"; +import { DateCalendarPopup } from "../date/calendar"; +import { DynamicDateHelper } from "./dynamicdate.caculate"; - props: { +@shortcut() +export class DynamicDatePopup extends Widget { + static xtype = "bi.dynamic_date_popup" + + props = { baseCls: "bi-dynamic-date-popup", width: 272, supportDynamic: true, - }, + }; + + static EVENT_CHANGE = "EVENT_CHANGE" + static BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE" + static BUTTON_lABEL_EVENT_CHANGE = "BUTTON_lABEL_EVENT_CHANGE" + static BUTTON_CLEAR_EVENT_CHANGE = "BUTTON_CLEAR_EVENT_CHANGE" + static EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW" - _init: function () { - BI.DynamicDatePopup.superclass._init.apply(this, arguments); - var self = this, opts = this.options, c = this.constants; - this.storeValue = {type: BI.DynamicDateCombo.Static}; - BI.createWidget({ + _init() { + super._init(...arguments); + const opts = this.options; + this.storeValue = { + type: DynamicDateCombo.Static, + }; + createWidget({ element: this, type: "bi.vertical", items: [{ - el: this._getTabJson() + el: this._getTabJson(), }, { el: { type: "bi.grid", - items: [[{ - type: "bi.text_button", - cls: "bi-high-light bi-split-top", - shadow: true, - text: BI.i18nText("BI-Basic_Clear"), - textHeight: BI.toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.DynamicDatePopup.BUTTON_CLEAR_EVENT_CHANGE); - } - }] - }, { - type: "bi.text_button", - cls: "bi-split-left bi-split-right bi-high-light bi-split-top", - shadow: true, - textHeight: BI.toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), - text: BI.i18nText("BI-Multi_Date_Today"), - disabled: this._checkTodayValid(), - ref: function () { - self.todayButton = this; - }, - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.DynamicDatePopup.BUTTON_lABEL_EVENT_CHANGE); - } - }] - }, { - type: "bi.text_button", - cls: "bi-high-light bi-split-top", - textHeight: BI.toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), - shadow: true, - text: BI.i18nText("BI-Basic_OK"), - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - var type = self.dateTab.getSelect(); - if (type === BI.DynamicDateCombo.Dynamic) { - self.dynamicPane.checkValidation(true) && self.fireEvent(BI.DynamicDatePopup.BUTTON_OK_EVENT_CHANGE); - } else { - self.fireEvent(BI.DynamicDatePopup.BUTTON_OK_EVENT_CHANGE); - } - } + items: [ + [{ + type: "bi.text_button", + cls: "bi-high-light bi-split-top", + shadow: true, + text: i18nText("BI-Basic_Clear"), + textHeight: toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), + listeners: [{ + eventName: TextButton.EVENT_CHANGE, + action: () => { + this.fireEvent(DynamicDatePopup.BUTTON_CLEAR_EVENT_CHANGE); + }, + }], + }, { + type: "bi.text_button", + cls: "bi-split-left bi-split-right bi-high-light bi-split-top", + shadow: true, + textHeight: toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), + text: i18nText("BI-Multi_Date_Today"), + disabled: this._checkTodayValid(), + ref: _ref => { + this.todayButton = _ref; + }, + listeners: [{ + eventName: TextButton.EVENT_CHANGE, + action: () => { + this.fireEvent(DynamicDatePopup.BUTTON_lABEL_EVENT_CHANGE); + }, + }], + }, { + type: "bi.text_button", + cls: "bi-high-light bi-split-top", + textHeight: toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), + shadow: true, + text: i18nText("BI-Basic_OK"), + listeners: [{ + eventName: TextButton.EVENT_CHANGE, + action: () => { + const type = this.dateTab.getSelect(); + if (type === DynamicDateCombo.Dynamic) { + this.dynamicPane.checkValidation(true) && this.fireEvent(DynamicDatePopup.BUTTON_OK_EVENT_CHANGE); + } else { + this.fireEvent(DynamicDatePopup.BUTTON_OK_EVENT_CHANGE); + } + }, + }], }] - }]], - height: BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT + ], + height: BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, }, - }] + }], }); this.setValue(opts.value); - }, + } - _getTabJson: function () { - var self = this, o = this.options; + _getTabJson() { + const o = this.options; + return { type: "bi.tab", logic: { - dynamic: true + dynamic: true, }, - ref: function () { - self.dateTab = this; + ref: _ref => { + this.dateTab = _ref; }, tab: { type: "bi.linear_segment", invisible: !o.supportDynamic, cls: "bi-split-bottom", height: this.constants.tabHeight, - items: BI.createItems([{ - text: BI.i18nText("BI-Multi_Date_YMD"), - value: BI.DynamicDateCombo.Static + items: createItems([{ + text: i18nText("BI-Multi_Date_YMD"), + value: DynamicDateCombo.Static, }, { - text: BI.i18nText("BI-Basic_Dynamic_Title"), - value: BI.DynamicDateCombo.Dynamic + text: i18nText("BI-Basic_Dynamic_Title"), + value: DynamicDateCombo.Dynamic, }], { - textAlign: "center" - }) + textAlign: "center", + }), }, - cardCreator: function (v) { + cardCreator: v => { switch (v) { - case BI.DynamicDateCombo.Dynamic: - return { - type: "bi.dynamic_date_card", - cls: "dynamic-date-pane", - listeners: [{ - eventName: "EVENT_CHANGE", - action: function () { - self._setInnerValue(self.year, v); - } - }], - min: self.options.min, - max: self.options.max, - ref: function () { - self.dynamicPane = this; - } - }; - case BI.DynamicDateCombo.Static: - default: - return { - type: "bi.date_calendar_popup", - behaviors: o.behaviors, - min: self.options.min, - max: self.options.max, - listeners: [{ - eventName: BI.DateCalendarPopup.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.DynamicDatePopup.EVENT_CHANGE); - } - }, { - eventName: BI.DateCalendarPopup.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW, - action: function () { - self.fireEvent(BI.DynamicDatePopup.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); - } - }], - ref: function () { - self.ymd = this; - } - }; + case DynamicDateCombo.Dynamic: + return { + type: "bi.dynamic_date_card", + cls: "dynamic-date-pane", + listeners: [{ + eventName: "EVENT_CHANGE", + action: () => { + this._setInnerValue(this.year, v); + }, + }], + min: this.options.min, + max: this.options.max, + ref: _ref => { + this.dynamicPane = _ref; + }, + }; + case DynamicDateCombo.Static: + default: + return { + type: "bi.date_calendar_popup", + behaviors: o.behaviors, + min: this.options.min, + max: this.options.max, + listeners: [{ + eventName: DateCalendarPopup.EVENT_CHANGE, + action: () => { + this.fireEvent(DynamicDatePopup.EVENT_CHANGE); + }, + }, { + eventName: DateCalendarPopup.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW, + action: () => { + this.fireEvent(DynamicDatePopup.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); + }, + }], + ref: _ref => { + this.ymd = _ref; + }, + }; } }, listeners: [{ - eventName: BI.Tab.EVENT_CHANGE, - action: function () { - var v = self.dateTab.getSelect(); + eventName: Tab.EVENT_CHANGE, + action: () => { + const v = this.dateTab.getSelect(); + let date; switch (v) { - case BI.DynamicDateCombo.Static: - var date = BI.DynamicDateHelper.getCalculation(self.dynamicPane.getValue()); - self.ymd.setValue({ - year: date.getFullYear(), - month: date.getMonth() + 1, - day: date.getDate() + case DynamicDateCombo.Static: + date = DynamicDateHelper.getCalculation(this.dynamicPane.getValue()); + this.ymd.setValue({ + year: date.getFullYear(), + month: date.getMonth() + 1, + day: date.getDate(), + }); + this._setInnerValue(); + break; + case DynamicDateCombo.Dynamic: + default: + if (this.storeValue && this.storeValue.type === DynamicDateCombo.Dynamic) { + this.dynamicPane.setValue(this.storeValue.value); + } else { + this.dynamicPane.setValue({ + year: 0, }); - self._setInnerValue(); - break; - case BI.DynamicDateCombo.Dynamic: - default: - if(self.storeValue && self.storeValue.type === BI.DynamicDateCombo.Dynamic) { - self.dynamicPane.setValue(self.storeValue.value); - }else{ - self.dynamicPane.setValue({ - year: 0 - }); - } - self._setInnerValue(); - break; + } + this._setInnerValue(); + break; } - } - }] + }, + }], }; - }, + } - _setInnerValue: function () { - if (this.dateTab.getSelect() === BI.DynamicDateCombo.Static) { - this.todayButton.setValue(BI.i18nText("BI-Multi_Date_Today")); + _setInnerValue() { + if (this.dateTab.getSelect() === DynamicDateCombo.Static) { + this.todayButton.setValue(i18nText("BI-Multi_Date_Today")); this.todayButton.setEnable(!this._checkTodayValid()); } else { - var date = BI.DynamicDateHelper.getCalculation(this.dynamicPane.getInputValue()); - date = BI.print(date, "%Y-%X-%d"); + let date = DynamicDateHelper.getCalculation(this.dynamicPane.getInputValue()); + date = print(date, "%Y-%X-%d"); this.todayButton.setValue(date); this.todayButton.setEnable(false); } - }, + } - _checkValueValid: function (value) { - return BI.isNull(value) || BI.isEmptyObject(value) || BI.isEmptyString(value); - }, + _checkValueValid(value) { + return isNull(value) || isEmptyObject(value) || isEmptyString(value); + } - _checkTodayValid: function () { - var o = this.options; - var today = BI.getDate(); - return !!BI.checkDateVoid(today.getFullYear(), today.getMonth() + 1, today.getDate(), o.min, o.max)[0]; - }, + _checkTodayValid() { + const o = this.options; + const today = getDate(); + + return !!checkDateVoid(today.getFullYear(), today.getMonth() + 1, today.getDate(), o.min, o.max)[0]; + } - setMinDate: function (minDate) { + setMinDate(minDate) { if (this.options.min !== minDate) { this.options.min = minDate; this.ymd && this.ymd.setMinDate(minDate); this.dynamicPane && this.dynamicPane.setMinDate(minDate); } - }, + } - setMaxDate: function (maxDate) { + setMaxDate(maxDate) { if (this.options.max !== maxDate) { this.options.max = maxDate; this.ymd && this.ymd.setMaxDate(maxDate); this.dynamicPane && this.dynamicPane.setMaxDate(maxDate); } - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v; - var self = this; - var type, value; v = v || {}; - type = v.type || BI.DynamicDateCombo.Static; - value = v.value || v; + const type = v.type || DynamicDateCombo.Static; + const value = v.value || v; this.dateTab.setSelect(type); switch (type) { - case BI.DynamicDateCombo.Dynamic: - this.dynamicPane.setValue(value); - self._setInnerValue(); - break; - case BI.DynamicDateCombo.Static: - default: - if (this._checkValueValid(value)) { - var date = BI.getDate(); - this.ymd.setValue({ - year: date.getFullYear(), - month: date.getMonth() + 1, - day: date.getDate() - }); - this.todayButton.setValue(BI.i18nText("BI-Multi_Date_Today")); - } else { - this.ymd.setValue(value); - this.todayButton.setValue(BI.i18nText("BI-Multi_Date_Today")); - } - this.todayButton.setEnable(!this._checkTodayValid()); - break; + case DynamicDateCombo.Dynamic: + this.dynamicPane.setValue(value); + this._setInnerValue(); + break; + case DynamicDateCombo.Static: + default: + if (this._checkValueValid(value)) { + const date = getDate(); + this.ymd.setValue({ + year: date.getFullYear(), + month: date.getMonth() + 1, + day: date.getDate(), + }); + this.todayButton.setValue(i18nText("BI-Multi_Date_Today")); + } else { + this.ymd.setValue(value); + this.todayButton.setValue(i18nText("BI-Multi_Date_Today")); + } + this.todayButton.setEnable(!this._checkTodayValid()); + break; } - }, + } - getValue: function () { + getValue() { return { type: this.dateTab.getSelect(), - value: this.dateTab.getValue() + value: this.dateTab.getValue(), }; } -}); -BI.DynamicDatePopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.DynamicDatePopup.BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE"; -BI.DynamicDatePopup.BUTTON_lABEL_EVENT_CHANGE = "BUTTON_lABEL_EVENT_CHANGE"; -BI.DynamicDatePopup.BUTTON_CLEAR_EVENT_CHANGE = "BUTTON_CLEAR_EVENT_CHANGE"; -BI.DynamicDatePopup.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW"; -BI.shortcut("bi.dynamic_date_popup", BI.DynamicDatePopup); \ No newline at end of file +} diff --git a/src/widget/dynamicdate/dynamicdate.trigger.js b/src/widget/dynamicdate/dynamicdate.trigger.js index 9ecaa3cd9..8e24b81d5 100644 --- a/src/widget/dynamicdate/dynamicdate.trigger.js +++ b/src/widget/dynamicdate/dynamicdate.trigger.js @@ -1,59 +1,84 @@ -BI.DynamicDateTrigger = BI.inherit(BI.Trigger, { - _const: { +import { shortcut, i18nText, createWidget, isKey, checkDateLegal, parseDateTime, bind, isNotNull, isNotEmptyString, isEqual, isEmptyObject, getDate, isEmptyString, isNull, each, checkDateVoid, print } from "@/core"; +import { Trigger } from "@/base"; +import { SignEditor } from "@/case"; +import { DynamicDateCombo } from "./dynamicdate.combo"; +import { DynamicDateHelper } from "./dynamicdate.caculate"; + + +@shortcut() +export class DynamicDateTrigger extends Trigger { + static xtype = "bi.dynamic_date_trigger" + + _const = { hgap: 4, vgap: 2, yearLength: 4, yearMonthLength: 6, yearFullMonthLength: 7, compareFormat: "%Y-%X-%d", - iconWidth: 24 - }, - - props: () => ({ - extraCls: "bi-date-trigger", - min: "1900-01-01", // 最小日期 - max: "2099-12-31", // 最大日期 - height: 24, iconWidth: 24, - format: "", // 显示的日期格式化方式 - allowEdit: true, // 是否允许编辑 - watermark: BI.i18nText("BI-Basic_Unrestricted"), - }), + }; + + static EVENT_BLUR = "EVENT_BLUR" + static EVENT_FOCUS = "EVENT_FOCUS" + static EVENT_START = "EVENT_START" + static EVENT_STOP = "EVENT_STOP" + static EVENT_CONFIRM = "EVENT_CONFIRM" + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_VALID = "EVENT_VALID" + static EVENT_ERROR = "EVENT_ERROR" + static EVENT_TRIGGER_CLICK = "EVENT_TRIGGER_CLICK" + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" + + props() { + return { + extraCls: "bi-date-trigger", + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 + height: 24, + iconWidth: 24, + format: "", // 显示的日期格式化方式 + allowEdit: true, // 是否允许编辑 + watermark: i18nText("BI-Basic_Unrestricted"), + }; + } - _init: function () { - BI.DynamicDateTrigger.superclass._init.apply(this, arguments); - var self = this, o = this.options, c = this._const; + _init() { + super._init(...arguments); + const o = this.options, + c = this._const; this.storeTriggerValue = ""; - this.editor = BI.createWidget({ + this.editor = createWidget({ type: "bi.sign_editor", simple: o.simple, height: o.height, - validationChecker: function (v) { - var formatStr = self._getStandardDateStr(v); - var date = formatStr.match(/\d+/g); - !BI.isKey(o.format) && self._autoAppend(v, date); - return self._dateCheck(formatStr) && BI.checkDateLegal(formatStr) && self._checkVoid({ + validationChecker: v => { + const formatStr = this._getStandardDateStr(v); + const date = formatStr.match(/\d+/g); + !isKey(o.format) && this._autoAppend(v, date); + + return this._dateCheck(formatStr) && checkDateLegal(formatStr) && this._checkVoid({ year: date[0] | 0, month: date[1] | 0, - day: date[2] | 0 + day: date[2] | 0, }); }, - quitChecker: function () { + quitChecker () { return false; }, hgap: c.hgap, vgap: c.vgap, allowBlank: true, watermark: o.watermark, - errorText: function (v) { - var str = ""; - if (!BI.isKey(o.format)) { - if (!self._dateCheck(v)) { - str = self.editor.isEditing() ? BI.i18nText("BI-Date_Trigger_Error_Text") : BI.i18nText("BI-Year_Trigger_Invalid_Text"); + errorText: v => { + let str = ""; + if (!isKey(o.format)) { + if (!this._dateCheck(v)) { + str = this.editor.isEditing() ? i18nText("BI-Date_Trigger_Error_Text") : i18nText("BI-Year_Trigger_Invalid_Text"); } else { - var start = BI.parseDateTime(o.min, "%Y-%X-%d"); - var end = BI.parseDateTime(o.max, "%Y-%X-%d"); - str = BI.i18nText("BI-Basic_Date_Range_Error", + const start = parseDateTime(o.min, "%Y-%X-%d"); + const end = parseDateTime(o.max, "%Y-%X-%d"); + str = i18nText("BI-Basic_Date_Range_Error", start.getFullYear(), start.getMonth() + 1, start.getDate(), @@ -66,276 +91,274 @@ BI.DynamicDateTrigger = BI.inherit(BI.Trigger, { return str; }, - title: BI.bind(this._getTitle, this) + title: bind(this._getTitle, this), }); - this.editor.on(BI.SignEditor.EVENT_KEY_DOWN, function () { - self.fireEvent(BI.DynamicDateTrigger.EVENT_KEY_DOWN, arguments); + this.editor.on(SignEditor.EVENT_KEY_DOWN, (...args) => { + this.fireEvent(DynamicDateTrigger.EVENT_KEY_DOWN, ...args); }); - this.editor.on(BI.SignEditor.EVENT_FOCUS, function () { - self.storeTriggerValue = self.getKey(); - self.fireEvent(BI.DynamicDateTrigger.EVENT_FOCUS); + this.editor.on(SignEditor.EVENT_FOCUS, () => { + this.storeTriggerValue = this.getKey(); + this.fireEvent(DynamicDateTrigger.EVENT_FOCUS); }); - this.editor.on(BI.SignEditor.EVENT_BLUR, function () { - self.fireEvent(BI.DynamicDateTrigger.EVENT_BLUR); + this.editor.on(SignEditor.EVENT_BLUR, () => { + this.fireEvent(DynamicDateTrigger.EVENT_BLUR); }); - this.editor.on(BI.SignEditor.EVENT_STOP, function () { - self.fireEvent(BI.DynamicDateTrigger.EVENT_STOP); + this.editor.on(SignEditor.EVENT_STOP, () => { + this.fireEvent(DynamicDateTrigger.EVENT_STOP); }); - this.editor.on(BI.SignEditor.EVENT_VALID, function () { - self.fireEvent(BI.DynamicDateTrigger.EVENT_VALID); + this.editor.on(SignEditor.EVENT_VALID, () => { + this.fireEvent(DynamicDateTrigger.EVENT_VALID); }); - this.editor.on(BI.SignEditor.EVENT_ERROR, function () { - self.fireEvent(BI.DynamicDateTrigger.EVENT_ERROR); + this.editor.on(SignEditor.EVENT_ERROR, () => { + this.fireEvent(DynamicDateTrigger.EVENT_ERROR); }); - this.editor.on(BI.SignEditor.EVENT_CONFIRM, function () { - var value = self.editor.getValue(); - if (BI.isNotNull(value)) { - self.editor.setState(value); + this.editor.on(SignEditor.EVENT_CONFIRM, () => { + const value = this.editor.getValue(); + if (isNotNull(value)) { + this.editor.setState(value); } - if (BI.isNotEmptyString(value) && !BI.isEqual(self.storeTriggerValue, self.getKey())) { - var formatStr = self._getStandardDateStr(value); - var date = formatStr.match(/\d+/g); - self.storeValue = { - type: BI.DynamicDateCombo.Static, + if (isNotEmptyString(value) && !isEqual(this.storeTriggerValue, this.getKey())) { + const formatStr = this._getStandardDateStr(value); + const date = formatStr.match(/\d+/g); + this.storeValue = { + type: DynamicDateCombo.Static, value: { year: date[0] | 0, month: date[1] | 0, - day: date[2] | 0 - } + day: date[2] | 0, + }, }; } - self.fireEvent(BI.DynamicDateTrigger.EVENT_CONFIRM); + this.fireEvent(DynamicDateTrigger.EVENT_CONFIRM); }); - this.editor.on(BI.SignEditor.EVENT_SPACE, function () { - if (self.editor.isValid()) { - self.editor.blur(); + this.editor.on(SignEditor.EVENT_SPACE, () => { + if (this.editor.isValid()) { + this.editor.blur(); } }); - this.editor.on(BI.SignEditor.EVENT_START, function () { - self.fireEvent(BI.DynamicDateTrigger.EVENT_START); + this.editor.on(SignEditor.EVENT_START, () => { + this.fireEvent(DynamicDateTrigger.EVENT_START); }); - this.editor.on(BI.SignEditor.EVENT_CHANGE, function () { - self.fireEvent(BI.DynamicDateTrigger.EVENT_CHANGE); + this.editor.on(SignEditor.EVENT_CHANGE, () => { + this.fireEvent(DynamicDateTrigger.EVENT_CHANGE); }); - BI.createWidget({ + createWidget({ type: "bi.htape", element: this, columnSize: ["", this._const.iconWidth], items: [{ - el: this.editor + el: this.editor, }, { el: { type: "bi.icon_button", cls: "bi-trigger-icon-button date-font", - width: this._const.iconWidth + width: this._const.iconWidth, }, - width: this._const.iconWidth - }] + width: this._const.iconWidth, + }], }); - !o.allowEdit && BI.createWidget({ + !o.allowEdit && createWidget({ type: "bi.absolute", element: this, items: [{ el: { type: "bi.text", - title: BI.bind(this._getTitle, this) + title: bind(this._getTitle, this), }, left: 0, right: o.iconWidth, top: 0, - bottom: 0 - }] + bottom: 0, + }], }); this.setValue(o.value); - }, + } - _getTitle: function () { - var storeValue = this.storeValue || {}; - if (BI.isEmptyObject(storeValue)) { + _getTitle() { + const storeValue = this.storeValue || {}; + if (isEmptyObject(storeValue)) { return this.options.watermark; } - var type = storeValue.type || BI.DynamicDateCombo.Static; - var value = storeValue.value; + const type = storeValue.type || DynamicDateCombo.Static; + const value = storeValue.value; + let text, date, dateStr; switch (type) { - case BI.DynamicDateCombo.Dynamic: - var text = this._getText(value); - var date = BI.getDate(); - date = BI.DynamicDateHelper.getCalculation(value); - var dateStr = BI.print(date, this._getFormatString()); - return BI.isEmptyString(text) ? dateStr : (text + ":" + dateStr); - case BI.DynamicDateCombo.Static: - default: - if (BI.isNull(value) || BI.isNull(value.day)) { - return ""; - } - return BI.print(BI.getDate(value.year, (value.month - 1), value.day), this._getFormatString()); + case DynamicDateCombo.Dynamic: + text = this._getText(value); + date = getDate(); + date = DynamicDateHelper.getCalculation(value); + dateStr = print(date, this._getFormatString()); + + return isEmptyString(text) ? dateStr : (`${text}:${dateStr}`); + case DynamicDateCombo.Static: + default: + if (isNull(value) || isNull(value.day)) { + return ""; + } + + return print(getDate(value.year, (value.month - 1), value.day), this._getFormatString()); } - }, + } - _getStandardDateStr: function (v) { - var c = this._const; - var result = [0, 1, 2]; - var formatArray = this._getFormatString().match(/%./g); - BI.each(formatArray, function (idx, v) { + _getStandardDateStr(v) { + const c = this._const; + let result = [0, 1, 2]; + const formatArray = this._getFormatString().match(/%./g); + each(formatArray, (idx, v) => { switch (v) { - case "%Y": - case "%y": - result[0] = idx; - break; - case "%X": - case "%x": - result[1] = idx; - break; - case "%d": - case "%e": - default: - result[2] = idx; - break; + case "%Y": + case "%y": + result[0] = idx; + break; + case "%X": + case "%x": + result[1] = idx; + break; + case "%d": + case "%e": + default: + result[2] = idx; + break; } }); // 这边不能直接用\d+去切日期, 因为format格式可能是20190607这样的没有分割符的 = = // 先看一下是否是合法的, 如果合法就变成标准格式的走原来的流程, 不合法不关心 - var date = BI.parseDateTime(v, this._getFormatString()); - if(BI.print(date, this._getFormatString()) === v) { - v = BI.print(date, c.compareFormat); + const date = parseDateTime(v, this._getFormatString()); + if (print(date, this._getFormatString()) === v) { + v = print(date, c.compareFormat); result = [0, 1, 2]; } - var dateArray = v.match(/\d+/g); - var newArray = []; - BI.each(dateArray, function (idx) { + const dateArray = v.match(/\d+/g); + const newArray = []; + each(dateArray, idx => { newArray[idx] = dateArray[result[idx]]; }); // 这边之所以不直接返回join结果是因为年的格式可能只有2位,所以需要format一下 - if(newArray.length === result.length && newArray[0].length === 2) { - return BI.print(BI.parseDateTime(newArray.join("-"), c.compareFormat), c.compareFormat); + if (newArray.length === result.length && newArray[0].length === 2) { + return print(parseDateTime(newArray.join("-"), c.compareFormat), c.compareFormat); } + // 这边format成-20-也没关系, 反正都是不合法的 return newArray.join("-"); - }, + } - _getFormatString: function () { + _getFormatString() { return this.options.format || this._const.compareFormat; - }, + } + + _dateCheck(date) { + return print(parseDateTime(date, "%Y-%x-%d"), "%Y-%x-%d") === date || + print(parseDateTime(date, "%Y-%X-%d"), "%Y-%X-%d") === date || + print(parseDateTime(date, "%Y-%x-%e"), "%Y-%x-%e") === date || + print(parseDateTime(date, "%Y-%X-%e"), "%Y-%X-%e") === date; + } - _dateCheck: function (date) { - return BI.print(BI.parseDateTime(date, "%Y-%x-%d"), "%Y-%x-%d") === date || - BI.print(BI.parseDateTime(date, "%Y-%X-%d"), "%Y-%X-%d") === date || - BI.print(BI.parseDateTime(date, "%Y-%x-%e"), "%Y-%x-%e") === date || - BI.print(BI.parseDateTime(date, "%Y-%X-%e"), "%Y-%X-%e") === date; - }, - _checkVoid: function (obj) { - return !BI.checkDateVoid(obj.year, obj.month, obj.day, this.options.min, this.options.max)[0]; - }, - _autoAppend: function (v, dateObj) { - if (BI.isNotNull(dateObj) && BI.checkDateLegal(v)) { + _checkVoid(obj) { + return !checkDateVoid(obj.year, obj.month, obj.day, this.options.min, this.options.max)[0]; + } + + _autoAppend(v, dateObj) { + const splitMonth = v.split("-")[1]; + if (isNotNull(dateObj) && checkDateLegal(v)) { switch (v.length) { - case this._const.yearLength: - if (this._yearCheck(v)) { - this.editor.setValue(v + "-"); - } - break; - case this._const.yearMonthLength: - case this._const.yearFullMonthLength: - var splitMonth = v.split("-")[1]; - if ((BI.isNotNull(splitMonth) && splitMonth.length === 2) || this._monthCheck(v)) { - this.editor.setValue(v + "-"); - } - break; + case this._const.yearLength: + if (this._yearCheck(v)) { + this.editor.setValue(`${v}-`); + } + break; + case this._const.yearMonthLength: + case this._const.yearFullMonthLength: + if ((isNotNull(splitMonth) && splitMonth.length === 2) || this._monthCheck(v)) { + this.editor.setValue(`${v}-`); + } + break; + default: } } - }, + } - _yearCheck: function (v) { - var date = BI.print(BI.parseDateTime(v, this._getFormatString()), this._const.compareFormat); - return BI.print(BI.parseDateTime(v, "%Y"), "%Y") === v && date >= this.options.min && date <= this.options.max; - }, + _yearCheck(v) { + const date = print(parseDateTime(v, this._getFormatString()), this._const.compareFormat); + + return print(parseDateTime(v, "%Y"), "%Y") === v && date >= this.options.min && date <= this.options.max; + } - _monthCheck: function (v) { - var date = BI.parseDateTime(v, this._getFormatString()); - var dateStr = BI.print(date, this._const.compareFormat); - return (date.getMonth() >= 0 && (BI.print(BI.parseDateTime(v, "%Y-%X"), "%Y-%X") === v || - BI.print(BI.parseDateTime(v, "%Y-%x"), "%Y-%x") === v)) && dateStr >= this.options.min && dateStr <= this.options.max; - }, + _monthCheck(v) { + const date = parseDateTime(v, this._getFormatString()); + const dateStr = print(date, this._const.compareFormat); + + return (date.getMonth() >= 0 && (print(parseDateTime(v, "%Y-%X"), "%Y-%X") === v || + print(parseDateTime(v, "%Y-%x"), "%Y-%x") === v)) && dateStr >= this.options.min && dateStr <= this.options.max; + } - _setInnerValue: function (date) { - var dateStr = BI.print(date, this._getFormatString()); + _setInnerValue(date) { + const dateStr = print(date, this._getFormatString()); this.editor.setState(dateStr); this.editor.setValue(dateStr); - }, + } - _getText: function (obj) { - return BI.DynamicDateHelper.getDescription(obj); - }, + _getText(obj) { + return DynamicDateHelper.getDescription(obj); + } - setValue: function (v) { - var type, value, self = this; - var date = BI.getDate(); + setValue(v) { + let type, value; + let date = getDate(); this.storeValue = v; - if (BI.isNotNull(v)) { - type = v.type || BI.DynamicDateCombo.Static; + if (isNotNull(v)) { + type = v.type || DynamicDateCombo.Static; value = v.value || v; } + const text = this._getText(value); switch (type) { - case BI.DynamicDateCombo.Dynamic: - var text = this._getText(value); - date = BI.DynamicDateHelper.getCalculation(value); - this._setInnerValue(date, text); - break; - case BI.DynamicDateCombo.Static: - default: - if (BI.isNull(value) || BI.isNull(value.day)) { - this.editor.setState(""); - this.editor.setValue(""); - } else { - var dateStr = BI.print(BI.getDate(value.year, (value.month - 1), value.day), this._getFormatString()); - this.editor.setState(dateStr); - this.editor.setValue(dateStr); - } - break; + case DynamicDateCombo.Dynamic: + date = DynamicDateHelper.getCalculation(value); + this._setInnerValue(date, text); + break; + case DynamicDateCombo.Static: + default: + if (isNull(value) || isNull(value.day)) { + this.editor.setState(""); + this.editor.setValue(""); + } else { + const dateStr = print(getDate(value.year, (value.month - 1), value.day), this._getFormatString()); + this.editor.setState(dateStr); + this.editor.setValue(dateStr); + } + break; } - }, + } - setMinDate: function (minDate) { - if (BI.isNotEmptyString(this.options.min)) { + setMinDate(minDate) { + if (isNotEmptyString(this.options.min)) { this.options.min = minDate; } - }, + } - setMaxDate: function (maxDate) { - if (BI.isNotEmptyString(this.options.max)) { + setMaxDate(maxDate) { + if (isNotEmptyString(this.options.max)) { this.options.max = maxDate; } - }, + } - getKey: function () { + getKey() { return this.editor.getValue(); - }, - getValue: function () { + } + + getValue() { return this.storeValue; - }, + } - focus: function () { + focus() { this.editor.focus(); - }, + } - blur: function () { + blur() { this.editor.blur(); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.editor.setWaterMark(v); } -}); - -BI.DynamicDateTrigger.EVENT_BLUR = "EVENT_BLUR"; -BI.DynamicDateTrigger.EVENT_FOCUS = "EVENT_FOCUS"; -BI.DynamicDateTrigger.EVENT_START = "EVENT_START"; -BI.DynamicDateTrigger.EVENT_STOP = "EVENT_STOP"; -BI.DynamicDateTrigger.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.DynamicDateTrigger.EVENT_CHANGE = "EVENT_CHANGE"; -BI.DynamicDateTrigger.EVENT_VALID = "EVENT_VALID"; -BI.DynamicDateTrigger.EVENT_ERROR = "EVENT_ERROR"; -BI.DynamicDateTrigger.EVENT_TRIGGER_CLICK = "EVENT_TRIGGER_CLICK"; -BI.DynamicDateTrigger.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.shortcut("bi.dynamic_date_trigger", BI.DynamicDateTrigger); +} diff --git a/src/widget/dynamicdate/index.js b/src/widget/dynamicdate/index.js new file mode 100644 index 000000000..5e3f3bf89 --- /dev/null +++ b/src/widget/dynamicdate/index.js @@ -0,0 +1,6 @@ +export { DynamicDateHelper } from "./dynamicdate.caculate"; +export { DynamicDateCard } from "./dynamicdate.card"; +export { DynamicDateCombo } from "./dynamicdate.combo"; +export { DynamicDateParamItem } from "./dynamicdate.param.item"; +export { DynamicDatePopup } from "./dynamicdate.popup"; +export { DynamicDateTrigger } from "./dynamicdate.trigger"; diff --git a/src/widget/dynamicdatetime/dynamicdatetime.combo.js b/src/widget/dynamicdatetime/dynamicdatetime.combo.js index 54a445415..2e41c32a6 100644 --- a/src/widget/dynamicdatetime/dynamicdatetime.combo.js +++ b/src/widget/dynamicdatetime/dynamicdatetime.combo.js @@ -1,13 +1,17 @@ -BI.DynamicDateTimeCombo = BI.inherit(BI.Single, { - constants: { - popupHeight: 259, - popupWidth: 270, - comboAdjustHeight: 1, - border: 1, - iconWidth: 24 - }, +import { shortcut, getDate, toPix, isEqual, isNotEmptyString, isEmptyString, isNotNull, isNotEmptyObject, checkDateVoid } from "@/core"; +import { Single, Combo } from "@/base"; +import { DynamicDateTimeTrigger } from "./dynamicdatetime.trigger"; +import { DynamicDateTimePopup } from "./dynamicdatetime.popup"; +import { DynamicDateCombo } from "../dynamicdate"; - props: { +@shortcut() +export class DynamicDateTimeCombo extends Single { + static xtype = "bi.dynamic_date_time_combo" + + static Static = 1 + static Dynamic = 2 + + props = { baseCls: "bi-dynamic-date--time-combo", height: 24, minDate: "1900-01-01", @@ -16,33 +20,44 @@ BI.DynamicDateTimeCombo = BI.inherit(BI.Single, { allowEdit: true, supportDynamic: true, attributes: { - tabIndex: -1 + tabIndex: -1, }, isNeedAdjustHeight: false, - isNeedAdjustWidth: false - }, + isNeedAdjustWidth: false, + }; - _init: function () { - BI.DynamicDateTimeCombo.superclass._init.apply(this, arguments); - }, + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" + static EVENT_CONFIRM = "EVENT_CONFIRM" + static EVENT_FOCUS = "EVENT_FOCUS" + static EVENT_BLUR = "EVENT_BLUR" + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_VALID = "EVENT_VALID" + static EVENT_ERROR = "EVENT_ERROR" + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW" + static EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW" - render: function () { - var self = this, opts = this.options; + + _init() { + super._init(...arguments); + } + + render() { + const opts = this.options; this.storeTriggerValue = ""; - var date = BI.getDate(); + const date = getDate(); this.storeValue = opts.value; - var border = opts.simple ? 1 : 2; + const border = opts.simple ? 1 : 2; return { type: "bi.absolute", items: [{ el: { type: "bi.combo", - cls: (opts.simple ? "bi-border-bottom" : "bi-border bi-border-radius") + " bi-focus-shadow", + cls: `${opts.simple ? "bi-border-bottom" : "bi-border bi-border-radius"} bi-focus-shadow`, destroyWhenHide: true, container: opts.container, - ref: function () { - self.combo = this; + ref: _ref => { + this.combo = _ref; }, toggle: false, isNeedAdjustHeight: opts.isNeedAdjustHeight, @@ -50,16 +65,16 @@ BI.DynamicDateTimeCombo = BI.inherit(BI.Single, { el: { type: "bi.horizontal_fill", columnSize: [this.constants.iconWidth, "fill"], - height: BI.toPix(opts.height, border), + height: toPix(opts.height, border), items: [{ el: { type: "bi.icon_button", cls: "bi-trigger-icon-button date-change-h-font", width: this.constants.iconWidth, - height: BI.toPix(opts.height, border), - ref: function () { - self.changeIcon = this; - } + height: toPix(opts.height, border), + ref: _ref => { + this.changeIcon = _ref; + }, }, }, { type: "bi.dynamic_date_time_trigger", @@ -70,90 +85,90 @@ BI.DynamicDateTimeCombo = BI.inherit(BI.Single, { watermark: opts.watermark, format: opts.format, iconWidth: this.constants.iconWidth, - height: BI.toPix(opts.height, border), + height: toPix(opts.height, border), value: opts.value, - ref: function () { - self.trigger = this; + ref: _ref => { + this.trigger = _ref; }, listeners: [{ - eventName: BI.DynamicDateTimeTrigger.EVENT_KEY_DOWN, - action: function () { - if (self.combo.isViewVisible()) { - self.combo.hideView(); + eventName: DynamicDateTimeTrigger.EVENT_KEY_DOWN, + action: (...args) => { + if (this.combo.isViewVisible()) { + this.combo.hideView(); } - self.fireEvent(BI.DynamicDateTimeCombo.EVENT_KEY_DOWN, arguments); - } + this.fireEvent(DynamicDateTimeCombo.EVENT_KEY_DOWN, ...args); + }, }, { - eventName: BI.DynamicDateTimeTrigger.EVENT_STOP, - action: function () { - if (!self.combo.isViewVisible()) { - self.combo.showView(); + eventName: DynamicDateTimeTrigger.EVENT_STOP, + action: () => { + if (!this.combo.isViewVisible()) { + this.combo.showView(); } - } + }, }, { - eventName: BI.DynamicDateTimeTrigger.EVENT_TRIGGER_CLICK, - action: function () { - self.combo.toggle(); - } + eventName: DynamicDateTimeTrigger.EVENT_TRIGGER_CLICK, + action: () => { + this.combo.toggle(); + }, }, { - eventName: BI.DynamicDateTimeTrigger.EVENT_FOCUS, - action: function () { - self.storeTriggerValue = self.trigger.getKey(); - if (!self.combo.isViewVisible()) { - self.combo.showView(); + eventName: DynamicDateTimeTrigger.EVENT_FOCUS, + action: () => { + this.storeTriggerValue = this.trigger.getKey(); + if (!this.combo.isViewVisible()) { + this.combo.showView(); } - self.fireEvent(BI.DynamicDateTimeCombo.EVENT_FOCUS); - } + this.fireEvent(DynamicDateTimeCombo.EVENT_FOCUS); + }, }, { - eventName: BI.DynamicDateTimeTrigger.EVENT_BLUR, - action: function () { - self.fireEvent(BI.DynamicDateTimeCombo.EVENT_BLUR); - } + eventName: DynamicDateTimeTrigger.EVENT_BLUR, + action: () => { + this.fireEvent(DynamicDateTimeCombo.EVENT_BLUR); + }, }, { - eventName: BI.DynamicDateTimeTrigger.EVENT_ERROR, - action: function () { - self.storeValue = { - type: BI.DynamicDateTimeCombo.Static, + eventName: DynamicDateTimeTrigger.EVENT_ERROR, + action: () => { + this.storeValue = { + type: DynamicDateTimeCombo.Static, value: { year: date.getFullYear(), - month: date.getMonth() + 1 - } + month: date.getMonth() + 1, + }, }; - self.combo.element.addClass("error"); - self.fireEvent(BI.DynamicDateTimeCombo.EVENT_ERROR); - } + this.combo.element.addClass("error"); + this.fireEvent(DynamicDateTimeCombo.EVENT_ERROR); + }, }, { - eventName: BI.DynamicDateTimeTrigger.EVENT_VALID, - action: function () { - self.storeValue = self.trigger.getValue(); - self.combo.element.removeClass("error"); - self.fireEvent(BI.DynamicDateTimeCombo.EVENT_VALID); - } + eventName: DynamicDateTimeTrigger.EVENT_VALID, + action: () => { + this.storeValue = this.trigger.getValue(); + this.combo.element.removeClass("error"); + this.fireEvent(DynamicDateTimeCombo.EVENT_VALID); + }, }, { - eventName: BI.DynamicDateTimeTrigger.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.DynamicDateTimeCombo.EVENT_CHANGE); - } + eventName: DynamicDateTimeTrigger.EVENT_CHANGE, + action: () => { + this.fireEvent(DynamicDateTimeCombo.EVENT_CHANGE); + }, }, { - eventName: BI.DynamicDateTimeTrigger.EVENT_CONFIRM, - action: function () { - var dateStore = self.storeTriggerValue; - var dateObj = self.trigger.getKey(); - if (self.combo.isViewVisible() || BI.isEqual(dateObj, dateStore)) { + eventName: DynamicDateTimeTrigger.EVENT_CONFIRM, + action: () => { + const dateStore = this.storeTriggerValue; + const dateObj = this.trigger.getKey(); + if (this.combo.isViewVisible() || isEqual(dateObj, dateStore)) { return; } - if (BI.isNotEmptyString(dateObj) && !BI.isEqual(dateObj, dateStore)) { - self.storeValue = self.trigger.getValue(); - self.setValue(self.trigger.getValue()); - } else if (BI.isEmptyString(dateObj)) { - self.storeValue = null; - self.trigger.setValue(); + if (isNotEmptyString(dateObj) && !isEqual(dateObj, dateStore)) { + this.storeValue = this.trigger.getValue(); + this.setValue(this.trigger.getValue()); + } else if (isEmptyString(dateObj)) { + this.storeValue = null; + this.trigger.setValue(); } - self._checkDynamicValue(self.storeValue); - self.fireEvent(BI.DynamicDateTimeCombo.EVENT_CONFIRM); - } - }] - }] + this._checkDynamicValue(this.storeValue); + this.fireEvent(DynamicDateTimeCombo.EVENT_CONFIRM); + }, + }], + }], }, adjustLength: this.constants.comboAdjustHeight, popup: { @@ -164,67 +179,67 @@ BI.DynamicDateTimeCombo = BI.inherit(BI.Single, { behaviors: opts.behaviors, min: opts.minDate, max: opts.maxDate, - ref: function () { - self.popup = this; + ref: _ref => { + this.popup = _ref; }, listeners: [{ - eventName: BI.DynamicDateTimePopup.BUTTON_CLEAR_EVENT_CHANGE, - action: function () { - self.setValue(); - self.combo.hideView(); - self.fireEvent(BI.DynamicDateTimeCombo.EVENT_CONFIRM); - } + eventName: DynamicDateTimePopup.BUTTON_CLEAR_EVENT_CHANGE, + action: () => { + this.setValue(); + this.combo.hideView(); + this.fireEvent(DynamicDateTimeCombo.EVENT_CONFIRM); + }, }, { - eventName: BI.DynamicDateTimePopup.BUTTON_lABEL_EVENT_CHANGE, - action: function () { - var date = BI.getDate(); - self.setValue({ - type: BI.DynamicDateTimeCombo.Static, + eventName: DynamicDateTimePopup.BUTTON_lABEL_EVENT_CHANGE, + action: () => { + const date = getDate(); + this.setValue({ + type: DynamicDateTimeCombo.Static, value: { year: date.getFullYear(), month: date.getMonth() + 1, day: date.getDate(), hour: 0, minute: 0, - second: 0 - } + second: 0, + }, }); - self.combo.hideView(); - self.fireEvent(BI.DynamicDateTimeCombo.EVENT_CONFIRM); - } + this.combo.hideView(); + this.fireEvent(DynamicDateTimeCombo.EVENT_CONFIRM); + }, }, { - eventName: BI.DynamicDateTimePopup.BUTTON_OK_EVENT_CHANGE, - action: function () { - var value = self.popup.getValue(); - if (self._checkValue(value)) { - self.setValue(value); + eventName: DynamicDateTimePopup.BUTTON_OK_EVENT_CHANGE, + action: () => { + const value = this.popup.getValue(); + if (this._checkValue(value)) { + this.setValue(value); } - self.combo.hideView(); - self.fireEvent(BI.DynamicDateTimeCombo.EVENT_CONFIRM); - } + this.combo.hideView(); + this.fireEvent(DynamicDateTimeCombo.EVENT_CONFIRM); + }, }, { - eventName: BI.DynamicDateTimePopup.EVENT_CHANGE, - action: function () { - self.setValue(self.popup.getValue()); - self.combo.hideView(); - self.fireEvent(BI.DynamicDateTimeCombo.EVENT_CONFIRM); - } + eventName: DynamicDateTimePopup.EVENT_CHANGE, + action: () => { + this.setValue(this.popup.getValue()); + this.combo.hideView(); + this.fireEvent(DynamicDateTimeCombo.EVENT_CONFIRM); + }, }, { - eventName: BI.DynamicDateTimePopup.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW, - action: function () { - self.fireEvent(BI.DynamicDateTimeCombo.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); - } - }] + eventName: DynamicDateTimePopup.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW, + action: () => { + this.fireEvent(DynamicDateTimeCombo.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); + }, + }], }, }, listeners: [{ - eventName: BI.Combo.EVENT_BEFORE_POPUPVIEW, - action: function () { - self.popup.setMinDate(opts.minDate); - self.popup.setMaxDate(opts.maxDate); - self.popup.setValue(self.storeValue); - self.fireEvent(BI.DynamicDateTimeCombo.EVENT_BEFORE_POPUPVIEW); - } + eventName: Combo.EVENT_BEFORE_POPUPVIEW, + action: () => { + this.popup.setMinDate(opts.minDate); + this.popup.setMaxDate(opts.maxDate); + this.popup.setValue(this.storeValue); + this.fireEvent(DynamicDateTimeCombo.EVENT_BEFORE_POPUPVIEW); + }, }], // // DEC-4250 和复选下拉一样,点击不收起 // hideChecker: function (e) { @@ -234,108 +249,92 @@ BI.DynamicDateTimeCombo = BI.inherit(BI.Single, { top: 0, left: 0, right: 0, - bottom: 0 - }] + bottom: 0, + }], }; - }, + } - created: function () { + created() { this._checkDynamicValue(this.storeValue); - }, + } - _checkDynamicValue: function (v) { - var o = this.options; - var type = null; - if (BI.isNotNull(v)) { + _checkDynamicValue(v) { + let type = null; + if (isNotNull(v)) { type = v.type; } switch (type) { - case BI.DynamicDateTimeCombo.Dynamic: - this.changeIcon.setVisible(true); - // this.comboWrapper.attr("items")[0].width = o.height - (this.options.simple ? 1 : 2); - // this.comboWrapper.resize(); - break; - default: - // this.comboWrapper.attr("items")[0].width = 0; - // this.comboWrapper.resize(); - this.changeIcon.setVisible(false); - break; + case DynamicDateTimeCombo.Dynamic: + this.changeIcon.setVisible(true); + // this.comboWrapper.attr("items")[0].width = o.height - (this.options.simple ? 1 : 2); + // this.comboWrapper.resize(); + break; + default: + // this.comboWrapper.attr("items")[0].width = 0; + // this.comboWrapper.resize(); + this.changeIcon.setVisible(false); + break; } - }, + } - _checkValue: function (v) { - var o = this.options; + _checkValue(v) { + const o = this.options; + const value = v.value || {}; switch (v.type) { - case BI.DynamicDateCombo.Dynamic: - return BI.isNotEmptyObject(v.value); - case BI.DynamicDateCombo.Static: - var value = v.value || {}; - - return !BI.checkDateVoid(value.year, value.month, value.day, o.minDate, o.maxDate)[0]; - default: - return true; + case DynamicDateCombo.Dynamic: + return isNotEmptyObject(v.value); + case DynamicDateCombo.Static: + return !checkDateVoid(value.year, value.month, value.day, o.minDate, o.maxDate)[0]; + default: + return true; } - }, + } - setMinDate: function (minDate) { - var o = this.options; + setMinDate(minDate) { + const o = this.options; o.minDate = minDate; this.trigger.setMinDate(minDate); this.popup && this.popup.setMinDate(minDate); - }, + } - setMaxDate: function (maxDate) { - var o = this.options; + setMaxDate(maxDate) { + const o = this.options; o.maxDate = maxDate; this.trigger.setMaxDate(maxDate); this.popup && this.popup.setMaxDate(maxDate); - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v; this.trigger.setValue(v); this._checkDynamicValue(v); - }, - getValue: function () { + } + + getValue() { return this.storeValue; - }, - getKey: function () { + } + + getKey() { return this.trigger.getKey(); - }, - hidePopupView: function () { + } + + hidePopupView() { this.combo.hideView(); - }, + } - isValid: function () { + isValid() { return this.trigger.isValid(); - }, + } - focus: function () { + focus() { this.trigger.focus(); - }, + } - blur: function () { + blur() { this.trigger.blur(); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.trigger.setWaterMark(v); } -}); - -BI.DynamicDateTimeCombo.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.DynamicDateTimeCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.DynamicDateTimeCombo.EVENT_FOCUS = "EVENT_FOCUS"; -BI.DynamicDateTimeCombo.EVENT_BLUR = "EVENT_BLUR"; -BI.DynamicDateTimeCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.DynamicDateTimeCombo.EVENT_VALID = "EVENT_VALID"; -BI.DynamicDateTimeCombo.EVENT_ERROR = "EVENT_ERROR"; -BI.DynamicDateTimeCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.DynamicDateTimeCombo.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW"; - -BI.shortcut("bi.dynamic_date_time_combo", BI.DynamicDateTimeCombo); - -BI.extend(BI.DynamicDateTimeCombo, { - Static: 1, - Dynamic: 2 -}); +} diff --git a/src/widget/dynamicdatetime/dynamicdatetime.popup.js b/src/widget/dynamicdatetime/dynamicdatetime.popup.js index e7858ba35..7f8bb6982 100644 --- a/src/widget/dynamicdatetime/dynamicdatetime.popup.js +++ b/src/widget/dynamicdatetime/dynamicdatetime.popup.js @@ -1,271 +1,280 @@ -BI.DynamicDateTimePopup = BI.inherit(BI.Widget, { - constants: { - tabHeight: 40, - buttonHeight: 24 - }, +import { shortcut, Widget, createWidget, toPix, i18nText, createItems, print, isNull, isEmptyObject, isEmptyString, getDate, checkDateVoid, extend } from "@/core"; +import { DynamicDateCombo, DynamicDateHelper } from "../dynamicdate"; +import { TextButton, Tab } from "@/base"; +import { DateCalendarPopup } from "../date/calendar"; +import { DynamicDateTimeCombo } from "./dynamicdatetime.combo"; - props: { +@shortcut() +export class DynamicDateTimePopup extends Widget { + static xtype = "bi.dynamic_date_time_popup" + + props = { baseCls: "bi-dynamic-date-time-popup", width: 272, supportDynamic: true, - }, + }; + + static EVENT_CHANGE = "EVENT_CHANGE" + static BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE" + static BUTTON_lABEL_EVENT_CHANGE = "BUTTON_lABEL_EVENT_CHANGE" + static BUTTON_CLEAR_EVENT_CHANGE = "BUTTON_CLEAR_EVENT_CHANGE" + static EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW" - _init: function () { - BI.DynamicDateTimePopup.superclass._init.apply(this, arguments); - var self = this, opts = this.options, c = this.constants; - this.storeValue = {type: BI.DynamicDateCombo.Static}; - BI.createWidget({ + _init() { + super._init(...arguments); + const opts = this.options; + this.storeValue = { + type: DynamicDateCombo.Static, + }; + createWidget({ element: this, type: "bi.vertical", items: [{ - el: this._getTabJson() + el: this._getTabJson(), }, { el: { type: "bi.grid", - items: [[{ - type: "bi.text_button", - cls: "bi-high-light bi-split-top", - textHeight: BI.toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), - shadow: true, - text: BI.i18nText("BI-Basic_Clear"), - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.DynamicDateTimePopup.BUTTON_CLEAR_EVENT_CHANGE); - } - }] - }, { - type: "bi.text_button", - cls: "bi-split-left bi-split-right bi-high-light bi-split-top", - textHeight: BI.toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), - shadow: true, - text: BI.i18nText("BI-Multi_Date_Today"), - disabled: this._checkTodayValid(), - ref: function () { - self.todayButton = this; - }, - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.DynamicDateTimePopup.BUTTON_lABEL_EVENT_CHANGE); - } - }] - }, { - type: "bi.text_button", - cls: "bi-high-light bi-split-top", - textHeight: BI.toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), - shadow: true, - text: BI.i18nText("BI-Basic_OK"), - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - var type = self.dateTab.getSelect(); - if (type === BI.DynamicDateCombo.Dynamic) { - self.dynamicPane.checkValidation(true) && self.fireEvent(BI.DynamicDateTimePopup.BUTTON_OK_EVENT_CHANGE); - } else { - self.fireEvent(BI.DynamicDateTimePopup.BUTTON_OK_EVENT_CHANGE) - } - } + items: [ + [{ + type: "bi.text_button", + cls: "bi-high-light bi-split-top", + textHeight: toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), + shadow: true, + text: i18nText("BI-Basic_Clear"), + listeners: [{ + eventName: TextButton.EVENT_CHANGE, + action: () => { + this.fireEvent(DynamicDateTimePopup.BUTTON_CLEAR_EVENT_CHANGE); + }, + }], + }, { + type: "bi.text_button", + cls: "bi-split-left bi-split-right bi-high-light bi-split-top", + textHeight: toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), + shadow: true, + text: i18nText("BI-Multi_Date_Today"), + disabled: this._checkTodayValid(), + ref: _ref => { + this.todayButton = _ref; + }, + listeners: [{ + eventName: TextButton.EVENT_CHANGE, + action: () => { + this.fireEvent(DynamicDateTimePopup.BUTTON_lABEL_EVENT_CHANGE); + }, + }], + }, { + type: "bi.text_button", + cls: "bi-high-light bi-split-top", + textHeight: toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), + shadow: true, + text: i18nText("BI-Basic_OK"), + listeners: [{ + eventName: TextButton.EVENT_CHANGE, + action: () => { + const type = this.dateTab.getSelect(); + if (type === DynamicDateCombo.Dynamic) { + this.dynamicPane.checkValidation(true) && this.fireEvent(DynamicDateTimePopup.BUTTON_OK_EVENT_CHANGE); + } else { + this.fireEvent(DynamicDateTimePopup.BUTTON_OK_EVENT_CHANGE); + } + }, + }], }] - }]], - height: BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT - } - }] + ], + height: BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, + }, + }], }); this.setValue(opts.value); - }, + } - _getTabJson: function () { - var self = this, o = this.options; + _getTabJson() { + const o = this.options; + return { type: "bi.tab", logic: { - dynamic: true + dynamic: true, }, - ref: function () { - self.dateTab = this; + ref: _ref => { + this.dateTab = _ref; }, tab: { type: "bi.linear_segment", invisible: !o.supportDynamic, cls: "bi-split-bottom", height: this.constants.tabHeight, - items: BI.createItems([{ - text: BI.i18nText("BI-Multi_Date_YMD"), - value: BI.DynamicDateCombo.Static + items: createItems([{ + text: i18nText("BI-Multi_Date_YMD"), + value: DynamicDateCombo.Static, }, { - text: BI.i18nText("BI-Basic_Dynamic_Title"), - value: BI.DynamicDateCombo.Dynamic + text: i18nText("BI-Basic_Dynamic_Title"), + value: DynamicDateCombo.Dynamic, }], { - textAlign: "center" - }) + textAlign: "center", + }), }, - cardCreator: function (v) { + cardCreator: v => { switch (v) { - case BI.DynamicDateCombo.Dynamic: - return { - type: "bi.dynamic_date_card", - cls: "dynamic-date-pane", + case DynamicDateCombo.Dynamic: + return { + type: "bi.dynamic_date_card", + cls: "dynamic-date-pane", + listeners: [{ + eventName: "EVENT_CHANGE", + action: () => { + this._setInnerValue(this.year, v); + }, + }], + ref: _ref => { + this.dynamicPane = _ref; + }, + min: this.options.min, + max: this.options.max, + }; + case DynamicDateCombo.Static: + default: + return { + type: "bi.vertical", + items: [{ + type: "bi.date_calendar_popup", + behaviors: o.behaviors, + min: this.options.min, + max: this.options.max, + ref: _ref => { + this.ymd = _ref; + }, listeners: [{ - eventName: "EVENT_CHANGE", - action: function () { - self._setInnerValue(self.year, v); - } + eventName: DateCalendarPopup.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW, + action: () => { + this.fireEvent(DynamicDateTimePopup.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); + }, }], - ref: function () { - self.dynamicPane = this; - }, - min: self.options.min, - max: self.options.max, - }; - case BI.DynamicDateCombo.Static: - default: - return { - type: "bi.vertical", - items: [{ - type: "bi.date_calendar_popup", - behaviors: o.behaviors, - min: self.options.min, - max: self.options.max, - ref: function () { - self.ymd = this; + }, { + el: { + type: "bi.dynamic_date_time_select", + cls: "bi-split-top", + ref: _ref => { + this.timeSelect = _ref; }, - listeners: [{ - eventName: BI.DateCalendarPopup.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW, - action: function () { - self.fireEvent(BI.DynamicDateTimePopup.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); - } - }], - }, { - el: { - type: "bi.dynamic_date_time_select", - cls: "bi-split-top", - ref: function () { - self.timeSelect = this; - }, - height: 40 - } - }] - }; + height: 40, + }, + }], + }; } }, listeners: [{ - eventName: BI.Tab.EVENT_CHANGE, - action: function () { - var v = self.dateTab.getSelect(); + eventName: Tab.EVENT_CHANGE, + action: () => { + const v = this.dateTab.getSelect(); + const date = DynamicDateHelper.getCalculation(this.dynamicPane.getValue()); switch (v) { - case BI.DynamicDateCombo.Static: - var date = BI.DynamicDateHelper.getCalculation(self.dynamicPane.getValue()); - self.ymd.setValue({ - year: date.getFullYear(), - month: date.getMonth() + 1, - day: date.getDate() + case DynamicDateCombo.Static: + this.ymd.setValue({ + year: date.getFullYear(), + month: date.getMonth() + 1, + day: date.getDate(), + }); + this.timeSelect.setValue(); + this._setInnerValue(); + break; + case DynamicDateCombo.Dynamic: + default: + if (this.storeValue && this.storeValue.type === DynamicDateCombo.Dynamic) { + this.dynamicPane.setValue(this.storeValue.value); + } else { + this.dynamicPane.setValue({ + year: 0, }); - self.timeSelect.setValue(); - self._setInnerValue(); - break; - case BI.DynamicDateCombo.Dynamic: - default: - if(self.storeValue && self.storeValue.type === BI.DynamicDateCombo.Dynamic) { - self.dynamicPane.setValue(self.storeValue.value); - }else{ - self.dynamicPane.setValue({ - year: 0 - }); - } - self._setInnerValue(); - break; + } + this._setInnerValue(); + break; } - } - }] + }, + }], }; - }, + } - _setInnerValue: function () { - if (this.dateTab.getSelect() === BI.DynamicDateCombo.Static) { - this.todayButton.setValue(BI.i18nText("BI-Multi_Date_Today")); + _setInnerValue() { + if (this.dateTab.getSelect() === DynamicDateCombo.Static) { + this.todayButton.setValue(i18nText("BI-Multi_Date_Today")); this.todayButton.setEnable(!this._checkTodayValid()); } else { - var date = BI.DynamicDateHelper.getCalculation(this.dynamicPane.getInputValue()); - date = BI.print(date, "%Y-%X-%d"); + let date = DynamicDateHelper.getCalculation(this.dynamicPane.getInputValue()); + date = print(date, "%Y-%X-%d"); this.todayButton.setValue(date); this.todayButton.setEnable(false); } - }, + } - _checkValueValid: function (value) { - return BI.isNull(value) || BI.isEmptyObject(value) || BI.isEmptyString(value); - }, + _checkValueValid(value) { + return isNull(value) || isEmptyObject(value) || isEmptyString(value); + } - _checkTodayValid: function () { - var o = this.options; - var today = BI.getDate(); - return !!BI.checkDateVoid(today.getFullYear(), today.getMonth() + 1, today.getDate(), o.min, o.max)[0]; - }, + _checkTodayValid() { + const o = this.options; + const today = getDate(); + + return !!checkDateVoid(today.getFullYear(), today.getMonth() + 1, today.getDate(), o.min, o.max)[0]; + } - setMinDate: function (minDate) { + setMinDate(minDate) { if (this.options.min !== minDate) { this.options.min = minDate; this.ymd.setMinDate(minDate); } - }, + } - setMaxDate: function (maxDate) { + setMaxDate(maxDate) { if (this.options.max !== maxDate) { this.options.max = maxDate; this.ymd.setMaxDate(maxDate); } - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v; - var self = this; - var type, value; v = v || {}; - type = v.type || BI.DynamicDateCombo.Static; - value = v.value || v; + const type = v.type || DynamicDateCombo.Static; + const value = v.value || v; this.dateTab.setSelect(type); switch (type) { - case BI.DynamicDateCombo.Dynamic: - this.dynamicPane.setValue(value); - self._setInnerValue(); - break; - case BI.DynamicDateCombo.Static: - default: - if (this._checkValueValid(value)) { - var date = BI.getDate(); - this.ymd.setValue({ - year: date.getFullYear(), - month: date.getMonth() + 1, - day: date.getDate() - }); - this.timeSelect.setValue(); - this.todayButton.setValue(BI.i18nText("BI-Multi_Date_Today")); - } else { - this.ymd.setValue(value); - this.timeSelect.setValue({ - hour: value.hour, - minute: value.minute, - second: value.second - }); - this.todayButton.setValue(BI.i18nText("BI-Multi_Date_Today")); - } - this.todayButton.setEnable(!this._checkTodayValid()); - break; + case DynamicDateCombo.Dynamic: + this.dynamicPane.setValue(value); + this._setInnerValue(); + break; + case DynamicDateCombo.Static: + default: + if (this._checkValueValid(value)) { + const date = getDate(); + this.ymd.setValue({ + year: date.getFullYear(), + month: date.getMonth() + 1, + day: date.getDate(), + }); + this.timeSelect.setValue(); + this.todayButton.setValue(i18nText("BI-Multi_Date_Today")); + } else { + this.ymd.setValue(value); + this.timeSelect.setValue({ + hour: value.hour, + minute: value.minute, + second: value.second, + }); + this.todayButton.setValue(i18nText("BI-Multi_Date_Today")); + } + this.todayButton.setEnable(!this._checkTodayValid()); + break; } - }, + } - getValue: function () { - var type = this.dateTab.getSelect(); + getValue() { + const type = this.dateTab.getSelect(); + return { - type: type, - value: type === BI.DynamicDateTimeCombo.Static ? BI.extend(this.ymd.getValue(), this.timeSelect.getValue()) : this.dynamicPane.getValue() + type, + value: type === DynamicDateTimeCombo.Static ? extend(this.ymd.getValue(), this.timeSelect.getValue()) : this.dynamicPane.getValue(), }; } -}); -BI.DynamicDateTimePopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.DynamicDateTimePopup.BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE"; -BI.DynamicDateTimePopup.BUTTON_lABEL_EVENT_CHANGE = "BUTTON_lABEL_EVENT_CHANGE"; -BI.DynamicDateTimePopup.BUTTON_CLEAR_EVENT_CHANGE = "BUTTON_CLEAR_EVENT_CHANGE"; -BI.DynamicDateTimePopup.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW"; -BI.shortcut("bi.dynamic_date_time_popup", BI.DynamicDateTimePopup); \ No newline at end of file +} diff --git a/src/widget/dynamicdatetime/dynamicdatetime.timeselect.js b/src/widget/dynamicdatetime/dynamicdatetime.timeselect.js index 5642cb799..00f21b78c 100644 --- a/src/widget/dynamicdatetime/dynamicdatetime.timeselect.js +++ b/src/widget/dynamicdatetime/dynamicdatetime.timeselect.js @@ -1,11 +1,21 @@ -BI.DynamicDateTimeSelect = BI.inherit(BI.Widget, { +import { shortcut, Widget, isNaturalNumber, parseInt, isNumeric, i18nText, isNull, isEmptyString } from "@/core"; +import { SignEditor } from "@/case"; - props: { - baseCls: "bi-date-time-select" - }, +@shortcut() +export class DynamicDateTimeSelect extends Widget { + static xtype = "bi.dynamic_date_time_select" - render: function () { - var self = this; + static HOUR = 1 + static MINUTE = 2 + static SECOND = 3 + + static EVENT_CONFIRM = "EVENT_CONFIRM" + + props = { + baseCls: "bi-date-time-select", + }; + + render() { return { type: "bi.center_adapt", items: [{ @@ -13,200 +23,197 @@ BI.DynamicDateTimeSelect = BI.inherit(BI.Widget, { items: [{ el: { type: "bi.number_editor", - ref: function () { - self.hour = this; + ref: _ref => { + this.hour = _ref; }, - validationChecker: function (v) { - return BI.isNaturalNumber(v) && BI.parseInt(v) < 24; + validationChecker (v) { + return isNaturalNumber(v) && parseInt(v) < 24; }, - errorText: function (v) { - if(BI.isNumeric(v)) { - return BI.i18nText("BI-Basic_Input_From_To_Number", "\"00-23\""); + errorText (v) { + if (isNumeric(v)) { + return i18nText("BI-Basic_Input_From_To_Number", "\"00-23\""); } - return BI.i18nText("BI-Numerical_Interval_Input_Data"); + + return i18nText("BI-Numerical_Interval_Input_Data"); }, listeners: [{ - eventName: BI.SignEditor.EVENT_CONFIRM, - action: function () { - var value = this.getValue(); - self._checkHour(value); - this.setValue(self._formatValueToDoubleDigit(value)); - self.fireEvent(BI.DynamicDateTimeSelect.EVENT_CONFIRM); - } + eventName: SignEditor.EVENT_CONFIRM, + action: () => { + const value = this.hour.getValue(); + this._checkHour(value); + this.hour.setValue(this._formatValueToDoubleDigit(value)); + this.fireEvent(DynamicDateTimeSelect.EVENT_CONFIRM); + }, }, { - eventName: BI.SignEditor.EVENT_CHANGE, - action: function () { - var value = self._autoSwitch(this.getValue(), BI.DynamicDateTimeSelect.HOUR); - this.setValue(value); - } + eventName: SignEditor.EVENT_CHANGE, + action: () => { + const value = this._autoSwitch(this.hour.getValue(), DynamicDateTimeSelect.HOUR); + this.hour.setValue(value); + }, }], width: 60, - height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT - } + height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, + }, }, { type: "bi.label", text: ":", - width: 20 + width: 20, }, { type: "bi.number_editor", - ref: function () { - self.minute = this; + ref: _ref => { + this.minute = _ref; }, - validationChecker: function (v) { - return BI.isNaturalNumber(v) && BI.parseInt(v) < 60; + validationChecker (v) { + return isNaturalNumber(v) && parseInt(v) < 60; }, - errorText: function (v) { - if(BI.isNumeric(v)) { - return BI.i18nText("BI-Basic_Input_From_To_Number", "\"00-59\""); + errorText (v) { + if (isNumeric(v)) { + return i18nText("BI-Basic_Input_From_To_Number", "\"00-59\""); } - return BI.i18nText("BI-Numerical_Interval_Input_Data"); + + return i18nText("BI-Numerical_Interval_Input_Data"); }, listeners: [{ - eventName: BI.SignEditor.EVENT_CONFIRM, - action: function () { - var value = this.getValue(); - self._checkMinute(value); - this.setValue(self._formatValueToDoubleDigit(value), BI.DynamicDateTimeSelect.MINUTE); - self.fireEvent(BI.DynamicDateTimeSelect.EVENT_CONFIRM); - } + eventName: SignEditor.EVENT_CONFIRM, + action: () => { + const value = this.minute.getValue(); + this._checkMinute(value); + this.minute.setValue(this._formatValueToDoubleDigit(value), DynamicDateTimeSelect.MINUTE); + this.fireEvent(DynamicDateTimeSelect.EVENT_CONFIRM); + }, }, { - eventName: BI.SignEditor.EVENT_CHANGE, - action: function () { - var value = self._autoSwitch(this.getValue(), BI.DynamicDateTimeSelect.MINUTE); - this.setValue(value); - } + eventName: SignEditor.EVENT_CHANGE, + action: () => { + const value = this._autoSwitch(this.getValue(), DynamicDateTimeSelect.MINUTE); + this.minute.setValue(value); + }, }], width: 60, - height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, }, { type: "bi.label", text: ":", - width: 20 + width: 20, }, { type: "bi.number_editor", - ref: function () { - self.second = this; + ref: _ref => { + this.second = _ref; }, - validationChecker: function (v) { - return BI.isNaturalNumber(v) && BI.parseInt(v) < 60; + validationChecker (v) { + return isNaturalNumber(v) && parseInt(v) < 60; }, - errorText: function (v) { - if(BI.isNumeric(v)) { - return BI.i18nText("BI-Basic_Input_From_To_Number", "\"00-59\""); + errorText (v) { + if (isNumeric(v)) { + return i18nText("BI-Basic_Input_From_To_Number", "\"00-59\""); } - return BI.i18nText("BI-Numerical_Interval_Input_Data"); + + return i18nText("BI-Numerical_Interval_Input_Data"); }, listeners: [{ - eventName: BI.SignEditor.EVENT_CONFIRM, - action: function () { - var value = this.getValue(); - self._checkSecond(value); - this.setValue(self._formatValueToDoubleDigit(value)); - self.fireEvent(BI.DynamicDateTimeSelect.EVENT_CONFIRM); - } + eventName: SignEditor.EVENT_CONFIRM, + action: () => { + const value = this.second.getValue(); + this._checkSecond(value); + this.second.setValue(this._formatValueToDoubleDigit(value)); + this.fireEvent(DynamicDateTimeSelect.EVENT_CONFIRM); + }, }], width: 60, - height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT - }] - }] + height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, + }], + }], }; - }, + } - _checkBorder: function (v) { + _checkBorder(v) { v = v || {}; this._checkHour(v.hour); this._checkMinute(v.minute); this._checkSecond(v.second); - }, + } - _checkHour: function (value) { - this.hour.setDownEnable(BI.parseInt(value) > 0); - this.hour.setUpEnable(BI.parseInt(value) < 23); - }, + _checkHour(value) { + this.hour.setDownEnable(parseInt(value) > 0); + this.hour.setUpEnable(parseInt(value) < 23); + } - _checkMinute: function (value) { - this.minute.setDownEnable(BI.parseInt(value) > 0); - this.minute.setUpEnable(BI.parseInt(value) < 59); - }, + _checkMinute(value) { + this.minute.setDownEnable(parseInt(value) > 0); + this.minute.setUpEnable(parseInt(value) < 59); + } - _checkSecond: function (value) { - this.second.setDownEnable(BI.parseInt(value) > 0); - this.second.setUpEnable(BI.parseInt(value) < 59); - }, + _checkSecond(value) { + this.second.setDownEnable(parseInt(value) > 0); + this.second.setUpEnable(parseInt(value) < 59); + } - _autoSwitch: function (v, type) { - var limit = 0; - var value = v + ""; + _autoSwitch(v, type) { + let limit = 0; + let value = `${v}`; switch (type) { - case BI.DynamicDateTimeSelect.HOUR: - limit = 2; - break; - case BI.DynamicDateTimeSelect.MINUTE: - limit = 5; - break; - default: - break; + case DynamicDateTimeSelect.HOUR: + limit = 2; + break; + case DynamicDateTimeSelect.MINUTE: + limit = 5; + break; + default: + break; } - if(value.length === 1 && BI.parseInt(value) > limit) { - value = "0" + value; + if (value.length === 1 && parseInt(value) > limit) { + value = `0${value}`; } if (value.length === 2) { switch (type) { - case BI.DynamicDateTimeSelect.HOUR: - this.hour.isEditing() && this.minute.focus(); - break; - case BI.DynamicDateTimeSelect.MINUTE: - this.minute.isEditing() && this.second.focus(); - break; - case BI.DynamicDateTimeSelect.SECOND: - default: - break; + case DynamicDateTimeSelect.HOUR: + this.hour.isEditing() && this.minute.focus(); + break; + case DynamicDateTimeSelect.MINUTE: + this.minute.isEditing() && this.second.focus(); + break; + case DynamicDateTimeSelect.SECOND: + default: + break; } } + return value; - }, + } - _formatValueToDoubleDigit: function (v) { - if(BI.isNull(v) || BI.isEmptyString(v)) { + _formatValueToDoubleDigit(v) { + if (isNull(v) || isEmptyString(v)) { v = 0; } - var value = BI.parseInt(v); - if(value < 10) { - value = "0" + value; + let value = parseInt(v); + if (value < 10) { + value = `0${value}`; } + return value; - }, + } - _assertValue: function (v) { + _assertValue(v) { v = v || {}; v.hour = this._formatValueToDoubleDigit(v.hour) || "00"; v.minute = this._formatValueToDoubleDigit(v.minute) || "00"; v.second = this._formatValueToDoubleDigit(v.second) || "00"; + return v; - }, + } - getValue: function () { + getValue() { return { - hour: BI.parseInt(this.hour.getValue()), - minute: BI.parseInt(this.minute.getValue()), - second: BI.parseInt(this.second.getValue()) + hour: parseInt(this.hour.getValue()), + minute: parseInt(this.minute.getValue()), + second: parseInt(this.second.getValue()), }; - }, + } - setValue: function (v) { + setValue(v) { v = this._assertValue(v); this.hour.setValue(v.hour); this.minute.setValue(v.minute); this.second.setValue(v.second); this._checkBorder(v); } - -}); -BI.DynamicDateTimeSelect.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut("bi.dynamic_date_time_select", BI.DynamicDateTimeSelect); - -BI.extend(BI.DynamicDateTimeSelect, { - HOUR: 1, - MINUTE: 2, - SECOND: 3 -}); \ No newline at end of file +} diff --git a/src/widget/dynamicdatetime/dynamicdatetime.trigger.js b/src/widget/dynamicdatetime/dynamicdatetime.trigger.js index 86a942fe7..82e6a1a83 100644 --- a/src/widget/dynamicdatetime/dynamicdatetime.trigger.js +++ b/src/widget/dynamicdatetime/dynamicdatetime.trigger.js @@ -1,59 +1,82 @@ -BI.DynamicDateTimeTrigger = BI.inherit(BI.Trigger, { - _const: { +import { shortcut, i18nText, createWidget, isKey, checkDateLegal, parseDateTime, bind, isNotNull, isNotEmptyString, isEqual, isEmptyObject, isEmptyString, isNull, getDate, each, isNumeric, checkDateVoid, parseInt, size, print } from "@/core"; +import { Trigger } from "@/base"; +import { SignEditor } from "@/case"; +import { DynamicDateCombo, DynamicDateCard, DynamicDateHelper } from "../dynamicdate"; + +@shortcut() +export class DynamicDateTimeTrigger extends Trigger { + static xtype = "bi.dynamic_date_time_trigger" + + _const = { hgap: 4, vgap: 2, yearLength: 4, yearMonthLength: 6, yearFullMonthLength: 7, compareFormat: "%Y-%X-%d %H:%M:%S", - iconWidth: 24 - }, - - props: () => ({ - extraCls: "bi-date-time-trigger", - min: "1900-01-01", // 最小日期 - max: "2099-12-31", // 最大日期 - height: 24, iconWidth: 24, - format: "", // 显示的日期格式化方式 - allowEdit: true, // 是否允许编辑 - watermark: BI.i18nText("BI-Basic_Unrestricted"), - }), + }; + + static EVENT_BLUR = "EVENT_BLUR" + static EVENT_FOCUS = "EVENT_FOCUS" + static EVENT_START = "EVENT_START" + static EVENT_STOP = "EVENT_STOP" + static EVENT_CONFIRM = "EVENT_CONFIRM" + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_VALID = "EVENT_VALID" + static EVENT_ERROR = "EVENT_ERROR" + static EVENT_TRIGGER_CLICK = "EVENT_TRIGGER_CLICK" + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" - _init: function () { - BI.DynamicDateTimeTrigger.superclass._init.apply(this, arguments); - var self = this, o = this.options, c = this._const; + props() { + return { + extraCls: "bi-date-time-trigger", + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 + height: 24, + iconWidth: 24, + format: "", // 显示的日期格式化方式 + allowEdit: true, // 是否允许编辑 + watermark: i18nText("BI-Basic_Unrestricted"), + }; + } + + _init() { + super._init(...arguments); + const o = this.options, + c = this._const; this.storeTriggerValue = ""; - this.editor = BI.createWidget({ + this.editor = createWidget({ type: "bi.sign_editor", simple: o.simple, height: o.height, - validationChecker: function (v) { - var formatStr = self._getStandardDateStr(v); - var date = formatStr.match(/\d+/g); - !BI.isKey(o.format) && self._autoAppend(v, date); - return self._dateCheck(formatStr) && BI.checkDateLegal(formatStr) && self._checkVoid({ + validationChecker: v => { + const formatStr = this._getStandardDateStr(v); + const date = formatStr.match(/\d+/g); + !isKey(o.format) && this._autoAppend(v, date); + + return this._dateCheck(formatStr) && checkDateLegal(formatStr) && this._checkVoid({ year: date[0] | 0, month: date[1] | 0, - day: date[2] | 0 + day: date[2] | 0, }); }, - quitChecker: function () { + quitChecker () { return false; }, hgap: c.hgap, vgap: c.vgap, allowBlank: true, watermark: o.watermark, - errorText: function (v) { - var str = ""; - if (!BI.isKey(o.format)) { - if (!self._dateCheck(v)) { - str = self.editor.isEditing() ? BI.i18nText("BI-Date_Trigger_Error_Text") : BI.i18nText("BI-Year_Trigger_Invalid_Text"); + errorText: v => { + let str = ""; + if (!isKey(o.format)) { + if (!this._dateCheck(v)) { + str = this.editor.isEditing() ? i18nText("BI-Date_Trigger_Error_Text") : i18nText("BI-Year_Trigger_Invalid_Text"); } else { - var start = BI.parseDateTime(o.min, "%Y-%X-%d"); - var end = BI.parseDateTime(o.max, "%Y-%X-%d"); - str = BI.i18nText("BI-Basic_Date_Range_Error", + const start = parseDateTime(o.min, "%Y-%X-%d"); + const end = parseDateTime(o.max, "%Y-%X-%d"); + str = i18nText("BI-Basic_Date_Range_Error", start.getFullYear(), start.getMonth() + 1, start.getDate(), @@ -66,348 +89,347 @@ BI.DynamicDateTimeTrigger = BI.inherit(BI.Trigger, { return str; }, - title: BI.bind(this._getTitle, this) + title: bind(this._getTitle, this), }); - this.editor.on(BI.SignEditor.EVENT_KEY_DOWN, function () { - self.fireEvent(BI.DynamicDateTimeTrigger.EVENT_KEY_DOWN, arguments); + this.editor.on(SignEditor.EVENT_KEY_DOWN, (...args) => { + this.fireEvent(DynamicDateTimeTrigger.EVENT_KEY_DOWN, ...args); }); - this.editor.on(BI.SignEditor.EVENT_FOCUS, function () { - self.storeTriggerValue = self.getKey(); - self.fireEvent(BI.DynamicDateTimeTrigger.EVENT_FOCUS); + this.editor.on(SignEditor.EVENT_FOCUS, () => { + this.storeTriggerValue = this.getKey(); + this.fireEvent(DynamicDateTimeTrigger.EVENT_FOCUS); }); - this.editor.on(BI.SignEditor.EVENT_BLUR, function () { - self.fireEvent(BI.DynamicDateTimeTrigger.EVENT_BLUR); + this.editor.on(SignEditor.EVENT_BLUR, () => { + this.fireEvent(DynamicDateTimeTrigger.EVENT_BLUR); }); - this.editor.on(BI.SignEditor.EVENT_STOP, function () { - self.fireEvent(BI.DynamicDateTimeTrigger.EVENT_STOP); + this.editor.on(SignEditor.EVENT_STOP, () => { + this.fireEvent(DynamicDateTimeTrigger.EVENT_STOP); }); - this.editor.on(BI.SignEditor.EVENT_VALID, function () { - self.fireEvent(BI.DynamicDateTimeTrigger.EVENT_VALID); + this.editor.on(SignEditor.EVENT_VALID, () => { + this.fireEvent(DynamicDateTimeTrigger.EVENT_VALID); }); - this.editor.on(BI.SignEditor.EVENT_ERROR, function () { - self.fireEvent(BI.DynamicDateTimeTrigger.EVENT_ERROR); + this.editor.on(SignEditor.EVENT_ERROR, () => { + this.fireEvent(DynamicDateTimeTrigger.EVENT_ERROR); }); - this.editor.on(BI.SignEditor.EVENT_CONFIRM, function () { - var value = self.editor.getValue(); - if (BI.isNotNull(value)) { - self.editor.setState(value); + this.editor.on(SignEditor.EVENT_CONFIRM, () => { + const value = this.editor.getValue(); + if (isNotNull(value)) { + this.editor.setState(value); } - if (BI.isNotEmptyString(value) && !BI.isEqual(self.storeTriggerValue, self.getKey())) { - var formatStr = self._getStandardDateStr(value); - var date = formatStr.match(/\d+/g); - self.storeValue = { - type: BI.DynamicDateCombo.Static, + if (isNotEmptyString(value) && !isEqual(this.storeTriggerValue, this.getKey())) { + const formatStr = this._getStandardDateStr(value); + const date = formatStr.match(/\d+/g); + this.storeValue = { + type: DynamicDateCombo.Static, value: { year: date[0] | 0, month: date[1] | 0, day: date[2] | 0, hour: date[3] | 0, minute: date[4] | 0, - second: date[5] | 0 - } + second: date[5] | 0, + }, }; } - self.fireEvent(BI.DynamicDateTimeTrigger.EVENT_CONFIRM); + this.fireEvent(DynamicDateTimeTrigger.EVENT_CONFIRM); }); - this.editor.on(BI.SignEditor.EVENT_START, function () { - self.fireEvent(BI.DynamicDateTimeTrigger.EVENT_START); + this.editor.on(SignEditor.EVENT_START, () => { + this.fireEvent(DynamicDateTimeTrigger.EVENT_START); }); - this.editor.on(BI.SignEditor.EVENT_CHANGE, function () { - self.fireEvent(BI.DynamicDateTimeTrigger.EVENT_CHANGE); + this.editor.on(SignEditor.EVENT_CHANGE, () => { + this.fireEvent(DynamicDateTimeTrigger.EVENT_CHANGE); }); - BI.createWidget({ + createWidget({ type: "bi.htape", element: this, columnSize: ["", this._const.iconWidth], items: [{ - el: this.editor + el: this.editor, }, { el: { type: "bi.icon_button", cls: "bi-trigger-icon-button date-font", }, - width: o.iconWidth - }] + width: o.iconWidth, + }], }); - !o.allowEdit && BI.createWidget({ + !o.allowEdit && createWidget({ type: "bi.absolute", element: this, items: [{ el: { type: "bi.text", - title: BI.bind(this._getTitle, this) + title: bind(this._getTitle, this), }, left: 0, right: o.iconWidth, top: 0, - bottom: 0 - }] + bottom: 0, + }], }); this.setValue(o.value); - }, + } - _getTitle: function () { - var o = this.options; - var storeValue = this.storeValue || {}; - if (BI.isEmptyObject(storeValue)) { + _getTitle() { + const o = this.options; + const storeValue = this.storeValue || {}; + if (isEmptyObject(storeValue)) { return o.watermark; } - var type = storeValue.type || BI.DynamicDateCombo.Static; - var value = storeValue.value; + const type = storeValue.type || DynamicDateCombo.Static; + const value = storeValue.value; + const text = this._getText(value); + const date = DynamicDateHelper.getCalculation(value); + const dateStr = print(date, this._getFormatString()); + switch (type) { - case BI.DynamicDateCombo.Dynamic: - var text = this._getText(value); - var date = BI.DynamicDateHelper.getCalculation(value); - var dateStr = BI.print(date, this._getFormatString()); - return BI.isEmptyString(text) ? dateStr : (text + ":" + dateStr); - case BI.DynamicDateCombo.Static: - default: - if (BI.isNull(value) || BI.isNull(value.day)) { - return ""; - } - return BI.print(BI.getDate(value.year, (value.month - 1), value.day, value.hour || 0, value.minute || 0, - value.second || 0), this._getFormatString()); + case DynamicDateCombo.Dynamic: + return isEmptyString(text) ? dateStr : (`${text}:${dateStr}`); + case DynamicDateCombo.Static: + default: + if (isNull(value) || isNull(value.day)) { + return ""; + } + + return print(getDate(value.year, (value.month - 1), value.day, value.hour || 0, value.minute || 0, + value.second || 0), this._getFormatString()); } - }, + } - _getStandardDateStr: function (v) { - var c = this._const; - var result = []; - var hasSecond = false; - var formatArray = this._getFormatString().match(/%./g); - BI.each(formatArray, function (idx, v) { + _getStandardDateStr(v) { + const c = this._const; + let result = []; + let hasSecond = false; + const formatArray = this._getFormatString().match(/%./g); + each(formatArray, (idx, v) => { switch (v) { - case "%Y": - case "%y": - result[0] = idx; - break; - case "%X": - case "%x": - result[1] = idx; - break; - case "%d": - case "%e": - result[2] = idx; - break; - case "%S": - hasSecond = true; - break; - default: - break; + case "%Y": + case "%y": + result[0] = idx; + break; + case "%X": + case "%x": + result[1] = idx; + break; + case "%d": + case "%e": + result[2] = idx; + break; + case "%S": + hasSecond = true; + break; + default: + break; } }); // 这边不能直接用\d+去切日期, 因为format格式可能是20190607这样的没有分割符的 = = // 先看一下是否是合法的, 如果合法就变成标准格式的走原来的流程, 不合法不关心 - var date = BI.parseDateTime(v, this._getFormatString()); - if (BI.print(date, this._getFormatString()) === v) { - v = BI.print(date, c.compareFormat); + const date = parseDateTime(v, this._getFormatString()); + if (print(date, this._getFormatString()) === v) { + v = print(date, c.compareFormat); result = [0, 1, 2]; } - var dateArray = v.match(/\d+/g) || []; - var newArray = []; + const dateArray = v.match(/\d+/g) || []; + const newArray = []; // 处理乱序的年月日 - BI.each(dateArray.slice(0, 3), function (idx) { + each(dateArray.slice(0, 3), idx => { newArray[idx] = dateArray[result[idx]]; }); // 拼接时分秒和pm - var suffixArray = dateArray.slice(3); + const suffixArray = dateArray.slice(3); // 时分秒补0 - BI.each(suffixArray, function (idx, v) { - BI.isNumeric(v) && v.length === 1 && (suffixArray[idx] = "0" + v); + each(suffixArray, (idx, v) => { + isNumeric(v) && v.length === 1 && (suffixArray[idx] = `0${v}`); }); // hh:mm if (suffixArray.length === 2 && !hasSecond) { suffixArray.push("00"); } - var suffixString = suffixArray.join(":"); - var dateString = newArray.slice(0, 3).join("-"); - if (BI.isNotEmptyString(suffixString)) { - dateString += " " + suffixString; + const suffixString = suffixArray.join(":"); + let dateString = newArray.slice(0, 3).join("-"); + if (isNotEmptyString(suffixString)) { + dateString += ` ${suffixString}`; } + return dateString; - }, + } - _getFormatString: function () { + _getFormatString() { return this.options.format || this._const.compareFormat; - }, + } + + _dateCheck(date) { + return print(parseDateTime(date, "%Y-%x-%d %H:%M:%S"), "%Y-%x-%d %H:%M:%S") === date || + print(parseDateTime(date, "%Y-%X-%d %H:%M:%S"), "%Y-%X-%d %H:%M:%S") === date || + print(parseDateTime(date, "%Y-%x-%e %H:%M:%S"), "%Y-%x-%e %H:%M:%S") === date || + print(parseDateTime(date, "%Y-%X-%e %H:%M:%S"), "%Y-%X-%e %H:%M:%S") === date || - _dateCheck: function (date) { - return BI.print(BI.parseDateTime(date, "%Y-%x-%d %H:%M:%S"), "%Y-%x-%d %H:%M:%S") === date || - BI.print(BI.parseDateTime(date, "%Y-%X-%d %H:%M:%S"), "%Y-%X-%d %H:%M:%S") === date || - BI.print(BI.parseDateTime(date, "%Y-%x-%e %H:%M:%S"), "%Y-%x-%e %H:%M:%S") === date || - BI.print(BI.parseDateTime(date, "%Y-%X-%e %H:%M:%S"), "%Y-%X-%e %H:%M:%S") === date || + print(parseDateTime(date, "%Y-%x-%d"), "%Y-%x-%d") === date || + print(parseDateTime(date, "%Y-%X-%d"), "%Y-%X-%d") === date || + print(parseDateTime(date, "%Y-%x-%e"), "%Y-%x-%e") === date || + print(parseDateTime(date, "%Y-%X-%e"), "%Y-%X-%e") === date; + } - BI.print(BI.parseDateTime(date, "%Y-%x-%d"), "%Y-%x-%d") === date || - BI.print(BI.parseDateTime(date, "%Y-%X-%d"), "%Y-%X-%d") === date || - BI.print(BI.parseDateTime(date, "%Y-%x-%e"), "%Y-%x-%e") === date || - BI.print(BI.parseDateTime(date, "%Y-%X-%e"), "%Y-%X-%e") === date; - }, - _checkVoid: function (obj) { - return !BI.checkDateVoid(obj.year, obj.month, obj.day, this.options.min, this.options.max)[0]; - }, - _autoAppend: function (v, dateObj) { - if (BI.isNotNull(dateObj) && BI.checkDateLegal(v)) { + _checkVoid(obj) { + return !checkDateVoid(obj.year, obj.month, obj.day, this.options.min, this.options.max)[0]; + } + + _autoAppend(v, dateObj) { + if (isNotNull(dateObj) && checkDateLegal(v)) { + const splitMonth = v.split("-")[1]; switch (v.length) { - case this._const.yearLength: - if (this._yearCheck(v)) { - this.editor.setValue(v + "-"); - } - break; - case this._const.yearMonthLength: - case this._const.yearFullMonthLength: - var splitMonth = v.split("-")[1]; - if ((BI.isNotNull(splitMonth) && splitMonth.length === 2) || this._monthCheck(v)) { - this.editor.setValue(v + "-"); - } - break; + case this._const.yearLength: + if (this._yearCheck(v)) { + this.editor.setValue(`${v}-`); + } + break; + case this._const.yearMonthLength: + case this._const.yearFullMonthLength: + if ((isNotNull(splitMonth) && splitMonth.length === 2) || this._monthCheck(v)) { + this.editor.setValue(`${v}-`); + } + break; + default: } } - }, + } - _yearCheck: function (v) { - var date = BI.print(BI.parseDateTime(v, "%Y-%X-%d"), "%Y-%X-%d"); - return BI.print(BI.parseDateTime(v, "%Y"), "%Y") === v && date >= this.options.min && date <= this.options.max; - }, + _yearCheck(v) { + const date = print(parseDateTime(v, "%Y-%X-%d"), "%Y-%X-%d"); + + return print(parseDateTime(v, "%Y"), "%Y") === v && date >= this.options.min && date <= this.options.max; + } - _monthCheck: function (v) { - var date = BI.parseDateTime(v, "%Y-%X-%d"); - var dateStr = BI.print(date, "%Y-%X-%d"); - return (date.getMonth() > 0 && (BI.print(BI.parseDateTime(v, "%Y-%X"), "%Y-%X") === v || - BI.print(BI.parseDateTime(v, "%Y-%x"), "%Y-%x") === v)) && dateStr >= this.options.min && dateStr <= this.options.max; - }, + _monthCheck(v) { + const date = parseDateTime(v, "%Y-%X-%d"); + const dateStr = print(date, "%Y-%X-%d"); + + return (date.getMonth() > 0 && (print(parseDateTime(v, "%Y-%X"), "%Y-%X") === v || + print(parseDateTime(v, "%Y-%x"), "%Y-%x") === v)) && dateStr >= this.options.min && dateStr <= this.options.max; + } - _setInnerValue: function (date) { - var dateStr = BI.print(date, this._getFormatString()); + _setInnerValue(date) { + const dateStr = print(date, this._getFormatString()); this.editor.setState(dateStr); this.editor.setValue(dateStr); - }, + } - _getText: function (obj) { - var value = ""; - var endText = ""; - if (BI.isNotNull(obj.year)) { - if (BI.parseInt(obj.year) !== 0) { - value += Math.abs(obj.year) + BI.i18nText("BI-Basic_Year") + (obj.year < 0 ? BI.i18nText("BI-Basic_Front") : BI.i18nText("BI-Basic_Behind")); + _getText(obj) { + let value = ""; + let endText = ""; + if (isNotNull(obj.year)) { + if (parseInt(obj.year) !== 0) { + value += Math.abs(obj.year) + i18nText("BI-Basic_Year") + (obj.year < 0 ? i18nText("BI-Basic_Front") : i18nText("BI-Basic_Behind")); } - endText = getPositionText(BI.i18nText("BI-Basic_Year"), obj.position); + endText = getPositionText(i18nText("BI-Basic_Year"), obj.position); } - if (BI.isNotNull(obj.quarter)) { - if (BI.parseInt(obj.quarter) !== 0) { - value += Math.abs(obj.quarter) + BI.i18nText("BI-Basic_Single_Quarter") + (obj.quarter < 0 ? BI.i18nText("BI-Basic_Front") : BI.i18nText("BI-Basic_Behind")); + if (isNotNull(obj.quarter)) { + if (parseInt(obj.quarter) !== 0) { + value += Math.abs(obj.quarter) + i18nText("BI-Basic_Single_Quarter") + (obj.quarter < 0 ? i18nText("BI-Basic_Front") : i18nText("BI-Basic_Behind")); } - endText = getPositionText(BI.i18nText("BI-Basic_Single_Quarter"), obj.position); + endText = getPositionText(i18nText("BI-Basic_Single_Quarter"), obj.position); } - if (BI.isNotNull(obj.month)) { - if (BI.parseInt(obj.month) !== 0) { - value += Math.abs(obj.month) + BI.i18nText("BI-Basic_Month") + (obj.month < 0 ? BI.i18nText("BI-Basic_Front") : BI.i18nText("BI-Basic_Behind")); + if (isNotNull(obj.month)) { + if (parseInt(obj.month) !== 0) { + value += Math.abs(obj.month) + i18nText("BI-Basic_Month") + (obj.month < 0 ? i18nText("BI-Basic_Front") : i18nText("BI-Basic_Behind")); } - endText = getPositionText(BI.i18nText("BI-Basic_Month"), obj.position); + endText = getPositionText(i18nText("BI-Basic_Month"), obj.position); } - if (BI.isNotNull(obj.week)) { - if (BI.parseInt(obj.week) !== 0) { - value += Math.abs(obj.week) + BI.i18nText("BI-Basic_Week") + (obj.week < 0 ? BI.i18nText("BI-Basic_Front") : BI.i18nText("BI-Basic_Behind")); + if (isNotNull(obj.week)) { + if (parseInt(obj.week) !== 0) { + value += Math.abs(obj.week) + i18nText("BI-Basic_Week") + (obj.week < 0 ? i18nText("BI-Basic_Front") : i18nText("BI-Basic_Behind")); } - endText = getPositionText(BI.i18nText("BI-Basic_Week"), obj.position); + endText = getPositionText(i18nText("BI-Basic_Week"), obj.position); } - if (BI.isNotNull(obj.day)) { - if (BI.parseInt(obj.day) !== 0) { - value += Math.abs(obj.day) + BI.i18nText("BI-Basic_Day") + (obj.day < 0 ? BI.i18nText("BI-Basic_Front") : BI.i18nText("BI-Basic_Behind")); + if (isNotNull(obj.day)) { + if (parseInt(obj.day) !== 0) { + value += Math.abs(obj.day) + i18nText("BI-Basic_Day") + (obj.day < 0 ? i18nText("BI-Basic_Front") : i18nText("BI-Basic_Behind")); } - endText = BI.size(obj) === 1 ? getPositionText(BI.i18nText("BI-Basic_Month"), obj.position) : ""; + endText = size(obj) === 1 ? getPositionText(i18nText("BI-Basic_Month"), obj.position) : ""; } - if (BI.isNotNull(obj.workDay) && BI.parseInt(obj.workDay) !== 0) { - value += Math.abs(obj.workDay) + BI.i18nText("BI-Basic_Work_Day") + (obj.workDay < 0 ? BI.i18nText("BI-Basic_Front") : BI.i18nText("BI-Basic_Behind")); + if (isNotNull(obj.workDay) && parseInt(obj.workDay) !== 0) { + value += Math.abs(obj.workDay) + i18nText("BI-Basic_Work_Day") + (obj.workDay < 0 ? i18nText("BI-Basic_Front") : i18nText("BI-Basic_Behind")); } + return value + endText; function getPositionText(baseText, position) { switch (position) { - case BI.DynamicDateCard.OFFSET.BEGIN: - return baseText + BI.i18nText("BI-Basic_Begin_Start"); - case BI.DynamicDateCard.OFFSET.END: - return baseText + BI.i18nText("BI-Basic_End_Stop"); - case BI.DynamicDateCard.OFFSET.CURRENT: - default: - return BI.i18nText("BI-Basic_Current_Day"); + case DynamicDateCard.OFFSET.BEGIN: + return baseText + i18nText("BI-Basic_Begin_Start"); + case DynamicDateCard.OFFSET.END: + return baseText + i18nText("BI-Basic_End_Stop"); + case DynamicDateCard.OFFSET.CURRENT: + default: + return i18nText("BI-Basic_Current_Day"); } } - }, + } - setMinDate: function (minDate) { - if (BI.isNotEmptyString(this.options.min)) { + setMinDate(minDate) { + if (isNotEmptyString(this.options.min)) { this.options.min = minDate; } - }, + } - setMaxDate: function (maxDate) { - if (BI.isNotEmptyString(this.options.max)) { + setMaxDate(maxDate) { + if (isNotEmptyString(this.options.max)) { this.options.max = maxDate; } - }, + } - setValue: function (v) { - var type, value, self = this; - var date = BI.getDate(); + setValue(v) { + let type, value; + let date = getDate(); this.storeValue = v; - if (BI.isNotNull(v)) { - type = v.type || BI.DynamicDateCombo.Static; + if (isNotNull(v)) { + type = v.type || DynamicDateCombo.Static; value = v.value || v; } + const text = this._getText(value); + switch (type) { - case BI.DynamicDateCombo.Dynamic: - var text = this._getText(value); - date = BI.DynamicDateHelper.getCalculation(value); - this._setInnerValue(date, text); - break; - case BI.DynamicDateCombo.Static: - default: - if (BI.isNull(value) || BI.isNull(value.day)) { - this.editor.setState(""); - this.editor.setValue(""); - } else { - var dateStr = BI.print(BI.getDate(value.year, (value.month - 1), value.day, value.hour || 0, value.minute || 0, - value.second || 0), this._getFormatString()); - this.editor.setState(dateStr); - this.editor.setValue(dateStr); - } - break; + case DynamicDateCombo.Dynamic: + date = DynamicDateHelper.getCalculation(value); + this._setInnerValue(date, text); + break; + case DynamicDateCombo.Static: + default: + if (isNull(value) || isNull(value.day)) { + this.editor.setState(""); + this.editor.setValue(""); + } else { + const dateStr = print(getDate(value.year, (value.month - 1), value.day, value.hour || 0, value.minute || 0, + value.second || 0), this._getFormatString()); + this.editor.setState(dateStr); + this.editor.setValue(dateStr); + } + break; } - }, + } - getKey: function () { + getKey() { return this.editor.getValue(); - }, - getValue: function () { + } + + getValue() { return this.storeValue; - }, + } - isValid: function () { + isValid() { return this.editor.isValid(); - }, + } - focus: function () { + focus() { this.editor.focus(); - }, + } - blur: function () { + blur() { this.editor.blur(); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.editor.setWaterMark(v); } -}); - -BI.DynamicDateTimeTrigger.EVENT_BLUR = "EVENT_BLUR"; -BI.DynamicDateTimeTrigger.EVENT_FOCUS = "EVENT_FOCUS"; -BI.DynamicDateTimeTrigger.EVENT_START = "EVENT_START"; -BI.DynamicDateTimeTrigger.EVENT_STOP = "EVENT_STOP"; -BI.DynamicDateTimeTrigger.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.DynamicDateTimeTrigger.EVENT_CHANGE = "EVENT_CHANGE"; -BI.DynamicDateTimeTrigger.EVENT_VALID = "EVENT_VALID"; -BI.DynamicDateTimeTrigger.EVENT_ERROR = "EVENT_ERROR"; -BI.DynamicDateTimeTrigger.EVENT_TRIGGER_CLICK = "EVENT_TRIGGER_CLICK"; -BI.DynamicDateTimeTrigger.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.shortcut("bi.dynamic_date_time_trigger", BI.DynamicDateTimeTrigger); +} diff --git a/src/widget/dynamicdatetime/index.js b/src/widget/dynamicdatetime/index.js new file mode 100644 index 000000000..2d289174f --- /dev/null +++ b/src/widget/dynamicdatetime/index.js @@ -0,0 +1,4 @@ +export { DynamicDateTimeSelect } from "./dynamicdatetime.timeselect"; +export { DynamicDateTimeCombo } from "./dynamicdatetime.combo"; +export { DynamicDateTimePopup } from "./dynamicdatetime.popup"; +export { DynamicDateTimeTrigger } from "./dynamicdatetime.trigger"; diff --git a/src/widget/index.js b/src/widget/index.js index 9e92a96ba..ce87719b2 100644 --- a/src/widget/index.js +++ b/src/widget/index.js @@ -1,12 +1,27 @@ import { Collapse } from "./collapse/collapse"; import * as calendar from "./date/calendar"; +import * as dynamicdate from "./dynamicdate"; +import * as datepane from "./datepane"; +import * as datetime from "./datetime"; +import * as datetimepane from "./datetimepane"; +import * as dynamicdatetime from "./dynamicdatetime"; Object.assign(BI, { Collapse, ...calendar, + ...dynamicdate, + ...datepane, + ...datetime, + ...datetimepane, + ...dynamicdatetime, }); export * from "./date/calendar"; +export * from "./dynamicdate"; +export * from "./datepane"; +export * from "./datetime"; +export * from "./datetimepane"; +export * from "./dynamicdatetime"; export { Collapse }; From 5b33d1e9c3ea88840e99b3964b6302d4cb447727 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Thu, 12 Jan 2023 10:15:39 +0800 Subject: [PATCH 080/300] =?UTF-8?q?KERNEL-14092=20=20refactor:=20widget/ti?= =?UTF-8?q?me=E5=8F=8A=E8=A7=A3=E5=86=B3parseDateTime=E7=9A=84=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/2.base.js | 12 +- src/widget/index.js | 3 + src/widget/time/datetime.popup.js | 166 +++++------ src/widget/time/index.js | 3 + src/widget/time/time.combo.js | 450 +++++++++++++++--------------- src/widget/time/time.trigger.js | 349 +++++++++++------------ 6 files changed, 493 insertions(+), 490 deletions(-) create mode 100644 src/widget/time/index.js diff --git a/src/core/2.base.js b/src/core/2.base.js index 003839ec4..c5d540a06 100644 --- a/src/core/2.base.js +++ b/src/core/2.base.js @@ -1230,22 +1230,22 @@ export function parseDateTime(str, fmt) { // if (!a[i]) { // continue; // } - if (isNaN(y)) { + if (_global.isNaN(y)) { y = today.getFullYear(); } - if (isNaN(m)) { + if (_global.isNaN(m)) { m = today.getMonth(); } - if (isNaN(d)) { + if (_global.isNaN(d)) { d = today.getDate(); } - if (isNaN(hr)) { + if (_global.isNaN(hr)) { hr = today.getHours(); } - if (isNaN(min)) { + if (_global.isNaN(min)) { min = today.getMinutes(); } - if (isNaN(sec)) { + if (_global.isNaN(sec)) { sec = today.getSeconds(); } if (y !== 0) { diff --git a/src/widget/index.js b/src/widget/index.js index ce87719b2..aee31d038 100644 --- a/src/widget/index.js +++ b/src/widget/index.js @@ -5,6 +5,7 @@ import * as datepane from "./datepane"; import * as datetime from "./datetime"; import * as datetimepane from "./datetimepane"; import * as dynamicdatetime from "./dynamicdatetime"; +import * as time from "./time"; Object.assign(BI, { Collapse, @@ -14,6 +15,7 @@ Object.assign(BI, { ...datetime, ...datetimepane, ...dynamicdatetime, + ...time, }); export * from "./date/calendar"; @@ -22,6 +24,7 @@ export * from "./datepane"; export * from "./datetime"; export * from "./datetimepane"; export * from "./dynamicdatetime"; +export * from "./time"; export { Collapse }; diff --git a/src/widget/time/datetime.popup.js b/src/widget/time/datetime.popup.js index 39c5e753d..017b8c0eb 100644 --- a/src/widget/time/datetime.popup.js +++ b/src/widget/time/datetime.popup.js @@ -1,94 +1,102 @@ -!(function () { - BI.TimePopup = BI.inherit(BI.Widget, { - props: { - baseCls: "bi-date-time-popup", - height: 68 - }, - render: function () { - var self = this, o = this.options; +import { shortcut, Widget, i18nText, CenterAdaptLayout, GridLayout, isNull, isEmptyObject, isEmptyString } from "@/core"; +import { TextButton } from "@/base"; +import { DynamicDateTimeSelect } from "../dynamicdatetime"; - return { - type: "bi.vtape", - items: [{ - el: { - type: "bi.center_adapt", - cls: "bi-split-top", - items: [{ - type: "bi.dynamic_date_time_select", - value: o.value, - ref: function (_ref) { - self.timeSelect = _ref; - } - }] - }, - hgap: 10, - height: 44 - }, { - el: { - type: "bi.grid", - items: [[{ - type: "bi.text_button", +@shortcut() +export class TimePopup extends Widget { + static xtype = "bi.time_popup" + + props = { + baseCls: "bi-date-time-popup", + height: 68, + }; + + static BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE" + static BUTTON_CLEAR_EVENT_CHANGE = "BUTTON_CLEAR_EVENT_CHANGE" + static BUTTON_NOW_EVENT_CHANGE = "BUTTON_NOW_EVENT_CHANGE" + static CALENDAR_EVENT_CHANGE = "CALENDAR_EVENT_CHANGE" + + render() { + const o = this.options; + + return { + type: "bi.vtape", + items: [{ + el: { + type: CenterAdaptLayout.xtype, + cls: "bi-split-top", + items: [{ + type: DynamicDateTimeSelect.xtype, + value: o.value, + ref: _ref => { + this.timeSelect = _ref; + }, + }], + }, + hgap: 10, + height: 44, + }, { + el: { + type: GridLayout.xtype, + items: [ + [{ + type: TextButton.xtype, cls: "bi-high-light bi-split-top", shadow: true, - text: BI.i18nText("BI-Basic_Clears"), + text: i18nText("BI-Basic_Clears"), listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.TimePopup.BUTTON_CLEAR_EVENT_CHANGE); - } - }] + eventName: TextButton.EVENT_CHANGE, + action: () => { + this.fireEvent(TimePopup.BUTTON_CLEAR_EVENT_CHANGE); + }, + }], }, { - type: "bi.text_button", + type: TextButton.xtype, cls: "bi-split-left bi-split-right bi-high-light bi-split-top", shadow: true, - text: BI.i18nText("BI-Basic_Now"), + text: i18nText("BI-Basic_Now"), listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.TimePopup.BUTTON_NOW_EVENT_CHANGE); - } - }] + eventName: TextButton.EVENT_CHANGE, + action: () => { + this.fireEvent(TimePopup.BUTTON_NOW_EVENT_CHANGE); + }, + }], }, { - type: "bi.text_button", + type: TextButton.xtype, cls: "bi-high-light bi-split-top", shadow: true, - text: BI.i18nText("BI-Basic_OK"), + text: i18nText("BI-Basic_OK"), listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.TimePopup.BUTTON_OK_EVENT_CHANGE); - } - }] - }]] - }, - height: 24 - }] - }; - }, + eventName: TextButton.EVENT_CHANGE, + action: () => { + this.fireEvent(TimePopup.BUTTON_OK_EVENT_CHANGE); + }, + }], + }] + ], + }, + height: 24, + }], + }; + } - setValue: function (value) { - if (this._checkValueValid(value)) { - this.timeSelect.setValue(); - } else { - this.timeSelect.setValue({ - hour: value.hour, - minute: value.minute, - second: value.second - }); - } - }, + setValue(value) { + if (this._checkValueValid(value)) { + this.timeSelect.setValue(); + } else { + this.timeSelect.setValue({ + hour: value.hour, + minute: value.minute, + second: value.second, + }); + } + } - getValue: function () { - return this.timeSelect.getValue(); - }, + getValue() { + return this.timeSelect.getValue(); + } - _checkValueValid: function (value) { - return BI.isNull(value) || BI.isEmptyObject(value) || BI.isEmptyString(value); - } - }); - BI.TimePopup.BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE"; - BI.TimePopup.BUTTON_CLEAR_EVENT_CHANGE = "BUTTON_CLEAR_EVENT_CHANGE"; - BI.TimePopup.BUTTON_NOW_EVENT_CHANGE = "BUTTON_NOW_EVENT_CHANGE"; - BI.TimePopup.CALENDAR_EVENT_CHANGE = "CALENDAR_EVENT_CHANGE"; - BI.shortcut("bi.time_popup", BI.TimePopup); -})(); \ No newline at end of file + _checkValueValid(value) { + return isNull(value) || isEmptyObject(value) || isEmptyString(value); + } +} diff --git a/src/widget/time/index.js b/src/widget/time/index.js new file mode 100644 index 000000000..da4e7bbe8 --- /dev/null +++ b/src/widget/time/index.js @@ -0,0 +1,3 @@ +export { TimePopup } from "./datetime.popup"; +export { TimeCombo } from "./time.combo"; +export { TimeTrigger } from "./time.trigger"; diff --git a/src/widget/time/time.combo.js b/src/widget/time/time.combo.js index 6f3f8947d..5cf7d74fe 100644 --- a/src/widget/time/time.combo.js +++ b/src/widget/time/time.combo.js @@ -1,247 +1,245 @@ -/** - * 时间选择 - * qcc - * 2019/2/28 - */ +import { shortcut, toPix, getDate, isNotEmptyString, isEqual, isEmptyString, AbsoluteLayout } from "@/core"; +import { Single, IconButton, Combo } from "@/base"; +import { TimePopup } from "./datetime.popup"; -!(function () { - BI.TimeCombo = BI.inherit(BI.Single, { - constants: { - popupHeight: 80, - popupWidth: 240, - comboAdjustHeight: 1, - border: 1, - iconWidth: 24 - }, - props: { - baseCls: "bi-time-combo", - height: 24, - format: "", - allowEdit: false, - isNeedAdjustHeight: false, - isNeedAdjustWidth: false - }, +@shortcut() +export class TimeCombo extends Single { + static xtype = "bi.time_combo" - _init: function () { - var o = this.options; - BI.TimeCombo.superclass._init.apply(this, arguments); - }, + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" + static EVENT_CONFIRM = "EVENT_CONFIRM" + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_VALID = "EVENT_VALID" + static EVENT_ERROR = "EVENT_ERROR" + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW" - render: function () { - var self = this, opts = this.options; - this.storeTriggerValue = ""; - this.storeValue = opts.value; + constants = { + popupHeight: 80, + popupWidth: 240, + comboAdjustHeight: 1, + border: 1, + iconWidth: 24, + } - var popup = { - type: "bi.time_popup", - value: opts.value, - listeners: [{ - eventName: BI.TimePopup.BUTTON_CLEAR_EVENT_CHANGE, - action: function () { - self.setValue(); - self.hidePopupView(); - self.fireEvent(BI.TimeCombo.EVENT_CONFIRM); - } - }, { - eventName: BI.TimePopup.BUTTON_OK_EVENT_CHANGE, - action: function () { - self.setValue(self.popup.getValue()); - self.hidePopupView(); - self.fireEvent(BI.TimeCombo.EVENT_CONFIRM); - } - }, { - eventName: BI.TimePopup.BUTTON_NOW_EVENT_CHANGE, - action: function () { - self._setNowTime(); - } - }], - ref: function (_ref) { - self.popup = _ref; - } - }; - return { - type: "bi.absolute", - items: [{ + props = { + baseCls: "bi-time-combo", + height: 24, + format: "", + allowEdit: false, + isNeedAdjustHeight: false, + isNeedAdjustWidth: false, + }; + + _init() { + super._init(...arguments); + } + + render() { + const opts = this.options; + this.storeTriggerValue = ""; + this.storeValue = opts.value; + + const popup = { + type: "bi.time_popup", + value: opts.value, + listeners: [{ + eventName: TimePopup.BUTTON_CLEAR_EVENT_CHANGE, + action: () => { + this.setValue(); + this.hidePopupView(); + this.fireEvent(TimeCombo.EVENT_CONFIRM); + }, + }, { + eventName: TimePopup.BUTTON_OK_EVENT_CHANGE, + action: () => { + this.setValue(this.popup.getValue()); + this.hidePopupView(); + this.fireEvent(TimeCombo.EVENT_CONFIRM); + }, + }, { + eventName: TimePopup.BUTTON_NOW_EVENT_CHANGE, + action: () => { + this._setNowTime(); + }, + }], + ref: _ref => { + this.popup = _ref; + }, + }; + + return { + type: AbsoluteLayout.xtype, + items: [{ + el: { + type: Combo.xtype, + cls: "bi-border bi-border-radius", + container: opts.container, + toggle: false, + isNeedAdjustHeight: opts.isNeedAdjustHeight, + isNeedAdjustWidth: opts.isNeedAdjustWidth, el: { - type: "bi.combo", - cls: "bi-border bi-border-radius", - container: opts.container, - toggle: false, - isNeedAdjustHeight: opts.isNeedAdjustHeight, - isNeedAdjustWidth: opts.isNeedAdjustWidth, - el: { - type: "bi.horizontal_fill", - columnSize: ["fill", this.constants.iconWidth], - height: BI.toPix(opts.height, 2), - items: [{ - type: "bi.time_trigger", - height: BI.toPix(opts.height, 2), - allowEdit: opts.allowEdit, - watermark: opts.watermark, - format: opts.format, - value: opts.value, - ref: function (_ref) { - self.trigger = _ref; - }, - listeners: [{ - eventName: "EVENT_KEY_DOWN", - action: function () { - if (self.combo.isViewVisible()) { - self.combo.hideView(); - } - self.fireEvent(BI.TimeCombo.EVENT_KEY_DOWN, arguments); - } - }, { - eventName: "EVENT_STOP", - action: function () { - if (!self.combo.isViewVisible()) { - self.combo.showView(); - } - } - }, { - eventName: "EVENT_FOCUS", - action: function () { - self.storeTriggerValue = self.trigger.getKey(); - if (!self.combo.isViewVisible()) { - self.combo.showView(); - } - self.fireEvent("EVENT_FOCUS"); + type: "bi.horizontal_fill", + columnSize: ["fill", this.constants.iconWidth], + height: toPix(opts.height, 2), + items: [{ + type: "bi.time_trigger", + height: toPix(opts.height, 2), + allowEdit: opts.allowEdit, + watermark: opts.watermark, + format: opts.format, + value: opts.value, + ref: _ref => { + this.trigger = _ref; + }, + listeners: [{ + eventName: "EVENT_KEY_DOWN", + action: () => { + if (this.combo.isViewVisible()) { + this.combo.hideView(); } - }, { - eventName: "EVENT_BLUR", - action: function () { - self.fireEvent("EVENT_BLUR"); - } - }, { - eventName: "EVENT_ERROR", - action: function () { - var date = BI.getDate(); - self.storeValue = { - hour: date.getHours(), - minute: date.getMinutes(), - second: date.getSeconds() - }; - self.fireEvent("EVENT_ERROR"); - } - }, { - eventName: "EVENT_VALID", - action: function () { - self.fireEvent("EVENT_VALID"); - } - }, { - eventName: "EVENT_CHANGE", - action: function () { - self.fireEvent("EVENT_CHANGE"); + this.fireEvent(TimeCombo.EVENT_KEY_DOWN, arguments); + }, + }, { + eventName: "EVENT_STOP", + action: () => { + if (!this.combo.isViewVisible()) { + this.combo.showView(); } - }, { - eventName: "EVENT_CONFIRM", - action: function () { - if (self.combo.isViewVisible()) { - return; - } - var dateStore = self.storeTriggerValue; - var dateObj = self.trigger.getKey(); - if (BI.isNotEmptyString(dateObj) && !BI.isEqual(dateObj, dateStore)) { - self.storeValue = self.trigger.getValue(); - self.setValue(self.trigger.getValue()); - } else if (BI.isEmptyString(dateObj)) { - self.storeValue = null; - self.trigger.setValue(); - } - self.fireEvent("EVENT_CONFIRM"); + }, + }, { + eventName: "EVENT_FOCUS", + action: () => { + this.storeTriggerValue = this.trigger.getKey(); + if (!this.combo.isViewVisible()) { + this.combo.showView(); } - }] + this.fireEvent("EVENT_FOCUS"); + }, }, { - el: { - type: "bi.icon_button", - cls: "bi-trigger-icon-button time-font", - width: this.constants.iconWidth, - listeners: [{ - eventName: BI.IconButton.EVENT_CHANGE, - action: function () { - if (self.combo.isViewVisible()) { - // self.combo.hideView(); - } else { - self.combo.showView(); - } - } - }], - ref: function (_ref) { - self.triggerBtn = _ref; + eventName: "EVENT_BLUR", + action: () => { + this.fireEvent("EVENT_BLUR"); + }, + }, { + eventName: "EVENT_ERROR", + action: () => { + const date = getDate(); + this.storeValue = { + hour: date.getHours(), + minute: date.getMinutes(), + second: date.getSeconds(), + }; + this.fireEvent("EVENT_ERROR"); + }, + }, { + eventName: "EVENT_VALID", + action: () => { + this.fireEvent("EVENT_VALID"); + }, + }, { + eventName: "EVENT_CHANGE", + action: () => { + this.fireEvent("EVENT_CHANGE"); + }, + }, { + eventName: "EVENT_CONFIRM", + action: () => { + if (this.combo.isViewVisible()) { + return; + } + const dateStore = this.storeTriggerValue; + const dateObj = this.trigger.getKey(); + if (isNotEmptyString(dateObj) && !isEqual(dateObj, dateStore)) { + this.storeValue = this.trigger.getValue(); + this.setValue(this.trigger.getValue()); + } else if (isEmptyString(dateObj)) { + this.storeValue = null; + this.trigger.setValue(); } + this.fireEvent("EVENT_CONFIRM"); }, }], - }, - adjustLength: this.constants.comboAdjustHeight, - popup: { - el: popup, - width: opts.isNeedAdjustWidth ? opts.width : this.constants.popupWidth, - stopPropagation: false - }, - hideChecker: function (e) { - return self.triggerBtn.element.find(e.target).length === 0; - }, - listeners: [{ - eventName: BI.Combo.EVENT_BEFORE_POPUPVIEW, - action: function () { - self.popup.setValue(self.storeValue); - self.fireEvent(BI.TimeCombo.EVENT_BEFORE_POPUPVIEW); - } + }, { + el: { + type: IconButton.xtype, + cls: "bi-trigger-icon-button time-font", + width: this.constants.iconWidth, + listeners: [{ + eventName: IconButton.EVENT_CHANGE, + action: () => { + if (this.combo.isViewVisible()) { + // this.combo.hideView(); + } else { + this.combo.showView(); + } + }, + }], + ref: _ref => { + this.triggerBtn = _ref; + }, + }, }], - ref: function (_ref) { - self.combo = _ref; - } }, - top: 0, - left: 0, - right: 0, - bottom: 0 - }] - }; - }, + adjustLength: this.constants.comboAdjustHeight, + popup: { + el: popup, + width: opts.isNeedAdjustWidth ? opts.width : this.constants.popupWidth, + stopPropagation: false, + }, + hideChecker: e => this.triggerBtn.element.find(e.target).length === 0, + listeners: [{ + eventName: Combo.EVENT_BEFORE_POPUPVIEW, + action: () => { + this.popup.setValue(this.storeValue); + this.fireEvent(TimeCombo.EVENT_BEFORE_POPUPVIEW); + }, + }], + ref: _ref => { + this.combo = _ref; + }, + }, + top: 0, + left: 0, + right: 0, + bottom: 0, + }], + }; + } - setValue: function (v) { - this.storeValue = v; - this.trigger.setValue(v); - }, - getValue: function () { - return this.storeValue; - }, + setValue(v) { + this.storeValue = v; + this.trigger.setValue(v); + } - hidePopupView: function () { - this.combo.hideView(); - }, + getValue() { + return this.storeValue; + } - _setNowTime: function () { - var date = BI.getDate(); - var nowTome = { - hour: date.getHours(), - minute: date.getMinutes(), - second: date.getSeconds() - }; - this.setValue(nowTome); - this.hidePopupView(); - this.fireEvent(BI.TimeCombo.EVENT_CONFIRM); - }, + hidePopupView() { + this.combo.hideView(); + } - focus: function () { - this.trigger.focus(); - }, + _setNowTime() { + const date = getDate(); + const nowTome = { + hour: date.getHours(), + minute: date.getMinutes(), + second: date.getSeconds(), + }; + this.setValue(nowTome); + this.hidePopupView(); + this.fireEvent(TimeCombo.EVENT_CONFIRM); + } - blur: function () { - this.trigger.blur(); - }, + focus() { + this.trigger.focus(); + } - setWaterMark: function (v) { - this.trigger.setWaterMark(v); - } - }); + blur() { + this.trigger.blur(); + } - BI.TimeCombo.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; - BI.TimeCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; - BI.TimeCombo.EVENT_CHANGE = "EVENT_CHANGE"; - BI.TimeCombo.EVENT_VALID = "EVENT_VALID"; - BI.TimeCombo.EVENT_ERROR = "EVENT_ERROR"; - BI.TimeCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; - BI.shortcut("bi.time_combo", BI.TimeCombo); -})(); \ No newline at end of file + setWaterMark(v) { + this.trigger.setWaterMark(v); + } +} diff --git a/src/widget/time/time.trigger.js b/src/widget/time/time.trigger.js index a15235cf4..2fc2b0751 100644 --- a/src/widget/time/time.trigger.js +++ b/src/widget/time/time.trigger.js @@ -1,202 +1,193 @@ -!(function () { - BI.TimeTrigger = BI.inherit(BI.Trigger, { +import { shortcut, i18nText, bind, isNotNull, isNotEmptyString, isEqual, AbsoluteLayout, any, print, parseDateTime, isEmptyObject, getDate, isNotEmptyObject } from "@/core"; +import { Trigger, Text } from "@/base"; +import { SignEditor } from "@/case"; - _const: { - COMPARE_FORMAT: "%H:%M:%S", - COMPLETE_COMPARE_FORMAT: "%Y-%M-%d %H:%M:%S %P", - FORMAT_ARRAY: [ - "%H:%M:%S", // HH:mm:ss - "%I:%M:%S", // hh:mm:ss - "%l:%M:%S", // h:mm:ss - "%k:%M:%S", // H:mm:ss - "%l:%M:%S %p", // h:mm:ss a - "%l:%M:%S %P", // h:mm:ss a - "%H:%M:%S %p", // HH:mm:ss a - "%H:%M:%S %P", // HH:mm:ss a - "%l:%M", // h:mm - "%k:%M", // H:mm - "%I:%M", // hh:mm - "%H:%M", // HH:mm - "%M:%S" // mm:ss - ], - DEFAULT_DATE_STRING: "2000-01-01", - DEFAULT_HOUR: "00" - }, +@shortcut() +export class TimeTrigger extends Trigger { + static xtype = "bi.time_trigger" - props: () => ({ + _const = { + COMPARE_FORMAT: "%H:%M:%S", + COMPLETE_COMPARE_FORMAT: "%Y-%M-%d %H:%M:%S %P", + FORMAT_ARRAY: ["%H:%M:%S", "%I:%M:%S", "%l:%M:%S", "%k:%M:%S", "%l:%M:%S %p", "%l:%M:%S %P", "%H:%M:%S %p", "%H:%M:%S %P", "%l:%M", "%k:%M", "%I:%M", "%H:%M", "%M:%S"], + DEFAULT_DATE_STRING: "2000-01-01", + DEFAULT_HOUR: "00", + }; + + props() { + return { extraCls: "bi-time-trigger", value: {}, format: "", allowEdit: false, - watermark: BI.i18nText("BI-Basic_Unrestricted"), - }), + watermark: i18nText("BI-Basic_Unrestricted"), + }; + } - render: function () { - var self = this, o = this.options; - this.storeTriggerValue = ""; - this.storeValue = o.value; - return { - type: "bi.absolute", - items: [{ - el: { - type: "bi.sign_editor", - height: o.height, - validationChecker: function (v) { - return self._dateCheck(v); + render() { + const o = this.options; + this.storeTriggerValue = ""; + this.storeValue = o.value; + + return { + type: AbsoluteLayout.xtype, + items: [{ + el: { + type: SignEditor.xtype, + height: o.height, + validationChecker: v => this._dateCheck(v), + quitChecker () { + return false; + }, + ref: _ref => { + this.editor = _ref; + }, + value: this._formatValue(o.value), + hgap: 4, + allowBlank: true, + watermark: o.watermark, + title: bind(this._getTitle, this), + listeners: [{ + eventName: "EVENT_KEY_DOWN", + action: (...args) => { + this.fireEvent("EVENT_KEY_DOWN", ...args); }, - quitChecker: function () { - return false; + }, { + eventName: "EVENT_FOCUS", + action: () => { + this.storeTriggerValue = this.getKey(); + this.fireEvent("EVENT_FOCUS"); }, - ref: function (_ref) { - self.editor = _ref; + }, { + eventName: "EVENT_BLUR", + action: () => { + this.fireEvent("EVENT_BLUR"); }, - value: this._formatValue(o.value), - hgap: 4, - allowBlank: true, - watermark: o.watermark, - title: BI.bind(this._getTitle, this), - listeners: [{ - eventName: "EVENT_KEY_DOWN", - action: function () { - self.fireEvent("EVENT_KEY_DOWN", arguments); - } - }, { - eventName: "EVENT_FOCUS", - action: function () { - self.storeTriggerValue = self.getKey(); - self.fireEvent("EVENT_FOCUS"); - } - }, { - eventName: "EVENT_BLUR", - action: function () { - self.fireEvent("EVENT_BLUR"); - } - }, { - eventName: "EVENT_STOP", - action: function () { - self.fireEvent("EVENT_STOP"); - } - }, { - eventName: "EVENT_VALID", - action: function () { - self.fireEvent("EVENT_VALID"); - } - }, { - eventName: "EVENT_ERROR", - action: function () { - self.fireEvent("EVENT_ERROR"); - } - }, { - eventName: "EVENT_CONFIRM", - action: function () { - var value = self.editor.getValue(); - if (BI.isNotNull(value)) { - self.editor.setState(value); - } - if (BI.isNotEmptyString(value) && !BI.isEqual(self.storeTriggerValue, self.getKey())) { - var date = value.match(/\d+/g); - self.storeValue = { - hour: date[0] | 0, - minute: date[1] | 0, - second: date[2] | 0 - }; - } - self.fireEvent("EVENT_CONFIRM"); - } - }, { - eventName: "EVENT_START", - action: function () { - self.fireEvent("EVENT_START"); + }, { + eventName: "EVENT_STOP", + action: () => { + this.fireEvent("EVENT_STOP"); + }, + }, { + eventName: "EVENT_VALID", + action: () => { + this.fireEvent("EVENT_VALID"); + }, + }, { + eventName: "EVENT_ERROR", + action: () => { + this.fireEvent("EVENT_ERROR"); + }, + }, { + eventName: "EVENT_CONFIRM", + action: () => { + const value = this.editor.getValue(); + if (isNotNull(value)) { + this.editor.setState(value); } - }, { - eventName: "EVENT_CHANGE", - action: function () { - self.fireEvent("EVENT_CHANGE"); + if (isNotEmptyString(value) && !isEqual(this.storeTriggerValue, this.getKey())) { + const date = value.match(/\d+/g); + this.storeValue = { + hour: date[0] | 0, + minute: date[1] | 0, + second: date[2] | 0, + }; } - }] - }, - left: 0, - right: 0, - top: 0, - bottom: 0 - }, { - el: { - type: "bi.text", - invisible: o.allowEdit, - cls: "show-text", - title: BI.bind(this._getTitle, this), - hgap: 4 - }, - left: 0, - right: 0, - top: 0, - bottom: 0 - }] - }; - }, + this.fireEvent("EVENT_CONFIRM"); + }, + }, { + eventName: "EVENT_START", + action: () => { + this.fireEvent("EVENT_START"); + }, + }, { + eventName: "EVENT_CHANGE", + action: () => { + this.fireEvent("EVENT_CHANGE"); + }, + }], + }, + left: 0, + right: 0, + top: 0, + bottom: 0, + }, { + el: { + type: Text.xtype, + invisible: o.allowEdit, + cls: "show-text", + title: bind(this._getTitle, this), + hgap: 4, + }, + left: 0, + right: 0, + top: 0, + bottom: 0, + }], + }; + } - _dateCheck: function (date) { - var c = this._const; - var self = this; - return BI.any(c.FORMAT_ARRAY, function (idx, format) { - return BI.print(BI.parseDateTime(c.DEFAULT_DATE_STRING + " " + self._getCompleteHMS(date, format), c.COMPLETE_COMPARE_FORMAT), format) === date; - }); - }, + _dateCheck(date) { + const c = this._const; + + return any(c.FORMAT_ARRAY, (idx, format) => print(parseDateTime(`${c.DEFAULT_DATE_STRING} ${this._getCompleteHMS(date, format)}`, c.COMPLETE_COMPARE_FORMAT), format) === date); + } - _getCompleteHMS: function (str, format) { - var c = this._const; - switch (format) { - case "%M:%S": - str = c.DEFAULT_HOUR + ":" + str; - break; - default: - break; - } - return str; - }, + _getCompleteHMS(str, format) { + const c = this._const; + switch (format) { + case "%M:%S": + str = `${c.DEFAULT_HOUR}:${str}`; + break; + default: + break; + } + + return str; + } - _getTitle: function () { - var storeValue = this.storeValue || {}; - if (BI.isEmptyObject(storeValue)) { - return this.options.watermark; - } - var date = BI.getDate(); - return BI.print(BI.getDate(date.getFullYear(), 0, 1, storeValue.hour, storeValue.minute, storeValue.second), this._getFormatString()); - }, + _getTitle() { + const storeValue = this.storeValue || {}; + if (isEmptyObject(storeValue)) { + return this.options.watermark; + } + const date = getDate(); + + return print(getDate(date.getFullYear(), 0, 1, storeValue.hour, storeValue.minute, storeValue.second), this._getFormatString()); + } - _getFormatString: function () { - return this.options.format || this._const.COMPARE_FORMAT; - }, + _getFormatString() { + return this.options.format || this._const.COMPARE_FORMAT; + } - _formatValue: function (v) { - var now = BI.getDate(); - return BI.isNotEmptyObject(v) ? BI.print(BI.getDate(now.getFullYear(), now.getMonth(), now.getDay(), v.hour, v.minute, v.second), this._getFormatString()) : ""; - }, + _formatValue(v) { + const now = getDate(); + + return isNotEmptyObject(v) ? print(getDate(now.getFullYear(), now.getMonth(), now.getDay(), v.hour, v.minute, v.second), this._getFormatString()) : ""; + } - getKey: function () { - return this.editor.getValue(); - }, + getKey() { + return this.editor.getValue(); + } - setValue: function (v) { - this.storeValue = v; - this.editor.setValue(this._formatValue(v)); - }, + setValue(v) { + this.storeValue = v; + this.editor.setValue(this._formatValue(v)); + } - getValue: function () { - return this.storeValue; - }, + getValue() { + return this.storeValue; + } - focus: function () { - this.editor.focus(); - }, + focus() { + this.editor.focus(); + } - blur: function () { - this.editor.blur(); - }, + blur() { + this.editor.blur(); + } - setWaterMark: function (v) { - this.editor.setWaterMark(v); - } - }); - BI.shortcut("bi.time_trigger", BI.TimeTrigger); -})(); + setWaterMark(v) { + this.editor.setWaterMark(v); + } +} From 2d2d87015e5fa623eefa10c0d934e4d6262b02ea Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Thu, 12 Jan 2023 10:38:27 +0800 Subject: [PATCH 081/300] =?UTF-8?q?=E6=97=A0JIRA=E4=BB=BB=E5=8A=A1=20fix:?= =?UTF-8?q?=20=E4=BD=BF=E7=94=A8=E8=84=9A=E6=9C=AC=E6=BC=8F=E6=8E=89?= =?UTF-8?q?=E7=9A=84=E5=B8=B8=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/widget/dynamicdate/dynamicdate.combo.js | 8 ++++++++ src/widget/dynamicdate/dynamicdate.popup.js | 4 ++++ src/widget/dynamicdatetime/dynamicdatetime.combo.js | 8 ++++++++ src/widget/dynamicdatetime/dynamicdatetime.popup.js | 5 +++++ 4 files changed, 25 insertions(+) diff --git a/src/widget/dynamicdate/dynamicdate.combo.js b/src/widget/dynamicdate/dynamicdate.combo.js index 7cb7165dc..173327f56 100644 --- a/src/widget/dynamicdate/dynamicdate.combo.js +++ b/src/widget/dynamicdate/dynamicdate.combo.js @@ -7,6 +7,14 @@ import { DynamicDatePopup } from "./dynamicdate.popup"; export class DynamicDateCombo extends Single { static xtype = "bi.dynamic_date_combo" + constants = { + popupHeight: 259, + popupWidth: 270, + comboAdjustHeight: 1, + border: 1, + iconWidth: 24, + } + props = { baseCls: "bi-dynamic-date-combo", height: 24, diff --git a/src/widget/dynamicdate/dynamicdate.popup.js b/src/widget/dynamicdate/dynamicdate.popup.js index f241f9597..4e8a8d157 100644 --- a/src/widget/dynamicdate/dynamicdate.popup.js +++ b/src/widget/dynamicdate/dynamicdate.popup.js @@ -8,6 +8,10 @@ import { DynamicDateHelper } from "./dynamicdate.caculate"; export class DynamicDatePopup extends Widget { static xtype = "bi.dynamic_date_popup" + constants = { + tabHeight: 40, + } + props = { baseCls: "bi-dynamic-date-popup", width: 272, diff --git a/src/widget/dynamicdatetime/dynamicdatetime.combo.js b/src/widget/dynamicdatetime/dynamicdatetime.combo.js index 2e41c32a6..0d88cf567 100644 --- a/src/widget/dynamicdatetime/dynamicdatetime.combo.js +++ b/src/widget/dynamicdatetime/dynamicdatetime.combo.js @@ -11,6 +11,14 @@ export class DynamicDateTimeCombo extends Single { static Static = 1 static Dynamic = 2 + constants = { + popupHeight: 259, + popupWidth: 270, + comboAdjustHeight: 1, + border: 1, + iconWidth: 24, + } + props = { baseCls: "bi-dynamic-date--time-combo", height: 24, diff --git a/src/widget/dynamicdatetime/dynamicdatetime.popup.js b/src/widget/dynamicdatetime/dynamicdatetime.popup.js index 7f8bb6982..a69aaabb1 100644 --- a/src/widget/dynamicdatetime/dynamicdatetime.popup.js +++ b/src/widget/dynamicdatetime/dynamicdatetime.popup.js @@ -8,6 +8,11 @@ import { DynamicDateTimeCombo } from "./dynamicdatetime.combo"; export class DynamicDateTimePopup extends Widget { static xtype = "bi.dynamic_date_time_popup" + constants = { + tabHeight: 40, + buttonHeight: 24, + } + props = { baseCls: "bi-dynamic-date-time-popup", width: 272, From b9d0902fa7643af84ce2c4bb61eb05f5a4b58aab Mon Sep 17 00:00:00 2001 From: zsmj Date: Thu, 12 Jan 2023 11:40:03 +0800 Subject: [PATCH 082/300] =?UTF-8?q?KERNEL-14086=20feat:=20widget/singletre?= =?UTF-8?q?e=E3=80=81selecttree?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.js | 4 +- src/case/index.js | 1 + src/case/tree/tree.level.js | 8 +- src/core/func/function.js | 25 +- src/widget/index.js | 15 + src/widget/multiselect/multiselect.trigger.js | 216 ++++---- .../trigger/button.checkselected.js | 146 +++--- .../multiselect/trigger/editor.multiselect.js | 123 ++--- .../trigger/searcher.multiselect.js | 255 +++++----- .../trigger/switcher.checkselected.js | 154 +++--- src/widget/multiselecttree/multiselecttree.js | 240 ++++----- .../multiselecttree/multiselecttree.popup.js | 77 +-- .../multitree/check/multi.tree.check.pane.js | 147 +++--- src/widget/multitree/multi.tree.combo.js | 371 ++++++++------ .../multitree/multi.tree.insert.combo.js | 371 ++++++++------ src/widget/multitree/multi.tree.list.combo.js | 460 ++++++++++-------- src/widget/multitree/multi.tree.popup.js | 114 ++--- .../multi.tree.button.checkselected.js | 93 ++-- .../trigger/multi.tree.search.insert.pane.js | 199 ++++---- .../trigger/multi.tree.search.pane.js | 132 ++--- .../trigger/searcher.list.multi.tree.js | 235 +++++---- .../multitree/trigger/searcher.multi.tree.js | 290 ++++++----- .../selecttree/nodes/node.first.plus.js | 129 +++-- src/widget/selecttree/nodes/node.last.plus.js | 129 +++-- src/widget/selecttree/nodes/node.mid.plus.js | 129 +++-- src/widget/selecttree/nodes/node.plus.js | 129 +++-- src/widget/selecttree/selecttree.combo.js | 114 +++-- src/widget/selecttree/selecttree.expander.js | 77 +-- src/widget/selecttree/selecttree.popup.js | 125 ++--- src/widget/singletree/singletree.combo.js | 147 +++--- src/widget/singletree/singletree.popup.js | 80 +-- src/widget/singletree/singletree.trigger.js | 91 ++-- 32 files changed, 2681 insertions(+), 2145 deletions(-) diff --git a/es6.js b/es6.js index c93a368fc..1a025d511 100644 --- a/es6.js +++ b/es6.js @@ -45,6 +45,8 @@ const target = [ "VerticalAlign", "transformItems", "print", + "Tree", + "Func", ]; // 加载模块 @@ -105,7 +107,7 @@ async function handleFile(srcName) { return matchedSentence; } }); - + fs.writeFileSync(srcName, noXtypeCode); return; diff --git a/src/case/index.js b/src/case/index.js index 8892c93e2..d2cbe36fc 100644 --- a/src/case/index.js +++ b/src/case/index.js @@ -40,6 +40,7 @@ export * from "./loader"; export * from "./segment"; export * from "./layer"; export * from "./linearsegment"; +export * from "./checkbox"; export { MultiSelectBar, SelectList diff --git a/src/case/tree/tree.level.js b/src/case/tree/tree.level.js index 23a2c4473..426175b54 100644 --- a/src/case/tree/tree.level.js +++ b/src/case/tree/tree.level.js @@ -9,7 +9,7 @@ import { isNotEmptyArray, Tree, createWidget, - VerticalLayout + VerticalLayout, Controller, Events } from "@/core"; import { ButtonTree, CustomTree } from "@/base"; import { TreeExpander } from "./treeexpander/tree.expander"; @@ -102,9 +102,9 @@ export class LevelTree extends Widget { ], }, o.el), }); - this.tree.on(BI.Controller.EVENT_CHANGE, function (type, value, ob) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if (type === BI.Events.CLICK) { + this.tree.on(Controller.EVENT_CHANGE, function (type, value, ob) { + self.fireEvent(Controller.EVENT_CHANGE, arguments); + if (type === Events.CLICK) { self.fireEvent(LevelTree.EVENT_CHANGE, value, ob); self.setValue(value); } diff --git a/src/core/func/function.js b/src/core/func/function.js index 5977e24d7..0de246721 100644 --- a/src/core/func/function.js +++ b/src/core/func/function.js @@ -15,13 +15,12 @@ export function createDistinctName(array, name) { let src = name, idx = 1; name = name || ""; while (true) { - if (every(array, function (i, item) { - return isKey(item) ? item !== name : item.name !== name; - })) { + if (every(array, (i, item) => isKey(item) ? item !== name : item.name !== name)) { break; } name = src + (idx++); } + return name; } @@ -31,8 +30,9 @@ export function createDistinctName(array, name) { * @return {number} */ export function getGBWidth(str) { - str = str + ""; + str = `${str}`; str = str.replace(/[^\x00-\xff]/g, "xx"); + return Math.ceil(str.length / 2); } @@ -55,7 +55,7 @@ export function getSearchResult(items, keyword, param) { let t, text, py; keyword = toUpperCase(keyword); const matched = array ? [] : {}, find = array ? [] : {}; - each(items, function (i, item) { + each(items, (i, item) => { // 兼容item为null的处理 if (isNull(item)) { return; @@ -77,7 +77,7 @@ export function getSearchResult(items, keyword, param) { } else { array ? find.push(item) : (find[i] = item); } - } else { // BI-56386 这边两个pid / text.length是为了防止截取的首字符串不是完整的,但光这样做还不够,即时错位了,也不能说明就不符合条件 + } else { // BI-56386 这边两个pid / text.length是为了防止截取的首字符串不是完整的,但光这样做还不够,即时错位了,也不能说明就不符合条件 pidx = py.indexOf(keyword); if (pidx > -1) { if (text === keyword || keyword.length === text.length) { @@ -88,9 +88,10 @@ export function getSearchResult(items, keyword, param) { } } }); + return { match: matched, - find: find, + find, }; } @@ -100,7 +101,7 @@ export function getSearchResult(items, keyword, param) { * @param key * @return {any[]} */ -export function getSortedResult(items, key) { +export function getSortedResult(items, key = null) { const getTextOfItem = BI.isFunction(key) ? key : function (item, key) { if (BI.isNotNull(key)) { @@ -112,10 +113,11 @@ export function getSortedResult(items, key) { if (BI.isNotNull(item.value)) { return item.value; } + return item; }; - return items.sort(function (item1, item2) { + return items.sort((item1, item2) => { const str1 = getTextOfItem(item1, key); const str2 = getTextOfItem(item2, key); if (BI.isNull(str1) && BI.isNull(str2)) { @@ -139,28 +141,33 @@ export function getSortedResult(items, key) { return (BI.isNull(BI.CODE_INDEX[char1]) ? BI.MAX : BI.CODE_INDEX[char1]) - (BI.isNull(BI.CODE_INDEX[char2]) ? BI.MAX : BI.CODE_INDEX[char2]); } } + return len1 - len2; }); } export function beforeFunc(sFunc, func) { const __self = sFunc; + return function () { if (func.apply(sFunc, arguments) === false) { return false; } + return __self.apply(sFunc, arguments); }; } export function afterFunc(sFunc, func) { const __self = sFunc; + return function () { const ret = __self.apply(sFunc, arguments); if (ret === false) { return false; } func.apply(sFunc, arguments); + return ret; }; } diff --git a/src/widget/index.js b/src/widget/index.js index aee31d038..6ce1b935c 100644 --- a/src/widget/index.js +++ b/src/widget/index.js @@ -6,6 +6,11 @@ import * as datetime from "./datetime"; import * as datetimepane from "./datetimepane"; import * as dynamicdatetime from "./dynamicdatetime"; import * as time from "./time"; +import { SelectTreeCombo } from "./selecttree/selecttree.combo"; +import { SingleTreeCombo } from "./singletree/singletree.combo"; +import { MultiTreeCombo } from "/multitree/multi.tree.combo"; +import { MultiTreeInsertCombo } from "/multitree/multi.tree.insert.combo"; +import { MultiTreeListCombo } from "/multitree/multi.tree.list.combo"; Object.assign(BI, { Collapse, @@ -16,6 +21,11 @@ Object.assign(BI, { ...datetimepane, ...dynamicdatetime, ...time, + SelectTreeCombo, + SingleTreeCombo, + MultiTreeCombo, + MultiTreeInsertCombo, + MultiTreeListCombo }); export * from "./date/calendar"; @@ -25,6 +35,11 @@ export * from "./datetime"; export * from "./datetimepane"; export * from "./dynamicdatetime"; export * from "./time"; +export { SelectTreeCombo } from "./selecttree/selecttree.combo"; +export { SingleTreeCombo } from "./singletree/singletree.combo"; +export { MultiTreeCombo } from "/multitree/multi.tree.combo"; +export { MultiTreeInsertCombo } from "/multitree/multi.tree.insert.combo"; +export { MultiTreeListCombo } from "/multitree/multi.tree.list.combo"; export { Collapse }; diff --git a/src/widget/multiselect/multiselect.trigger.js b/src/widget/multiselect/multiselect.trigger.js index f8f95c02b..f2affe91a 100644 --- a/src/widget/multiselect/multiselect.trigger.js +++ b/src/widget/multiselect/multiselect.trigger.js @@ -1,40 +1,56 @@ -/** - * - * 复选下拉框 - * @class BI.MultiSelectTrigger - * @extends BI.Trigger - */ - -BI.MultiSelectTrigger = BI.inherit(BI.Trigger, { - - constants: { - height: 14, - rgap: 4, - lgap: 4 - }, - - _defaultConfig: function () { - return BI.extend(BI.MultiSelectTrigger.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + emptyFn, + createWidget, + isFunction, + Layout, + HTapeLayout, + AbsoluteLayout +} from "@/core"; +import { Trigger, Text } from "@/base"; +import { MultiSelectSearcher } from "trigger/searcher.multiselect"; + +@shortcut() +export class MultiSelectTrigger extends Trigger { + static xtype = "bi.multi_select_trigger"; + + constants = { height: 14, rgap: 4, lgap: 4 }; + + static EVENT_TRIGGER_CLICK = "EVENT_TRIGGER_CLICK"; + static EVENT_COUNTER_CLICK = "EVENT_COUNTER_CLICK"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_START = "EVENT_START"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_BEFORE_COUNTER_POPUPVIEW = "EVENT_BEFORE_COUNTER_POPUPVIEW"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_FOCUS = "EVENT_FOCUS"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-trigger", - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, + itemsCreator: emptyFn, + valueFormatter: emptyFn, searcher: {}, switcher: {}, adapter: null, masker: {}, allowEdit: true, - itemHeight: 24 + itemHeight: 24, }); - }, + } - _init: function () { - BI.MultiSelectTrigger.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, o = this.options; + const self = this, + o = this.options; - this.searcher = BI.createWidget(o.searcher, { - type: "bi.multi_select_searcher", + this.searcher = createWidget(o.searcher, { + type: MultiSelectSearcher.xtype, height: o.height, text: o.text, defaultText: o.defaultText, @@ -46,125 +62,111 @@ BI.MultiSelectTrigger = BI.inherit(BI.Trigger, { popup: {}, adapter: o.adapter, masker: o.masker, - value: o.value + value: o.value, }); - this.searcher.on(BI.MultiSelectSearcher.EVENT_START, function () { - self.fireEvent(BI.MultiSelectTrigger.EVENT_START); + this.searcher.on(MultiSelectSearcher.EVENT_START, () => { + self.fireEvent(MultiSelectTrigger.EVENT_START); }); - this.searcher.on(BI.MultiSelectSearcher.EVENT_PAUSE, function () { - self.fireEvent(BI.MultiSelectTrigger.EVENT_PAUSE); + this.searcher.on(MultiSelectSearcher.EVENT_PAUSE, () => { + self.fireEvent(MultiSelectTrigger.EVENT_PAUSE); }); - this.searcher.on(BI.MultiSelectSearcher.EVENT_SEARCHING, function () { - self.fireEvent(BI.MultiSelectTrigger.EVENT_SEARCHING, arguments); + this.searcher.on(MultiSelectSearcher.EVENT_SEARCHING, function () { + self.fireEvent(MultiSelectTrigger.EVENT_SEARCHING, arguments); }); - this.searcher.on(BI.MultiSelectSearcher.EVENT_STOP, function () { - self.fireEvent(BI.MultiSelectTrigger.EVENT_STOP); + this.searcher.on(MultiSelectSearcher.EVENT_STOP, () => { + self.fireEvent(MultiSelectTrigger.EVENT_STOP); }); - this.searcher.on(BI.MultiSelectSearcher.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiSelectTrigger.EVENT_CHANGE, arguments); + this.searcher.on(MultiSelectSearcher.EVENT_CHANGE, function () { + self.fireEvent(MultiSelectTrigger.EVENT_CHANGE, arguments); }); - this.searcher.on(BI.MultiSelectSearcher.EVENT_BLUR, function () { - self.fireEvent(BI.MultiSelectTrigger.EVENT_BLUR); + this.searcher.on(MultiSelectSearcher.EVENT_BLUR, () => { + self.fireEvent(MultiSelectTrigger.EVENT_BLUR); }); - this.searcher.on(BI.MultiSelectSearcher.EVENT_FOCUS, function () { - self.fireEvent(BI.MultiSelectTrigger.EVENT_FOCUS); + this.searcher.on(MultiSelectSearcher.EVENT_FOCUS, () => { + self.fireEvent(MultiSelectTrigger.EVENT_FOCUS); }); - this.wrapNumberCounter = BI.createWidget({ - type: "bi.layout" + this.wrapNumberCounter = createWidget({ + type: Layout.xtype, }); - this.wrapper = BI.createWidget({ - type: "bi.htape", + this.wrapper = createWidget({ + type: HTapeLayout.xtype, element: this, items: [ { el: this.searcher, width: "fill", - rgap: 24 + rgap: 24, } - ] + ], }); - !o.allowEdit && BI.createWidget({ - type: "bi.absolute", - element: this, - items: [ - { - el: { - type: "bi.text", - title: function () { - /** 修正REPORT-73699引入,需要考虑到传递过来的值是方法的情况 */ - var state = self.searcher.getState(); - if (BI.isFunction(state)) { - return state(); - } - return state; - } - }, - left: 0, - right: 24, - top: 0, - bottom: 0 - } - ] - }); - }, + !o.allowEdit && + createWidget({ + type: AbsoluteLayout.xtype, + element: this, + items: [ + { + el: { + type: Text.xtype, + title () { + /** 修正REPORT-73699引入,需要考虑到传递过来的值是方法的情况 */ + const state = self.searcher.getState(); + if (isFunction(state)) { + return state(); + } + + return state; + }, + }, + left: 0, + right: 24, + top: 0, + bottom: 0, + } + ], + }); + } - /** - * 重新调整numberCounter的空白占位符 - */ - refreshPlaceHolderWidth: function (width) { + refreshPlaceHolderWidth(width) { this.wrapper.attr("items")[0].rgap = 24 + width; this.wrapper.resize(); - }, + } - getSearcher: function () { + getSearcher() { return this.searcher; - }, + } - stopEditing: function () { + stopEditing() { this.searcher.stopSearch(); - }, + } - setAdapter: function (adapter) { + setAdapter(adapter) { this.searcher.setAdapter(adapter); - }, + } - setValue: function (ob) { + setValue(ob) { this.searcher.setValue(ob); - }, + } - getKey: function () { + getKey() { return this.searcher.getKey(); - }, + } - getValue: function () { + getValue() { return this.searcher.getValue(); - }, + } - focus: function () { + focus() { this.searcher.focus(); - }, + } - blur: function () { + blur() { this.searcher.blur(); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.searcher.setWaterMark(v); } -}); - -BI.MultiSelectTrigger.EVENT_TRIGGER_CLICK = "EVENT_TRIGGER_CLICK"; -BI.MultiSelectTrigger.EVENT_COUNTER_CLICK = "EVENT_COUNTER_CLICK"; -BI.MultiSelectTrigger.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiSelectTrigger.EVENT_START = "EVENT_START"; -BI.MultiSelectTrigger.EVENT_STOP = "EVENT_STOP"; -BI.MultiSelectTrigger.EVENT_PAUSE = "EVENT_PAUSE"; -BI.MultiSelectTrigger.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.MultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW = "EVENT_BEFORE_COUNTER_POPUPVIEW"; -BI.MultiSelectTrigger.EVENT_BLUR = "EVENT_BLUR"; -BI.MultiSelectTrigger.EVENT_FOCUS = "EVENT_FOCUS"; - -BI.shortcut("bi.multi_select_trigger", BI.MultiSelectTrigger); +} diff --git a/src/widget/multiselect/trigger/button.checkselected.js b/src/widget/multiselect/trigger/button.checkselected.js index 17468061f..97854a485 100644 --- a/src/widget/multiselect/trigger/button.checkselected.js +++ b/src/widget/multiselect/trigger/button.checkselected.js @@ -1,102 +1,122 @@ -/** - * 查看已选按钮 - * Created by guy on 15/11/3. - * @class BI.MultiSelectCheckSelectedButton - * @extends BI.Single - */ -BI.MultiSelectCheckSelectedButton = BI.inherit(BI.Single, { +import { + shortcut, + extend, + emptyFn, + createWidget, + Controller, + i18nText, + isNotNull, + isNotEmptyString, + nextTick +} from "@/core"; +import { Single, TextButton } from "@/base"; +import { MultiSelectCombo } from "../multiselect.combo"; - _defaultConfig: function () { - return BI.extend(BI.MultiSelectCheckSelectedButton.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class MultiSelectCheckSelectedButton extends Single { + static xtype = "bi.multi_select_check_selected_button"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-check-selected-button", - itemsCreator: BI.emptyFn + itemsCreator: emptyFn, }); - }, + } - _init: function () { - BI.MultiSelectCheckSelectedButton.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.numberCounter = BI.createWidget({ - type: "bi.text_button", + _init() { + super._init(...arguments); + const self = this, + o = this.options; + this.numberCounter = createWidget({ + type: TextButton.xtype, element: this, hgap: 4, text: "0", textAlign: "center", textHeight: 16, - cls: "bi-high-light-background count-tip" + cls: "bi-high-light-background count-tip", }); - this.numberCounter.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.numberCounter.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.numberCounter.on(BI.TextButton.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiSelectCheckSelectedButton.EVENT_CHANGE, arguments); + this.numberCounter.on(TextButton.EVENT_CHANGE, function () { + self.fireEvent( + MultiSelectCheckSelectedButton.EVENT_CHANGE, + arguments + ); }); - this.numberCounter.element.hover(function () { - self.numberCounter.setTag(self.numberCounter.getText()); - self.numberCounter.setText(BI.i18nText("BI-Check_Selected")); - }, function () { - self.numberCounter.setText(self.numberCounter.getTag()); - }); + this.numberCounter.element.hover( + () => { + self.numberCounter.setTag(self.numberCounter.getText()); + self.numberCounter.setText(i18nText("BI-Check_Selected")); + }, + () => { + self.numberCounter.setText(self.numberCounter.getTag()); + } + ); this.setVisible(false); - if (BI.isNotNull(o.value)) { + if (isNotNull(o.value)) { this.setValue(o.value); } - }, + } - _populate: function (ob) { - var self = this, o = this.options; + _populate(ob) { + const self = this, + o = this.options; if (ob.type === BI.Selection.All) { - o.itemsCreator({ - type: BI.MultiSelectCombo.REQ_GET_DATA_LENGTH - }, function (res) { - if (self.options.value.type !== BI.Selection.All) { - return; - } - if (BI.isNotEmptyString(res.count)) { - BI.nextTick(function () { - self.numberCounter.setText(res.count); - self.setVisible(true); - }); + o.itemsCreator( + { + type: MultiSelectCombo.REQ_GET_DATA_LENGTH, + }, + res => { + if (self.options.value.type !== BI.Selection.All) { + return; + } + if (isNotEmptyString(res.count)) { + nextTick(() => { + self.numberCounter.setText(res.count); + self.setVisible(true); + }); - return; + return; + } + const length = res.count - ob.value.length; + nextTick(() => { + self.numberCounter.setText(length); + self.setVisible(length > 0); + }); } - var length = res.count - ob.value.length; - BI.nextTick(function () { - self.numberCounter.setText(length); - self.setVisible(length > 0); - }); - }); + ); + return; } - BI.nextTick(function () { + nextTick(() => { self.numberCounter.setText(ob.value.length); self.setVisible(ob.value.length > 0); }); - }, + } - _assertValue: function (ob) { + _assertValue(ob) { ob || (ob = {}); ob.type || (ob.type = BI.Selection.Multi); ob.value || (ob.value = []); + return ob; - }, + } - setValue: function (ob) { + setValue(ob) { ob = this._assertValue(ob); this.options.value = ob; this._populate(ob); - }, + } - populate: function () { + populate() { this._populate(this._assertValue(this.options.value)); - }, - - getValue: function () { - } -}); -BI.MultiSelectCheckSelectedButton.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multi_select_check_selected_button", BI.MultiSelectCheckSelectedButton); + getValue() {} +} diff --git a/src/widget/multiselect/trigger/editor.multiselect.js b/src/widget/multiselect/trigger/editor.multiselect.js index db9acc9a4..ed8217cb6 100644 --- a/src/widget/multiselect/trigger/editor.multiselect.js +++ b/src/widget/multiselect/trigger/editor.multiselect.js @@ -1,23 +1,36 @@ -/** - * 多选输入框 - * Created by guy on 15/11/3. - * @class BI.MultiSelectEditor - * @extends Widget - */ -BI.MultiSelectEditor = BI.inherit(BI.Widget, { - - _defaultConfig: function () { - return BI.extend(BI.MultiSelectEditor.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + Widget, + extend, + i18nText, + createWidget, + Controller, + isEmptyString, + isEmptyArray +} from "@/core"; +import { StateEditor } from "@/case"; + +@shortcut() +export class MultiSelectEditor extends Widget { + static xtype = "bi.multi_select_editor"; + + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_PAUSE = "EVENT_PAUSE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-editor", el: {}, - watermark: BI.i18nText("BI-Basic_Search") + watermark: i18nText("BI-Basic_Search"), }); - }, + } - _init: function () { - BI.MultiSelectEditor.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.editor = BI.createWidget(o.el, { + _init() { + super._init(...arguments); + const self = this, + o = this.options; + this.editor = createWidget(o.el, { type: "bi.select_patch_editor", element: this, height: o.height, @@ -30,49 +43,49 @@ BI.MultiSelectEditor = BI.inherit(BI.Widget, { warningTitle: o.warningTitle, }); - this.editor.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.editor.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.editor.on(BI.StateEditor.EVENT_FOCUS, function () { - self.fireEvent(BI.MultiSelectEditor.EVENT_FOCUS); + this.editor.on(StateEditor.EVENT_FOCUS, () => { + self.fireEvent(MultiSelectEditor.EVENT_FOCUS); }); - this.editor.on(BI.StateEditor.EVENT_BLUR, function () { - self.fireEvent(BI.MultiSelectEditor.EVENT_BLUR); + this.editor.on(StateEditor.EVENT_BLUR, () => { + self.fireEvent(MultiSelectEditor.EVENT_BLUR); }); - }, + } - focus: function () { + focus() { this.editor.focus(); - }, + } - blur: function () { + blur() { this.editor.blur(); - }, + } - setState: function (state) { + setState(state) { this.editor.setState(state); - }, + } - setValue: function (v) { + setValue(v) { this.editor.setValue(v); - }, + } - setTipType: function (v) { + setTipType(v) { this.editor.setTipType(v); - }, + } - getValue: function () { + getValue() { return this.editor.getValue(); - }, + } - getState: function () { + getState() { return this.editor.getText(); - }, + } - getKeywords: function () { - var val = this.editor.getValue(); - var keywords = val.split(/\u200b\s\u200b/); - if (BI.isEmptyString(keywords[keywords.length - 1])) { + getKeywords() { + const val = this.editor.getValue(); + let keywords = val.split(/\u200b\s\u200b/); + if (isEmptyString(keywords[keywords.length - 1])) { keywords = keywords.slice(0, keywords.length - 1); } if (/\u200b\s\u200b$/.test(val)) { @@ -80,27 +93,21 @@ BI.MultiSelectEditor = BI.inherit(BI.Widget, { } return keywords; - }, + } - getKeyword: function () { - var val = this.editor.getValue(); - var keywords = val.split(/\u200b\s\u200b/); - if (BI.isEmptyString(keywords[keywords.length - 1])) { + getKeyword() { + const val = this.editor.getValue(); + let keywords = val.split(/\u200b\s\u200b/); + if (isEmptyString(keywords[keywords.length - 1])) { keywords = keywords.slice(0, keywords.length - 1); } - return BI.isEmptyArray(keywords) ? "" : keywords[keywords.length - 1]; - }, - - populate: function (items) { + + return isEmptyArray(keywords) ? "" : keywords[keywords.length - 1]; + } - }, + populate(items) {} - setWaterMark: function (v) { + setWaterMark(v) { this.editor.setWaterMark(v); } -}); - -BI.MultiSelectEditor.EVENT_FOCUS = "EVENT_FOCUS"; -BI.MultiSelectEditor.EVENT_BLUR = "EVENT_BLUR"; -BI.MultiSelectEditor.EVENT_PAUSE = "EVENT_PAUSE"; -BI.shortcut("bi.multi_select_editor", BI.MultiSelectEditor); +} diff --git a/src/widget/multiselect/trigger/searcher.multiselect.js b/src/widget/multiselect/trigger/searcher.multiselect.js index e7ed00874..a1a18c661 100644 --- a/src/widget/multiselect/trigger/searcher.multiselect.js +++ b/src/widget/multiselect/trigger/searcher.multiselect.js @@ -1,160 +1,187 @@ -/** - * searcher - * Created by guy on 15/11/3. - * @class BI.MultiSelectSearcher - * @extends Widget - */ -BI.MultiSelectSearcher = BI.inherit(BI.Widget, { - - _defaultConfig: function () { - return BI.extend(BI.MultiSelectSearcher.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + Widget, + extend, + emptyFn, + i18nText, + createWidget, + isNotNull, + size, + each +} from "@/core"; +import { MultiSelectEditor } from "editor.multiselect"; +import { Searcher } from "@/base"; + +@shortcut() +export class MultiSelectSearcher extends Widget { + static xtype = "bi.multi_select_searcher"; + + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_START = "EVENT_START"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-searcher", - itemsCreator: BI.emptyFn, + itemsCreator: emptyFn, el: {}, popup: {}, - valueFormatter: BI.emptyFn, + valueFormatter: emptyFn, adapter: null, masker: {}, - defaultText: BI.i18nText("BI-Basic_Please_Select"), - itemHeight: 24 + defaultText: i18nText("BI-Basic_Please_Select"), + itemHeight: 24, }); - }, + } - _init: function () { - BI.MultiSelectSearcher.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.editor = BI.createWidget(o.el, { - type: "bi.multi_select_editor", + _init() { + super._init(...arguments); + const self = this, + o = this.options; + this.editor = createWidget(o.el, { + type: MultiSelectEditor.xtype, height: o.height, text: o.text, defaultText: o.defaultText, watermark: o.watermark, listeners: [ { - eventName: BI.MultiSelectEditor.EVENT_FOCUS, - action: function () { - self.fireEvent(BI.MultiSelectSearcher.EVENT_FOCUS); - } - }, { - eventName: BI.MultiSelectEditor.EVENT_BLUR, - action: function () { - self.fireEvent(BI.MultiSelectSearcher.EVENT_BLUR); - } + eventName: MultiSelectEditor.EVENT_FOCUS, + action () { + self.fireEvent(MultiSelectSearcher.EVENT_FOCUS); + }, + }, + { + eventName: MultiSelectEditor.EVENT_BLUR, + action () { + self.fireEvent(MultiSelectSearcher.EVENT_BLUR); + }, } - ] + ], }); - this.searcher = BI.createWidget({ - type: "bi.searcher", + this.searcher = createWidget({ + type: Searcher.xtype, element: this, height: o.height, isAutoSearch: false, isAutoSync: false, - onSearch: function (op, callback) { + onSearch (op, callback) { callback(); }, el: this.editor, - popup: BI.extend({ - type: "bi.multi_select_search_pane", - valueFormatter: o.valueFormatter, - itemFormatter: o.itemFormatter, - keywordGetter: function () { - return self.editor.getValue(); - }, - itemsCreator: function (op, callback) { - var keyword = self.editor.getValue(); - op.keywords = [keyword]; - o.itemsCreator(op, function () { - var keyword = self.editor.getValue(); + popup: extend( + { + type: "bi.multi_select_search_pane", + valueFormatter: o.valueFormatter, + itemFormatter: o.itemFormatter, + keywordGetter () { + return self.editor.getValue(); + }, + itemsCreator (op, callback) { + const keyword = self.editor.getValue(); op.keywords = [keyword]; - o.itemsCreator(op, function () { - if (keyword === self.editor.getValue()) { - callback.apply(null, arguments); - } + o.itemsCreator(op, () => { + const keyword = self.editor.getValue(); + op.keywords = [keyword]; + o.itemsCreator(op, function () { + if (keyword === self.editor.getValue()) { + callback.apply(null, arguments); + } + }); }); - }); + }, + itemHeight: o.itemHeight, + value: o.value, }, - itemHeight: o.itemHeight, - value: o.value - }, o.popup), + o.popup + ), adapter: o.adapter, - masker: o.masker + masker: o.masker, }); - this.searcher.on(BI.Searcher.EVENT_START, function () { - self.fireEvent(BI.MultiSelectSearcher.EVENT_START); + this.searcher.on(Searcher.EVENT_START, () => { + self.fireEvent(MultiSelectSearcher.EVENT_START); }); - this.searcher.on(BI.Searcher.EVENT_PAUSE, function () { + this.searcher.on(Searcher.EVENT_PAUSE, function () { if (this.hasMatched()) { - } - self.fireEvent(BI.MultiSelectSearcher.EVENT_PAUSE); + self.fireEvent(MultiSelectSearcher.EVENT_PAUSE); }); - this.searcher.on(BI.Searcher.EVENT_STOP, function () { - self.fireEvent(BI.MultiSelectSearcher.EVENT_STOP); + this.searcher.on(Searcher.EVENT_STOP, () => { + self.fireEvent(MultiSelectSearcher.EVENT_STOP); }); - this.searcher.on(BI.Searcher.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiSelectSearcher.EVENT_CHANGE, arguments); + this.searcher.on(Searcher.EVENT_CHANGE, function () { + self.fireEvent(MultiSelectSearcher.EVENT_CHANGE, arguments); }); - this.searcher.on(BI.Searcher.EVENT_SEARCHING, function () { - var keywords = this.getKeywords(); - self.fireEvent(BI.MultiSelectSearcher.EVENT_SEARCHING, keywords); + this.searcher.on(Searcher.EVENT_SEARCHING, function () { + const keywords = this.getKeywords(); + self.fireEvent(MultiSelectSearcher.EVENT_SEARCHING, keywords); }); - if (BI.isNotNull(o.value)) { + if (isNotNull(o.value)) { this.setState(o.value); } - }, + } - focus: function () { + focus() { this.editor.focus(); - }, + } - blur: function () { + blur() { this.editor.blur(); - }, + } - adjustView: function () { + adjustView() { this.searcher.adjustView(); - }, + } - isSearching: function () { + isSearching() { return this.searcher.isSearching(); - }, + } - stopSearch: function () { + stopSearch() { this.searcher.stopSearch(); - }, + } - getKeyword: function () { + getKeyword() { return this.editor.getValue(); - }, + } - hasMatched: function () { + hasMatched() { return this.searcher.hasMatched(); - }, + } - hasChecked: function () { + hasChecked() { return this.searcher.getView() && this.searcher.getView().hasChecked(); - }, + } - setAdapter: function (adapter) { + setAdapter(adapter) { this.searcher.setAdapter(adapter); - }, + } - setState: function (ob) { - var o = this.options; + setState(ob) { + const o = this.options; ob || (ob = {}); ob.value || (ob.value = []); if (ob.type === BI.Selection.All) { if (ob.value.length === 0) { this.editor.setState(BI.Selection.All); - } else if (BI.size(ob.assist) <= 20) { + } else if (size(ob.assist) <= 20) { var state = ""; - BI.each(ob.assist, function (i, v) { + each(ob.assist, (i, v) => { if (i === 0) { - state += "" + (v === null ? "" : (o.valueFormatter(v + "") || v)); + state += + `${ + v === null ? "" : o.valueFormatter(`${v}`) || v}`; } else { - state += "," + (v === null ? "" : (o.valueFormatter(v + "") || v)); + state += + `,${ + v === null ? "" : o.valueFormatter(`${v}`) || v}`; } }); this.editor.setState(state); @@ -164,13 +191,17 @@ BI.MultiSelectSearcher = BI.inherit(BI.Widget, { } else { if (ob.value.length === 0) { this.editor.setState(BI.Selection.None); - } else if (BI.size(ob.value) <= 20) { + } else if (size(ob.value) <= 20) { var state = ""; - BI.each(ob.value, function (i, v) { + each(ob.value, (i, v) => { if (i === 0) { - state += "" + (v === null ? "" : (o.valueFormatter(v + "") || v)); + state += + `${ + v === null ? "" : o.valueFormatter(`${v}`) || v}`; } else { - state += "," + (v === null ? "" : (o.valueFormatter(v + "") || v)); + state += + `,${ + v === null ? "" : o.valueFormatter(`${v}`) || v}`; } }); this.editor.setState(state); @@ -178,36 +209,26 @@ BI.MultiSelectSearcher = BI.inherit(BI.Widget, { this.editor.setState(BI.Selection.Multi); } } - }, + } - getState: function () { + getState() { return this.editor.getState(); - }, + } - setValue: function (ob) { + setValue(ob) { this.setState(ob); this.searcher.setValue(ob); - }, + } - getKey: function () { + getKey() { return this.editor.getValue(); - }, + } - getValue: function () { + getValue() { return this.searcher.getValue(); - }, + } - populate: function (items) { + populate(items) { this.searcher.populate.apply(this.searcher, arguments); } -}); - -BI.MultiSelectSearcher.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.MultiSelectSearcher.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiSelectSearcher.EVENT_START = "EVENT_START"; -BI.MultiSelectSearcher.EVENT_STOP = "EVENT_STOP"; -BI.MultiSelectSearcher.EVENT_PAUSE = "EVENT_PAUSE"; -BI.MultiSelectSearcher.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.MultiSelectSearcher.EVENT_FOCUS = "EVENT_FOCUS"; -BI.MultiSelectSearcher.EVENT_BLUR = "EVENT_BLUR"; -BI.shortcut("bi.multi_select_searcher", BI.MultiSelectSearcher); +} diff --git a/src/widget/multiselect/trigger/switcher.checkselected.js b/src/widget/multiselect/trigger/switcher.checkselected.js index 6804c2c5e..b264f8220 100644 --- a/src/widget/multiselect/trigger/switcher.checkselected.js +++ b/src/widget/multiselect/trigger/switcher.checkselected.js @@ -1,112 +1,126 @@ -/** - * 查看已选switcher - * Created by guy on 15/11/3. - * @class BI.MultiSelectCheckSelectedSwitcher - * @extends Widget - */ -BI.MultiSelectCheckSelectedSwitcher = BI.inherit(BI.Widget, { +import { + shortcut, + Widget, + extend, + emptyFn, + createWidget, + Events, + nextTick +} from "@/core"; +import { Switcher } from "@/base"; +import { MultiSelectCheckSelectedButton } from "button.checkselected"; - _defaultConfig: function () { - return BI.extend(BI.MultiSelectCheckSelectedSwitcher.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class MultiSelectCheckSelectedSwitcher extends Widget { + static xtype = "bi.multi_select_check_selected_switcher"; + + static EVENT_TRIGGER_CHANGE = "EVENT_TRIGGER_CHANGE"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + static EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-check-selected-switcher", - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, + itemsCreator: emptyFn, + valueFormatter: emptyFn, el: {}, popup: {}, adapter: null, - masker: {} + masker: {}, }); - }, + } - _init: function () { - BI.MultiSelectCheckSelectedSwitcher.superclass._init.apply(this, arguments); - var self = this, o = this.options; + _init() { + super._init(...arguments); + const self = this, + o = this.options; - this.button = BI.createWidget(o.el, { - type: "bi.multi_select_check_selected_button", + this.button = createWidget(o.el, { + type: MultiSelectCheckSelectedButton.xtype, itemsCreator: o.itemsCreator, - value: o.value + value: o.value, }); - this.button.on(BI.Events.VIEW, function () { - self.fireEvent(BI.Events.VIEW, arguments); + this.button.on(Events.VIEW, function () { + self.fireEvent(Events.VIEW, arguments); }); - this.switcher = BI.createWidget({ - type: "bi.switcher", + this.switcher = createWidget({ + type: Switcher.xtype, toggle: false, element: this, el: this.button, - popup: BI.extend({ - type: "bi.multi_select_check_pane", - valueFormatter: o.valueFormatter, - itemsCreator: o.itemsCreator, - onClickContinueSelect: function () { - self.switcher.hideView(); - }, - ref: function (_ref) { - self.checkPane = _ref; + popup: extend( + { + type: "bi.multi_select_check_pane", + valueFormatter: o.valueFormatter, + itemsCreator: o.itemsCreator, + onClickContinueSelect () { + self.switcher.hideView(); + }, + ref (_ref) { + self.checkPane = _ref; + }, + value: o.value, }, - value: o.value - }, o.popup), + o.popup + ), adapter: o.adapter, - masker: o.masker + masker: o.masker, }); - this.switcher.on(BI.Switcher.EVENT_TRIGGER_CHANGE, function () { - self.fireEvent(BI.MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE); + this.switcher.on(Switcher.EVENT_TRIGGER_CHANGE, () => { + self.fireEvent( + MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE + ); }); - this.switcher.on(BI.Switcher.EVENT_BEFORE_POPUPVIEW, function () { - self.fireEvent(BI.MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW); + this.switcher.on(Switcher.EVENT_BEFORE_POPUPVIEW, () => { + self.fireEvent( + MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW + ); }); - this.switcher.on(BI.Switcher.EVENT_AFTER_HIDEVIEW, function () { - self.fireEvent(BI.MultiSelectCheckSelectedSwitcher.EVENT_AFTER_HIDEVIEW); + this.switcher.on(Switcher.EVENT_AFTER_HIDEVIEW, () => { + self.fireEvent( + MultiSelectCheckSelectedSwitcher.EVENT_AFTER_HIDEVIEW + ); }); - this.switcher.on(BI.Switcher.EVENT_AFTER_POPUPVIEW, function () { - var me = this; - BI.nextTick(function () { + this.switcher.on(Switcher.EVENT_AFTER_POPUPVIEW, function () { + const me = this; + nextTick(() => { me._populate(); }); }); - }, + } - adjustView: function () { + adjustView() { this.switcher.adjustView(); - }, + } - hideView: function () { + hideView() { this.switcher.empty(); this.switcher.hideView(); - }, + } - setAdapter: function (adapter) { + setAdapter(adapter) { this.switcher.setAdapter(adapter); - }, + } - setValue: function (v) { + setValue(v) { this.switcher.setValue(v); - }, + } - // 与setValue的区别是只更新查看已选面板的的selectedValue, 不会更新按钮的计数 - updateSelectedValue: function (v) { + updateSelectedValue(v) { this.checkPane.setValue(v); - }, + } - setButtonChecked: function (v) { + setButtonChecked(v) { this.button.setValue(v); - }, - - getValue: function () { + } - }, + getValue() {} - populate: function (items) { + populate(items) { this.switcher.populate.apply(this.switcher, arguments); - }, + } - populateSwitcher: function () { + populateSwitcher() { this.button.populate.apply(this.button, arguments); } -}); - -BI.MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE = "EVENT_TRIGGER_CHANGE"; -BI.MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.MultiSelectCheckSelectedSwitcher.EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; -BI.shortcut("bi.multi_select_check_selected_switcher", BI.MultiSelectCheckSelectedSwitcher); \ No newline at end of file +} diff --git a/src/widget/multiselecttree/multiselecttree.js b/src/widget/multiselecttree/multiselecttree.js index 959c6593b..3e77234cd 100644 --- a/src/widget/multiselecttree/multiselecttree.js +++ b/src/widget/multiselecttree/multiselecttree.js @@ -1,171 +1,193 @@ -/** - * Created by zcf_1 on 2017/5/11. - */ -BI.MultiSelectTree = BI.inherit(BI.Single, { - _constant: { - EDITOR_HEIGHT: 24 - }, - - _defaultConfig: function () { - return BI.extend(BI.MultiSelectTree.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + emptyFn, + createWidget, + nextTick, + AbsoluteLayout +} from "@/core"; +import { Single, Searcher } from "@/base"; +import { MultiSelectTreePopup } from "./multiselecttree.popup"; + +@shortcut() +export class MultiSelectTree extends Single { + static xtype = "bi.multi_select_tree"; + + _constant = { EDITOR_HEIGHT: 24 }; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-tree", - itemsCreator: BI.emptyFn + itemsCreator: emptyFn, }); - }, + } - _init: function () { - BI.MultiSelectTree.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.storeValue = {value: {}}; + _init() { + super._init(...arguments); + const self = this, + o = this.options; + this.storeValue = { value: {} }; - this.adapter = BI.createWidget({ - type: "bi.multi_select_tree_popup", + this.adapter = createWidget({ + type: MultiSelectTreePopup.xtype, itemsCreator: o.itemsCreator, - showLine: o.showLine + showLine: o.showLine, }); - this.adapter.on(BI.MultiSelectTreePopup.EVENT_CHANGE, function () { + this.adapter.on(MultiSelectTreePopup.EVENT_CHANGE, () => { if (self.searcher.isSearching()) { - self.storeValue = {value: self.searcherPane.getValue()}; + self.storeValue = { value: self.searcherPane.getValue() }; } else { - self.storeValue = {value: self.adapter.getValue()}; + self.storeValue = { value: self.adapter.getValue() }; } self.setSelectedValue(self.storeValue.value); - self.fireEvent(BI.MultiSelectTree.EVENT_CHANGE); + self.fireEvent(MultiSelectTree.EVENT_CHANGE); }); // 搜索中的时候用的是parttree,同adapter中的synctree不一样 - this.searcherPane = BI.createWidget({ + this.searcherPane = createWidget({ type: "bi.multi_tree_search_pane", cls: "bi-border-left bi-border-right bi-border-bottom", - keywordGetter: function () { + keywordGetter() { return self.searcher.getKeyword(); }, - itemsCreator: function (op, callback) { + itemsCreator(op, callback) { op.keyword = self.searcher.getKeyword(); o.itemsCreator(op, callback); - } + }, }); this.searcherPane.setVisible(false); - this.searcher = BI.createWidget({ - type: "bi.searcher", + this.searcher = createWidget({ + type: Searcher.xtype, isAutoSearch: false, isAutoSync: false, - onSearch: function (op, callback) { + onSearch(op, callback) { callback({ - keyword: self.searcher.getKeyword() + keyword: self.searcher.getKeyword(), }); }, adapter: this.adapter, popup: this.searcherPane, masker: false, - listeners: [{ - eventName: BI.Searcher.EVENT_START, - action: function () { - self._showSearcherPane(); - // self.storeValue = {value: self.adapter.getValue()}; - // self.searcherPane.setSelectedValue(self.storeValue.value); - } - }, { - eventName: BI.Searcher.EVENT_STOP, - action: function () { - self._showAdapter(); - // self.storeValue = {value: self.searcherPane.getValue()}; - // self.adapter.setSelectedValue(self.storeValue.value); - BI.nextTick(function () { - self.adapter.populate(); - }); - } - }, { - eventName: BI.Searcher.EVENT_CHANGE, - action: function () { - if (self.searcher.isSearching()) { - self.storeValue = {value: self.searcherPane.getValue()}; - } else { - self.storeValue = {value: self.adapter.getValue()}; - } - self.setSelectedValue(self.storeValue.value); - self.fireEvent(BI.MultiSelectTree.EVENT_CHANGE); + listeners: [ + { + eventName: Searcher.EVENT_START, + action() { + self._showSearcherPane(); + // self.storeValue = {value: self.adapter.getValue()}; + // self.searcherPane.setSelectedValue(self.storeValue.value); + }, + }, + { + eventName: Searcher.EVENT_STOP, + action() { + self._showAdapter(); + // self.storeValue = {value: self.searcherPane.getValue()}; + // self.adapter.setSelectedValue(self.storeValue.value); + nextTick(() => { + self.adapter.populate(); + }); + }, + }, + { + eventName: Searcher.EVENT_CHANGE, + action() { + if (self.searcher.isSearching()) { + self.storeValue = { + value: self.searcherPane.getValue(), + }; + } else { + self.storeValue = { + value: self.adapter.getValue(), + }; + } + self.setSelectedValue(self.storeValue.value); + self.fireEvent(MultiSelectTree.EVENT_CHANGE); + }, + }, + { + eventName: Searcher.EVENT_PAUSE, + action() { + self._showAdapter(); + // BI-64732 pause 和stop一致, 都应该刷新adapter + nextTick(() => { + self.adapter.populate(); + }); + }, } - }, { - eventName: BI.Searcher.EVENT_PAUSE, - action: function () { - self._showAdapter(); - // BI-64732 pause 和stop一致, 都应该刷新adapter - BI.nextTick(function () { - self.adapter.populate(); - }); - } - }] + ], }); - BI.createWidget({ + createWidget({ type: "bi.vertical_fill", element: this, - items: [{ - el: this.searcher, - height: "" - }, { - el: this.adapter, - height: "fill" - }] + items: [ + { + el: this.searcher, + height: "", + }, + { + el: this.adapter, + height: "fill", + } + ], }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.searcherPane, - top: this._constant.EDITOR_HEIGHT, - bottom: 0, - left: 0, - right: 0 - }] + items: [ + { + el: this.searcherPane, + top: this._constant.EDITOR_HEIGHT, + bottom: 0, + left: 0, + right: 0, + } + ], }); + } - }, - - _showAdapter: function () { + _showAdapter() { this.adapter.setVisible(true); this.searcherPane.setVisible(false); - }, + } - _showSearcherPane: function () { + _showSearcherPane() { this.searcherPane.setVisible(true); this.adapter.setVisible(false); - }, - - resize: function () { + } - }, + resize() { + } - setSelectedValue: function (v) { + setSelectedValue(v) { this.storeValue.value = v || {}; this.adapter.setSelectedValue(v); this.searcherPane.setSelectedValue(v); this.searcher.setValue({ - value: v || {} + value: v || {}, }); - }, + } - setValue: function (v) { + setValue(v) { this.adapter.setValue(v); - }, + } - stopSearch: function () { + stopSearch() { this.searcher.stopSearch(); - }, + } - updateValue: function (v) { + updateValue(v) { this.adapter.updateValue(v); - }, + } - getValue: function () { + getValue() { return this.storeValue.value; - }, + } - populate: function () { + populate() { this.adapter.populate(); } -}); -BI.MultiSelectTree.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multi_select_tree", BI.MultiSelectTree); +} diff --git a/src/widget/multiselecttree/multiselecttree.popup.js b/src/widget/multiselecttree/multiselecttree.popup.js index 95af718ce..805d0571c 100644 --- a/src/widget/multiselecttree/multiselecttree.popup.js +++ b/src/widget/multiselecttree/multiselecttree.popup.js @@ -1,58 +1,63 @@ -/** - * Created by zcf on 2016/12/21. - */ -BI.MultiSelectTreePopup = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.MultiSelectTreePopup.superclass._defaultConfig.apply(this, arguments), { - baseCls: "bi-multi-select-tree-popup bi-border-left bi-border-right bi-border-bottom", - itemsCreator: BI.emptyFn +import { shortcut, Widget, extend, emptyFn, createWidget } from "@/core"; +import { TreeView, Asynctree } from "@/case"; + +@shortcut() +export class MultiSelectTreePopup extends Widget { + static xtype = "bi.multi_select_tree_popup"; + + static EVENT_AFTER_INIT = "EVENT_AFTER_INIT"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { + baseCls: + "bi-multi-select-tree-popup bi-border-left bi-border-right bi-border-bottom", + itemsCreator: emptyFn, }); - }, - _init: function () { - BI.MultiSelectTreePopup.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.popup = BI.createWidget({ - type: "bi.async_tree", + } + + _init() { + super._init(...arguments); + const self = this, + o = this.options; + this.popup = createWidget({ + type: Asynctree.xtype, showLine: o.showLine, element: this, - itemsCreator: o.itemsCreator + itemsCreator: o.itemsCreator, }); - this.popup.on(BI.TreeView.EVENT_AFTERINIT, function () { - self.fireEvent(BI.MultiSelectTreePopup.EVENT_AFTER_INIT); + this.popup.on(TreeView.EVENT_AFTERINIT, () => { + self.fireEvent(MultiSelectTreePopup.EVENT_AFTER_INIT); }); - this.popup.on(BI.TreeView.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiSelectTreePopup.EVENT_CHANGE); + this.popup.on(TreeView.EVENT_CHANGE, () => { + self.fireEvent(MultiSelectTreePopup.EVENT_CHANGE); }); - }, + } - hasChecked: function () { + hasChecked() { return this.popup.hasChecked(); - }, + } - getValue: function () { + getValue() { return this.popup.getValue(); - }, + } - setValue: function (v) { + setValue(v) { v || (v = {}); this.popup.setValue(v); - }, + } - setSelectedValue: function (v) { + setSelectedValue(v) { v || (v = {}); this.popup.setSelectedValue(v); - }, + } - updateValue: function (v) { + updateValue(v) { this.popup.updateValue(v); this.popup.refresh(); - }, + } - populate: function (config) { + populate(config) { this.popup.stroke(config); } - -}); -BI.MultiSelectTreePopup.EVENT_AFTER_INIT = "EVENT_AFTER_INIT"; -BI.MultiSelectTreePopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multi_select_tree_popup", BI.MultiSelectTreePopup); \ No newline at end of file +} diff --git a/src/widget/multitree/check/multi.tree.check.pane.js b/src/widget/multitree/check/multi.tree.check.pane.js index 598a19f21..56ef73fca 100644 --- a/src/widget/multitree/check/multi.tree.check.pane.js +++ b/src/widget/multitree/check/multi.tree.check.pane.js @@ -1,121 +1,128 @@ -/** - * - * @class BI.MultiTreeCheckPane - * @extends BI.Pane - */ -BI.MultiTreeCheckPane = BI.inherit(BI.Pane, { - - constants: { - height: 25, - lgap: 10, - tgap: 5 - }, - - _defaultConfig: function () { - return BI.extend(BI.MultiTreeCheckPane.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + emptyFn, + createWidget, + i18nText, + nextTick, + Events, + VerticalAdaptLayout, VTapeLayout +} from "@/core"; +import { Pane, TextButton, Label } from "@/base"; +import { DisplayTree, TreeView } from "@/case"; + +@shortcut() +export class MultiTreeCheckPane extends Pane { + static xtype = "bi.multi_tree_check_pane"; + + constants = { height: 25, lgap: 10, tgap: 5 }; + + static EVENT_CONTINUE_CLICK = "EVENT_CONTINUE_CLICK"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-tree-check-pane bi-background", - onClickContinueSelect: BI.emptyFn, + onClickContinueSelect: emptyFn, el: { - type: "bi.display_tree" - } + type: DisplayTree.xtype, + }, }); - }, + } - _init: function () { - BI.MultiTreeCheckPane.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, opts = this.options; + const self = this, + opts = this.options; this.selectedValues = {}; - var continueSelect = BI.createWidget({ - type: "bi.text_button", - title: BI.i18nText("BI-Continue_Select"), - text: BI.i18nText("BI-Continue_Select"), - cls: "multi-tree-check-selected" + const continueSelect = createWidget({ + type: TextButton.xtype, + title: i18nText("BI-Continue_Select"), + text: i18nText("BI-Continue_Select"), + cls: "multi-tree-check-selected", }); - continueSelect.on(BI.TextButton.EVENT_CHANGE, function () { + continueSelect.on(TextButton.EVENT_CHANGE, () => { opts.onClickContinueSelect(); - BI.nextTick(function () { + nextTick(() => { self.empty(); }); }); - var backToPopup = BI.createWidget({ - type: "bi.vertical_adapt", + const backToPopup = createWidget({ + type: VerticalAdaptLayout.xtype, columnSize: ["auto", "auto"], cls: "multi-tree-continue-select", items: [ { el: { - type: "bi.label", - title: BI.i18nText("BI-Selected_Data"), - text: BI.i18nText("BI-Selected_Data") + type: Label.xtype, + title: i18nText("BI-Selected_Data"), + text: i18nText("BI-Selected_Data"), }, lgap: this.constants.lgap, - tgap: this.constants.tgap + tgap: this.constants.tgap, }, { el: continueSelect, hgap: this.constants.lgap, - tgap: this.constants.tgap - }] + tgap: this.constants.tgap, + } + ], }); - this.display = BI.createWidget(opts.el, { - type: "bi.display_tree", + this.display = createWidget(opts.el, { + type: DisplayTree.xtype, cls: "bi-multi-tree-display", - itemsCreator: function (op, callback) { - op.type = BI.TreeView.REQ_TYPE_GET_SELECTED_DATA; + itemsCreator(op, callback) { + op.type = TreeView.REQ_TYPE_GET_SELECTED_DATA; opts.itemsCreator(op, callback); }, - value: (opts.value || {}).value + value: (opts.value || {}).value, }); - this.display.on(BI.Events.AFTERINIT, function () { - self.fireEvent(BI.Events.AFTERINIT); + this.display.on(Events.AFTERINIT, () => { + self.fireEvent(Events.AFTERINIT); }); - this.display.on(BI.TreeView.EVENT_INIT, function () { + this.display.on(TreeView.EVENT_INIT, () => { backToPopup.setVisible(false); }); - this.display.on(BI.TreeView.EVENT_AFTERINIT, function () { + this.display.on(TreeView.EVENT_AFTERINIT, () => { backToPopup.setVisible(true); }); - BI.createWidget({ - type: "bi.vtape", + createWidget({ + type: VTapeLayout.xtype, element: this, - items: [{ - height: this.constants.height, - el: backToPopup - }, { - height: "fill", - el: this.display - }] + items: [ + { + height: this.constants.height, + el: backToPopup, + }, + { + height: "fill", + el: this.display, + } + ], }); - }, + } - empty: function () { + empty() { this.display.empty(); - }, + } - populate: function (configs) { + populate(configs) { this.display.stroke(configs); - }, + } - setValue: function (v) { + setValue(v) { v || (v = {}); this.display.setSelectedValue(v.value); - }, - - getValue: function () { - } -}); -BI.MultiTreeCheckPane.EVENT_CONTINUE_CLICK = "EVENT_CONTINUE_CLICK"; - - -BI.shortcut("bi.multi_tree_check_pane", BI.MultiTreeCheckPane); + getValue() { + } +} diff --git a/src/widget/multitree/multi.tree.combo.js b/src/widget/multitree/multi.tree.combo.js index 5fca0ca4f..571f86e03 100644 --- a/src/widget/multitree/multi.tree.combo.js +++ b/src/widget/multitree/multi.tree.combo.js @@ -1,33 +1,67 @@ -/** - * - * @class BI.MultiTreeCombo - * @extends BI.Single - */ - -BI.MultiTreeCombo = BI.inherit(BI.Single, { - _defaultConfig: function () { - return BI.extend(BI.MultiTreeCombo.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + emptyFn, + createWidget, + toPix, + nextTick, + Events, + AbsoluteLayout, + VerticalAdaptLayout, + deepClone +} from "@/core"; +import { Single, Combo } from "@/base"; +import { MultiTreeSearcher } from "trigger/searcher.multi.tree"; +import { MultiTreePopup } from "multi.tree.popup"; +import { MultiSelectTrigger } from "../multiselect/multiselect.trigger"; +import { TriggerIconButton } from "@/case"; +import { MultiSelectCheckSelectedSwitcher } from "../multiselect/trigger/switcher.checkselected"; + +@shortcut() +export class MultiTreeCombo extends Single { + static xtype = "bi.multi_tree_combo"; + + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_CLICK_ITEM = "EVENT_CLICK_ITEM"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + static EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-tree-combo", - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, + itemsCreator: emptyFn, + valueFormatter: emptyFn, height: 24, allowEdit: true, isNeedAdjustWidth: true, }); - }, + } - _init: function () { - var self = this, o = this.options; - BI.MultiTreeCombo.superclass._init.apply(this, arguments); - var isInit = false; - var want2showCounter = false; + _init() { + const triggerBtn = createWidget({ + type: TriggerIconButton.xtype, + width: o.height, + height: o.height, + cls: "multi-select-trigger-icon-button", + }); + let clear; + let change; + const self = this, + o = this.options; + super._init(...arguments); + let isInit = false; + let want2showCounter = false; this.storeValue = { value: o.value || {} }; - this.trigger = BI.createWidget({ + this.trigger = createWidget({ type: "bi.multi_select_trigger", allowEdit: o.allowEdit, - height: BI.toPix(o.height, o.simple ? 1 : 2), + height: toPix(o.height, o.simple ? 1 : 2), valueFormatter: o.valueFormatter, text: o.text, defaultText: o.defaultText, @@ -45,72 +79,78 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { itemsCreator: o.itemsCreator, listeners: [ { - eventName: BI.MultiTreeSearcher.EVENT_CLICK_TREE_NODE, - action: function () { + eventName: MultiTreeSearcher.EVENT_CLICK_TREE_NODE, + action() { self._dataChange = true; - } + }, } ], }, - value: { value: o.value || {} } + value: { value: o.value || {} }, }); - this.combo = BI.createWidget({ - type: "bi.combo", - cls: (o.simple ? "bi-border-bottom" : "bi-border bi-border-radius"), + this.combo = createWidget({ + type: Combo.xtype, + cls: o.simple ? "bi-border-bottom" : "bi-border bi-border-radius", toggle: !o.allowEdit, container: o.container, el: this.trigger, adjustLength: 1, popup: { type: "bi.multi_tree_popup_view", - ref: function () { + ref() { self.popup = this; self.trigger.setAdapter(this); self.numberCounter.setAdapter(this); }, listeners: [ { - eventName: BI.MultiTreePopup.EVENT_AFTERINIT, - action: function () { + eventName: MultiTreePopup.EVENT_AFTERINIT, + action() { self.numberCounter.adjustView(); isInit = true; if (want2showCounter === true) { showCounter(); } - } - }, { - eventName: BI.MultiTreePopup.EVENT_CHANGE, - action: function () { + }, + }, + { + eventName: MultiTreePopup.EVENT_CHANGE, + action() { change = true; - var val = { + const val = { type: BI.Selection.Multi, - value: this.hasChecked() ? this.getValue() : {} + value: this.hasChecked() ? this.getValue() : {}, }; self.trigger.getSearcher().setState(val); self.numberCounter.setButtonChecked(val); self.storeValue = { value: self.combo.getValue() }; - self.fireEvent(BI.MultiTreeCombo.EVENT_CLICK_ITEM, self.combo.getValue()); + self.fireEvent( + MultiTreeCombo.EVENT_CLICK_ITEM, + self.combo.getValue() + ); self._dataChange = true; - } - }, { - eventName: BI.MultiTreePopup.EVENT_CLICK_CONFIRM, - action: function () { + }, + }, + { + eventName: MultiTreePopup.EVENT_CLICK_CONFIRM, + action() { self.combo.hideView(); - } - }, { - eventName: BI.MultiTreePopup.EVENT_CLICK_CLEAR, - action: function () { + }, + }, + { + eventName: MultiTreePopup.EVENT_CLICK_CLEAR, + action() { clear = true; self._dataChange = true; self.setValue(); self._defaultState(); - } + }, } ], itemsCreator: o.itemsCreator, - onLoaded: function () { - BI.nextTick(function () { + onLoaded() { + nextTick(() => { self.numberCounter.adjustView(); self.trigger.getSearcher().adjustView(); }); @@ -119,49 +159,51 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { }, isNeedAdjustWidth: o.isNeedAdjustWidth, value: { value: o.value || {} }, - hideChecker: function (e) { - return triggerBtn.element.find(e.target).length === 0 && - self.numberCounter.element.find(e.target).length === 0; - } + hideChecker(e) { + return ( + triggerBtn.element.find(e.target).length === 0 && + self.numberCounter.element.find(e.target).length === 0 + ); + }, }); - var change = false; - var clear = false; // 标识当前是否点击了清空 + change = false; + clear = false; // 标识当前是否点击了清空 - var isSearching = function () { + function isSearching() { return self.trigger.getSearcher().isSearching(); - }; + } - var isPopupView = function () { + function isPopupView() { return self.combo.isViewVisible(); - }; + } - this.trigger.on(BI.MultiSelectTrigger.EVENT_FOCUS, function () { - self.fireEvent(BI.MultiTreeCombo.EVENT_FOCUS); + this.trigger.on(MultiSelectTrigger.EVENT_FOCUS, () => { + self.fireEvent(MultiTreeCombo.EVENT_FOCUS); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_BLUR, function () { - self.fireEvent(BI.MultiTreeCombo.EVENT_BLUR); + this.trigger.on(MultiSelectTrigger.EVENT_BLUR, () => { + self.fireEvent(MultiTreeCombo.EVENT_BLUR); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_START, function () { + this.trigger.on(MultiSelectTrigger.EVENT_START, function () { self.storeValue = { value: self.combo.getValue() }; this.setValue(self.storeValue); self.numberCounter.setValue(self.storeValue); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_STOP, function () { + this.trigger.on(MultiSelectTrigger.EVENT_STOP, function () { self.storeValue = { value: this.getValue() }; self.combo.setValue(self.storeValue); self.numberCounter.setValue(self.storeValue); - BI.nextTick(function () { + nextTick(() => { if (isPopupView()) { self.combo.populate(); } }); - self.fireEvent(BI.MultiTreeCombo.EVENT_STOP); + self.fireEvent(MultiTreeCombo.EVENT_STOP); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_SEARCHING, function () { - self.fireEvent(BI.MultiTreeCombo.EVENT_SEARCHING); + this.trigger.on(MultiSelectTrigger.EVENT_SEARCHING, () => { + self.fireEvent(MultiTreeCombo.EVENT_SEARCHING); }); function showCounter() { @@ -174,28 +216,33 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { self.numberCounter.setValue(self.storeValue); } - this.trigger.on(BI.MultiSelectTrigger.EVENT_TRIGGER_CLICK, function () { + this.trigger.on(MultiSelectTrigger.EVENT_TRIGGER_CLICK, () => { self.combo.toggle(); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_COUNTER_CLICK, function () { + this.trigger.on(MultiSelectTrigger.EVENT_COUNTER_CLICK, () => { if (!self.combo.isViewVisible()) { self.combo.showView(); } }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_CHANGE, function () { - var checked = this.getSearcher().hasChecked(); - var val = { + this.trigger.on(MultiSelectTrigger.EVENT_CHANGE, function () { + const checked = this.getSearcher().hasChecked(); + const val = { type: BI.Selection.Multi, - value: checked ? { 1: 1 } : {} + value: checked ? { 1: 1 } : {}, }; - this.getSearcher().setState(checked ? BI.Selection.Multi : BI.Selection.None); + this.getSearcher().setState( + checked ? BI.Selection.Multi : BI.Selection.None + ); self.numberCounter.setButtonChecked(val); - self.fireEvent(BI.MultiTreeCombo.EVENT_CLICK_ITEM, self.combo.getValue()); + self.fireEvent( + MultiTreeCombo.EVENT_CLICK_ITEM, + self.combo.getValue() + ); self._dataChange = true; }); - this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { + this.combo.on(Combo.EVENT_BEFORE_POPUPVIEW, function () { if (isSearching()) { return; } @@ -209,12 +256,13 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { self.combo.setValue(self.storeValue); self.numberCounter.setValue(self.storeValue); self.populate(); - self.fireEvent(BI.MultiTreeCombo.EVENT_BEFORE_POPUPVIEW); + self.fireEvent(MultiTreeCombo.EVENT_BEFORE_POPUPVIEW); }); - this.combo.on(BI.Combo.EVENT_BEFORE_HIDEVIEW, function () { + this.combo.on(Combo.EVENT_BEFORE_HIDEVIEW, () => { if (isSearching()) { self._stopEditing(); - self._dataChange && self.fireEvent(BI.MultiTreeCombo.EVENT_CONFIRM); + self._dataChange && + self.fireEvent(MultiTreeCombo.EVENT_CONFIRM); } else { if (isPopupView()) { self._stopEditing(); @@ -222,23 +270,18 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { if (clear === true) { self.storeValue = { value: {} }; } - self._dataChange && self.fireEvent(BI.MultiTreeCombo.EVENT_CONFIRM); + self._dataChange && + self.fireEvent(MultiTreeCombo.EVENT_CONFIRM); } } clear = false; change = false; }); - this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { - self.fireEvent(BI.MultiTreeCombo.EVENT_AFTER_HIDEVIEW); + this.combo.on(Combo.EVENT_AFTER_HIDEVIEW, () => { + self.fireEvent(MultiTreeCombo.EVENT_AFTER_HIDEVIEW); }); - var triggerBtn = BI.createWidget({ - type: "bi.trigger_icon_button", - width: o.height, - height: o.height, - cls: "multi-select-trigger-icon-button" - }); - triggerBtn.on(BI.TriggerIconButton.EVENT_CHANGE, function () { + triggerBtn.on(TriggerIconButton.EVENT_CHANGE, () => { self.numberCounter.hideView(); if (self.combo.isViewVisible()) { self.combo.hideView(); @@ -247,13 +290,13 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { } }); - this.numberCounter = BI.createWidget({ + this.numberCounter = createWidget({ type: "bi.multi_select_check_selected_switcher", el: { - type: "bi.multi_tree_check_selected_button" + type: "bi.multi_tree_check_selected_button", }, popup: { - type: "bi.multi_tree_check_pane" + type: "bi.multi_tree_check_pane", }, masker: { offset: { @@ -265,43 +308,56 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { }, itemsCreator: o.itemsCreator, valueFormatter: o.valueFormatter, - value: { value: o.value || {} } - }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE, function () { - if (!self.combo.isViewVisible()) { - self.combo.showView(); - } + value: { value: o.value || {} }, }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW, function () { - if (want2showCounter === false) { - want2showCounter = true; + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE, + () => { + if (!self.combo.isViewVisible()) { + self.combo.showView(); + } } - if (isInit === true) { - want2showCounter = null; - showCounter(); + ); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW, + () => { + if (want2showCounter === false) { + want2showCounter = true; + } + if (isInit === true) { + want2showCounter = null; + showCounter(); + } } - }); - - this.numberCounter.on(BI.Events.VIEW, function (b) { - BI.nextTick(function () {// 自动调整宽度 - self.trigger.refreshPlaceHolderWidth((b === true ? self.numberCounter.element.outerWidth() + 8 : 0)); + ); + + this.numberCounter.on(Events.VIEW, b => { + nextTick(() => { + // 自动调整宽度 + self.trigger.refreshPlaceHolderWidth( + b === true ? self.numberCounter.element.outerWidth() + 8 : 0 + ); }); }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_AFTER_HIDEVIEW, function () { - BI.nextTick(function () {// 收起时自动调整宽度 - self.trigger.refreshPlaceHolderWidth(0); - }); - }); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_AFTER_HIDEVIEW, + () => { + nextTick(() => { + // 收起时自动调整宽度 + self.trigger.refreshPlaceHolderWidth(0); + }); + } + ); - this.trigger.element.click(function (e) { + this.trigger.element.click(e => { if (self.trigger.element.find(e.target).length > 0) { self.numberCounter.hideView(); } }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, items: [ { @@ -309,85 +365,76 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { left: 0, right: 0, top: 0, - bottom: 0 - }, { + bottom: 0, + }, + { el: triggerBtn, right: 0, top: 0, - bottom: 0 - }, { + bottom: 0, + }, + { el: { - type: "bi.vertical_adapt", - items: [this.numberCounter] + type: VerticalAdaptLayout.xtype, + items: [this.numberCounter], }, right: o.height, top: 0, - bottom: 0 + bottom: 0, } - ] + ], }); - }, + } - _stopEditing: function () { + _stopEditing() { this.trigger.stopEditing(); this.numberCounter.hideView(); - }, + } - _defaultState: function () { + _defaultState() { this._stopEditing(); this.combo.hideView(); - }, + } - showView: function () { + showView() { this.combo.showView(); - }, + } - hideView: function () { + hideView() { this.combo.hideView(); - }, + } - setValue: function (v) { + setValue(v) { this.storeValue.value = v || {}; this.combo.setValue({ - value: v || {} + value: v || {}, }); this.numberCounter.setValue({ - value: v || {} + value: v || {}, }); - }, + } - getSearcher: function () { + getSearcher() { return this.trigger.getSearcher(); - }, + } - getValue: function () { - return BI.deepClone(this.storeValue.value); - }, + getValue() { + return deepClone(this.storeValue.value); + } - populate: function () { + populate() { this.combo.populate(); - }, + } - focus: function () { + focus() { this.trigger.focus(); - }, + } - blur: function () { + blur() { this.trigger.blur(); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.trigger.setWaterMark(v); } -}); - -BI.MultiTreeCombo.EVENT_FOCUS = "EVENT_FOCUS"; -BI.MultiTreeCombo.EVENT_BLUR = "EVENT_BLUR"; -BI.MultiTreeCombo.EVENT_STOP = "EVENT_STOP"; -BI.MultiTreeCombo.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.MultiTreeCombo.EVENT_CLICK_ITEM = "EVENT_CLICK_ITEM"; -BI.MultiTreeCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.MultiTreeCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.MultiTreeCombo.EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; - -BI.shortcut("bi.multi_tree_combo", BI.MultiTreeCombo); +} diff --git a/src/widget/multitree/multi.tree.insert.combo.js b/src/widget/multitree/multi.tree.insert.combo.js index acacbb875..604fddd6d 100644 --- a/src/widget/multitree/multi.tree.insert.combo.js +++ b/src/widget/multitree/multi.tree.insert.combo.js @@ -1,34 +1,58 @@ -/** - * 可以往当前选中节点下添加新值的下拉树 - * @class BI.MultiTreeInsertCombo - * @extends BI.Single - */ - -BI.MultiTreeInsertCombo = BI.inherit(BI.Single, { - - _defaultConfig: function () { - return BI.extend(BI.MultiTreeInsertCombo.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + emptyFn, + createWidget, + toPix, + nextTick, + Events, + AbsoluteLayout, + VerticalAdaptLayout, + deepClone +} from "@/core"; +import { Single, Combo } from "@/base"; +import { MultiTreeSearchInsertPane } from "trigger/multi.tree.search.insert.pane"; +import { MultiTreePopup } from "multi.tree.popup"; +import { MultiSelectTrigger } from "../multiselect/multiselect.trigger"; +import { TriggerIconButton } from "@/case"; +import { MultiSelectCheckSelectedSwitcher } from "../multiselect/trigger/switcher.checkselected"; + +@shortcut() +export class MultiTreeInsertCombo extends Single { + static xtype = "bi.multi_tree_insert_combo"; + + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_CLICK_ITEM = "EVENT_CLICK_ITEM"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-tree-insert-combo", - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, + itemsCreator: emptyFn, + valueFormatter: emptyFn, height: 24, allowEdit: true, isNeedAdjustWidth: true, }); - }, + } - _init: function () { - var self = this, o = this.options; - BI.MultiTreeInsertCombo.superclass._init.apply(this, arguments); - var isInit = false; - var want2showCounter = false; + _init() { + const self = this, + o = this.options; + super._init(...arguments); + let isInit = false; + let want2showCounter = false; this.storeValue = { value: o.value || {} }; - this.trigger = BI.createWidget({ + this.trigger = createWidget({ type: "bi.multi_select_trigger", allowEdit: o.allowEdit, - height: BI.toPix(o.height, o.simple ? 1 : 2), + height: toPix(o.height, o.simple ? 1 : 2), valueFormatter: o.valueFormatter, text: o.text, defaultText: o.defaultText, @@ -49,85 +73,94 @@ BI.MultiTreeInsertCombo = BI.inherit(BI.Single, { type: "bi.multi_tree_search_insert_pane", listeners: [ { - eventName: BI.MultiTreeSearchInsertPane.EVENT_ADD_ITEM, - action: function () { - self.storeValue.value[self.trigger.getSearcher().getKeyword()] = {}; + eventName: MultiTreeSearchInsertPane.EVENT_ADD_ITEM, + action () { + self.storeValue.value[ + self.trigger.getSearcher().getKeyword() + ] = {}; self._assertShowValue(); // setValue以更新paras.value, 之后从search popup中拿到的就能有add的值了 self.combo.setValue(self.storeValue); self.numberCounter.setValue(self.storeValue); self._stopEditing(); self._dataChange = true; - } - }, { - eventName: BI.MultiTreeSearchInsertPane.EVENT_CLICK_TREE_NODE, - action: function () { + }, + }, + { + eventName: + MultiTreeSearchInsertPane.EVENT_CLICK_TREE_NODE, + action () { self._dataChange = true; - } + }, } - ] - } + ], + }, }, - value: { value: o.value || {} } - + value: { value: o.value || {} }, }); - this.combo = BI.createWidget({ - type: "bi.combo", - cls: (o.simple ? "bi-border-bottom" : "bi-border bi-border-radius"), + this.combo = createWidget({ + type: Combo.xtype, + cls: o.simple ? "bi-border-bottom" : "bi-border bi-border-radius", toggle: !o.allowEdit, container: o.container, el: this.trigger, adjustLength: 1, popup: { type: "bi.multi_tree_popup_view", - ref: function () { + ref () { self.popup = this; self.trigger.setAdapter(this); self.numberCounter.setAdapter(this); }, listeners: [ { - eventName: BI.MultiTreePopup.EVENT_AFTERINIT, - action: function () { + eventName: MultiTreePopup.EVENT_AFTERINIT, + action () { self.numberCounter.adjustView(); isInit = true; if (want2showCounter === true) { showCounter(); } - } - }, { - eventName: BI.MultiTreePopup.EVENT_CHANGE, - action: function () { + }, + }, + { + eventName: MultiTreePopup.EVENT_CHANGE, + action () { change = true; - var val = { + const val = { type: BI.Selection.Multi, - value: this.hasChecked() ? this.getValue() : {} + value: this.hasChecked() ? this.getValue() : {}, }; self.trigger.getSearcher().setState(val); self.numberCounter.setButtonChecked(val); self.storeValue = { value: self.combo.getValue() }; - self.fireEvent(BI.MultiTreeInsertCombo.EVENT_CLICK_ITEM, self.getValue()); + self.fireEvent( + MultiTreeInsertCombo.EVENT_CLICK_ITEM, + self.getValue() + ); self._dataChange = true; - } - }, { - eventName: BI.MultiTreePopup.EVENT_CLICK_CONFIRM, - action: function () { + }, + }, + { + eventName: MultiTreePopup.EVENT_CLICK_CONFIRM, + action () { self.combo.hideView(); - } - }, { - eventName: BI.MultiTreePopup.EVENT_CLICK_CLEAR, - action: function () { + }, + }, + { + eventName: MultiTreePopup.EVENT_CLICK_CLEAR, + action () { clear = true; self._dataChange = true; self.setValue(); self._defaultState(); - } + }, } ], itemsCreator: o.itemsCreator, - onLoaded: function () { - BI.nextTick(function () { + onLoaded () { + nextTick(() => { self.numberCounter.adjustView(); self.trigger.getSearcher().adjustView(); }); @@ -136,49 +169,51 @@ BI.MultiTreeInsertCombo = BI.inherit(BI.Single, { }, isNeedAdjustWidth: o.isNeedAdjustWidth, value: { value: o.value || {} }, - hideChecker: function (e) { - return triggerBtn.element.find(e.target).length === 0 && - self.numberCounter.element.find(e.target).length === 0; - } + hideChecker (e) { + return ( + triggerBtn.element.find(e.target).length === 0 && + self.numberCounter.element.find(e.target).length === 0 + ); + }, }); var change = false; - var clear = false; // 标识当前是否点击了清空 + var clear = false; // 标识当前是否点击了清空 - var isSearching = function () { + const isSearching = function () { return self.trigger.getSearcher().isSearching(); }; - var isPopupView = function () { + const isPopupView = function () { return self.combo.isViewVisible(); }; - this.trigger.on(BI.MultiSelectTrigger.EVENT_FOCUS, function () { - self.fireEvent(BI.MultiTreeInsertCombo.EVENT_FOCUS); + this.trigger.on(MultiSelectTrigger.EVENT_FOCUS, () => { + self.fireEvent(MultiTreeInsertCombo.EVENT_FOCUS); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_BLUR, function () { - self.fireEvent(BI.MultiTreeInsertCombo.EVENT_BLUR); + this.trigger.on(MultiSelectTrigger.EVENT_BLUR, () => { + self.fireEvent(MultiTreeInsertCombo.EVENT_BLUR); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_START, function () { + this.trigger.on(MultiSelectTrigger.EVENT_START, function () { self.storeValue = { value: self.combo.getValue() }; this.setValue(self.storeValue); self.numberCounter.setValue(self.storeValue); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_STOP, function () { + this.trigger.on(MultiSelectTrigger.EVENT_STOP, function () { self.storeValue = { value: this.getValue() }; self.combo.setValue(self.storeValue); self.numberCounter.setValue(self.storeValue); - BI.nextTick(function () { + nextTick(() => { if (isPopupView()) { self.combo.populate(); } }); - self.fireEvent(BI.MultiTreeInsertCombo.EVENT_STOP); + self.fireEvent(MultiTreeInsertCombo.EVENT_STOP); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_SEARCHING, function () { - self.fireEvent(BI.MultiTreeInsertCombo.EVENT_SEARCHING); + this.trigger.on(MultiSelectTrigger.EVENT_SEARCHING, () => { + self.fireEvent(MultiTreeInsertCombo.EVENT_SEARCHING); }); function showCounter() { @@ -191,23 +226,28 @@ BI.MultiTreeInsertCombo = BI.inherit(BI.Single, { self.numberCounter.setValue(self.storeValue); } - this.trigger.on(BI.MultiSelectTrigger.EVENT_TRIGGER_CLICK, function () { + this.trigger.on(MultiSelectTrigger.EVENT_TRIGGER_CLICK, () => { self.combo.toggle(); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_CHANGE, function () { - var checked = this.getSearcher().hasChecked(); - var val = { + this.trigger.on(MultiSelectTrigger.EVENT_CHANGE, function () { + const checked = this.getSearcher().hasChecked(); + const val = { type: BI.Selection.Multi, - value: checked ? { 1: 1 } : {} + value: checked ? { 1: 1 } : {}, }; - this.getSearcher().setState(checked ? BI.Selection.Multi : BI.Selection.None); + this.getSearcher().setState( + checked ? BI.Selection.Multi : BI.Selection.None + ); self.numberCounter.setButtonChecked(val); - self.fireEvent(BI.MultiTreeInsertCombo.EVENT_CLICK_ITEM, self.combo.getValue()); + self.fireEvent( + MultiTreeInsertCombo.EVENT_CLICK_ITEM, + self.combo.getValue() + ); self._dataChange = true; }); - this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { + this.combo.on(Combo.EVENT_BEFORE_POPUPVIEW, function () { if (isSearching()) { return; } @@ -221,12 +261,13 @@ BI.MultiTreeInsertCombo = BI.inherit(BI.Single, { self.combo.setValue(self.storeValue); self.numberCounter.setValue(self.storeValue); self.populate(); - self.fireEvent(BI.MultiTreeInsertCombo.EVENT_BEFORE_POPUPVIEW); + self.fireEvent(MultiTreeInsertCombo.EVENT_BEFORE_POPUPVIEW); }); - this.combo.on(BI.Combo.EVENT_BEFORE_HIDEVIEW, function () { + this.combo.on(Combo.EVENT_BEFORE_HIDEVIEW, () => { if (isSearching()) { self._stopEditing(); - self._dataChange && self.fireEvent(BI.MultiTreeInsertCombo.EVENT_CONFIRM); + self._dataChange && + self.fireEvent(MultiTreeInsertCombo.EVENT_CONFIRM); } else { if (isPopupView()) { self._stopEditing(); @@ -234,20 +275,21 @@ BI.MultiTreeInsertCombo = BI.inherit(BI.Single, { if (clear === true) { self.storeValue = { value: {} }; } - self._dataChange && self.fireEvent(BI.MultiTreeInsertCombo.EVENT_CONFIRM); + self._dataChange && + self.fireEvent(MultiTreeInsertCombo.EVENT_CONFIRM); } } clear = false; change = false; }); - var triggerBtn = BI.createWidget({ - type: "bi.trigger_icon_button", + var triggerBtn = createWidget({ + type: TriggerIconButton.xtype, width: o.height, height: o.height, - cls: "multi-select-trigger-icon-button" + cls: "multi-select-trigger-icon-button", }); - triggerBtn.on(BI.TriggerIconButton.EVENT_CHANGE, function () { + triggerBtn.on(TriggerIconButton.EVENT_CHANGE, () => { self.numberCounter.hideView(); if (self.combo.isViewVisible()) { self.combo.hideView(); @@ -256,13 +298,13 @@ BI.MultiTreeInsertCombo = BI.inherit(BI.Single, { } }); - this.numberCounter = BI.createWidget({ + this.numberCounter = createWidget({ type: "bi.multi_select_check_selected_switcher", el: { - type: "bi.multi_tree_check_selected_button" + type: "bi.multi_tree_check_selected_button", }, popup: { - type: "bi.multi_tree_check_pane" + type: "bi.multi_tree_check_pane", }, itemsCreator: o.itemsCreator, masker: { @@ -274,43 +316,56 @@ BI.MultiTreeInsertCombo = BI.inherit(BI.Single, { }, }, valueFormatter: o.valueFormatter, - value: o.value + value: o.value, }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE, function () { - if (!self.combo.isViewVisible()) { - self.combo.showView(); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE, + () => { + if (!self.combo.isViewVisible()) { + self.combo.showView(); + } } - }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW, function () { - if (want2showCounter === false) { - want2showCounter = true; + ); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW, + () => { + if (want2showCounter === false) { + want2showCounter = true; + } + if (isInit === true) { + want2showCounter = null; + showCounter(); + } } - if (isInit === true) { - want2showCounter = null; - showCounter(); + ); + + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_AFTER_HIDEVIEW, + () => { + nextTick(() => { + // 收起时自动调整宽度 + self.trigger.refreshPlaceHolderWidth(0); + }); } - }); - - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_AFTER_HIDEVIEW, function () { - BI.nextTick(function () {// 收起时自动调整宽度 - self.trigger.refreshPlaceHolderWidth(0); - }); - }); - - this.numberCounter.on(BI.Events.VIEW, function (b) { - BI.nextTick(function () {// 自动调整宽度 - self.trigger.refreshPlaceHolderWidth((b === true ? self.numberCounter.element.outerWidth() + 8 : 0)); + ); + + this.numberCounter.on(Events.VIEW, b => { + nextTick(() => { + // 自动调整宽度 + self.trigger.refreshPlaceHolderWidth( + b === true ? self.numberCounter.element.outerWidth() + 8 : 0 + ); }); }); - this.trigger.element.click(function (e) { + this.trigger.element.click(e => { if (self.trigger.element.find(e.target).length > 0) { self.numberCounter.hideView(); } }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, items: [ { @@ -318,89 +373,81 @@ BI.MultiTreeInsertCombo = BI.inherit(BI.Single, { left: 0, right: 0, top: 0, - bottom: 0 - }, { + bottom: 0, + }, + { el: triggerBtn, right: 0, top: 0, - bottom: 0 - }, { + bottom: 0, + }, + { el: { - type: "bi.vertical_adapt", - items: [this.numberCounter] + type: VerticalAdaptLayout.xtype, + items: [this.numberCounter], }, right: o.height, top: 0, height: o.height, } - ] + ], }); - }, + } - _assertShowValue: function () { + _assertShowValue() { this.trigger.getSearcher().setState(this.storeValue); this.numberCounter.setButtonChecked(this.storeValue); - }, + } - _stopEditing: function () { + _stopEditing() { this.trigger.stopEditing(); this.numberCounter.hideView(); - }, + } - _defaultState: function () { + _defaultState() { this._stopEditing(); this.combo.hideView(); - }, + } - getSearcher: function () { + getSearcher() { return this.trigger.getSearcher(); - }, + } - showView: function () { + showView() { this.combo.showView(); - }, + } - hideView: function () { + hideView() { this.combo.hideView(); - }, + } - setValue: function (v) { + setValue(v) { this.storeValue.value = v || {}; this.combo.setValue({ - value: v || {} + value: v || {}, }); this.numberCounter.setValue({ - value: v || {} + value: v || {}, }); - }, + } - getValue: function () { - return BI.deepClone(this.storeValue.value); - }, + getValue() { + return deepClone(this.storeValue.value); + } - populate: function () { + populate() { this.combo.populate(); - }, + } - focus: function () { + focus() { this.trigger.focus(); - }, + } - blur: function () { + blur() { this.trigger.blur(); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.trigger.setWaterMark(v); } -}); - -BI.MultiTreeInsertCombo.EVENT_FOCUS = "EVENT_FOCUS"; -BI.MultiTreeInsertCombo.EVENT_BLUR = "EVENT_BLUR"; -BI.MultiTreeInsertCombo.EVENT_STOP = "EVENT_STOP"; -BI.MultiTreeInsertCombo.EVENT_CLICK_ITEM = "EVENT_CLICK_ITEM"; -BI.MultiTreeInsertCombo.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.MultiTreeInsertCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.MultiTreeInsertCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; - -BI.shortcut("bi.multi_tree_insert_combo", BI.MultiTreeInsertCombo); +} diff --git a/src/widget/multitree/multi.tree.list.combo.js b/src/widget/multitree/multi.tree.list.combo.js index a3a016179..3d6e6d269 100644 --- a/src/widget/multitree/multi.tree.list.combo.js +++ b/src/widget/multitree/multi.tree.list.combo.js @@ -1,38 +1,68 @@ -/** - * 选中节点不影响父子节点状态的下拉树 - * @class BI.MultiTreeListCombo - * @extends BI.Single - */ - -BI.MultiTreeListCombo = BI.inherit(BI.Single, { - _defaultConfig: function () { - return BI.extend(BI.MultiTreeListCombo.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + emptyFn, + createWidget, + toPix, + nextTick, + Events, + AbsoluteLayout, + VerticalAdaptLayout, + deepClone +} from "@/core"; +import { Single, Combo } from "@/base"; +import { MultiTreeSearchInsertPane } from "trigger/multi.tree.search.insert.pane"; +import { MultiTreePopup } from "multi.tree.popup"; +import { MultiSelectTrigger } from "../multiselect/multiselect.trigger"; +import { + TriggerIconButton, + ListPartTree, + ListDisplayTree, + Listasynctree +} from "@/case"; +import { MultiSelectCheckSelectedSwitcher } from "../multiselect/trigger/switcher.checkselected"; + +@shortcut() +export class MultiTreeListCombo extends Single { + static xtype = "bi.multi_tree_list_combo"; + + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_CLICK_ITEM = "EVENT_CLICK_ITEM"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-tree-list-combo", - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, + itemsCreator: emptyFn, + valueFormatter: emptyFn, height: 24, allowEdit: true, allowInsertValue: true, isNeedAdjustWidth: true, text: "", }); - }, + } - _init: function () { - var self = this, o = this.options; - BI.MultiTreeListCombo.superclass._init.apply(this, arguments); - var isInit = false; - var want2showCounter = false; + _init() { + const self = this, + o = this.options; + super._init(...arguments); + let isInit = false; + let want2showCounter = false; this.storeValue = { value: o.value || [] }; - this.trigger = BI.createWidget({ + this.trigger = createWidget({ type: "bi.multi_select_trigger", allowEdit: o.allowEdit, text: o.text, defaultText: o.defaultText, watermark: o.watermark, - height: BI.toPix(o.height, o.simple ? 1 : 2), + height: toPix(o.height, o.simple ? 1 : 2), valueFormatter: o.valueFormatter, masker: { offset: { @@ -46,96 +76,110 @@ BI.MultiTreeListCombo = BI.inherit(BI.Single, { type: "bi.multi_list_tree_searcher", itemsCreator: o.itemsCreator, popup: { - type: o.allowInsertValue ? "bi.multi_tree_search_insert_pane" : "bi.multi_tree_search_pane", + type: o.allowInsertValue + ? "bi.multi_tree_search_insert_pane" + : "bi.multi_tree_search_pane", el: { - type: "bi.list_part_tree" + type: ListPartTree.xtype, }, - listeners: [{ - eventName: BI.MultiTreeSearchInsertPane.EVENT_ADD_ITEM, - action: function () { - self.storeValue.value.unshift([self.trigger.getSearcher().getKeyword()]); - self._assertShowValue(); - // setValue以更新paras.value, 之后从search popup中拿到的就能有add的值了 - self.combo.setValue(self.storeValue); - self.numberCounter.setValue(self.storeValue); - self._stopEditing(); - self._dataChange = true; + listeners: [ + { + eventName: MultiTreeSearchInsertPane.EVENT_ADD_ITEM, + action () { + self.storeValue.value.unshift([ + self.trigger.getSearcher().getKeyword() + ]); + self._assertShowValue(); + // setValue以更新paras.value, 之后从search popup中拿到的就能有add的值了 + self.combo.setValue(self.storeValue); + self.numberCounter.setValue(self.storeValue); + self._stopEditing(); + self._dataChange = true; + }, } - }] - } + ], + }, }, switcher: { el: { - type: "bi.multi_tree_check_selected_button" + type: "bi.multi_tree_check_selected_button", }, popup: { type: "bi.multi_tree_check_pane", el: { - type: "bi.list_display_tree" + type: ListDisplayTree.xtype, }, - itemsCreator: o.itemsCreator - } + itemsCreator: o.itemsCreator, + }, }, - value: this.storeValue + value: this.storeValue, }); - this.combo = BI.createWidget({ - type: "bi.combo", - cls: (o.simple ? "bi-border-bottom" : "bi-border bi-border-radius"), + this.combo = createWidget({ + type: Combo.xtype, + cls: o.simple ? "bi-border-bottom" : "bi-border bi-border-radius", toggle: !o.allowEdit, container: o.container, el: this.trigger, adjustLength: 1, popup: { - type: "bi.multi_tree_popup_view", - ref: function () { + type: MultiTreePopup.xtype, + ref () { self.popup = this; self.trigger.setAdapter(this); self.numberCounter.setAdapter(this); }, el: { - type: "bi.list_async_tree" + type: Listasynctree.xtype, }, - listeners: [{ - eventName: BI.MultiTreePopup.EVENT_AFTERINIT, - action: function () { - self.numberCounter.adjustView(); - isInit = true; - if (want2showCounter === true) { - showCounter(); - } - } - }, { - eventName: BI.MultiTreePopup.EVENT_CHANGE, - action: function () { - change = true; - var val = { - type: BI.Selection.Multi, - value: this.hasChecked() ? this.getValue() : [] - }; - self.trigger.getSearcher().setState(val); - self.numberCounter.setButtonChecked(val); - self.storeValue = { value: self.combo.getValue() }; - self.fireEvent(BI.MultiTreeListCombo.EVENT_CLICK_ITEM, self.getValue()); - self._dataChange = true; - } - }, { - eventName: BI.MultiTreePopup.EVENT_CLICK_CONFIRM, - action: function () { - self.combo.hideView(); - } - }, { - eventName: BI.MultiTreePopup.EVENT_CLICK_CLEAR, - action: function () { - clear = true; - self._dataChange = true; - self.setValue(); - self._defaultState(); + listeners: [ + { + eventName: MultiTreePopup.EVENT_AFTERINIT, + action () { + self.numberCounter.adjustView(); + isInit = true; + if (want2showCounter === true) { + showCounter(); + } + }, + }, + { + eventName: MultiTreePopup.EVENT_CHANGE, + action () { + change = true; + const val = { + type: BI.Selection.Multi, + value: this.hasChecked() ? this.getValue() : [], + }; + self.trigger.getSearcher().setState(val); + self.numberCounter.setButtonChecked(val); + self.storeValue = { value: self.combo.getValue() }; + self.fireEvent( + MultiTreeListCombo.EVENT_CLICK_ITEM, + self.getValue() + ); + self._dataChange = true; + }, + }, + { + eventName: MultiTreePopup.EVENT_CLICK_CONFIRM, + action () { + self.combo.hideView(); + }, + }, + { + eventName: MultiTreePopup.EVENT_CLICK_CLEAR, + action () { + clear = true; + self._dataChange = true; + self.setValue(); + self._defaultState(); + }, } - }], + ], itemsCreator: o.itemsCreator, - onLoaded: function () { - BI.nextTick(function () { + onLoaded () { + nextTick(() => { self.numberCounter.adjustView(); self.trigger.getSearcher().adjustView(); }); @@ -144,49 +188,51 @@ BI.MultiTreeListCombo = BI.inherit(BI.Single, { }, isNeedAdjustWidth: o.isNeedAdjustWidth, value: this.storeValue, - hideChecker: function (e) { - return triggerBtn.element.find(e.target).length === 0 && - self.numberCounter.element.find(e.target).length === 0; - } + hideChecker (e) { + return ( + triggerBtn.element.find(e.target).length === 0 && + self.numberCounter.element.find(e.target).length === 0 + ); + }, }); var change = false; - var clear = false; // 标识当前是否点击了清空 + var clear = false; // 标识当前是否点击了清空 - var isSearching = function () { + const isSearching = function () { return self.trigger.getSearcher().isSearching(); }; - var isPopupView = function () { + const isPopupView = function () { return self.combo.isViewVisible(); }; - this.trigger.on(BI.MultiSelectTrigger.EVENT_FOCUS, function () { - self.fireEvent(BI.MultiTreeListCombo.EVENT_FOCUS); + this.trigger.on(MultiSelectTrigger.EVENT_FOCUS, () => { + self.fireEvent(MultiTreeListCombo.EVENT_FOCUS); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_BLUR, function () { - self.fireEvent(BI.MultiTreeListCombo.EVENT_BLUR); + this.trigger.on(MultiSelectTrigger.EVENT_BLUR, () => { + self.fireEvent(MultiTreeListCombo.EVENT_BLUR); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_START, function () { + this.trigger.on(MultiSelectTrigger.EVENT_START, function () { self.storeValue = { value: self.combo.getValue() }; this.setValue(self.storeValue); self.numberCounter.setValue(self.storeValue); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_STOP, function () { + this.trigger.on(MultiSelectTrigger.EVENT_STOP, function () { self.storeValue = { value: this.getValue() }; self.combo.setValue(self.storeValue); self.numberCounter.setValue(self.storeValue); - BI.nextTick(function () { + nextTick(() => { if (isPopupView()) { self.combo.populate(); } }); - self.fireEvent(BI.MultiTreeListCombo.EVENT_STOP); + self.fireEvent(MultiTreeListCombo.EVENT_STOP); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_SEARCHING, function () { - self.fireEvent(BI.MultiTreeListCombo.EVENT_SEARCHING); + this.trigger.on(MultiSelectTrigger.EVENT_SEARCHING, () => { + self.fireEvent(MultiTreeListCombo.EVENT_SEARCHING); }); function showCounter() { @@ -199,23 +245,28 @@ BI.MultiTreeListCombo = BI.inherit(BI.Single, { self.numberCounter.setValue(self.storeValue); } - this.trigger.on(BI.MultiSelectTrigger.EVENT_TRIGGER_CLICK, function () { + this.trigger.on(MultiSelectTrigger.EVENT_TRIGGER_CLICK, () => { self.combo.toggle(); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_CHANGE, function () { - var checked = this.getSearcher().hasChecked(); - var val = { + this.trigger.on(MultiSelectTrigger.EVENT_CHANGE, function () { + const checked = this.getSearcher().hasChecked(); + const val = { type: BI.Selection.Multi, - value: checked ? { 1: 1 } : {} + value: checked ? { 1: 1 } : {}, }; - this.getSearcher().setState(checked ? BI.Selection.Multi : BI.Selection.None); + this.getSearcher().setState( + checked ? BI.Selection.Multi : BI.Selection.None + ); self.numberCounter.setButtonChecked(val); - self.fireEvent(BI.MultiTreeListCombo.EVENT_CLICK_ITEM, self.combo.getValue()); + self.fireEvent( + MultiTreeListCombo.EVENT_CLICK_ITEM, + self.combo.getValue() + ); self._dataChange = true; }); - this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { + this.combo.on(Combo.EVENT_BEFORE_POPUPVIEW, function () { if (isSearching()) { return; } @@ -229,12 +280,13 @@ BI.MultiTreeListCombo = BI.inherit(BI.Single, { self.combo.setValue(self.storeValue); self.numberCounter.setValue(self.storeValue); self.populate(); - self.fireEvent(BI.MultiTreeListCombo.EVENT_BEFORE_POPUPVIEW); + self.fireEvent(MultiTreeListCombo.EVENT_BEFORE_POPUPVIEW); }); - this.combo.on(BI.Combo.EVENT_BEFORE_HIDEVIEW, function () { + this.combo.on(Combo.EVENT_BEFORE_HIDEVIEW, () => { if (isSearching()) { self.trigger.stopEditing(); - self._dataChange && self.fireEvent(BI.MultiTreeListCombo.EVENT_CONFIRM); + self._dataChange && + self.fireEvent(MultiTreeListCombo.EVENT_CONFIRM); } else { if (isPopupView()) { self._stopEditing(); @@ -242,20 +294,21 @@ BI.MultiTreeListCombo = BI.inherit(BI.Single, { if (clear === true) { self.storeValue = { value: [] }; } - self._dataChange && self.fireEvent(BI.MultiTreeListCombo.EVENT_CONFIRM); + self._dataChange && + self.fireEvent(MultiTreeListCombo.EVENT_CONFIRM); } } clear = false; change = false; }); - var triggerBtn = BI.createWidget({ - type: "bi.trigger_icon_button", + var triggerBtn = createWidget({ + type: TriggerIconButton.xtype, width: o.height, height: o.height, - cls: "multi-select-trigger-icon-button" + cls: "multi-select-trigger-icon-button", }); - triggerBtn.on(BI.TriggerIconButton.EVENT_CHANGE, function () { + triggerBtn.on(TriggerIconButton.EVENT_CHANGE, () => { self.numberCounter.hideView(); if (self.combo.isViewVisible()) { self.combo.hideView(); @@ -264,13 +317,13 @@ BI.MultiTreeListCombo = BI.inherit(BI.Single, { } }); - this.numberCounter = BI.createWidget({ + this.numberCounter = createWidget({ type: "bi.multi_select_check_selected_switcher", el: { - type: "bi.multi_tree_check_selected_button" + type: "bi.multi_tree_check_selected_button", }, popup: { - type: "bi.multi_tree_check_pane" + type: "bi.multi_tree_check_pane", }, itemsCreator: o.itemsCreator, masker: { @@ -282,131 +335,138 @@ BI.MultiTreeListCombo = BI.inherit(BI.Single, { }, }, valueFormatter: o.valueFormatter, - value: o.value - }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE, function () { - if (!self.combo.isViewVisible()) { - self.combo.showView(); - } + value: o.value, }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW, function () { - if (want2showCounter === false) { - want2showCounter = true; + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE, + () => { + if (!self.combo.isViewVisible()) { + self.combo.showView(); + } } - if (isInit === true) { - want2showCounter = null; - showCounter(); + ); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW, + () => { + if (want2showCounter === false) { + want2showCounter = true; + } + if (isInit === true) { + want2showCounter = null; + showCounter(); + } } - }); - - this.numberCounter.on(BI.Events.VIEW, function (b) { - BI.nextTick(function () {// 自动调整宽度 - self.trigger.refreshPlaceHolderWidth((b === true ? self.numberCounter.element.outerWidth() + 8 : 0)); + ); + + this.numberCounter.on(Events.VIEW, b => { + nextTick(() => { + // 自动调整宽度 + self.trigger.refreshPlaceHolderWidth( + b === true ? self.numberCounter.element.outerWidth() + 8 : 0 + ); }); }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_AFTER_HIDEVIEW, function () { - BI.nextTick(function () {// 收起时自动调整宽度 - self.trigger.refreshPlaceHolderWidth(0); - }); - }); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_AFTER_HIDEVIEW, + () => { + nextTick(() => { + // 收起时自动调整宽度 + self.trigger.refreshPlaceHolderWidth(0); + }); + } + ); - this.trigger.element.click(function (e) { + this.trigger.element.click(e => { if (self.trigger.element.find(e.target).length > 0) { self.numberCounter.hideView(); } }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.combo, - left: 0, - right: 0, - top: 0, - bottom: 0 - }, { - el: triggerBtn, - right: 0, - top: 0, - bottom: 0 - }, { - el: { - type: "bi.vertical_adapt", - items: [this.numberCounter] + items: [ + { + el: this.combo, + left: 0, + right: 0, + top: 0, + bottom: 0, + }, + { + el: triggerBtn, + right: 0, + top: 0, + bottom: 0, }, - right: o.height, - top: 0, - height: o.height, - }] + { + el: { + type: VerticalAdaptLayout.xtype, + items: [this.numberCounter], + }, + right: o.height, + top: 0, + height: o.height, + } + ], }); - }, + } - _assertShowValue: function () { + _assertShowValue() { this.trigger.getSearcher().setState(this.storeValue); this.numberCounter.setButtonChecked(this.storeValue); - }, + } - _stopEditing: function () { + _stopEditing() { this.trigger.stopEditing(); this.numberCounter.hideView(); - }, + } - _defaultState: function () { + _defaultState() { this._stopEditing(); this.combo.hideView(); - }, + } - showView: function () { + showView() { this.combo.showView(); - }, + } - hideView: function () { + hideView() { this.combo.hideView(); - }, + } - getSearcher: function () { + getSearcher() { return this.trigger.getSearcher(); - }, + } - setValue: function (v) { + setValue(v) { this.storeValue.value = v || []; this.combo.setValue({ - value: v || [] + value: v || [], }); this.numberCounter.setValue({ - value: v || [] + value: v || [], }); - }, + } - getValue: function () { - return BI.deepClone(this.storeValue.value); - }, + getValue() { + return deepClone(this.storeValue.value); + } - populate: function () { + populate() { this.combo.populate(); - }, + } - focus: function () { + focus() { this.trigger.focus(); - }, + } - blur: function () { + blur() { this.trigger.blur(); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.trigger.setWaterMark(v); } -}); - -BI.MultiTreeListCombo.EVENT_FOCUS = "EVENT_FOCUS"; -BI.MultiTreeListCombo.EVENT_BLUR = "EVENT_BLUR"; -BI.MultiTreeListCombo.EVENT_STOP = "EVENT_STOP"; -BI.MultiTreeListCombo.EVENT_CLICK_ITEM = "EVENT_CLICK_ITEM"; -BI.MultiTreeListCombo.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.MultiTreeListCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.MultiTreeListCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; - -BI.shortcut("bi.multi_tree_list_combo", BI.MultiTreeListCombo); +} diff --git a/src/widget/multitree/multi.tree.popup.js b/src/widget/multitree/multi.tree.popup.js index 970c76cc6..aeb1ced3d 100644 --- a/src/widget/multitree/multi.tree.popup.js +++ b/src/widget/multitree/multi.tree.popup.js @@ -1,106 +1,108 @@ -/** - * 带加载的多选下拉面板 - * @class BI.MultiTreePopup - * @extends BI.Pane - */ -BI.MultiTreePopup = BI.inherit(BI.Pane, { - - _defaultConfig: function () { - return BI.extend(BI.MultiTreePopup.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, extend, emptyFn, createWidget, i18nText } from "@/core"; +import { Pane } from "@/base"; +import { Asynctree, MultiPopupView, TreeView } from "@/case"; + +@shortcut() +export class MultiTreePopup extends Pane { + static xtype = "bi.multi_tree_popup_view"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_CLICK_CONFIRM = "EVENT_CLICK_CONFIRM"; + static EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; + static EVENT_AFTERINIT = "EVENT_AFTERINIT"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-tree-popup", maxWidth: "auto", minWidth: 140, maxHeight: 400, - onLoaded: BI.emptyFn, + onLoaded: emptyFn, el: { - type: "bi.async_tree" - } + type: Asynctree.xtype, + }, }); - }, + } - _init: function () { - BI.MultiTreePopup.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, opts = this.options, v = opts.value; + const self = this, + opts = this.options, + v = opts.value; this.selectedValues = {}; - this.tree = BI.createWidget(opts.el, { - type: "bi.async_tree", + this.tree = createWidget(opts.el, { + type: Asynctree.xtype, showLine: opts.showLine, height: 400, cls: "popup-view-tree", itemsCreator: opts.itemsCreator, onLoaded: opts.onLoaded, - value: v.value || {} + value: v.value || {}, }); - this.popupView = BI.createWidget({ - type: "bi.multi_popup_view", + this.popupView = createWidget({ + type: MultiPopupView.xtype, element: this, stopPropagation: false, maxWidth: opts.maxWidth, minWidth: opts.minWidth, maxHeight: opts.maxHeight, - buttons: [BI.i18nText("BI-Basic_Clears"), BI.i18nText("BI-Basic_OK")], - el: this.tree + buttons: [i18nText("BI-Basic_Clears"), i18nText("BI-Basic_OK")], + el: this.tree, }); - this.popupView.on(BI.MultiPopupView.EVENT_CLICK_TOOLBAR_BUTTON, function (index) { - switch (index) { + this.popupView.on( + MultiPopupView.EVENT_CLICK_TOOLBAR_BUTTON, + index => { + switch (index) { case 0: - self.fireEvent(BI.MultiTreePopup.EVENT_CLICK_CLEAR); + self.fireEvent(MultiTreePopup.EVENT_CLICK_CLEAR); break; case 1: - self.fireEvent(BI.MultiTreePopup.EVENT_CLICK_CONFIRM); + self.fireEvent(MultiTreePopup.EVENT_CLICK_CONFIRM); break; + } } - }); + ); - this.tree.on(BI.TreeView.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiTreePopup.EVENT_CHANGE); + this.tree.on(TreeView.EVENT_CHANGE, () => { + self.fireEvent(MultiTreePopup.EVENT_CHANGE); }); - this.tree.on(BI.TreeView.EVENT_AFTERINIT, function () { - self.fireEvent(BI.MultiTreePopup.EVENT_AFTERINIT); + this.tree.on(TreeView.EVENT_AFTERINIT, () => { + self.fireEvent(MultiTreePopup.EVENT_AFTERINIT); }); + } - }, - - getValue: function () { + getValue() { return this.tree.getValue(); - }, + } - setValue: function (v) { + setValue(v) { v || (v = {}); this.tree.setSelectedValue(v.value); - }, + } - populate: function (config) { + populate(config) { this.tree.stroke(config); - }, + } - hasChecked: function () { + hasChecked() { return this.tree.hasChecked(); - }, + } - setDirection: function (direction, position) { + setDirection(direction, position) { this.popupView.setDirection(direction, position); - }, + } - resetHeight: function (h) { + resetHeight(h) { this.popupView.resetHeight(h); - }, + } - resetWidth: function (w) { + resetWidth(w) { this.popupView.resetWidth(w); } -}); - -BI.MultiTreePopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiTreePopup.EVENT_CLICK_CONFIRM = "EVENT_CLICK_CONFIRM"; -BI.MultiTreePopup.EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; -BI.MultiTreePopup.EVENT_AFTERINIT = "EVENT_AFTERINIT"; - - -BI.shortcut("bi.multi_tree_popup_view", BI.MultiTreePopup); +} diff --git a/src/widget/multitree/trigger/multi.tree.button.checkselected.js b/src/widget/multitree/trigger/multi.tree.button.checkselected.js index 5efd65b2e..7c8e95444 100644 --- a/src/widget/multitree/trigger/multi.tree.button.checkselected.js +++ b/src/widget/multitree/trigger/multi.tree.button.checkselected.js @@ -1,67 +1,80 @@ -/** - * 查看已选按钮 - * Created by guy on 15/11/3. - * @class BI.MultiTreeCheckSelectedButton - * @extends BI.Single - */ -BI.MultiTreeCheckSelectedButton = BI.inherit(BI.Single, { +import { + shortcut, + extend, + emptyFn, + createWidget, + i18nText, + Controller, + size +} from "@/core"; +import { Single, TextButton, IconButton } from "@/base"; +import { MultiSelectCheckSelectedButton } from "../../multiselect/trigger/button.checkselected"; - _defaultConfig: function () { - return BI.extend(BI.MultiTreeCheckSelectedButton.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class MultiTreeCheckSelectedButton extends Single { + static xtype = "bi.multi_tree_check_selected_button"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-tree-check-selected-button", - itemsCreator: BI.emptyFn + itemsCreator: emptyFn, }); - }, + } - _init: function () { - BI.MultiTreeCheckSelectedButton.superclass._init.apply(this, arguments); - var self = this; - this.indicator = BI.createWidget({ - type: "bi.icon_button", + _init() { + super._init(...arguments); + const self = this; + this.indicator = createWidget({ + type: IconButton.xtype, cls: "check-font trigger-check-selected icon-size-12", width: 16, height: 16, - stopPropagation: true + stopPropagation: true, }); - this.checkSelected = BI.createWidget({ - type: "bi.text_button", + this.checkSelected = createWidget({ + type: TextButton.xtype, cls: "bi-high-light-background trigger-check-text", invisible: true, hgap: 4, - text: BI.i18nText("BI-Check_Selected"), + text: i18nText("BI-Check_Selected"), textAlign: "center", }); - this.checkSelected.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.checkSelected.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.checkSelected.on(BI.TextButton.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiSelectCheckSelectedButton.EVENT_CHANGE, arguments); + this.checkSelected.on(TextButton.EVENT_CHANGE, function () { + self.fireEvent( + MultiSelectCheckSelectedButton.EVENT_CHANGE, + arguments + ); }); - BI.createWidget({ + createWidget({ type: "bi.horizontal", element: this, - items: [this.indicator, this.checkSelected] + items: [this.indicator, this.checkSelected], }); - this.element.hover(function () { - self.indicator.setVisible(false); - self.checkSelected.setVisible(true); - }, function () { - self.indicator.setVisible(true); - self.checkSelected.setVisible(false); - }); + this.element.hover( + () => { + self.indicator.setVisible(false); + self.checkSelected.setVisible(true); + }, + () => { + self.indicator.setVisible(true); + self.checkSelected.setVisible(false); + } + ); this.setVisible(false); - }, + } - setValue: function (v) { + setValue(v) { v || (v = {}); - var show = BI.size(v.value) > 0; + const show = size(v.value) > 0; this.setVisible(show); } -}); - -BI.MultiTreeCheckSelectedButton.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multi_tree_check_selected_button", BI.MultiTreeCheckSelectedButton); +} diff --git a/src/widget/multitree/trigger/multi.tree.search.insert.pane.js b/src/widget/multitree/trigger/multi.tree.search.insert.pane.js index 345d8dab2..bb0a8f219 100644 --- a/src/widget/multitree/trigger/multi.tree.search.insert.pane.js +++ b/src/widget/multitree/trigger/multi.tree.search.insert.pane.js @@ -1,129 +1,148 @@ -/** - * - * 在搜索框中输入文本弹出的面板 - * @class BI.MultiTreeSearchInsertPane - * @extends BI.Pane - */ +import { + shortcut, + Widget, + i18nText, + extend, + Controller, + AbsoluteLayout, + isEmptyArray +} from "@/core"; +import { TreeView, PartTree } from "@/case"; +import { TextButton } from "@/base"; -BI.MultiTreeSearchInsertPane = BI.inherit(BI.Widget, { +@shortcut() +export class MultiTreeSearchInsertPane extends Widget { + static xtype = "bi.multi_tree_search_insert_pane"; - constants: { - height: 24, - }, - - props: { + props = { baseCls: "bi-multi-tree-search-insert-pane bi-card", - itemsCreator: BI.emptyFn, - keywordGetter: BI.emptyFn, - el: { - type: "bi.part_tree" - } - }, + el: { type: PartTree.xtype }, + }; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_CLICK_CONFIRM = "EVENT_CLICK_CONFIRM"; + static EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; + static EVENT_ADD_ITEM = "EVENT_ADD_ITEM"; + static EVENT_CLICK_TREE_NODE = "EVENT_CLICK_TREE_NODE"; - render: function () { - var self = this, opts = this.options; + render() { + const self = this, + opts = this.options; return { - type: "bi.absolute", + type: AbsoluteLayout.xtype, items: [ { el: { - type: "bi.text_button", + type: TextButton.xtype, invisible: true, - ref: function (_ref) { + ref(_ref) { self.addTip = _ref; }, - text: BI.i18nText("BI-Basic_Click_To_Add_Text", ""), + text: i18nText("BI-Basic_Click_To_Add_Text", ""), height: this.constants.height, cls: "bi-high-light", - handler: function () { - self.fireEvent(BI.MultiTreeSearchInsertPane.EVENT_ADD_ITEM, opts.keywordGetter()); - } + handler() { + self.fireEvent( + MultiTreeSearchInsertPane.EVENT_ADD_ITEM, + opts.keywordGetter() + ); + }, }, top: 5, left: 0, - right: 0 - }, { - el: BI.extend({ - type: "bi.part_tree", - tipText: BI.i18nText("BI-No_Select"), - itemsCreator: function (op, callback) { - op.keyword = opts.keywordGetter(); - opts.itemsCreator(op, function (res) { - callback(res); - self.setKeyword(opts.keywordGetter(), res.items); - }); - }, - ref: function (_ref) { - self.partTree = _ref; - }, - value: opts.value, - listeners: [ - { - eventName: BI.Controller.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - } - }, { - eventName: BI.TreeView.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.MultiTreeSearchInsertPane.EVENT_CHANGE); - } - }, { - eventName: BI.PartTree.EVENT_CLICK_TREE_NODE, - action: function () { - self.fireEvent(BI.MultiTreeSearchInsertPane.EVENT_CLICK_TREE_NODE); + right: 0, + }, + { + el: extend( + { + type: PartTree.xtype, + tipText: i18nText("BI-No_Select"), + itemsCreator(op, callback) { + op.keyword = opts.keywordGetter(); + opts.itemsCreator(op, res => { + callback(res); + self.setKeyword( + opts.keywordGetter(), + res.items + ); + }); + }, + ref(_ref) { + self.partTree = _ref; + }, + value: opts.value, + listeners: [ + { + eventName: Controller.EVENT_CHANGE, + action() { + self.fireEvent( + Controller.EVENT_CHANGE, + arguments + ); + }, + }, + { + eventName: TreeView.EVENT_CHANGE, + action() { + self.fireEvent( + MultiTreeSearchInsertPane.EVENT_CHANGE + ); + }, + }, + { + eventName: PartTree.EVENT_CLICK_TREE_NODE, + action() { + self.fireEvent( + MultiTreeSearchInsertPane.EVENT_CLICK_TREE_NODE + ); + }, } - } - ] - }, opts.el), + ], + }, + opts.el + ), left: 0, top: 0, bottom: 0, - right: 0 + right: 0, } - ] + ], }; - }, + } - setKeyword: function (keyword, nodes) { - var isAddTipVisible = BI.isEmptyArray(nodes); + setKeyword(keyword, nodes) { + const isAddTipVisible = isEmptyArray(nodes); this.addTip.setVisible(isAddTipVisible); this.partTree.setVisible(!isAddTipVisible); - isAddTipVisible && this.addTip.setText(BI.i18nText("BI-Basic_Click_To_Add_Text", keyword)); - }, + isAddTipVisible && + this.addTip.setText( + i18nText("BI-Basic_Click_To_Add_Text", keyword) + ); + } - hasChecked: function () { + hasChecked() { return this.partTree.hasChecked(); - }, + } - setValue: function (v) { + setValue(v) { this.setSelectedValue(v.value); - }, + } - setSelectedValue: function (v) { + setSelectedValue(v) { v || (v = {}); this.partTree.setSelectedValue(v); - }, + } - getValue: function () { + getValue() { return this.partTree.getValue(); - }, + } - empty: function () { + empty() { this.partTree.empty(); - }, - - populate: function (op) { - this.partTree.stroke.apply(this.partTree, arguments); } -}); - -BI.MultiTreeSearchInsertPane.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiTreeSearchInsertPane.EVENT_CLICK_CONFIRM = "EVENT_CLICK_CONFIRM"; -BI.MultiTreeSearchInsertPane.EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; -BI.MultiTreeSearchInsertPane.EVENT_ADD_ITEM = "EVENT_ADD_ITEM"; -BI.MultiTreeSearchInsertPane.EVENT_CLICK_TREE_NODE = "EVENT_CLICK_TREE_NODE"; - -BI.shortcut("bi.multi_tree_search_insert_pane", BI.MultiTreeSearchInsertPane); + populate(op) { + this.partTree.stroke(...arguments); + } +} diff --git a/src/widget/multitree/trigger/multi.tree.search.pane.js b/src/widget/multitree/trigger/multi.tree.search.pane.js index 82c221d18..bfea3f11b 100644 --- a/src/widget/multitree/trigger/multi.tree.search.pane.js +++ b/src/widget/multitree/trigger/multi.tree.search.pane.js @@ -1,84 +1,84 @@ -/** - * - * 在搜索框中输入文本弹出的面板 - * @class BI.MultiTreeSearchPane - * @extends BI.Pane - */ +import { shortcut, extend, i18nText, Controller } from "@/core"; +import { Pane } from "@/base"; +import { TreeView, PartTree } from "@/case"; -BI.MultiTreeSearchPane = BI.inherit(BI.Pane, { +@shortcut() +export class MultiTreeSearchPane extends Pane { + static xtype = "bi.multi_tree_search_pane"; - props: { - baseCls: "bi-multi-tree-search-pane bi-card", - itemsCreator: BI.emptyFn, - keywordGetter: BI.emptyFn - }, + props = { baseCls: "bi-multi-tree-search-pane bi-card" }; - render: function () { - var self = this, opts = this.options; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_CLICK_CONFIRM = "EVENT_CLICK_CONFIRM"; + static EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; + static EVENT_CLICK_TREE_NODE = "EVENT_CLICK_TREE_NODE"; - return BI.extend({ - type: "bi.part_tree", - element: this, - tipText: BI.i18nText("BI-No_Select"), - itemsCreator: function (op, callback) { - op.keyword = opts.keywordGetter(); - opts.itemsCreator(op, callback); - }, - value: opts.value, - listeners: [ - { - eventName: BI.Controller.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - } - }, { - eventName: BI.TreeView.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.MultiTreeSearchPane.EVENT_CHANGE); - } - }, { - eventName: BI.PartTree.EVENT_CLICK_TREE_NODE, - action: function () { - self.fireEvent(BI.MultiTreeSearchPane.EVENT_CLICK_TREE_NODE); + render() { + const self = this, + opts = this.options; + + return extend( + { + type: PartTree.xtype, + element: this, + tipText: i18nText("BI-No_Select"), + itemsCreator(op, callback) { + op.keyword = opts.keywordGetter(); + opts.itemsCreator(op, callback); + }, + value: opts.value, + listeners: [ + { + eventName: Controller.EVENT_CHANGE, + action() { + self.fireEvent(Controller.EVENT_CHANGE, arguments); + }, + }, + { + eventName: TreeView.EVENT_CHANGE, + action() { + self.fireEvent(MultiTreeSearchPane.EVENT_CHANGE); + }, + }, + { + eventName: PartTree.EVENT_CLICK_TREE_NODE, + action() { + self.fireEvent( + MultiTreeSearchPane.EVENT_CLICK_TREE_NODE + ); + }, } - } - ], - ref: function (_ref) { - self.partTree = _ref; - } - }, opts.el); - }, + ], + ref(_ref) { + self.partTree = _ref; + }, + }, + opts.el + ); + } - hasChecked: function () { + hasChecked() { return this.partTree.hasChecked(); - }, + } - setValue: function (v) { + setValue(v) { this.setSelectedValue(v.value); - }, + } - setSelectedValue: function (v) { + setSelectedValue(v) { v || (v = {}); this.partTree.setSelectedValue(v); - }, + } - getValue: function () { + getValue() { return this.partTree.getValue(); - }, + } - empty: function () { + empty() { this.partTree.empty(); - }, - - populate: function (op) { - this.partTree.stroke.apply(this.partTree, arguments); } -}); -BI.MultiTreeSearchPane.EVENT_CHANGE = "EVENT_CHANGE"; - -BI.MultiTreeSearchPane.EVENT_CLICK_CONFIRM = "EVENT_CLICK_CONFIRM"; -BI.MultiTreeSearchPane.EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; -BI.MultiTreeSearchPane.EVENT_CLICK_TREE_NODE = "EVENT_CLICK_TREE_NODE"; - -BI.shortcut("bi.multi_tree_search_pane", BI.MultiTreeSearchPane); + populate(op) { + this.partTree.stroke(...arguments); + } +} diff --git a/src/widget/multitree/trigger/searcher.list.multi.tree.js b/src/widget/multitree/trigger/searcher.list.multi.tree.js index 8c54afe63..0a853ca54 100644 --- a/src/widget/multitree/trigger/searcher.list.multi.tree.js +++ b/src/widget/multitree/trigger/searcher.list.multi.tree.js @@ -1,140 +1,168 @@ -/** - * searcher - * Created by guy on 15/11/3. - * @class BI.MultiListTreeSearcher - * @extends Widget - */ -BI.MultiListTreeSearcher = BI.inherit(BI.Widget, { - - _defaultConfig: function () { - return BI.extend(BI.MultiListTreeSearcher.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + Widget, + extend, + emptyFn, + createWidget, + isNotNull, + isNumber, + size, + each, + last +} from "@/core"; +import { MultiSelectEditor } from "../../multiselect/trigger/editor.multiselect"; +import { MultiSelectSearcher } from "../../multiselect/trigger/searcher.multiselect"; +import { Searcher } from "@/base"; +import { SimpleStateEditor } from "@/case"; +import { MultiTreeSearchPane } from "multi.tree.search.pane"; + +@shortcut() +export class MultiListTreeSearcher extends Widget { + static xtype = "bi.multi_list_tree_searcher"; + + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_START = "EVENT_START"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_PAUSE = "EVENT_PAUSE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-list-tree-searcher", - itemsCreator: BI.emptyFn, - valueFormatter: function (v) { + itemsCreator: emptyFn, + valueFormatter(v) { return v; }, popup: {}, adapter: null, - masker: {} + masker: {}, }); - }, + } - _init: function () { - BI.MultiListTreeSearcher.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.editor = BI.createWidget({ - type: "bi.multi_select_editor", + _init() { + super._init(...arguments); + const self = this, + o = this.options; + this.editor = createWidget({ + type: MultiSelectEditor.xtype, height: o.height, text: o.text, defaultText: o.defaultText, watermark: o.watermark, el: { - type: "bi.simple_state_editor", - height: o.height + type: SimpleStateEditor.xtype, + height: o.height, }, - listeners: [{ - eventName: BI.MultiSelectEditor.EVENT_FOCUS, - action: function () { - self.fireEvent(BI.MultiSelectSearcher.EVENT_FOCUS); - } - }, { - eventName: BI.MultiSelectEditor.EVENT_BLUR, - action: function () { - self.fireEvent(BI.MultiSelectSearcher.EVENT_BLUR); + listeners: [ + { + eventName: MultiSelectEditor.EVENT_FOCUS, + action() { + self.fireEvent(MultiSelectSearcher.EVENT_FOCUS); + }, + }, + { + eventName: MultiSelectEditor.EVENT_BLUR, + action() { + self.fireEvent(MultiSelectSearcher.EVENT_BLUR); + }, } - }] + ], }); - this.searcher = BI.createWidget({ - type: "bi.searcher", + this.searcher = createWidget({ + type: Searcher.xtype, element: this, isAutoSearch: false, isAutoSync: false, - onSearch: function (op, callback) { + onSearch(op, callback) { callback({ - keyword: self.editor.getValue() + keyword: self.editor.getValue(), }); }, el: this.editor, - popup: BI.extend({ - type: "bi.multi_tree_search_pane", - keywordGetter: function () { - return self.editor.getValue(); + popup: extend( + { + type: MultiTreeSearchPane.xtype, + keywordGetter() { + return self.editor.getValue(); + }, + itemsCreator(op, callback) { + op.keyword = self.editor.getValue(); + o.itemsCreator(op, callback); + }, + value: o.value, }, - itemsCreator: function (op, callback) { - op.keyword = self.editor.getValue(); - o.itemsCreator(op, callback); - }, - value: o.value - }, o.popup), + o.popup + ), adapter: o.adapter, - masker: o.masker + masker: o.masker, }); - this.searcher.on(BI.Searcher.EVENT_START, function () { - self.fireEvent(BI.MultiListTreeSearcher.EVENT_START); + this.searcher.on(Searcher.EVENT_START, () => { + self.fireEvent(MultiListTreeSearcher.EVENT_START); }); - this.searcher.on(BI.Searcher.EVENT_PAUSE, function () { - if (this.hasMatched()) { - - } - self.fireEvent(BI.MultiListTreeSearcher.EVENT_PAUSE); + this.searcher.on(Searcher.EVENT_PAUSE, () => { + self.fireEvent(MultiListTreeSearcher.EVENT_PAUSE); }); - this.searcher.on(BI.Searcher.EVENT_STOP, function () { - self.fireEvent(BI.MultiListTreeSearcher.EVENT_STOP); + this.searcher.on(Searcher.EVENT_STOP, () => { + self.fireEvent(MultiListTreeSearcher.EVENT_STOP); }); - this.searcher.on(BI.Searcher.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiListTreeSearcher.EVENT_CHANGE, arguments); + this.searcher.on(Searcher.EVENT_CHANGE, function () { + self.fireEvent(MultiListTreeSearcher.EVENT_CHANGE, arguments); }); - if (BI.isNotNull(o.value)) { + if (isNotNull(o.value)) { this.setState(o.value); } - }, + } - adjustView: function () { + adjustView() { this.searcher.adjustView(); - }, + } - setAdapter: function (adapter) { + setAdapter(adapter) { this.searcher.setAdapter(adapter); - }, + } - isSearching: function () { + isSearching() { return this.searcher.isSearching(); - }, + } - stopSearch: function () { + stopSearch() { this.searcher.stopSearch(); - }, + } - getKeyword: function () { + getKeyword() { return this.editor.getValue(); - }, + } - hasMatched: function () { + hasMatched() { return this.searcher.hasMatched(); - }, + } - hasChecked: function () { + hasChecked() { return this.searcher.getView() && this.searcher.getView().hasChecked(); - }, + } - setState: function (ob) { - var o = this.options; + setState(ob) { + const o = this.options; ob || (ob = {}); ob.value || (ob.value = []); - var count = 0; - if (BI.isNumber(ob)) { + let count = 0; + if (isNumber(ob)) { this.editor.setState(ob); - } else if (BI.size(ob.value) === 0) { + } else if (size(ob.value) === 0) { this.editor.setState(BI.Selection.None); } else { - var text = ""; - BI.each(ob.value, function (idx, path) { - var childValue = BI.last(path); - text += (path === "null" ? "" : (o.valueFormatter(childValue + "") || childValue) + "; "); + let text = ""; + each(ob.value, (idx, path) => { + const childValue = last(path); + text += + path === "null" + ? "" + : `${o.valueFormatter(`${childValue}`) || childValue + }; `; count++; }); @@ -144,45 +172,38 @@ BI.MultiListTreeSearcher = BI.inherit(BI.Widget, { this.editor.setState(text); } } - }, + } - getState: function () { + getState() { return this.editor.getState(); - }, + } - setValue: function (ob) { + setValue(ob) { this.setState(ob); this.searcher.setValue(ob); - }, + } - getKey: function () { + getKey() { return this.editor.getValue(); - }, + } - getValue: function () { + getValue() { return this.searcher.getValue(); - }, + } - populate: function (items) { - this.searcher.populate.apply(this.searcher, arguments); - }, + populate(items) { + this.searcher.populate(...arguments); + } - focus: function () { + focus() { this.editor.focus(); - }, + } - blur: function () { + blur() { this.editor.blur(); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.editor.setWaterMark(v); } -}); - -BI.MultiListTreeSearcher.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.MultiListTreeSearcher.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiListTreeSearcher.EVENT_START = "EVENT_START"; -BI.MultiListTreeSearcher.EVENT_STOP = "EVENT_STOP"; -BI.MultiListTreeSearcher.EVENT_PAUSE = "EVENT_PAUSE"; -BI.shortcut("bi.multi_list_tree_searcher", BI.MultiListTreeSearcher); +} diff --git a/src/widget/multitree/trigger/searcher.multi.tree.js b/src/widget/multitree/trigger/searcher.multi.tree.js index 1b2dc6983..8a10023ea 100644 --- a/src/widget/multitree/trigger/searcher.multi.tree.js +++ b/src/widget/multitree/trigger/searcher.multi.tree.js @@ -1,220 +1,260 @@ -/** - * searcher - * Created by guy on 15/11/3. - * @class BI.MultiTreeSearcher - * @extends Widget - */ -BI.MultiTreeSearcher = BI.inherit(BI.Widget, { - - _defaultConfig: function () { - return BI.extend(BI.MultiTreeSearcher.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + Widget, + extend, + emptyFn, + createWidget, + isNotNull, + isNumber, + size, + keys, + each, + isEmptyObject, Func +} from "@/core"; +import { MultiSelectEditor } from "../../multiselect/trigger/editor.multiselect"; +import { MultiSelectSearcher } from "../../multiselect/trigger/searcher.multiselect"; +import { MultiTreeSearchPane } from "multi.tree.search.pane"; +import { Searcher } from "@/base"; +import { SimpleStateEditor } from "@/case"; + +@shortcut() +export class MultiTreeSearcher extends Widget { + static xtype = "bi.multi_tree_searcher"; + + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_START = "EVENT_START"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_CLICK_TREE_NODE = "EVENT_CLICK_TREE_NODE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-tree-searcher", - itemsCreator: BI.emptyFn, - valueFormatter: function (v) { + itemsCreator: emptyFn, + valueFormatter(v) { return v; }, popup: {}, adapter: null, - masker: {} + masker: {}, }); - }, + } - _init: function () { - BI.MultiTreeSearcher.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.editor = BI.createWidget({ + _init() { + super._init(...arguments); + const self = this, + o = this.options; + this.editor = createWidget({ type: "bi.multi_select_editor", watermark: o.watermark, height: o.height, el: { - type: "bi.simple_state_editor", + type: SimpleStateEditor.xtype, text: o.text, defaultText: o.defaultText, - height: o.height + height: o.height, }, listeners: [ { - eventName: BI.MultiSelectEditor.EVENT_FOCUS, - action: function () { - self.fireEvent(BI.MultiSelectSearcher.EVENT_FOCUS); - } - }, { - eventName: BI.MultiSelectEditor.EVENT_BLUR, - action: function () { - self.fireEvent(BI.MultiSelectSearcher.EVENT_BLUR); - } + eventName: MultiSelectEditor.EVENT_FOCUS, + action() { + self.fireEvent(MultiSelectSearcher.EVENT_FOCUS); + }, + }, + { + eventName: MultiSelectEditor.EVENT_BLUR, + action() { + self.fireEvent(MultiSelectSearcher.EVENT_BLUR); + }, } - ] + ], }); - this.searcher = BI.createWidget({ - type: "bi.searcher", + this.searcher = createWidget({ + type: Searcher.xtype, element: this, isAutoSearch: false, isAutoSync: false, - onSearch: function (op, callback) { + onSearch(op, callback) { callback({ - keyword: self.editor.getValue() + keyword: self.editor.getValue(), }); }, el: this.editor, - popup: BI.extend({ - type: "bi.multi_tree_search_pane", - keywordGetter: function () { - return self.editor.getValue(); - }, - itemsCreator: function (op, callback) { - op.keyword = self.editor.getValue(); - o.itemsCreator(op, callback); - }, - listeners: [ - { - eventName: BI.MultiTreeSearchPane.EVENT_CLICK_TREE_NODE, - action: function () { - self.fireEvent(BI.MultiTreeSearcher.EVENT_CLICK_TREE_NODE, arguments); + popup: extend( + { + type: MultiTreeSearchPane.xtype, + keywordGetter() { + return self.editor.getValue(); + }, + itemsCreator(op, callback) { + op.keyword = self.editor.getValue(); + o.itemsCreator(op, callback); + }, + listeners: [ + { + eventName: + MultiTreeSearchPane.EVENT_CLICK_TREE_NODE, + action() { + self.fireEvent( + MultiTreeSearcher.EVENT_CLICK_TREE_NODE, + arguments + ); + }, } - } - ], - value: o.value - }, o.popup), + ], + value: o.value, + }, + o.popup + ), adapter: o.adapter, - masker: o.masker + masker: o.masker, }); - this.searcher.on(BI.Searcher.EVENT_START, function () { - self.fireEvent(BI.MultiTreeSearcher.EVENT_START); + this.searcher.on(Searcher.EVENT_START, () => { + self.fireEvent(MultiTreeSearcher.EVENT_START); }); - this.searcher.on(BI.Searcher.EVENT_PAUSE, function () { - self.fireEvent(BI.MultiTreeSearcher.EVENT_PAUSE); + this.searcher.on(Searcher.EVENT_PAUSE, () => { + self.fireEvent(MultiTreeSearcher.EVENT_PAUSE); }); - this.searcher.on(BI.Searcher.EVENT_STOP, function () { - self.fireEvent(BI.MultiTreeSearcher.EVENT_STOP); + this.searcher.on(Searcher.EVENT_STOP, () => { + self.fireEvent(MultiTreeSearcher.EVENT_STOP); }); - this.searcher.on(BI.Searcher.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiTreeSearcher.EVENT_CHANGE, arguments); + this.searcher.on(Searcher.EVENT_CHANGE, function () { + self.fireEvent(MultiTreeSearcher.EVENT_CHANGE, arguments); }); - this.searcher.on(BI.Searcher.EVENT_SEARCHING, function () { - var keywords = this.getKeywords(); - self.fireEvent(BI.MultiTreeSearcher.EVENT_SEARCHING, keywords); + this.searcher.on(Searcher.EVENT_SEARCHING, function () { + const keywords = this.getKeywords(); + self.fireEvent(MultiTreeSearcher.EVENT_SEARCHING, keywords); }); - if (BI.isNotNull(o.value)) { + if (isNotNull(o.value)) { this.setState(o.value); } - }, + } - adjustView: function () { + adjustView() { this.searcher.adjustView(); - }, + } - setAdapter: function (adapter) { + setAdapter(adapter) { this.searcher.setAdapter(adapter); - }, + } - isSearching: function () { + isSearching() { return this.searcher.isSearching(); - }, + } - stopSearch: function () { + stopSearch() { this.searcher.stopSearch(); - }, + } - getKeyword: function () { + getKeyword() { return this.editor.getValue(); - }, + } - hasMatched: function () { + hasMatched() { return this.searcher.hasMatched(); - }, + } - hasChecked: function () { + hasChecked() { return this.searcher.getView() && this.searcher.getView().hasChecked(); - }, + } - setState: function (ob) { - var o = this.options; + setState(ob) { + const o = this.options; ob || (ob = {}); ob.value || (ob.value = {}); - var count = 0; - if (BI.isNumber(ob)) { + let count = 0; + if (isNumber(ob)) { this.editor.setState(ob); - } else if (BI.size(ob.value) === 0) { + } else if (size(ob.value) === 0) { this.editor.setState(BI.Selection.None); } else { - var text = ""; - var value = ob.value; - var names = BI.Func.getSortedResult(BI.keys(value)); - BI.each(names, function (idx, name) { - var childNodes = getChildrenNode(value[name]); - text += (name === "null" ? "" : (o.valueFormatter(name + "") || name)) + (childNodes === "" ? (BI.isEmptyObject(value[name]) ? "" : ":") : (":" + childNodes)) + "; "; + let text = ""; + const value = ob.value; + const names = BI.Func.getSortedResult(keys(value)); + each(names, (idx, name) => { + const childNodes = getChildrenNode(value[name]); + text += + `${(name === "null" + ? "" + : o.valueFormatter(`${name}`) || name) + + (childNodes === "" + ? isEmptyObject(value[name]) + ? "" + : ":" + : `:${childNodes}`) + }; `; if (childNodes === "") { count++; } }); if (count > 20) { - this.editor.setState(BI.Selection.Multi); + this.editor.setState(Selection.Multi); } else { this.editor.setState(text); } } function getChildrenNode(ob) { - var text = ""; - var index = 0, size = BI.size(ob); - var names = BI.Func.getSortedResult(BI.keys(ob)); - BI.each(names, function (idx, name) { + let text = ""; + const size = size(ob); + let index = 0; + + const names = Func.getSortedResult(keys(ob)); + each(names, (idx, name) => { index++; - var childNodes = getChildrenNode(ob[name]); - text += (name === "null" ? "" : (o.valueFormatter(name + "") || name)) + (childNodes === "" ? "" : (":" + childNodes)) + (index === size ? "" : ","); + const childNodes = getChildrenNode(ob[name]); + text += + (name === "null" + ? "" + : o.valueFormatter(`${name}`) || name) + + (childNodes === "" ? "" : `:${childNodes}`) + + (index === size ? "" : ","); if (childNodes === "") { count++; } }); + return text; } - }, + } - getState: function () { + getState() { return this.editor.getState(); - }, + } - setValue: function (ob) { + setValue(ob) { this.setState(ob); this.searcher.setValue(ob); - }, + } - getKey: function () { + getKey() { return this.editor.getValue(); - }, + } - getValue: function () { + getValue() { return this.searcher.getValue(); - }, + } - populate: function (items) { - this.searcher.populate.apply(this.searcher, arguments); - }, + populate(items) { + this.searcher.populate(...arguments); + } - focus: function () { + focus() { this.editor.focus(); - }, + } - blur: function () { + blur() { this.editor.blur(); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.editor.setWaterMark(v); } -}); - -BI.MultiTreeSearcher.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.MultiTreeSearcher.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.MultiTreeSearcher.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiTreeSearcher.EVENT_START = "EVENT_START"; -BI.MultiTreeSearcher.EVENT_STOP = "EVENT_STOP"; -BI.MultiTreeSearcher.EVENT_PAUSE = "EVENT_PAUSE"; -BI.MultiTreeSearcher.EVENT_CLICK_TREE_NODE = "EVENT_CLICK_TREE_NODE"; -BI.shortcut("bi.multi_tree_searcher", BI.MultiTreeSearcher); +} diff --git a/src/widget/selecttree/nodes/node.first.plus.js b/src/widget/selecttree/nodes/node.first.plus.js index 378eac230..484128e4d 100644 --- a/src/widget/selecttree/nodes/node.first.plus.js +++ b/src/widget/selecttree/nodes/node.first.plus.js @@ -1,35 +1,48 @@ -/** - * 加号表示的组节点 - * Created by GUY on 2015/9/6. - * @class BI.SelectTreeFirstPlusGroupNode - * @extends BI.NodeButton - */ -BI.SelectTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.SelectTreeFirstPlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-select-tree-first-plus-group-node bi-list-item-active", +import { + shortcut, + extend, + createWidget, + Controller, + Events, + isNotNull, LogicFactory, Direction +} from "@/core"; +import { NodeButton, Label } from "@/base"; +import { FirstTreeNodeCheckbox } from "@/case"; + +@shortcut() +export class SelectTreeFirstPlusGroupNode extends NodeButton { + static xtype = "bi.select_tree_first_plus_group_node"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: + `${conf.baseCls || "" + } bi-select-tree-first-plus-group-node bi-list-item-active`, logic: { - dynamic: false + dynamic: false, }, id: "", pId: "", readonly: true, open: false, - height: 24 + height: 24, }); - }, - _init: function () { - BI.SelectTreeFirstPlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.checkbox = BI.createWidget({ - type: "bi.first_tree_node_checkbox", + } + + _init() { + super._init(...arguments); + const self = this, + o = this.options; + this.checkbox = createWidget({ + type: FirstTreeNodeCheckbox.xtype, stopPropagation: true, iconHeight: o.height, - iconWidth: o.height + iconWidth: o.height, }); - this.text = BI.createWidget({ - type: "bi.label", + this.text = createWidget({ + type: Label.xtype, textAlign: "left", whiteSpace: "nowrap", textHeight: o.height, @@ -38,10 +51,10 @@ BI.SelectTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { text: o.text, value: o.value, keyword: o.keyword, - py: o.py + py: o.py, }); - this.checkbox.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) { + this.checkbox.on(Controller.EVENT_CHANGE, function (type) { + if (type === Events.CLICK) { if (this.isSelected()) { self.triggerExpand(); } else { @@ -49,40 +62,48 @@ BI.SelectTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { } } }); - var type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - var items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: this.checkbox - }, this.text); - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic(type, BI.extend(o.logic, { - items: items - })))); - }, + const type = LogicFactory.createLogicTypeByDirection( + Direction.Left + ); + const items = LogicFactory.createLogicItemsByDirection( + Direction.Left, + { + width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, + el: this.checkbox, + }, + this.text + ); + createWidget( + extend( + { + element: this, + }, + LogicFactory.createLogic( + type, + extend(o.logic, { + items, + }) + ) + ) + ); + } - isOnce: function () { + isOnce() { return true; - }, - - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - doClick: function () { - BI.NodeButton.superclass.doClick.apply(this, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - setOpened: function (v) { - BI.SelectTreeFirstPlusGroupNode.superclass.setOpened.apply(this, arguments); - if (BI.isNotNull(this.checkbox)) { + setOpened(v) { + super.setOpened(...arguments); + if (isNotNull(this.checkbox)) { this.checkbox.setSelected(v); } } -}); - -BI.shortcut("bi.select_tree_first_plus_group_node", BI.SelectTreeFirstPlusGroupNode); \ No newline at end of file +} diff --git a/src/widget/selecttree/nodes/node.last.plus.js b/src/widget/selecttree/nodes/node.last.plus.js index f8e764e10..572d66e55 100644 --- a/src/widget/selecttree/nodes/node.last.plus.js +++ b/src/widget/selecttree/nodes/node.last.plus.js @@ -1,35 +1,48 @@ -/** - * 加号表示的组节点 - * Created by GUY on 2015/9/6. - * @class BI.SelectTreeLastPlusGroupNode - * @extends BI.NodeButton - */ -BI.SelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.SelectTreeLastPlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-select-tree-last-plus-group-node bi-list-item-active", +import { + shortcut, + extend, + createWidget, + Controller, + Events, + isNotNull, LogicFactory, Direction +} from "@/core"; +import { NodeButton, Label } from "@/base"; +import { LastTreeNodeCheckbox } from "@/case"; + +@shortcut() +export class SelectTreeLastPlusGroupNode extends NodeButton { + static xtype = "bi.select_tree_last_plus_group_node"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: + `${conf.baseCls || "" + } bi-select-tree-last-plus-group-node bi-list-item-active`, logic: { - dynamic: false + dynamic: false, }, id: "", pId: "", readonly: true, open: false, - height: 24 + height: 24, }); - }, - _init: function () { - BI.SelectTreeLastPlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.checkbox = BI.createWidget({ - type: "bi.last_tree_node_checkbox", + } + + _init() { + super._init(...arguments); + const self = this, + o = this.options; + this.checkbox = createWidget({ + type: LastTreeNodeCheckbox.xtype, stopPropagation: true, iconHeight: o.height, - iconWidth: o.height + iconWidth: o.height, }); - this.text = BI.createWidget({ - type: "bi.label", + this.text = createWidget({ + type: Label.xtype, textAlign: "left", whiteSpace: "nowrap", textHeight: o.height, @@ -38,10 +51,10 @@ BI.SelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { text: o.text, value: o.value, keyword: o.keyword, - py: o.py + py: o.py, }); - this.checkbox.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) { + this.checkbox.on(Controller.EVENT_CHANGE, function (type) { + if (type === Events.CLICK) { if (this.isSelected()) { self.triggerExpand(); } else { @@ -49,40 +62,48 @@ BI.SelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { } } }); - var type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - var items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: this.checkbox - }, this.text); - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic(type, BI.extend(o.logic, { - items: items - })))); - }, + const type = LogicFactory.createLogicTypeByDirection( + Direction.Left + ); + const items = LogicFactory.createLogicItemsByDirection( + Direction.Left, + { + width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, + el: this.checkbox, + }, + this.text + ); + createWidget( + extend( + { + element: this, + }, + LogicFactory.createLogic( + type, + extend(o.logic, { + items, + }) + ) + ) + ); + } - isOnce: function () { + isOnce() { return true; - }, - - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - doClick: function () { - BI.NodeButton.superclass.doClick.apply(this, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - setOpened: function (v) { - BI.SelectTreeLastPlusGroupNode.superclass.setOpened.apply(this, arguments); - if (BI.isNotNull(this.checkbox)) { + setOpened(v) { + super.setOpened(...arguments); + if (isNotNull(this.checkbox)) { this.checkbox.setSelected(v); } } -}); - -BI.shortcut("bi.select_tree_last_plus_group_node", BI.SelectTreeLastPlusGroupNode); \ No newline at end of file +} diff --git a/src/widget/selecttree/nodes/node.mid.plus.js b/src/widget/selecttree/nodes/node.mid.plus.js index ddafe5704..670533dd5 100644 --- a/src/widget/selecttree/nodes/node.mid.plus.js +++ b/src/widget/selecttree/nodes/node.mid.plus.js @@ -1,35 +1,48 @@ -/** - * 加号表示的组节点 - * Created by GUY on 2015/9/6. - * @class BI.SelectTreeMidPlusGroupNode - * @extends BI.NodeButton - */ -BI.SelectTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.SelectTreeMidPlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-select-tree-mid-plus-group-node bi-list-item-active", +import { + shortcut, + extend, + createWidget, + Controller, + Events, + isNotNull, Direction, LogicFactory +} from "@/core"; +import { NodeButton, Label } from "@/base"; +import { MidTreeNodeCheckbox } from "@/case"; + +@shortcut() +export class SelectTreeMidPlusGroupNode extends NodeButton { + static xtype = "bi.select_tree_mid_plus_group_node"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: + `${conf.baseCls || "" + } bi-select-tree-mid-plus-group-node bi-list-item-active`, logic: { - dynamic: false + dynamic: false, }, id: "", pId: "", readonly: true, open: false, - height: 24 + height: 24, }); - }, - _init: function () { - BI.SelectTreeMidPlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.checkbox = BI.createWidget({ - type: "bi.mid_tree_node_checkbox", + } + + _init() { + super._init(...arguments); + const self = this, + o = this.options; + this.checkbox = createWidget({ + type: MidTreeNodeCheckbox.xtype, stopPropagation: true, iconHeight: o.height, - iconWidth: o.height + iconWidth: o.height, }); - this.text = BI.createWidget({ - type: "bi.label", + this.text = createWidget({ + type: Label.xtype, textAlign: "left", whiteSpace: "nowrap", textHeight: o.height, @@ -38,10 +51,10 @@ BI.SelectTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { text: o.text, value: o.value, keyword: o.keyword, - py: o.py + py: o.py, }); - this.checkbox.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) { + this.checkbox.on(Controller.EVENT_CHANGE, function (type) { + if (type === Events.CLICK) { if (this.isSelected()) { self.triggerExpand(); } else { @@ -49,40 +62,48 @@ BI.SelectTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { } } }); - var type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - var items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: this.checkbox - }, this.text); - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic(type, BI.extend(o.logic, { - items: items - })))); - }, + const type = LogicFactory.createLogicTypeByDirection( + Direction.Left + ); + const items = LogicFactory.createLogicItemsByDirection( + Direction.Left, + { + width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, + el: this.checkbox, + }, + this.text + ); + createWidget( + extend( + { + element: this, + }, + LogicFactory.createLogic( + type, + extend(o.logic, { + items, + }) + ) + ) + ); + } - isOnce: function () { + isOnce() { return true; - }, - - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - doClick: function () { - BI.NodeButton.superclass.doClick.apply(this, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - setOpened: function (v) { - BI.SelectTreeMidPlusGroupNode.superclass.setOpened.apply(this, arguments); - if (BI.isNotNull(this.checkbox)) { + setOpened(v) { + super.setOpened(...arguments); + if (isNotNull(this.checkbox)) { this.checkbox.setSelected(v); } } -}); - -BI.shortcut("bi.select_tree_mid_plus_group_node", BI.SelectTreeMidPlusGroupNode); \ No newline at end of file +} diff --git a/src/widget/selecttree/nodes/node.plus.js b/src/widget/selecttree/nodes/node.plus.js index d5cd39c66..e3e41de7f 100644 --- a/src/widget/selecttree/nodes/node.plus.js +++ b/src/widget/selecttree/nodes/node.plus.js @@ -1,35 +1,48 @@ -/** - * 加号表示的组节点 - * Created by GUY on 2015/9/6. - * @class BI.SelectTreePlusGroupNode - * @extends BI.NodeButton - */ -BI.SelectTreePlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.SelectTreePlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-select-tree-plus-group-node bi-list-item-active", +import { + shortcut, + extend, + createWidget, + Controller, + Events, + isNotNull, LogicFactory +} from "@/core"; +import { NodeButton, Label } from "@/base"; +import { TreeNodeCheckbox } from "@/case"; + +@shortcut() +export class SelectTreePlusGroupNode extends NodeButton { + static xtype = "bi.select_tree_plus_group_node"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: + `${conf.baseCls || "" + } bi-select-tree-plus-group-node bi-list-item-active`, logic: { - dynamic: false + dynamic: false, }, id: "", pId: "", readonly: true, open: false, - height: 24 + height: 24, }); - }, - _init: function () { - BI.SelectTreePlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.checkbox = BI.createWidget({ - type: "bi.tree_node_checkbox", + } + + _init() { + super._init(...arguments); + const self = this, + o = this.options; + this.checkbox = createWidget({ + type: TreeNodeCheckbox.xtype, stopPropagation: true, iconHeight: o.height, - iconWidth: o.iconWrapperWidth || o.height + iconWidth: o.iconWrapperWidth || o.height, }); - this.text = BI.createWidget({ - type: "bi.label", + this.text = createWidget({ + type: Label.xtype, textAlign: "left", whiteSpace: "nowrap", textHeight: o.height, @@ -38,10 +51,10 @@ BI.SelectTreePlusGroupNode = BI.inherit(BI.NodeButton, { text: o.text, value: o.value, keyword: o.keyword, - py: o.py + py: o.py, }); - this.checkbox.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) { + this.checkbox.on(Controller.EVENT_CHANGE, function (type) { + if (type === Events.CLICK) { if (this.isSelected()) { self.triggerExpand(); } else { @@ -49,40 +62,48 @@ BI.SelectTreePlusGroupNode = BI.inherit(BI.NodeButton, { } } }); - var type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - var items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { - width: 24, - el: this.checkbox - }, this.text); - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic(type, BI.extend(o.logic, { - items: items - })))); - }, + const type = LogicFactory.createLogicTypeByDirection( + BI.Direction.Left + ); + const items = LogicFactory.createLogicItemsByDirection( + BI.Direction.Left, + { + width: 24, + el: this.checkbox, + }, + this.text + ); + createWidget( + extend( + { + element: this, + }, + LogicFactory.createLogic( + type, + extend(o.logic, { + items, + }) + ) + ) + ); + } - isOnce: function () { + isOnce() { return true; - }, - - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + doRedMark() { + this.text.doRedMark(...arguments); + } - doClick: function () { - BI.NodeButton.superclass.doClick.apply(this, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - setOpened: function (v) { - BI.SelectTreePlusGroupNode.superclass.setOpened.apply(this, arguments); - if (BI.isNotNull(this.checkbox)) { + setOpened(v) { + super.setOpened(...arguments); + if (isNotNull(this.checkbox)) { this.checkbox.setSelected(v); } } -}); - -BI.shortcut("bi.select_tree_plus_group_node", BI.SelectTreePlusGroupNode); \ No newline at end of file +} diff --git a/src/widget/selecttree/selecttree.combo.js b/src/widget/selecttree/selecttree.combo.js index 5095c120d..4e80f3c3b 100644 --- a/src/widget/selecttree/selecttree.combo.js +++ b/src/widget/selecttree/selecttree.combo.js @@ -1,11 +1,32 @@ /** - * @class BI.SelectTreeCombo - * @extends BI.Widget + * @class SelectTreeCombo + * @extends Widget */ -BI.SelectTreeCombo = BI.inherit(BI.Widget, { - - _defaultConfig: function () { - return BI.extend(BI.SelectTreeCombo.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + Widget, + extend, + createWidget, + Controller, + contains, + isArray, + toPix, + isKey, + isEmptyArray, + isEmptyString, + find, + isNull +} from "@/core"; +import { Combo } from "@/base"; +import { SingleTreeTrigger } from "@/widget/singletree/singletree.trigger"; +import { SelectTreePopup } from "./selecttree.popup"; + +@shortcut() +export class SelectTreeCombo extends Widget { + static xtype = "bi.select_tree_combo"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-select-tree-combo bi-border bi-border-radius", height: 24, text: "", @@ -13,70 +34,68 @@ BI.SelectTreeCombo = BI.inherit(BI.Widget, { value: "", allowClear: false, }); - }, + } - _init: function () { - var self = this, o = this.options; - BI.SelectTreeCombo.superclass._init.apply(this, arguments); + _init() { + const self = this, o = this.options; + super._init(...arguments); - this.trigger = BI.createWidget({ - type: "bi.single_tree_trigger", + this.trigger = createWidget({ + type: SingleTreeTrigger.xtype, text: o.text, - height: BI.toPix(o.height, 2), + height: toPix(o.height, 2), items: o.items, value: o.value, allowClear: o.allowClear, warningTitle: o.warningTitle, }); - this.trigger.on(BI.SingleTreeTrigger.EVENT_CLEAR, function () { - self._clear(); + this.trigger.on(SingleTreeTrigger.EVENT_CLEAR, () => { + this._clear(); }); - this.popup = BI.createWidget({ - type: "bi.select_level_tree", + this.popup = createWidget({ + type: SelectTreePopup.xtype, items: o.items, - value: o.value + value: o.value, }); - this.combo = BI.createWidget({ - type: "bi.combo", - width: BI.toPix(o.width, 2), - height: BI.toPix(o.height, 2), + this.combo = createWidget({ + type: Combo.xtype, + width: toPix(o.width, 2), + height: toPix(o.height, 2), container: o.container, element: this, adjustLength: 2, el: this.trigger, popup: { - el: this.popup - } + el: this.popup, + }, }); - this.combo.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.combo.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.popup.on(BI.SingleTreePopup.EVENT_CHANGE, function () { + this.popup.on(SelectTreePopup.EVENT_CHANGE, () => { self.setValue(self.popup.getValue()); self.combo.hideView(); }); - if (BI.isKey(o.value)) { + if (isKey(o.value)) { this._checkError(o.value); } - }, + } - _checkError: function (v) { - if (BI.isNull(v) || BI.isEmptyArray(v) || BI.isEmptyString(v)) { + _checkError(v) { + if (isNull(v) || isEmptyArray(v) || isEmptyString(v)) { this.trigger.options.tipType = "success"; this.trigger.element.removeClass("error"); this.element.removeClass("error"); } else { - v = BI.isArray(v) ? v : [v]; - var result = BI.find(this.options.items, function (idx, item) { - return BI.contains(v, item.value); - }); - if (BI.isNull(result)) { + v = isArray(v) ? v : [v]; + const result = find(this.options.items, (idx, item) => contains(v, item.value)); + if (isNull(result)) { this.trigger.setTipType("warning"); this.element.removeClass("error").addClass("error"); this.trigger.element.removeClass("error").addClass("error"); @@ -86,27 +105,24 @@ BI.SelectTreeCombo = BI.inherit(BI.Widget, { this.element.removeClass("error"); } } - }, + } - _clear: function () { + _clear() { this.setValue([]); - }, + } - setValue: function (v) { - v = BI.isArray(v) ? v : [v]; + setValue(v) { + v = isArray(v) ? v : [v]; this.trigger.setValue(v); this.popup.setValue(v); this._checkError(v); - }, + } - getValue: function () { + getValue() { return this.popup.getValue(); - }, + } - populate: function (items) { + populate(items) { this.combo.populate(items); } -}); - - -BI.shortcut("bi.select_tree_combo", BI.SelectTreeCombo); +} diff --git a/src/widget/selecttree/selecttree.expander.js b/src/widget/selecttree/selecttree.expander.js index b708e4bb9..9220d8811 100644 --- a/src/widget/selecttree/selecttree.expander.js +++ b/src/widget/selecttree/selecttree.expander.js @@ -1,77 +1,86 @@ -/** - * @class BI.SelectTreeExpander - * @extends BI.Widget - */ -BI.SelectTreeExpander = BI.inherit(BI.Widget, { +import { + shortcut, + Widget, + extend, + createWidget, + Controller, + Events, + contains +} from "@/core"; +import { Expander } from "@/base"; - _defaultConfig: function () { - return BI.extend(BI.SelectTreeExpander.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class SelectTreeExpander extends Widget { + static xtype = "bi.select_tree_expander"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-select-tree-expander", trigger: "", toggle: true, direction: "bottom", isDefaultInit: true, el: {}, - popup: {} + popup: {}, }); - }, + } - _init: function () { - BI.SelectTreeExpander.superclass._init.apply(this, arguments); - var self = this, o = this.options; + _init() { + super._init(...arguments); + const self = this, + o = this.options; - this.trigger = BI.createWidget(o.el); - this.trigger.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) { + this.trigger = createWidget(o.el); + this.trigger.on(Controller.EVENT_CHANGE, function (type) { + if (type === Events.CLICK) { if (this.isSelected()) { self.expander.setValue([]); } } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.expander = BI.createWidget({ - type: "bi.expander", + this.expander = createWidget({ + type: Expander.xtype, element: this, trigger: o.trigger, toggle: o.toggle, direction: o.direction, isDefaultInit: o.isDefaultInit, el: this.trigger, - popup: o.popup + popup: o.popup, }); - this.expander.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) { + this.expander.on(Controller.EVENT_CHANGE, function (type) { + if (type === Events.CLICK) { self.trigger.setSelected(false); } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - }, + } - getAllLeaves: function () { + getAllLeaves() { return this.expander.getAllLeaves(); - }, + } - setValue: function (v) { - if (BI.contains(v, this.trigger.getValue())) { + setValue(v) { + if (contains(v, this.trigger.getValue())) { this.trigger.setSelected(true); this.expander.setValue([]); } else { this.trigger.setSelected(false); this.expander.setValue(v); } - }, + } - getValue: function () { + getValue() { if (this.trigger.isSelected()) { return [this.trigger.getValue()]; } + return this.expander.getValue(); - }, + } - populate: function (items) { + populate(items) { this.expander.populate(items); } -}); - -BI.shortcut("bi.select_tree_expander", BI.SelectTreeExpander); \ No newline at end of file +} diff --git a/src/widget/selecttree/selecttree.popup.js b/src/widget/selecttree/selecttree.popup.js index cfce060ef..b9ea1e2e2 100644 --- a/src/widget/selecttree/selecttree.popup.js +++ b/src/widget/selecttree/selecttree.popup.js @@ -1,94 +1,109 @@ -/** - * @class BI.SelectTreePopup - * @extends BI.Pane - */ - -BI.SelectTreePopup = BI.inherit(BI.Pane, { - - _defaultConfig: function () { - return BI.extend(BI.SelectTreePopup.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + i18nText, + each, + createWidget, + Controller, + isArray, isNotEmptyArray, UUID, defaults, Tree, VerticalLayout +} from "@/core"; +import { Pane } from "@/base"; +import { BasicTreeItem, BasicTreeNode, LevelTree, TreeExpander } from "@/case"; + +@shortcut() +export class SelectTreePopup extends Pane { + static xtype = "bi.select_level_tree"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-select-level-tree", - tipText: BI.i18nText("BI-No_Selected_Item"), + tipText: i18nText("BI-No_Selected_Item"), items: [], - value: "" + value: "", }); - }, + } - _formatItems: function (nodes, layer, pNode) { - var self = this; - BI.each(nodes, function (i, node) { - var extend = { - layer: layer, + _formatItems(nodes, layer, pNode) { + const self = this; + each(nodes, (i, node) => { + const extend = { + layer, isFirstNode: i === 0, isLastNode: i === nodes.length - 1, height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - pNode: pNode, + pNode, }; - node.id = node.id || BI.UUID(); - - if (node.isParent === true || node.parent === true || BI.isNotEmptyArray(node.children)) { - - extend.type = "bi.tree_node"; + node.id = node.id || UUID(); + + if ( + node.isParent === true || + node.parent === true || + isNotEmptyArray(node.children) + ) { + extend.type = BasicTreeNode.xtype; extend.selectable = true; - BI.defaults(node, extend); + defaults(node, extend); self._formatItems(node.children, layer + 1, node); } else { - extend.type = "bi.tree_item"; - BI.defaults(node, extend); + extend.type = BasicTreeItem.xtype; + defaults(node, extend); } }); + return nodes; - }, + } - _init: function () { - BI.SelectTreePopup.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, o = this.options; + const self = this, + o = this.options; - this.tree = BI.createWidget({ - type: "bi.level_tree", + this.tree = createWidget({ + type: LevelTree.xtype, expander: { - type: "bi.tree_expander", + type: TreeExpander.xtype, // isDefaultInit: true, selectable: true, }, - items: this._formatItems(BI.Tree.transformToTreeFormat(o.items), 0), + items: this._formatItems(Tree.transformToTreeFormat(o.items), 0), value: o.value, - chooseType: BI.Selection.Single + chooseType: Selection.Single, }); - BI.createWidget({ - type: "bi.vertical", + createWidget({ + type: VerticalLayout.xtype, element: this, vgap: 5, - items: [this.tree] + items: [this.tree], }); - this.tree.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.tree.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.tree.on(BI.LevelTree.EVENT_CHANGE, function () { - self.fireEvent(BI.SelectTreePopup.EVENT_CHANGE); + this.tree.on(LevelTree.EVENT_CHANGE, () => { + self.fireEvent(SelectTreePopup.EVENT_CHANGE); }); this.check(); - }, + } - getValue: function () { + getValue() { return this.tree.getValue(); - }, + } - setValue: function (v) { - v = BI.isArray(v) ? v : [v]; + setValue(v) { + v = isArray(v) ? v : [v]; this.tree.setValue(v); - }, - - populate: function (items) { - BI.SelectTreePopup.superclass.populate.apply(this, arguments); - this.tree.populate(this._formatItems(BI.Tree.transformToTreeFormat(items))); } -}); -BI.SelectTreePopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.select_level_tree", BI.SelectTreePopup); + populate(items) { + super.populate(...arguments); + this.tree.populate( + this._formatItems(Tree.transformToTreeFormat(items)) + ); + } +} diff --git a/src/widget/singletree/singletree.combo.js b/src/widget/singletree/singletree.combo.js index 589c205c6..cfa92ea91 100644 --- a/src/widget/singletree/singletree.combo.js +++ b/src/widget/singletree/singletree.combo.js @@ -1,12 +1,35 @@ -/** - * @class BI.SingleTreeCombo - * @extends BI.Widget - */ -BI.SingleTreeCombo = BI.inherit(BI.Widget, { - - _defaultConfig: function (config) { - return BI.extend(BI.SingleTreeCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: "bi-single-tree-combo " + (config.simple ? "bi-border-bottom" : "bi-border bi-border-radius"), +import { + shortcut, + Widget, + extend, + createWidget, + toPix, + Controller, + isKey, + isNull, + isEmptyArray, + isEmptyString, + isArray, + contains, find +} from "@/core"; +import { Combo } from "@/base"; +import { SingleTreeTrigger } from "./singletree.trigger"; +import { SingleTreePopup } from "./singletree.popup"; + +@shortcut() +export class SingleTreeCombo extends Widget { + static xtype = "bi.single_tree_combo"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + + _defaultConfig(config) { + return extend(super._defaultConfig(...arguments), { + baseCls: + `bi-single-tree-combo ${ + config.simple + ? "bi-border-bottom" + : "bi-border bi-border-radius"}`, trigger: {}, height: 24, text: "", @@ -14,75 +37,79 @@ BI.SingleTreeCombo = BI.inherit(BI.Widget, { value: "", allowClear: false, }); - }, + } - _init: function () { - var self = this, o = this.options; - BI.SingleTreeCombo.superclass._init.apply(this, arguments); + _init() { + const self = this, + o = this.options; + super._init(...arguments); - this.trigger = BI.createWidget(BI.extend({ - type: "bi.single_tree_trigger", - text: o.text, - defaultText: o.defaultText, - height: BI.toPix(o.height, 2), - items: o.items, - value: o.value, - allowClear: o.allowClear, - warningTitle: o.warningTitle, - }, o.trigger)); + this.trigger = createWidget( + extend( + { + type: SingleTreeTrigger.xtype, + text: o.text, + defaultText: o.defaultText, + height: toPix(o.height, 2), + items: o.items, + value: o.value, + allowClear: o.allowClear, + warningTitle: o.warningTitle, + }, + o.trigger + ) + ); - this.trigger.on(BI.SingleTreeTrigger.EVENT_CLEAR, function () { + this.trigger.on(SingleTreeTrigger.EVENT_CLEAR, () => { self._clear(); }); - this.popup = BI.createWidget({ - type: "bi.single_level_tree", + this.popup = createWidget({ + type: SingleTreePopup.xtype, items: o.items, - value: o.value + value: o.value, }); - this.combo = BI.createWidget({ - type: "bi.combo", - width: BI.toPix(o.width, 2), - height: BI.toPix(o.height, 2), + this.combo = createWidget({ + type: Combo.xtype, + width: toPix(o.width, 2), + height: toPix(o.height, 2), container: o.container, element: this, adjustLength: 2, el: this.trigger, popup: { - el: this.popup - } + el: this.popup, + }, }); - this.combo.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.combo.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { - self.fireEvent(BI.SingleTreeCombo.EVENT_BEFORE_POPUPVIEW, arguments); + this.combo.on(Combo.EVENT_BEFORE_POPUPVIEW, function () { + self.fireEvent(SingleTreeCombo.EVENT_BEFORE_POPUPVIEW, arguments); }); - this.popup.on(BI.SingleTreePopup.EVENT_CHANGE, function () { + this.popup.on(SingleTreePopup.EVENT_CHANGE, () => { self.setValue(self.popup.getValue()); self.combo.hideView(); - self.fireEvent(BI.SingleTreeCombo.EVENT_CHANGE); + self.fireEvent(SingleTreeCombo.EVENT_CHANGE); }); - if (BI.isKey(o.value)) { + if (isKey(o.value)) { this._checkError(o.value); } - }, + } - _checkError: function (v) { - if (BI.isNull(v) || BI.isEmptyArray(v) || BI.isEmptyString(v)) { + _checkError(v) { + if (isNull(v) || isEmptyArray(v) || isEmptyString(v)) { this.trigger.options.tipType = "success"; this.trigger.element.removeClass("error"); this.element.removeClass("error"); } else { - v = BI.isArray(v) ? v : [v]; - var result = BI.find(this.options.items, function (idx, item) { - return BI.contains(v, item.value); - }); - if (BI.isNull(result)) { + v = isArray(v) ? v : [v]; + const result = find(this.options.items, (idx, item) => contains(v, item.value)); + if (isNull(result)) { this.trigger.setTipType("warning"); this.element.removeClass("error").addClass("error"); this.trigger.element.removeClass("error").addClass("error"); @@ -92,28 +119,24 @@ BI.SingleTreeCombo = BI.inherit(BI.Widget, { this.element.removeClass("error"); } } - }, + } - _clear: function () { + _clear() { this.setValue([]); - }, + } - populate: function (items) { + populate(items) { this.combo.populate(items); - }, + } - setValue: function (v) { - v = BI.isArray(v) ? v : [v]; + setValue(v) { + v = isArray(v) ? v : [v]; this.trigger.setValue(v); this.popup.setValue(v); this._checkError(v); - }, + } - getValue: function () { + getValue() { return this.popup.getValue(); } -}); - -BI.SingleTreeCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.SingleTreeCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut("bi.single_tree_combo", BI.SingleTreeCombo); +} diff --git a/src/widget/singletree/singletree.popup.js b/src/widget/singletree/singletree.popup.js index 6a73680af..7e4b6899d 100644 --- a/src/widget/singletree/singletree.popup.js +++ b/src/widget/singletree/singletree.popup.js @@ -1,66 +1,74 @@ -/** - * @class BI.SingleTreePopup - * @extends BI.Pane - */ +import { + shortcut, + extend, + i18nText, + createWidget, + Controller, + isArray, VerticalLayout +} from "@/core"; +import { Pane } from "@/base"; +import { LevelTree } from "@/case"; -BI.SingleTreePopup = BI.inherit(BI.Pane, { +@shortcut() +export class SingleTreePopup extends Pane { + static xtype = "bi.single_level_tree"; - _defaultConfig: function () { - return BI.extend(BI.SingleTreePopup.superclass._defaultConfig.apply(this, arguments), { + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-single-level-tree", - tipText: BI.i18nText("BI-No_Selected_Item"), + tipText: i18nText("BI-No_Selected_Item"), items: [], - value: "" + value: "", }); - }, + } - _init: function () { - BI.SingleTreePopup.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, o = this.options; - - this.tree = BI.createWidget({ + const self = this, + o = this.options; + + this.tree = createWidget({ type: "bi.level_tree", expander: { - isDefaultInit: true + isDefaultInit: true, }, items: o.items, value: o.value, - chooseType: BI.Selection.Single + chooseType: Selection.Single, }); - BI.createWidget({ - type: "bi.vertical", + createWidget({ + type: VerticalLayout.xtype, element: this, vgap: 5, - items: [this.tree] + items: [this.tree], }); - this.tree.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.tree.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.tree.on(BI.LevelTree.EVENT_CHANGE, function () { - self.fireEvent(BI.SingleTreePopup.EVENT_CHANGE); + this.tree.on(LevelTree.EVENT_CHANGE, () => { + self.fireEvent(SingleTreePopup.EVENT_CHANGE); }); this.check(); - }, + } - getValue: function () { + getValue() { return this.tree.getValue(); - }, + } - setValue: function (v) { - v = BI.isArray(v) ? v : [v]; + setValue(v) { + v = isArray(v) ? v : [v]; this.tree.setValue(v); - }, + } - populate: function (items) { - BI.SingleTreePopup.superclass.populate.apply(this, arguments); + populate(items) { + super.populate(...arguments); this.tree.populate(items); } -}); - -BI.SingleTreePopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.single_level_tree", BI.SingleTreePopup); \ No newline at end of file +} diff --git a/src/widget/singletree/singletree.trigger.js b/src/widget/singletree/singletree.trigger.js index 221c8b069..a328a147c 100644 --- a/src/widget/singletree/singletree.trigger.js +++ b/src/widget/singletree/singletree.trigger.js @@ -1,29 +1,41 @@ -/** - * @class BI.SingleTreeTrigger - * @extends BI.Trigger - */ +import { + shortcut, + extend, + emptyFn, + createWidget, + contains, + isArray, + some +} from "@/core"; +import { Trigger } from "@/base"; +import { SelectTextTrigger } from "@/case"; -BI.SingleTreeTrigger = BI.inherit(BI.Trigger, { +@shortcut() +export class SingleTreeTrigger extends Trigger { + static xtype = "bi.single_tree_trigger"; - _defaultConfig: function () { - return BI.extend(BI.SingleTreeTrigger.superclass._defaultConfig.apply(this, arguments), { + static EVENT_CLEAR = "EVENT_CLEAR"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-single-tree-trigger", height: 24, text: "", items: [], value: "", allowClear: false, - valueFormatter: BI.emptyFn, + valueFormatter: emptyFn, }); - }, + } - _init: function () { - BI.SingleTreeTrigger.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, o = this.options; + const self = this, + o = this.options; - this.trigger = BI.createWidget({ - type: "bi.select_text_trigger", + this.trigger = createWidget({ + type: SelectTextTrigger.xtype, element: this, text: o.text, defaultText: o.defaultText, @@ -36,50 +48,47 @@ BI.SingleTreeTrigger = BI.inherit(BI.Trigger, { valueFormatter: o.valueFormatter, listeners: [ { - eventName: BI.SelectTextTrigger.EVENT_CLEAR, - action: function () { - self.fireEvent(BI.SingleTreeTrigger.EVENT_CLEAR); - } + eventName: SelectTextTrigger.EVENT_CLEAR, + action() { + self.fireEvent(SingleTreeTrigger.EVENT_CLEAR); + }, } - ] + ], }); - }, + } + + _checkTitle() { + const val = this.getValue(); + some(this.options.items, (i, item) => { + if (contains(val, item.value)) { + this.trigger.setTitle(item.text || item.value); - _checkTitle: function () { - var self = this, val = this.getValue(); - BI.any(this.options.items, function (i, item) { - if (BI.contains(val, item.value)) { - self.trigger.setTitle(item.text || item.value); return true; } }); - }, + } - setValue: function (v) { - v = BI.isArray(v) ? v : [v]; + setValue(v) { + v = isArray(v) ? v : [v]; this.options.value = v; this.trigger.setValue(v); this._checkTitle(); - }, + } - setTipType: function (v) { + setTipType(v) { this.options.tipType = v; this.trigger.setTipType(v); - }, + } - getValue: function () { + getValue() { return this.options.value || []; - }, + } - getTextor: function () { + getTextor() { return this.trigger.getTextor(); - }, + } - populate: function (items) { + populate(items) { this.trigger.populate(items); } - -}); - -BI.SingleTreeTrigger.EVENT_CLEAR = "EVENT_CLEAR"; -BI.shortcut("bi.single_tree_trigger", BI.SingleTreeTrigger); +} From 6f283469e1d9a726b7379331ab211e51dcea4d10 Mon Sep 17 00:00:00 2001 From: Treecat Date: Thu, 12 Jan 2023 11:40:09 +0800 Subject: [PATCH 083/300] =?UTF-8?q?KERNEL-14060=20refact:=20combo=20&&=20K?= =?UTF-8?q?ERNEL-14076=20fix:=20=E4=BF=AE=E5=A4=8D=E4=BA=86=E9=83=A8?= =?UTF-8?q?=E5=88=86=E5=8F=91=E7=8E=B0=E7=9A=84=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.js | 8 +- es6.xtype.js | 24 +- src/case/combo/bubblecombo/combo.bubble.js | 139 ++++---- src/case/combo/bubblecombo/popup.bubble.js | 142 ++------ .../combo.editiconcheck.js | 118 ++++--- src/case/combo/iconcombo/combo.icon.js | 117 ++++--- src/case/combo/iconcombo/popup.iconcombo.js | 97 +++--- src/case/combo/iconcombo/trigger.iconcombo.js | 125 ++++--- .../icontextvaluecombo/combo.icontextvalue.js | 138 ++++---- .../icontextvaluecombo/popup.icontextvalue.js | 102 +++--- src/case/combo/index.js | 22 ++ .../combo.searchtextvalue.js | 207 +++++++----- .../popup.searchtextvalue.js | 142 ++++---- .../trigger.searchtextvalue.js | 202 +++++++----- .../combo.textvaluecheck.js | 131 +++++--- .../popup.textvaluecheck.js | 101 +++--- .../combo/textvaluecombo/combo.textvalue.js | 229 +++++++------ .../textvaluecombo/combo.textvaluesmall.js | 76 +++-- .../combo/textvaluecombo/popup.textvalue.js | 312 ++++++++++-------- src/case/index.js | 2 + 20 files changed, 1360 insertions(+), 1074 deletions(-) create mode 100644 src/case/combo/index.js diff --git a/es6.js b/es6.js index 7c8f87934..a8240f421 100644 --- a/es6.js +++ b/es6.js @@ -211,7 +211,8 @@ async function handleFile(srcName) { M += `${f}\n`; }); - Object.keys(G).forEach(moduleKey => { + Object.keys(G).forEach(key => { + let moduleKey = key; if (moduleKey === path.basename(srcName).replace(/.js$/g, "")) { return; } @@ -219,6 +220,11 @@ async function handleFile(srcName) { Object.keys(G[moduleKey]).forEach(key => { i += `${key}, `; }); + const single = !/\//.test(moduleKey); + if (single) { + moduleKey = `./${moduleKey}`; + } + I += `import {${i}} from '${moduleKey}'\n`; }); diff --git a/es6.xtype.js b/es6.xtype.js index dd9bec56c..28c934c80 100644 --- a/es6.xtype.js +++ b/es6.xtype.js @@ -106,22 +106,28 @@ function search(src, module) { while (dstPath[i] === srcPath[i] && i < dstPath.length && i < srcPath.length) { i++; } + + // i 代表同名的位置 + i--; + // 没有匹配完 if (i < srcPath.length) { let result = ""; - const rawI = i; - - // 回溯 - for (let j = 0; j < srcPath.length - rawI; j++) { + + // 回溯,向上找,回到目录 i + for (let j = srcPath.length - 1; j > i; j--) { result += "../"; - i--; } + + // 匹配过的下一个位置 i++; - // dstPath 也没有了 - if (i < dstPath.length) { - return result + findDstIndexPath(dstPath, i); - } else if (i === dstPath.length) { + + if (i >= dstPath.length) { + // 越界 return `${result}${dstName}`; + } else { + // 看看这个目录下有没有 index + return result + findDstIndexPath(dstPath, i); } } else if (i === srcPath.length) { if (i === dstPath.length) { diff --git a/src/case/combo/bubblecombo/combo.bubble.js b/src/case/combo/bubblecombo/combo.bubble.js index 7f2448ac0..f7e79c93d 100644 --- a/src/case/combo/bubblecombo/combo.bubble.js +++ b/src/case/combo/bubblecombo/combo.bubble.js @@ -1,12 +1,29 @@ -/** - * Created by GUY on 2017/2/8. - * - * @class BI.BubbleCombo - * @extends BI.Widget - */ -BI.BubbleCombo = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.BubbleCombo.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + Widget, + extend, + emptyFn, + createWidget, + isFunction +} from "@/core"; +import { Combo } from "@/base"; + +@shortcut() +export class BubbleCombo extends Widget { + static xtype = "bi.bubble_combo"; + + static EVENT_TRIGGER_CHANGE = "EVENT_TRIGGER_CHANGE"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_EXPAND = "EVENT_EXPAND"; + static EVENT_COLLAPSE = "EVENT_COLLAPSE"; + static EVENT_AFTER_INIT = "EVENT_AFTER_INIT"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + static EVENT_AFTER_POPUPVIEW = "EVENT_AFTER_POPUPVIEW"; + static EVENT_BEFORE_HIDEVIEW = "EVENT_BEFORE_HIDEVIEW"; + static EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-bubble-combo", trigger: "click", toggle: true, @@ -22,17 +39,18 @@ BI.BubbleCombo = BI.inherit(BI.Widget, { adjustLength: 0, // 调整的距离 adjustXOffset: 0, adjustYOffset: 0, - hideChecker: BI.emptyFn, + hideChecker: emptyFn, offsetStyle: "left", // left,right,center el: {}, - popup: {} + popup: {}, }); - }, - _init: function () { - BI.BubbleCombo.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.combo = BI.createWidget({ - type: "bi.combo", + } + + _init() { + super._init(...arguments); + const o = this.options; + this.combo = createWidget({ + type: Combo.xtype, element: this, trigger: o.trigger, toggle: o.toggle, @@ -55,72 +73,67 @@ BI.BubbleCombo = BI.inherit(BI.Widget, { comboClass: o.comboClass, supportCSSTransform: o.supportCSSTransform, el: o.el, - popup: () => BI.extend({ - type: "bi.bubble_popup_view", - animation: "bi-zoom-big", - animationDuring: 200, - primary: o.primary - }, BI.isFunction(this.options.popup) ? this.options.popup() : this.options.popup) + popup: () => + extend( + { + type: "bi.bubble_popup_view", + animation: "bi-zoom-big", + animationDuring: 200, + primary: o.primary, + }, + isFunction(this.options.popup) + ? this.options.popup() + : this.options.popup + ), }); - this.combo.on(BI.Combo.EVENT_TRIGGER_CHANGE, function () { - self.fireEvent(BI.BubbleCombo.EVENT_TRIGGER_CHANGE, arguments); + this.combo.on(Combo.EVENT_TRIGGER_CHANGE, (...args) => { + this.fireEvent(BubbleCombo.EVENT_TRIGGER_CHANGE, ...args); }); - this.combo.on(BI.Combo.EVENT_CHANGE, function () { - self.fireEvent(BI.BubbleCombo.EVENT_CHANGE, arguments); + this.combo.on(Combo.EVENT_CHANGE, (...args) => { + this.fireEvent(BubbleCombo.EVENT_CHANGE, ...args); }); - this.combo.on(BI.Combo.EVENT_EXPAND, function () { - self.fireEvent(BI.BubbleCombo.EVENT_EXPAND, arguments); + this.combo.on(Combo.EVENT_EXPAND, (...args) => { + this.fireEvent(BubbleCombo.EVENT_EXPAND, ...args); }); - this.combo.on(BI.Combo.EVENT_COLLAPSE, function () { - self.fireEvent(BI.BubbleCombo.EVENT_COLLAPSE, arguments); + this.combo.on(Combo.EVENT_COLLAPSE, (...args) => { + this.fireEvent(BubbleCombo.EVENT_COLLAPSE, ...args); }); - this.combo.on(BI.Combo.EVENT_AFTER_INIT, function () { - self.fireEvent(BI.BubbleCombo.EVENT_AFTER_INIT, arguments); + this.combo.on(Combo.EVENT_AFTER_INIT, (...args) => { + this.fireEvent(BubbleCombo.EVENT_AFTER_INIT, ...args); }); - this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { - self.fireEvent(BI.BubbleCombo.EVENT_BEFORE_POPUPVIEW, arguments); + this.combo.on(Combo.EVENT_BEFORE_POPUPVIEW, (...args) => { + this.fireEvent(BubbleCombo.EVENT_BEFORE_POPUPVIEW, ...args); }); - this.combo.on(BI.Combo.EVENT_AFTER_POPUPVIEW, function () { - self.fireEvent(BI.BubbleCombo.EVENT_AFTER_POPUPVIEW, arguments); + this.combo.on(Combo.EVENT_AFTER_POPUPVIEW, (...args) => { + this.fireEvent(BubbleCombo.EVENT_AFTER_POPUPVIEW, ...args); }); - this.combo.on(BI.Combo.EVENT_BEFORE_HIDEVIEW, function () { - self.fireEvent(BI.BubbleCombo.EVENT_BEFORE_HIDEVIEW, arguments); + this.combo.on(Combo.EVENT_BEFORE_HIDEVIEW, (...args) => { + this.fireEvent(BubbleCombo.EVENT_BEFORE_HIDEVIEW, ...args); }); - this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { - self.fireEvent(BI.BubbleCombo.EVENT_AFTER_HIDEVIEW, arguments); + this.combo.on(Combo.EVENT_AFTER_HIDEVIEW, (...args) => { + this.fireEvent(BubbleCombo.EVENT_AFTER_HIDEVIEW, ...args); }); - }, + } - hideView: function () { + hideView() { this.combo && this.combo.hideView(); - }, + } - showView: function () { + showView() { this.combo && this.combo.showView(); - }, + } - isViewVisible: function () { + isViewVisible() { return this.combo.isViewVisible(); - }, + } - adjustWidth: function () { + adjustWidth() { this.combo.adjustWidth(); - }, + } - adjustHeight: function () { + adjustHeight() { this.combo.adjustHeight(); } -}); - -BI.BubbleCombo.EVENT_TRIGGER_CHANGE = "EVENT_TRIGGER_CHANGE"; -BI.BubbleCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.BubbleCombo.EVENT_EXPAND = "EVENT_EXPAND"; -BI.BubbleCombo.EVENT_COLLAPSE = "EVENT_COLLAPSE"; -BI.BubbleCombo.EVENT_AFTER_INIT = "EVENT_AFTER_INIT"; +} -BI.BubbleCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.BubbleCombo.EVENT_AFTER_POPUPVIEW = "EVENT_AFTER_POPUPVIEW"; -BI.BubbleCombo.EVENT_BEFORE_HIDEVIEW = "EVENT_BEFORE_HIDEVIEW"; -BI.BubbleCombo.EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; -BI.shortcut("bi.bubble_combo", BI.BubbleCombo); diff --git a/src/case/combo/bubblecombo/popup.bubble.js b/src/case/combo/bubblecombo/popup.bubble.js index 6826a99f5..2b145941a 100644 --- a/src/case/combo/bubblecombo/popup.bubble.js +++ b/src/case/combo/bubblecombo/popup.bubble.js @@ -1,133 +1,37 @@ -/** - * Created by GUY on 2017/2/8. - * - * @class BI.BubblePopupView - * @extends BI.PopupView - */ -BI.BubblePopupView = BI.inherit(BI.PopupView, { - _defaultConfig: function () { - var config = BI.BubblePopupView.superclass._defaultConfig.apply(this, arguments); - return BI.extend(config, { - baseCls: config.baseCls + " bi-bubble-popup-view", - minWidth: 70, - maxWidth: 300, - // minHeight: 50, - showArrow: true, - }); - } -}); - -BI.shortcut("bi.bubble_popup_view", BI.BubblePopupView); - -/** - * Created by GUY on 2017/2/8. - * - * @class BI.BubblePopupBarView - * @extends BI.BubblePopupView - */ -BI.BubblePopupBarView = BI.inherit(BI.BubblePopupView, { - _defaultConfig: function () { - return BI.extend(BI.BubblePopupBarView.superclass._defaultConfig.apply(this, arguments), { - extraCls: "bi-bubble-bar-popup-view", - buttons: [{ - value: false, - text: BI.i18nText("BI-Basic_Cancel"), - level: "ignore" - }, { - text: BI.i18nText(BI.i18nText("BI-Basic_OK")), - value: true - }], - innerVgap: 16, - innerHgap: 16, - }); - }, - - _createToolBar: function () { - var o = this.options, self = this; - - var items = []; - BI.each(o.buttons, function (i, buttonOpt) { - if (BI.isWidget(buttonOpt)) { - items.push({ - el: buttonOpt, - lgap: 12, - }); - } else { - items.push({ - el: BI.extend({ - type: "bi.button", - height: 24, - handler: function (v) { - self.fireEvent(BI.BubblePopupBarView.EVENT_CLICK_TOOLBAR_BUTTON, v); - } - }, buttonOpt), - lgap: 12, - }); - } - }); - return BI.createWidget({ - type: "bi.right_vertical_adapt", - innerVgap: o.innerVgap, - innerHgap: o.innerHgap, - items: items - }); - }, +import { shortcut, extend } from "@/core"; +import { PopupView, Label } from "@/base"; - _createContent: function () { - return this.options.el; - }, +@shortcut() +export class BubblePopupView extends PopupView { + static xtype = "bi.text_bubble_bar_popup_view"; - _createView: function () { - var o = this.options; + static EVENT_CLICK_TOOLBAR_BUTTON = "EVENT_CLICK_TOOLBAR_BUTTON"; + static EVENT_CHANGE = "EVENT_CLICK_TOOLBAR_BUTTON"; - var view = BI.createWidget({ - type: "bi.vertical", - items: [this._createContent()], - cls: "bar-popup-container", - hgap: o.innerHgap, - tgap: o.innerVgap, - }); - - view.element.css("min-height", o.minHeight); - - return view; - } -}); -BI.BubblePopupBarView.EVENT_CLICK_TOOLBAR_BUTTON = "EVENT_CLICK_TOOLBAR_BUTTON"; -BI.shortcut("bi.bubble_bar_popup_view", BI.BubblePopupBarView); - -/** - * Created by Windy on 2018/2/2. - * - * @class BI.TextBubblePopupBarView - * @extends BI.BubblePopupView - */ -BI.TextBubblePopupBarView = BI.inherit(BI.BubblePopupBarView, { - - _defaultConfig: function () { - var config = BI.TextBubblePopupBarView.superclass._defaultConfig.apply(this, arguments); - return BI.extend(config, { - baseCls: config.baseCls + " bi-text-bubble-bar-popup-view", + _defaultConfig() { + const config = super._defaultConfig(...arguments); + + return extend(config, { + baseCls: `${config.baseCls} bi-text-bubble-bar-popup-view`, text: "", }); - }, + } - _createContent: function () { - var self = this, o = this.options; + _createContent() { + const o = this.options; + return { - type: "bi.label", + type: Label.xtype, text: o.text, whiteSpace: "normal", textAlign: "left", - ref: function () { - self.text = this; - } + ref: _ref => { + this.text = _ref; + }, }; - }, + } - populate: function (v) { + populate(v) { this.text.setText(v || this.options.text); } -}); -BI.TextBubblePopupBarView.EVENT_CHANGE = "EVENT_CLICK_TOOLBAR_BUTTON"; -BI.shortcut("bi.text_bubble_bar_popup_view", BI.TextBubblePopupBarView); +} diff --git a/src/case/combo/editoriconcheckcombo/combo.editiconcheck.js b/src/case/combo/editoriconcheckcombo/combo.editiconcheck.js index 28c57a2e9..b3bb8e29f 100644 --- a/src/case/combo/editoriconcheckcombo/combo.editiconcheck.js +++ b/src/case/combo/editoriconcheckcombo/combo.editiconcheck.js @@ -1,26 +1,44 @@ -/** - * Created by Young's on 2016/4/28. - */ -BI.EditorIconCheckCombo = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.EditorIconCheckCombo.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + Widget, + extend, + emptyFn, + createWidget, + Controller +} from "@/core"; +import { ButtonGroup, Combo } from "@/base"; +import { EditorTrigger } from "../../trigger"; +import { TextValueCheckComboPopup } from "../textvaluecheckcombo/popup.textvaluecheck"; + +@shortcut() +export class EditorIconCheckCombo extends Widget { + static xtype = "bi.editor_icon_check_combo"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_EMPTY = "EVENT_EMPTY"; + static EVENT_VALID = "EVENT_VALID"; + static EVENT_ERROR = "EVENT_ERROR"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseClass: "bi-check-editor-combo", width: 100, height: 24, - chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, - validationChecker: BI.emptyFn, - quitChecker: BI.emptyFn, + chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, + validationChecker: emptyFn, + quitChecker: emptyFn, allowBlank: true, watermark: "", - errorText: "" + errorText: "", }); - }, + } - _init: function () { - BI.EditorIconCheckCombo.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.trigger = BI.createWidget({ - type: "bi.editor_trigger", + _init() { + super._init(...arguments); + const o = this.options; + this.trigger = createWidget({ + type: EditorTrigger.xtype, items: o.items, height: o.height, validationChecker: o.validationChecker, @@ -28,41 +46,41 @@ BI.EditorIconCheckCombo = BI.inherit(BI.Widget, { allowBlank: o.allowBlank, watermark: o.watermark, errorText: o.errorText, - value: o.value + value: o.value, }); - this.trigger.on(BI.EditorTrigger.EVENT_CHANGE, function () { - self.popup.setValue(this.getValue()); - self.fireEvent(BI.EditorIconCheckCombo.EVENT_CHANGE, arguments); + this.trigger.on(EditorTrigger.EVENT_CHANGE, (...args) => { + this.popup.setValue(this.getValue()); + this.fireEvent(EditorIconCheckCombo.EVENT_CHANGE, ...args); }); - this.trigger.on(BI.EditorTrigger.EVENT_FOCUS, function () { - self.fireEvent(BI.EditorIconCheckCombo.EVENT_FOCUS, arguments); + this.trigger.on(EditorTrigger.EVENT_FOCUS, (...args) => { + this.fireEvent(EditorIconCheckCombo.EVENT_FOCUS, ...args); }); - this.trigger.on(BI.EditorTrigger.EVENT_EMPTY, function () { - self.fireEvent(BI.EditorIconCheckCombo.EVENT_EMPTY, arguments); + this.trigger.on(EditorTrigger.EVENT_EMPTY, (...args) => { + this.fireEvent(EditorIconCheckCombo.EVENT_EMPTY, ...args); }); - this.trigger.on(BI.EditorTrigger.EVENT_VALID, function () { - self.fireEvent(BI.EditorIconCheckCombo.EVENT_VALID, arguments); + this.trigger.on(EditorTrigger.EVENT_VALID, (...args) => { + this.fireEvent(EditorIconCheckCombo.EVENT_VALID, ...args); }); - this.trigger.on(BI.EditorTrigger.EVENT_ERROR, function () { - self.fireEvent(BI.EditorIconCheckCombo.EVENT_ERROR, arguments); + this.trigger.on(EditorTrigger.EVENT_ERROR, (...args) => { + this.fireEvent(EditorIconCheckCombo.EVENT_ERROR, ...args); }); - this.popup = BI.createWidget({ + this.popup = createWidget({ type: "bi.text_value_check_combo_popup", chooseType: o.chooseType, items: o.items, - value: o.value + value: o.value, }); - this.popup.on(BI.TextValueCheckComboPopup.EVENT_CHANGE, function () { - self.setValue(self.popup.getValue()); - self.editorIconCheckCombo.hideView(); - self.fireEvent(BI.EditorIconCheckCombo.EVENT_CHANGE); + this.popup.on(TextValueCheckComboPopup.EVENT_CHANGE, () => { + this.setValue(this.popup.getValue()); + this.editorIconCheckCombo.hideView(); + this.fireEvent(EditorIconCheckCombo.EVENT_CHANGE); }); - this.popup.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.popup.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.editorIconCheckCombo = BI.createWidget({ - type: "bi.combo", + this.editorIconCheckCombo = createWidget({ + type: Combo.xtype, container: o.container, direction: o.direction, element: this, @@ -70,27 +88,21 @@ BI.EditorIconCheckCombo = BI.inherit(BI.Widget, { el: this.trigger, popup: { el: this.popup, - maxHeight: 300 - } + maxHeight: 300, + }, }); - }, + } - setValue: function (v) { + setValue(v) { this.editorIconCheckCombo.setValue(v); - }, + } - getValue: function () { + getValue() { return this.trigger.getValue(); - }, + } - populate: function (items) { + populate(items) { this.options.items = items; this.editorIconCheckCombo.populate(items); } -}); -BI.EditorIconCheckCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.EditorIconCheckCombo.EVENT_FOCUS = "EVENT_FOCUS"; -BI.EditorIconCheckCombo.EVENT_EMPTY = "EVENT_EMPTY"; -BI.EditorIconCheckCombo.EVENT_VALID = "EVENT_VALID"; -BI.EditorIconCheckCombo.EVENT_ERROR = "EVENT_ERROR"; -BI.shortcut("bi.editor_icon_check_combo", BI.EditorIconCheckCombo); +} \ No newline at end of file diff --git a/src/case/combo/iconcombo/combo.icon.js b/src/case/combo/iconcombo/combo.icon.js index 6c0f45c51..338e10183 100644 --- a/src/case/combo/iconcombo/combo.icon.js +++ b/src/case/combo/iconcombo/combo.icon.js @@ -1,12 +1,24 @@ -/** - * Created by GUY on 2016/2/2. - * - * @class BI.IconCombo - * @extend BI.Widget - */ -BI.IconCombo = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.IconCombo.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + Widget, + extend, + isFunction, + createWidget, + Controller, + isNull, + isArray +} from "@/core"; +import { ButtonGroup, Combo } from "@/base"; +import { IconComboPopup } from "./popup.iconcombo"; + +@shortcut() +export class IconCombo extends Widget { + static xtype = "bi.icon_combo"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-icon-combo", width: 24, height: 24, @@ -20,22 +32,26 @@ BI.IconCombo = BI.inherit(BI.Widget, { adjustXOffset: 0, adjustYOffset: 0, offsetStyle: "left", - chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, + chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, isShowDown: true, - hideWhenAnotherComboOpen: false + hideWhenAnotherComboOpen: false, }); - }, + } - _init: function () { - var self = this, o = this.options; - o.value = BI.isFunction(o.value) ? this.__watch(o.value, function (context, newValue) { - self.setValue(newValue); - }) : o.value; - o.items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); - }) : o.items; - BI.IconCombo.superclass._init.apply(this, arguments); - this.trigger = BI.createWidget(o.el, { + _init() { + const o = this.options; + o.value = isFunction(o.value) + ? this.__watch(o.value, (context, newValue) => { + this.setValue(newValue); + }) + : o.value; + o.items = isFunction(o.items) + ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); + }) + : o.items; + super._init(...arguments); + this.trigger = createWidget(o.el, { type: "bi.icon_combo_trigger", iconCls: o.iconCls, title: o.title, @@ -45,24 +61,24 @@ BI.IconCombo = BI.inherit(BI.Widget, { iconWidth: o.iconWidth, iconHeight: o.iconHeight, value: o.value, - isShowDown: o.isShowDown + isShowDown: o.isShowDown, }); - this.popup = BI.createWidget(o.popup, { - type: "bi.icon_combo_popup", + this.popup = createWidget(o.popup, { + type: IconComboPopup.xtype, chooseType: o.chooseType, items: o.items, - value: o.value + value: o.value, }); - this.popup.on(BI.IconComboPopup.EVENT_CHANGE, function () { - self.setValue(self.popup.getValue()); - self.iconCombo.hideView(); - self.fireEvent(BI.IconCombo.EVENT_CHANGE); + this.popup.on(IconComboPopup.EVENT_CHANGE, () => { + this.setValue(this.popup.getValue()); + this.iconCombo.hideView(); + this.fireEvent(IconCombo.EVENT_CHANGE); }); - this.popup.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.popup.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.iconCombo = BI.createWidget({ - type: "bi.combo", + this.iconCombo = createWidget({ + type: Combo.xtype, element: this, direction: o.direction, trigger: o.trigger, @@ -77,33 +93,32 @@ BI.IconCombo = BI.inherit(BI.Widget, { el: this.popup, maxWidth: o.maxWidth, maxHeight: o.maxHeight, - minWidth: o.minWidth - } + minWidth: o.minWidth, + }, }); - }, + } - showView: function () { + showView() { this.iconCombo.showView(); - }, + } - hideView: function () { + hideView() { this.iconCombo.hideView(); - }, + } - setValue: function (v) { + setValue(v) { this.trigger.setValue(v); this.popup.setValue(v); - }, + } - getValue: function () { - var value = this.popup.getValue(); - return BI.isNull(value) ? [] : (BI.isArray(value) ? value : [value]); - }, + getValue() { + const value = this.popup.getValue(); + + return isNull(value) ? [] : isArray(value) ? value : [value]; + } - populate: function (items) { + populate(items) { this.options.items = items; this.iconCombo.populate(items); } -}); -BI.IconCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.icon_combo", BI.IconCombo); \ No newline at end of file +} diff --git a/src/case/combo/iconcombo/popup.iconcombo.js b/src/case/combo/iconcombo/popup.iconcombo.js index 9b0f4cc80..a503dd427 100644 --- a/src/case/combo/iconcombo/popup.iconcombo.js +++ b/src/case/combo/iconcombo/popup.iconcombo.js @@ -1,63 +1,74 @@ -/** - * Created by GUY on 2016/2/2. - * - * @class BI.IconComboPopup - * @extend BI.Pane - */ -BI.IconComboPopup = BI.inherit(BI.Pane, { - _defaultConfig: function () { - return BI.extend(BI.IconComboPopup.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + createWidget, + createItems, + Controller, + Events, + VerticalLayout +} from "@/core"; +import { Pane, ButtonGroup } from "@/base"; +import { SingleSelectIconTextItem } from "../../button"; + +@shortcut() +export class IconComboPopup extends Pane { + static xtype = "bi.icon_combo_popup"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi.icon-combo-popup", - chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE + chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, }); - }, - - _init: function () { - BI.IconComboPopup.superclass._init.apply(this, arguments); - var o = this.options, self = this; - this.popup = BI.createWidget({ - type: "bi.button_group", - items: BI.createItems(o.items, { - type: "bi.single_select_icon_text_item", + } + + _init() { + super._init(...arguments); + const o = this.options; + this.popup = createWidget({ + type: ButtonGroup.xtype, + items: createItems(o.items, { + type: SingleSelectIconTextItem.xtype, }), chooseType: o.chooseType, - layouts: [{ - type: "bi.vertical" - }], - value: o.value + layouts: [ + { + type: VerticalLayout.xtype, + } + ], + value: o.value, }); - this.popup.on(BI.Controller.EVENT_CHANGE, function (type, val, obj) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if (type === BI.Events.CLICK) { - self.fireEvent(BI.IconComboPopup.EVENT_CHANGE, val, obj); + this.popup.on(Controller.EVENT_CHANGE, (...args) => { + const [type, val, obj] = args; + this.fireEvent(Controller.EVENT_CHANGE, ...args); + if (type === Events.CLICK) { + this.fireEvent(IconComboPopup.EVENT_CHANGE, val, obj); } }); - BI.createWidget({ - type: "bi.vertical", + createWidget({ + type: VerticalLayout.xtype, element: this, vgap: 5, - items: [this.popup] + items: [this.popup], }); - }, + } - populate: function (items) { - BI.IconComboPopup.superclass.populate.apply(this, arguments); - items = BI.createItems(items, { - type: "bi.single_select_icon_text_item", + populate(items) { + super.populate(...arguments); + items = createItems(items, { + type: SingleSelectIconTextItem.xtype, }); this.popup.populate(items); - }, + } - getValue: function () { + getValue() { return this.popup.getValue(); - }, + } - setValue: function (v) { + setValue(v) { this.popup.setValue(v); } - -}); -BI.IconComboPopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.icon_combo_popup", BI.IconComboPopup); \ No newline at end of file +} diff --git a/src/case/combo/iconcombo/trigger.iconcombo.js b/src/case/combo/iconcombo/trigger.iconcombo.js index 65c353504..67293f2fc 100644 --- a/src/case/combo/iconcombo/trigger.iconcombo.js +++ b/src/case/combo/iconcombo/trigger.iconcombo.js @@ -1,12 +1,24 @@ -/** - * Created by GUY on 2016/2/2. - * - * @class BI.IconComboTrigger - * @extend BI.Widget - */ -BI.IconComboTrigger = BI.inherit(BI.Trigger, { - _defaultConfig: function () { - return BI.extend(BI.IconComboTrigger.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + isKey, + createWidget, + isNotEmptyString, + AbsoluteLayout, + isArray, + any +} from "@/core"; +import { Trigger, IconButton } from "@/base"; +import { IconChangeButton } from "../../button"; + +@shortcut() +export class IconComboTrigger extends Trigger { + static xtype = "bi.icon_combo_trigger"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-icon-combo-trigger", el: {}, items: [], @@ -14,80 +26,85 @@ BI.IconComboTrigger = BI.inherit(BI.Trigger, { width: 24, height: 24, isShowDown: true, - value: "" + value: "", }); - }, + } - _init: function () { - BI.IconComboTrigger.superclass._init.apply(this, arguments); - var o = this.options, self = this; - var iconCls = ""; - if(BI.isKey(o.value)){ + _init() { + super._init(...arguments); + const o = this.options; + let iconCls = ""; + if (isKey(o.value)) { iconCls = this._digest(o.value, o.items); } - this.button = BI.createWidget(o.el, { - type: "bi.icon_change_button", + this.button = createWidget(o.el, { + type: IconChangeButton.xtype, cls: "icon-combo-trigger-icon", - iconCls: iconCls, + iconCls, disableSelected: true, width: o.isShowDown ? o.width - 12 : o.width, height: o.height, iconWidth: o.iconWidth, iconHeight: o.iconHeight, - selected: BI.isNotEmptyString(iconCls) + selected: isNotEmptyString(iconCls), }); - this.down = BI.createWidget({ - type: "bi.icon_button", + this.down = createWidget({ + type: IconButton.xtype, disableSelected: true, cls: "icon-combo-down-icon trigger-triangle-font font-size-12", width: 12, height: 8, - selected: BI.isNotEmptyString(iconCls), - invisible: !o.isShowDown + selected: isNotEmptyString(iconCls), + invisible: !o.isShowDown, }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.button, - left: 0, - right: 0, - top: 0, - bottom: 0 - }, { - el: this.down, - right: 3, - bottom: 0 - }] + items: [ + { + el: this.button, + left: 0, + right: 0, + top: 0, + bottom: 0, + }, + { + el: this.down, + right: 3, + bottom: 0, + } + ], }); - }, + } - _digest: function (v, items) { - var iconCls = ""; - v = BI.isArray(v) ? v[0] : v; - BI.any(items, function (i, item) { + _digest(v, items) { + let iconCls = ""; + v = isArray(v) ? v[0] : v; + any(items, (i, item) => { if (v === item.value) { iconCls = item.iconCls; + return true; } }); + return iconCls; - }, + } - populate: function (items) { - var o = this.options; + populate(items) { + const o = this.options; this.options.items = items || []; this.button.setIcon(o.iconCls); this.button.setSelected(false); this.down.setSelected(false); - }, + } - setValue: function (v) { - BI.IconComboTrigger.superclass.setValue.apply(this, arguments); - var o = this.options; - var iconCls = this._digest(v, this.options.items); - v = BI.isArray(v) ? v[0] : v; - if (BI.isNotEmptyString(iconCls)) { + setValue(v) { + super.setValue(...arguments); + const o = this.options; + const iconCls = this._digest(v, this.options.items); + v = isArray(v) ? v[0] : v; + if (isNotEmptyString(iconCls)) { this.button.setIcon(iconCls); this.button.setSelected(true); this.down.setSelected(true); @@ -97,6 +114,4 @@ BI.IconComboTrigger = BI.inherit(BI.Trigger, { this.down.setSelected(false); } } -}); -BI.IconComboTrigger.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.icon_combo_trigger", BI.IconComboTrigger); +} diff --git a/src/case/combo/icontextvaluecombo/combo.icontextvalue.js b/src/case/combo/icontextvaluecombo/combo.icontextvalue.js index 9a920240a..85004eb22 100644 --- a/src/case/combo/icontextvaluecombo/combo.icontextvalue.js +++ b/src/case/combo/icontextvaluecombo/combo.icontextvalue.js @@ -1,32 +1,61 @@ -/** - * Created by Windy on 2017/12/12. - * combo : icon + text + icon, popup : icon + text - */ -BI.IconTextValueCombo = BI.inherit(BI.Widget, { - _defaultConfig: function (config) { - return BI.extend(BI.IconTextValueCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: "bi-icon-text-value-combo " + (config.simple ? "bi-border-bottom" : "bi-border bi-border-radius"), +import { + shortcut, + Widget, + extend, + isFunction, + createWidget, + toPix, + Controller, + isKey, + isNull, + isEmptyArray, + isEmptyString, + isArray, + find, + contains +} from "@/core"; +import { IconTextValueComboPopup } from "./popup.icontextvalue"; +import { SelectIconTextTrigger } from "../../trigger"; +import { Combo } from "@/base"; + +@shortcut() +export class IconTextValueCombo extends Widget { + static xtype = "bi.icon_text_value_combo"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig(config) { + return extend(super._defaultConfig(...arguments), { + baseCls: + `bi-icon-text-value-combo ${ + config.simple + ? "bi-border-bottom" + : "bi-border bi-border-radius"}`, height: 24, iconHeight: null, iconWidth: null, value: "", }); - }, + } - _init: function () { - var self = this, o = this.options; - o.value = BI.isFunction(o.value) ? this.__watch(o.value, function (context, newValue) { - self.setValue(newValue); - }) : o.value; - o.items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); - }) : o.items; - BI.IconTextValueCombo.superclass._init.apply(this, arguments); - this.trigger = BI.createWidget({ - type: "bi.select_icon_text_trigger", + _init() { + const o = this.options; + o.value = isFunction(o.value) + ? this.__watch(o.value, (context, newValue) => { + this.setValue(newValue); + }) + : o.value; + o.items = isFunction(o.items) + ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); + }) + : o.items; + super._init(...arguments); + this.trigger = createWidget({ + type: SelectIconTextTrigger.xtype, cls: "icon-text-value-trigger", items: o.items, - height: BI.toPix(o.height, 2), + height: toPix(o.height, 2), text: o.text, iconCls: o.iconCls, value: o.value, @@ -34,28 +63,28 @@ BI.IconTextValueCombo = BI.inherit(BI.Widget, { iconWidth: o.iconWidth, iconWrapperWidth: o.iconWrapperWidth, title: o.title, - warningTitle: o.warningTitle + warningTitle: o.warningTitle, }); - this.popup = BI.createWidget({ + this.popup = createWidget({ type: "bi.icon_text_value_combo_popup", items: o.items, value: o.value, iconHeight: o.iconHeight, iconWidth: o.iconWidth, - iconWrapperWidth: o.iconWrapperWidth + iconWrapperWidth: o.iconWrapperWidth, }); - this.popup.on(BI.IconTextValueComboPopup.EVENT_CHANGE, function () { - self.setValue(self.popup.getValue()); - self.textIconCombo.hideView(); - self.fireEvent(BI.IconTextValueCombo.EVENT_CHANGE, arguments); + this.popup.on(IconTextValueComboPopup.EVENT_CHANGE, (...args) => { + this.setValue(this.popup.getValue()); + this.textIconCombo.hideView(); + this.fireEvent(IconTextValueCombo.EVENT_CHANGE, ...args); }); - this.popup.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.popup.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.textIconCombo = BI.createWidget({ - type: "bi.combo", - height: BI.toPix(o.height, 2), - width: BI.toPix(o.width, 2), + this.textIconCombo = createWidget({ + type: Combo.xtype, + height: toPix(o.height, 2), + width: toPix(o.width, 2), element: this, container: o.container, direction: o.direction, @@ -64,24 +93,22 @@ BI.IconTextValueCombo = BI.inherit(BI.Widget, { popup: { el: this.popup, maxHeight: 240, - minHeight: 25 - } + minHeight: 25, + }, }); - if (BI.isKey(o.value)) { + if (isKey(o.value)) { this.setValue(o.value); } - }, + } - _checkError: function (v) { - if(BI.isNull(v) || BI.isEmptyArray(v) || BI.isEmptyString(v)) { + _checkError(v) { + if (isNull(v) || isEmptyArray(v) || isEmptyString(v)) { this.trigger.options.tipType = "success"; this.element.removeClass("combo-error"); } else { - v = BI.isArray(v) ? v : [v]; - var result = BI.find(this.options.items, function (idx, item) { - return BI.contains(v, item.value); - }); - if (BI.isNull(result)) { + v = isArray(v) ? v : [v]; + const result = find(this.options.items, (idx, item) => contains(v, item.value)); + if (isNull(result)) { this.trigger.options.tipType = "warning"; this.element.removeClass("combo-error").addClass("combo-error"); } else { @@ -89,23 +116,22 @@ BI.IconTextValueCombo = BI.inherit(BI.Widget, { this.element.removeClass("combo-error"); } } - }, + } - setValue: function (v) { + setValue(v) { this.trigger.setValue(v); this.popup.setValue(v); this._checkError(v); - }, + } - getValue: function () { - var value = this.popup.getValue(); - return BI.isNull(value) ? [] : (BI.isArray(value) ? value : [value]); - }, + getValue() { + const value = this.popup.getValue(); + + return isNull(value) ? [] : isArray(value) ? value : [value]; + } - populate: function (items) { + populate(items) { this.options.items = items; this.textIconCombo.populate(items); } -}); -BI.IconTextValueCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.icon_text_value_combo", BI.IconTextValueCombo); +} diff --git a/src/case/combo/icontextvaluecombo/popup.icontextvalue.js b/src/case/combo/icontextvaluecombo/popup.icontextvalue.js index 88db08e67..02edd74f3 100644 --- a/src/case/combo/icontextvaluecombo/popup.icontextvalue.js +++ b/src/case/combo/icontextvaluecombo/popup.icontextvalue.js @@ -1,74 +1,88 @@ -/** - * Created by Windy on 2017/12/12. - */ -BI.IconTextValueComboPopup = BI.inherit(BI.Pane, { - _defaultConfig: function () { - return BI.extend(BI.IconTextValueComboPopup.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + createWidget, + createItems, + Controller, + Events, + VerticalLayout +} from "@/core"; +import { Pane, ButtonGroup } from "@/base"; +import { SingleSelectIconTextItem } from "../../button"; + +@shortcut() +export class IconTextValueComboPopup extends Pane { + static xtype = "bi.icon_text_value_combo_popup"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-icon-text-icon-popup", behaviors: { - redmark: function () { + redmark () { return true; - } - } + }, + }, }); - }, + } - _init: function () { - BI.IconTextValueComboPopup.superclass._init.apply(this, arguments); - var o = this.options, self = this; - this.popup = BI.createWidget({ - type: "bi.button_group", - items: BI.createItems(o.items, { - type: "bi.single_select_icon_text_item", + _init() { + super._init(...arguments); + const o = this.options; + this.popup = createWidget({ + type: ButtonGroup.xtype, + items: createItems(o.items, { + type: SingleSelectIconTextItem.xtype, iconHeight: o.iconHeight, iconWidth: o.iconWidth, - iconWrapperWidth: o.iconWrapperWidth + iconWrapperWidth: o.iconWrapperWidth, }), - chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, - layouts: [{ - type: "bi.vertical" - }], + chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, + layouts: [ + { + type: VerticalLayout.xtype, + } + ], behaviors: o.behaviors, - value: o.value + value: o.value, }); - this.popup.on(BI.Controller.EVENT_CHANGE, function (type, val, obj) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if (type === BI.Events.CLICK) { - self.fireEvent(BI.IconTextValueComboPopup.EVENT_CHANGE, val, obj); + this.popup.on(Controller.EVENT_CHANGE, (...args) => { + const [type, val, obj] = args; + this.fireEvent(Controller.EVENT_CHANGE, ...args); + if (type === Events.CLICK) { + this.fireEvent(IconTextValueComboPopup.EVENT_CHANGE, val, obj); } }); this.check(); - BI.createWidget({ - type: "bi.vertical", + createWidget({ + type: VerticalLayout.xtype, element: this, vgap: 5, - items: [this.popup] + items: [this.popup], }); - }, + } - populate: function (items, keyword) { - BI.IconTextValueComboPopup.superclass.populate.apply(this, arguments); - var o = this.options; - items = BI.createItems(items, { - type: "bi.single_select_icon_text_item", + populate(items, keyword) { + super.populate(...arguments); + const o = this.options; + items = createItems(items, { + type: SingleSelectIconTextItem.xtype, iconWrapperWidth: o.iconWrapperWidth, iconHeight: o.iconHeight, iconWidth: o.iconWidth, }); this.popup.populate(items, keyword); - }, + } - getValue: function () { + getValue() { return this.popup.getValue(); - }, + } - setValue: function (v) { + setValue(v) { this.popup.setValue(v); } - -}); -BI.IconTextValueComboPopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.icon_text_value_combo_popup", BI.IconTextValueComboPopup); +} diff --git a/src/case/combo/index.js b/src/case/combo/index.js new file mode 100644 index 000000000..12b79a169 --- /dev/null +++ b/src/case/combo/index.js @@ -0,0 +1,22 @@ +export { BubbleCombo } from "./bubblecombo/combo.bubble"; +export { BubblePopupView } from "./bubblecombo/popup.bubble"; + +export { EditorIconCheckCombo } from "./editoriconcheckcombo/combo.editiconcheck"; + +export { IconCombo } from "./iconcombo/combo.icon"; +export { IconComboPopup } from "./iconcombo/popup.iconcombo"; +export { IconComboTrigger } from "./iconcombo/trigger.iconcombo"; + +export { IconTextValueCombo } from "./icontextvaluecombo/combo.icontextvalue"; +export { IconTextValueComboPopup } from "./icontextvaluecombo/popup.icontextvalue"; + +export { SearchTextValueCombo } from "./searchtextvaluecombo/combo.searchtextvalue"; +export { SearchTextValueComboPopup } from "./searchtextvaluecombo/popup.searchtextvalue"; +export { SearchTextValueTrigger } from "./searchtextvaluecombo/trigger.searchtextvalue"; + +export { TextValueCheckCombo } from "./textvaluecheckcombo/combo.textvaluecheck"; +export { TextValueCheckComboPopup } from "./textvaluecheckcombo/popup.textvaluecheck"; + +export { TextValueCombo } from "./textvaluecombo/combo.textvalue"; +export { SmallTextValueCombo } from "./textvaluecombo/combo.textvaluesmall"; +export { TextValueComboPopup } from "./textvaluecombo/popup.textvalue"; diff --git a/src/case/combo/searchtextvaluecombo/combo.searchtextvalue.js b/src/case/combo/searchtextvaluecombo/combo.searchtextvalue.js index baa653207..a5c586773 100644 --- a/src/case/combo/searchtextvaluecombo/combo.searchtextvalue.js +++ b/src/case/combo/searchtextvaluecombo/combo.searchtextvalue.js @@ -1,9 +1,25 @@ -/** - * Created by Windy on 2018/2/2. - */ -BI.SearchTextValueCombo = BI.inherit(BI.Widget, { +import { + shortcut, + Widget, + isFunction, + toPix, + isKey, + isNull, + isEmptyArray, + isEmptyString, + isArray, + find, + contains +} from "@/core"; +import { SearchTextValueTrigger } from "./trigger.searchtextvalue"; +import { ButtonGroup, Combo } from "@/base"; +import { TextValueComboPopup } from "../textvaluecombo/popup.textvalue"; - props: { +@shortcut() +export class SearchTextValueCombo extends Widget { + static xtype = "bi.search_text_value_combo"; + + props = { baseCls: "bi-search-text-value-combo", height: 24, text: "", @@ -12,36 +28,46 @@ BI.SearchTextValueCombo = BI.inherit(BI.Widget, { tipType: "", warningTitle: "", allowClear: false, - }, + }; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + static EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; - render: function () { - var self = this, o = this.options; - o.value = BI.isFunction(o.value) ? this.__watch(o.value, function (context, newValue) { - self.setValue(newValue); - }) : o.value; - o.items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); - }) : o.items; + render() { + const o = this.options; + o.value = isFunction(o.value) + ? this.__watch(o.value, (context, newValue) => { + this.setValue(newValue); + }) + : o.value; + o.items = isFunction(o.items) + ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); + }) + : o.items; return { - type: "bi.combo", - cls: (o.simple ? "bi-border-bottom" : "bi-border bi-border-radius") + " bi-focus-shadow", + type: Combo.xtype, + cls: + `${o.simple ? "bi-border-bottom" : "bi-border bi-border-radius" + } bi-focus-shadow`, container: o.container, adjustLength: 2, - height: BI.toPix(o.height, o.simple ? 1 : 2), - width: BI.toPix(o.width, 2), - ref: function () { - self.combo = this; + height: toPix(o.height, o.simple ? 1 : 2), + width: toPix(o.width, 2), + ref: _ref => { + this.combo = _ref; }, el: { type: "bi.search_text_value_trigger", cls: "search-text-value-trigger", watermark: o.watermark, - ref: function () { - self.trigger = this; + ref: _ref => { + this.trigger = _ref; }, items: o.items, - height: BI.toPix(o.height, o.simple ? 1 : 2), + height: toPix(o.height, o.simple ? 1 : 2), text: o.text, defaultText: o.defaultText, value: o.value, @@ -49,80 +75,92 @@ BI.SearchTextValueCombo = BI.inherit(BI.Widget, { warningTitle: o.warningTitle, title: o.title, allowClear: o.allowClear, - listeners: [{ - eventName: BI.SearchTextValueTrigger.EVENT_CHANGE, - action: function () { - self.setValue(this.getValue()[0]); - self.combo.hideView(); - self.fireEvent(BI.SearchTextValueCombo.EVENT_CHANGE); - } - }, { - eventName: BI.SearchTextValueTrigger.EVENT_CLEAR, - action: function () { - self._clear(); - self.fireEvent(BI.SearchTextValueCombo.EVENT_CHANGE); + listeners: [ + { + eventName: SearchTextValueTrigger.EVENT_CHANGE, + action: () => { + this.setValue(this.getValue()[0]); + this.combo.hideView(); + this.fireEvent(SearchTextValueCombo.EVENT_CHANGE); + }, + }, + { + eventName: SearchTextValueTrigger.EVENT_CLEAR, + action: () => { + this._clear(); + this.fireEvent(SearchTextValueCombo.EVENT_CHANGE); + }, } - }] + ], }, popup: { el: { type: "bi.text_value_combo_popup", - chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, + chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, value: o.value, items: o.items, - ref: function () { - self.popup = this; - self.trigger.getSearcher().setAdapter(self.popup); + ref: _ref => { + this.popup = _ref; + this.trigger.getSearcher().setAdapter(this.popup); }, - listeners: [{ - eventName: BI.TextValueComboPopup.EVENT_CHANGE, - action: function () { - self.setValue(this.getValue()[0]); - self.combo.hideView(); - self.fireEvent(BI.SearchTextValueCombo.EVENT_CHANGE); + listeners: [ + { + eventName: TextValueComboPopup.EVENT_CHANGE, + action: () => { + this.setValue(this.getValue()[0]); + this.combo.hideView(); + this.fireEvent( + SearchTextValueCombo.EVENT_CHANGE + ); + }, } - }] + ], }, value: o.value, maxHeight: 252, - minHeight: 25 + minHeight: 25, }, - listeners: [{ - eventName: BI.Combo.EVENT_AFTER_HIDEVIEW, - action: function () { - self.trigger.stopEditing(); - self.fireEvent(BI.SearchTextValueCombo.EVENT_AFTER_HIDEVIEW); - } - }, { - eventName: BI.Combo.EVENT_BEFORE_POPUPVIEW, - action: function () { - self.fireEvent(BI.SearchTextValueCombo.EVENT_BEFORE_POPUPVIEW); + listeners: [ + { + eventName: Combo.EVENT_AFTER_HIDEVIEW, + action: () => { + this.trigger.stopEditing(); + this.fireEvent( + SearchTextValueCombo.EVENT_AFTER_HIDEVIEW + ); + }, + }, + { + eventName: Combo.EVENT_BEFORE_POPUPVIEW, + action: () => { + this.fireEvent( + SearchTextValueCombo.EVENT_BEFORE_POPUPVIEW + ); + }, } - }], + ], }; - }, + } - created: function () { - var o = this.options; - if (BI.isKey(o.value)) { + created() { + const o = this.options; + if (isKey(o.value)) { this._checkError(o.value); } - }, + } - _clear: function () { + _clear() { this.setValue(); - }, + } - _checkError: function (v) { - if (BI.isNull(v) || BI.isEmptyArray(v) || BI.isEmptyString(v)) { + _checkError(v) { + if (isNull(v) || isEmptyArray(v) || isEmptyString(v)) { this.trigger.options.tipType = "success"; this.element.removeClass("combo-error"); } else { - v = BI.isArray(v) ? v : [v]; - var result = BI.find(this.options.items, function (idx, item) { - return BI.contains(v, item.value); - }); - if (BI.isNull(result)) { + v = isArray(v) ? v : [v]; + const result = find(this.options.items, (idx, item) => contains(v, item.value)); + if (isNull(result)) { this.element.removeClass("combo-error").addClass("combo-error"); this.trigger.attr("tipType", "warning"); } else { @@ -130,24 +168,21 @@ BI.SearchTextValueCombo = BI.inherit(BI.Widget, { this.trigger.attr("tipType", "success"); } } - }, + } - populate: function (items) { + populate(items) { this.options.items = items; this.combo.populate(items); - }, + } - setValue: function (v) { + setValue(v) { this.combo.setValue(v); this._checkError(v); - }, + } - getValue: function () { - var value = this.combo.getValue(); - return BI.isNull(value) ? [] : (BI.isArray(value) ? value : [value]); + getValue() { + const value = this.combo.getValue(); + + return isNull(value) ? [] : isArray(value) ? value : [value]; } -}); -BI.SearchTextValueCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.SearchTextValueCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.SearchTextValueCombo.EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW" -BI.shortcut("bi.search_text_value_combo", BI.SearchTextValueCombo); +} diff --git a/src/case/combo/searchtextvaluecombo/popup.searchtextvalue.js b/src/case/combo/searchtextvaluecombo/popup.searchtextvalue.js index dc1107fb1..36975c1d7 100644 --- a/src/case/combo/searchtextvaluecombo/popup.searchtextvalue.js +++ b/src/case/combo/searchtextvaluecombo/popup.searchtextvalue.js @@ -1,76 +1,100 @@ -/** - * Created by Windy on 2018/2/5. - */ -BI.SearchTextValueComboPopup = BI.inherit(BI.Pane, { +import { + shortcut, + Controller, + Events, + VerticalLayout, + map, + extend, + concat +} from "@/core"; +import { ButtonGroup, Pane } from "@/base"; +import { SingleSelectItem } from "../../button"; - props: { - baseCls: "bi-search-text-value-popup" - }, +@shortcut() +export class SearchTextValueComboPopup extends Pane { + static xtype = "bi.search_text_value_combo_popup"; - render: function () { - var self = this, o = this.options; + props = { baseCls: "bi-search-text-value-popup" }; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + render() { + const o = this.options; + return { - type: "bi.vertical", + type: VerticalLayout.xtype, vgap: 5, - items: [{ - type: "bi.button_group", - ref: function () { - self.popup = this; - }, - items: this._formatItems(o.items), - chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, - layouts: [{ - type: "bi.vertical" - }], - behaviors: { - redmark: function () { - return true; - } - }, - value: o.value, - listeners: [{ - eventName: BI.Controller.EVENT_CHANGE, - action: function (type, val, obj) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if (type === BI.Events.CLICK) { - self.fireEvent(BI.SearchTextValueComboPopup.EVENT_CHANGE, val, obj); + items: [ + { + type: ButtonGroup.xtype, + ref: _ref => { + this.popup = _ref; + }, + items: this._formatItems(o.items), + chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, + layouts: [ + { + type: VerticalLayout.xtype, + } + ], + behaviors: { + redmark () { + return true; + }, + }, + value: o.value, + listeners: [ + { + eventName: Controller.EVENT_CHANGE, + action: (...args) => { + const [type, val, obj] = args; + this.fireEvent( + Controller.EVENT_CHANGE, + ...args + ); + if (type === Events.CLICK) { + this.fireEvent( + SearchTextValueComboPopup.EVENT_CHANGE, + val, + obj + ); + } + }, } - } - }] - }] + ], + } + ], }; - }, + } - _formatItems: function (items) { - var o = this.options; - return BI.map(items, function (i, item) { - return BI.extend({ - type: "bi.single_select_item", + _formatItems(items) { + const o = this.options; + + return map(items, (i, item) => extend( + { + type: SingleSelectItem.xtype, textAlign: o.textAlign, - title: item.title || item.text - }, item); - }); - }, + title: item.title || item.text, + }, + item + )); + } - // mounted之后做check - mounted: function() { + mounted() { this.check(); - }, + } - populate: function (find, match, keyword) { - var items = BI.concat(find, match); - BI.SearchTextValueComboPopup.superclass.populate.apply(this, items); + populate(find, match, keyword) { + const items = concat(find, match); + super.populate.apply(this, items); this.popup.populate(this._formatItems(items), keyword); - }, + } - getValue: function () { + getValue() { return this.popup.getValue(); - }, + } - setValue: function (v) { + setValue(v) { this.popup.setValue(v); } - -}); -BI.SearchTextValueComboPopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.search_text_value_combo_popup", BI.SearchTextValueComboPopup); +} diff --git a/src/case/combo/searchtextvaluecombo/trigger.searchtextvalue.js b/src/case/combo/searchtextvaluecombo/trigger.searchtextvalue.js index 7f6f7925d..a090b4c66 100644 --- a/src/case/combo/searchtextvaluecombo/trigger.searchtextvalue.js +++ b/src/case/combo/searchtextvaluecombo/trigger.searchtextvalue.js @@ -1,32 +1,53 @@ -/** - * Created by Windy on 2018/2/2. - */ -BI.SearchTextValueTrigger = BI.inherit(BI.Trigger, { +import { + shortcut, + find, + i18nText, + isNotEmptyString, + VerticalAdaptLayout +} from "@/core"; +import { + ButtonGroup, + Trigger, + Searcher, + IconButton +} from "@/base"; +import { TriggerIconButton } from "../../button"; +import { DefaultTextEditor } from "../../editor"; - props: function () { +@shortcut() +export class SearchTextValueTrigger extends Trigger { + static xtype = "bi.search_text_value_trigger"; + + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_START = "EVENT_START"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_CLEAR = "EVENT_CLEAR"; + + props() { return { baseCls: "bi-search-text-value-trigger", height: 24, - watermark: BI.i18nText("BI-Basic_Search"), + watermark: i18nText("BI-Basic_Search"), allowClear: false, title: () => this.editor.getText(), }; - }, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; - var triggerButton = { - type: "bi.trigger_icon_button", + const triggerButton = { + type: TriggerIconButton.xtype, cls: "trigger-icon-button", - ref: function () { - self.triggerBtn = this; + ref: _ref => { + this.triggerBtn = _ref; }, width: o.height, height: o.height, }; - var stateText = this._digest(o.value, o.items) || o.text; + const stateText = this._digest(o.value, o.items) || o.text; return { type: "bi.horizontal_fill", @@ -34,15 +55,15 @@ BI.SearchTextValueTrigger = BI.inherit(BI.Trigger, { items: [ { el: { - type: "bi.searcher", - ref: function () { - self.searcher = this; + type: Searcher.xtype, + ref: _ref => { + this.searcher = this; }, isAutoSearch: false, el: { - type: "bi.default_text_editor", - ref: function () { - self.editor = this; + type: DefaultTextEditor.xtype, + ref: _ref => { + this.editor = _ref; }, watermark: o.watermark, defaultText: o.defaultText, @@ -53,90 +74,103 @@ BI.SearchTextValueTrigger = BI.inherit(BI.Trigger, { popup: { type: "bi.search_text_value_combo_popup", cls: "bi-card", - chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, - tipText: BI.i18nText("BI-No_Select"), + chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, + tipText: i18nText("BI-No_Select"), }, - onSearch: function (obj, callback) { - var keyword = obj.keyword; - var finding = BI.Func.getSearchResult(o.items, keyword); - var matched = finding.match, find = finding.find; + onSearch (obj, callback) { + const keyword = obj.keyword; + const finding = BI.Func.getSearchResult( + o.items, + keyword + ); + const matched = finding.match, + find = finding.find; callback(matched, find); }, - listeners: [{ - eventName: BI.Searcher.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.SearchTextValueTrigger.EVENT_CHANGE); - } - }] - } - }, { - el: o.allowClear ? { - type: "bi.vertical_adapt", - horizontalAlign: "left", - scrollable: false, - items: [ + listeners: [ { - el: { - type: "bi.icon_button", - ref: function (_ref) { - self.clearBtn = _ref; - }, - cls: "close-h-font " + (o.allowClear ? "clear-button" : ""), - stopPropagation: true, - invisible: !BI.isNotEmptyString(stateText), - width: o.height, - height: o.height, - handler: function () { - self.fireEvent(BI.SearchTextValueTrigger.EVENT_CLEAR); - }, + eventName: Searcher.EVENT_CHANGE, + action: () => { + this.fireEvent( + SearchTextValueTrigger.EVENT_CHANGE + ); }, - }, { - el: triggerButton, } - ] - } : triggerButton, - width: 24 + ], + }, + }, + { + el: o.allowClear + ? { + type: VerticalAdaptLayout.xtype, + horizontalAlign: "left", + scrollable: false, + items: [ + { + el: { + type: IconButton.xtype, + ref: _ref => { + this.clearBtn = _ref; + }, + cls: + `close-h-font ${ + o.allowClear + ? "clear-button" + : ""}`, + stopPropagation: true, + invisible: + !isNotEmptyString(stateText), + width: o.height, + height: o.height, + handler: () => { + this.fireEvent( + SearchTextValueTrigger.EVENT_CLEAR + ); + }, + }, + }, + { + el: triggerButton, + } + ], + } + : triggerButton, + width: 24, } - ] + ], }; - }, + } - _setState: function (v) { + _setState(v) { this.editor.setState(v); - }, + } - _digest: function (value, items) { - var result = BI.find(items, function (i, item) { - return item.value === value; - }); + _digest(value, items) { + const result = find(items, (i, item) => item.value === value); + return result?.text; - }, + } - stopEditing: function () { + stopEditing() { this.searcher.stopSearch(); - }, + } - getSearcher: function () { + getSearcher() { return this.searcher; - }, + } - populate: function (items) { + populate(items) { this.options.items = items; - }, + } - setValue: function (vals) { - var digestText = this._digest(vals, this.options.items); + setValue(vals) { + const digestText = this._digest(vals, this.options.items); this._setState(digestText); - this.options.allowClear && this.clearBtn.setVisible(BI.isNotEmptyString(digestText)); - }, + this.options.allowClear && + this.clearBtn.setVisible(isNotEmptyString(digestText)); + } - getValue: function () { + getValue() { return this.searcher.getValue(); } -}); -BI.SearchTextValueTrigger.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.SearchTextValueTrigger.EVENT_STOP = "EVENT_STOP"; -BI.SearchTextValueTrigger.EVENT_START = "EVENT_START"; -BI.SearchTextValueTrigger.EVENT_CHANGE = "EVENT_CHANGE"; -BI.SearchTextValueTrigger.EVENT_CLEAR = "EVENT_CLEAR"; -BI.shortcut("bi.search_text_value_trigger", BI.SearchTextValueTrigger); +} diff --git a/src/case/combo/textvaluecheckcombo/combo.textvaluecheck.js b/src/case/combo/textvaluecheckcombo/combo.textvaluecheck.js index 9c5f0d0fc..c2fcfe901 100644 --- a/src/case/combo/textvaluecheckcombo/combo.textvaluecheck.js +++ b/src/case/combo/textvaluecheckcombo/combo.textvaluecheck.js @@ -1,92 +1,113 @@ -/** - * @class BI.TextValueCheckCombo - * @extend BI.Widget - * combo : text + icon, popup : check + text - */ -BI.TextValueCheckCombo = BI.inherit(BI.Widget, { - _defaultConfig: function (config) { - return BI.extend(BI.TextValueCheckCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: "bi-text-value-check-combo " + (config.simple ? "bi-border-bottom" : "bi-border"), +import { + shortcut, + Widget, + extend, + isFunction, + createWidget, + toPix, + Controller, + isKey, + isNull, + isArray +} from "@/core"; +import { ButtonGroup, Combo } from "@/base"; +import { TextValueCheckComboPopup } from "./popup.textvaluecheck"; +import { SelectTextTrigger } from "../../trigger"; + +@shortcut() +export class TextValueCheckCombo extends Widget { + static xtype = "bi.text_value_check_combo"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig(config) { + return extend(super._defaultConfig(...arguments), { + baseCls: + `bi-text-value-check-combo ${ + config.simple ? "bi-border-bottom" : "bi-border"}`, width: 100, height: 24, - chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, + chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, value: "", }); - }, + } - _init: function () { - var self = this, o = this.options; - o.value = BI.isFunction(o.value) ? this.__watch(o.value, function (context, newValue) { - self.setValue(newValue); - }) : o.value; - o.items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); - }) : o.items; - BI.TextValueCheckCombo.superclass._init.apply(this, arguments); - this.trigger = BI.createWidget({ - type: "bi.select_text_trigger", + _init() { + const o = this.options; + o.value = isFunction(o.value) + ? this.__watch(o.value, (context, newValue) => { + this.setValue(newValue); + }) + : o.value; + o.items = isFunction(o.items) + ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); + }) + : o.items; + super._init(...arguments); + this.trigger = createWidget({ + type: SelectTextTrigger.xtype, cls: "text-value-trigger", items: o.items, - height: BI.toPix(o.height, 2), + height: toPix(o.height, 2), text: o.text, - value: o.value + value: o.value, }); - this.popup = BI.createWidget({ - type: "bi.text_value_check_combo_popup", + this.popup = createWidget({ + type: TextValueCheckComboPopup.xtype, chooseType: o.chooseType, items: o.items, - value: o.value + value: o.value, }); - this.popup.on(BI.TextValueCheckComboPopup.EVENT_CHANGE, function () { - self.setValue(self.popup.getValue()); - self.textIconCheckCombo.hideView(); - self.fireEvent(BI.TextValueCheckCombo.EVENT_CHANGE); + this.popup.on(TextValueCheckComboPopup.EVENT_CHANGE, () => { + this.setValue(this.popup.getValue()); + this.textIconCheckCombo.hideView(); + this.fireEvent(TextValueCheckCombo.EVENT_CHANGE); }); - this.popup.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.popup.on(Controller.EVENT_CHANGE, ...args => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.textIconCheckCombo = BI.createWidget({ - type: "bi.combo", + this.textIconCheckCombo = createWidget({ + type: Combo.xtype, container: o.container, direction: o.direction, element: this, - width: BI.toPix(o.width, 2), - height: BI.toPix(o.height, 2), + width: toPix(o.width, 2), + height: toPix(o.height, 2), adjustLength: 2, el: this.trigger, popup: { el: this.popup, - maxHeight: 300 - } + maxHeight: 300, + }, }); - if (BI.isKey(o.value)) { + if (isKey(o.value)) { this.setValue(o.value); } - }, + } - setTitle: function (title) { + setTitle(title) { this.trigger.setTitle(title); - }, + } - setValue: function (v) { + setValue(v) { this.trigger.setValue(v); this.popup.setValue(v); - }, + } - setWarningTitle: function (title) { + setWarningTitle(title) { this.trigger.setWarningTitle(title); - }, + } - getValue: function () { - var value = this.popup.getValue(); - return BI.isNull(value) ? [] : (BI.isArray(value) ? value : [value]); - }, + getValue() { + const value = this.popup.getValue(); + + return isNull(value) ? [] : isArray(value) ? value : [value]; + } - populate: function (items) { + populate(items) { this.options.items = items; this.textIconCheckCombo.populate(items); } -}); -BI.TextValueCheckCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.text_value_check_combo", BI.TextValueCheckCombo); +} diff --git a/src/case/combo/textvaluecheckcombo/popup.textvaluecheck.js b/src/case/combo/textvaluecheckcombo/popup.textvaluecheck.js index b25ccc141..9c32c2b68 100644 --- a/src/case/combo/textvaluecheckcombo/popup.textvaluecheck.js +++ b/src/case/combo/textvaluecheckcombo/popup.textvaluecheck.js @@ -1,64 +1,83 @@ -BI.TextValueCheckComboPopup = BI.inherit(BI.Pane, { - _defaultConfig: function () { - return BI.extend(BI.TextValueCheckComboPopup.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + createWidget, + Controller, + Events, + VerticalLayout, + map +} from "@/core"; +import { Pane, ButtonGroup } from "@/base"; +import { SingleSelectItem } from "../../button"; + +@shortcut() +export class TextValueCheckComboPopup extends Pane { + static xtype = "bi.text_value_check_combo_popup"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-text-icon-popup", - chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE + chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, }); - }, + } - _init: function () { - BI.TextValueCheckComboPopup.superclass._init.apply(this, arguments); - var o = this.options, self = this; - this.popup = BI.createWidget({ - type: "bi.button_group", + _init() { + super._init(...arguments); + const o = this.options; + this.popup = createWidget({ + type: ButtonGroup.xtype, items: this._formatItems(o.items), chooseType: o.chooseType, - layouts: [{ - type: "bi.vertical" - }], - value: o.value + layouts: [ + { + type: VerticalLayout.xtype, + } + ], + value: o.value, }); - this.popup.on(BI.Controller.EVENT_CHANGE, function (type, val, obj) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if (type === BI.Events.CLICK) { - self.fireEvent(BI.TextValueCheckComboPopup.EVENT_CHANGE, val, obj); + this.popup.on(Controller.EVENT_CHANGE, (...args) => { + const [type, val, obj] = args; + this.fireEvent(Controller.EVENT_CHANGE, ...args); + if (type === Events.CLICK) { + this.fireEvent(TextValueCheckComboPopup.EVENT_CHANGE, val, obj); } }); - BI.createWidget({ - type: "bi.vertical", + createWidget({ + type: VerticalLayout.xtype, element: this, vgap: 5, - items: [this.popup] + items: [this.popup], }); - }, + } - _formatItems: function (items) { - var o = this.options; - return BI.map(items, function (i, item) { - return BI.extend({ - type: "bi.single_select_item", + _formatItems(items) { + const o = this.options; + + return map(items, (i, item) => extend( + { + type: SingleSelectItem.xtype, cls: "bi-list-item", textAlign: o.textAlign, - title: item.title || item.text - }, item); - }); - }, + title: item.title || item.text, + }, + item + )); + } - populate: function (items) { - BI.TextValueCheckComboPopup.superclass.populate.apply(this, arguments); + populate(items) { + super.populate(...arguments); this.popup.populate(this._formatItems(items)); - }, + } - getValue: function () { + getValue() { return this.popup.getValue(); - }, + } - setValue: function (v) { + setValue(v) { this.popup.setValue(v); } - -}); -BI.TextValueCheckComboPopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.text_value_check_combo_popup", BI.TextValueCheckComboPopup); +} diff --git a/src/case/combo/textvaluecombo/combo.textvalue.js b/src/case/combo/textvaluecombo/combo.textvalue.js index 9dc088639..a9bf892b5 100644 --- a/src/case/combo/textvaluecombo/combo.textvalue.js +++ b/src/case/combo/textvaluecombo/combo.textvalue.js @@ -1,15 +1,37 @@ -/** - * @class BI.TextValueCombo - * @extend BI.Widget - * combo : text + icon, popup : text - * 参见场景dashboard布局方式选择 - */ -BI.TextValueCombo = BI.inherit(BI.Widget, { - _defaultConfig: function (config) { - return BI.extend(BI.TextValueCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: "bi-text-value-combo " + (config.simple ? "bi-border-bottom" : "bi-border bi-border-radius"), +import { + shortcut, + Widget, + extend, + isFunction, + toPix, + isEmptyArray, + Controller, + isKey, + isObject, + isNull, + isArray, + intersection, + map +} from "@/core"; +import { ButtonGroup, Combo } from "@/base"; +import { SelectTextTrigger } from "../../trigger"; +import { TextValueComboPopup } from "./popup.textvalue"; + +@shortcut() +export class TextValueCombo extends Widget { + static xtype = "bi.text_value_combo"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig(config) { + return extend(super._defaultConfig(...arguments), { + baseCls: + `bi-text-value-combo ${ + config.simple + ? "bi-border-bottom" + : "bi-border bi-border-radius"}`, height: 24, - chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, + chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, text: "", value: "", defaultText: "", @@ -19,44 +41,48 @@ BI.TextValueCombo = BI.inherit(BI.Widget, { title: null, allowSelectAll: true, }); - }, - - _init: function () { - var self = this, o = this.options; - o.value = BI.isFunction(o.value) ? this.__watch(o.value, function (context, newValue) { - self.setValue(newValue); - }) : o.value; - o.items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { - self.populate(newValue); - }) : o.items; - BI.TextValueCombo.superclass._init.apply(this, arguments); - }, + } - render: function () { + _init() { + const o = this.options; + o.value = isFunction(o.value) + ? this.__watch(o.value, (context, newValue) => { + this.setValue(newValue); + }) + : o.value; + o.items = isFunction(o.items) + ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); + }) + : o.items; + super._init(...arguments); + } + render() { const o = this.options; const title = () => { - if (BI.isFunction(o.title)) { + if (isFunction(o.title)) { return o.title(); } if (this.options.status === "error") { return { level: "warning", - text: o.warningTitle + text: o.warningTitle, }; } + return { - level: "success" + level: "success", }; }; const trigger = { - type: "bi.select_text_trigger", - ref: ref => this.trigger = ref, + type: SelectTextTrigger.xtype, + ref: ref => (this.trigger = ref), cls: "text-value-trigger", items: o.items, - height: BI.toPix(o.height, o.simple ? 1 : 2), + height: toPix(o.height, o.simple ? 1 : 2), text: o.text, value: o.value, title, @@ -64,150 +90,169 @@ BI.TextValueCombo = BI.inherit(BI.Widget, { defaultText: o.defaultText, listeners: [ { - eventName: BI.SelectTextTrigger.EVENT_CLEAR, + eventName: SelectTextTrigger.EVENT_CLEAR, action: () => { this._clear(); - this.fireEvent(BI.TextValueCombo.EVENT_CHANGE); - } + this.fireEvent(TextValueCombo.EVENT_CHANGE); + }, } ], - ...o.el + ...o.el, }; let changeTag = false; const popup = { type: "bi.text_value_combo_popup", - ref: ref => this.popup = ref, + ref: ref => (this.popup = ref), chooseType: o.chooseType, items: o.items, allowSelectAll: o.allowSelectAll, listeners: [ { - eventName: BI.TextValueComboPopup.EVENT_CHANGE, + eventName: TextValueComboPopup.EVENT_CHANGE, action: (...args) => { changeTag = true; const value = this.popup.getValue(); this.setValue(value); - if (o.chooseType === BI.ButtonGroup.CHOOSE_TYPE_SINGLE) { + if (o.chooseType === ButtonGroup.CHOOSE_TYPE_SINGLE) { this.combo.hideView(...args); - this.fireEvent(BI.TextValueCombo.EVENT_CHANGE, ...args); + this.fireEvent( + TextValueCombo.EVENT_CHANGE, + ...args + ); } - if (o.chooseType === BI.ButtonGroup.CHOOSE_TYPE_MULTI && BI.isEmptyArray(value)) { + if ( + o.chooseType === ButtonGroup.CHOOSE_TYPE_MULTI && + isEmptyArray(value) + ) { this._clear(); } - } - }, { - eventName: BI.Controller.EVENT_CHANGE, + }, + }, + { + eventName: Controller.EVENT_CHANGE, action: (...args) => { - this.fireEvent(BI.Controller.EVENT_CHANGE, ...args); - } - }, { - eventName: BI.TextValueComboPopup.EVENT_CLEAR, + this.fireEvent(Controller.EVENT_CHANGE, ...args); + }, + }, + { + eventName: TextValueComboPopup.EVENT_CLEAR, action: (...args) => { changeTag = true; this._clear(); this.combo.hideView(); - } - }, { - eventName: BI.TextValueComboPopup.EVENT_CONFIRM, + }, + }, + { + eventName: TextValueComboPopup.EVENT_CONFIRM, action: (...args) => { this.combo.hideView(); - } + }, } - ] + ], }; return { - type: "bi.combo", - height: BI.toPix(o.height, 2), - width: BI.toPix(o.width, 2), - ref: ref => this.combo = ref, + type: Combo.xtype, + height: toPix(o.height, 2), + width: toPix(o.width, 2), + ref: ref => (this.combo = ref), container: o.container, direction: o.direction, adjustLength: 2, el: trigger, listeners: [ { - eventName: BI.Combo.EVENT_BEFORE_POPUPVIEW, + eventName: Combo.EVENT_BEFORE_POPUPVIEW, action: () => { changeTag = false; - } - }, { - eventName: BI.Combo.EVENT_AFTER_HIDEVIEW, + }, + }, + { + eventName: Combo.EVENT_AFTER_HIDEVIEW, action: (...args) => { - if (o.chooseType !== BI.ButtonGroup.CHOOSE_TYPE_SINGLE && changeTag) { - this.fireEvent(BI.TextValueCombo.EVENT_CHANGE, ...args); + if ( + o.chooseType !== ButtonGroup.CHOOSE_TYPE_SINGLE && + changeTag + ) { + this.fireEvent( + TextValueCombo.EVENT_CHANGE, + ...args + ); } - } + }, } ], popup: { el: popup, value: o.value, maxHeight: 240, - minHeight: (o.chooseType === BI.ButtonGroup.CHOOSE_TYPE_MULTI && o.allowSelectAll) ? 55 : 25 - } + minHeight: + o.chooseType === ButtonGroup.CHOOSE_TYPE_MULTI && + o.allowSelectAll + ? 55 + : 25, + }, }; - }, + } - mounted: function () { + mounted() { const o = this.options; - if (BI.isKey(o.value) || BI.isObject(o.value)) { + if (isKey(o.value) || isObject(o.value)) { this._checkError(o.value); } - }, + } - _clear: function () { + _clear() { this.trigger.setText(""); this.combo.setValue(); this.setStatus("success"); - }, - - _checkError: function (v) { + } - if (BI.isNull(v)) { + _checkError(v) { + if (isNull(v)) { this.setStatus("success"); + return; } - var vals = BI.isArray(v) ? v : [v]; + const vals = isArray(v) ? v : [v]; - var result = BI.intersection(BI.map(this.options.items, "value"), vals); + const result = intersection(map(this.options.items, "value"), vals); if (result.length !== vals.length) { this.setStatus("error"); } else { this.setStatus("success"); } - }, + } - clear: function () { + clear() { this._clear(); - }, + } - setText: function (text) { + setText(text) { this.trigger.setText(text); - }, + } - setValue: function (v) { + setValue(v) { this.combo.setValue(v); this._checkError(v); - }, + } - setStatus: function (status) { + setStatus(status) { this.element.removeClass(`bi-status-${this.options.status}`); this.element.addClass(`bi-status-${status}`); this.options.status = status; - }, + } - getValue: function () { - var value = this.combo.getValue(); - return BI.isNull(value) ? [] : (BI.isArray(value) ? value : [value]); - }, + getValue() { + const value = this.combo.getValue(); + + return isNull(value) ? [] : isArray(value) ? value : [value]; + } - populate: function (items) { + populate(items) { this.options.items = items; this.combo.populate(items); } -}); -BI.TextValueCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.text_value_combo", BI.TextValueCombo); +} diff --git a/src/case/combo/textvaluecombo/combo.textvaluesmall.js b/src/case/combo/textvaluecombo/combo.textvaluesmall.js index 155b124ce..d531e1885 100644 --- a/src/case/combo/textvaluecombo/combo.textvaluesmall.js +++ b/src/case/combo/textvaluecombo/combo.textvaluesmall.js @@ -1,32 +1,41 @@ -/** - * @class BI.SmallTextValueCombo - * @extend BI.Widget - * combo : text + icon, popup : text - * 参见场景dashboard布局方式选择 - */ -BI.SmallTextValueCombo = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.SmallTextValueCombo.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + Widget, + extend +} from "@/core"; +import { ButtonGroup } from "@/base"; +import { SmallSelectTextTrigger } from "../../trigger"; +import { TextValueCombo } from "./combo.textvalue"; + +@shortcut() +export class SmallTextValueCombo extends Widget { + static xtype = "bi.small_text_value_combo"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { width: 100, height: 20, - chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, + chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, el: {}, - text: "" + text: "", }); - }, + } - render: function () { - var o = this.options; + render() { + const o = this.options; + return { type: "bi.text_value_combo", - ref: (_ref) => { + ref: _ref => { this.combo = _ref; }, height: o.height, chooseType: o.chooseType, el: { - type: "bi.small_select_text_trigger", - ...o.el + type: SmallSelectTextTrigger.xtype, + ...o.el, }, text: o.text, value: o.value, @@ -34,26 +43,29 @@ BI.SmallTextValueCombo = BI.inherit(BI.Widget, { allowClear: o.allowClear, status: o.status, title: o.title, - listeners: [{ - eventName: BI.TextValueCombo.EVENT_CHANGE, - action: (...args) => { - this.fireEvent(BI.SmallTextValueCombo.EVENT_CHANGE, ...args); + listeners: [ + { + eventName: TextValueCombo.EVENT_CHANGE, + action: (...args) => { + this.fireEvent( + SmallTextValueCombo.EVENT_CHANGE, + ...args + ); + }, } - }] - } - }, + ], + }; + } - setValue: function (v) { + setValue(v) { this.combo.setValue(v); - }, + } - getValue: function () { + getValue() { return this.combo.getValue(); - }, + } - populate: function (items) { + populate(items) { this.combo.populate(items); } -}); -BI.SmallTextValueCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.small_text_value_combo", BI.SmallTextValueCombo); +} diff --git a/src/case/combo/textvaluecombo/popup.textvalue.js b/src/case/combo/textvaluecombo/popup.textvalue.js index aed1b0979..a9fa0caaf 100644 --- a/src/case/combo/textvaluecombo/popup.textvalue.js +++ b/src/case/combo/textvaluecombo/popup.textvalue.js @@ -1,190 +1,240 @@ -BI.TextValueComboPopup = BI.inherit(BI.Pane, { - _defaultConfig: function () { - return BI.extend(BI.TextValueComboPopup.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + Controller, + map, + Events, + VerticalAlign, + createItems, + i18nText, + VerticalLayout, + CenterLayout +} from "@/core"; +import { ButtonGroup, Pane, TextButton } from "@/base"; +import { SelectList } from "../../list/list.select"; +import { ListPane } from "../../layer"; +import { SingleSelectItem, MultiSelectItem } from "../../button"; + +@shortcut() +export class TextValueComboPopup extends Pane { + static xtype = "bi.text_value_combo_popup"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_CLEAR = "EVENT_CLEAR"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-text-icon-popup", - chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, + chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, allowSelectAll: true, }); - }, + } render() { - var o = this.options, self = this; - if (o.chooseType !== BI.ButtonGroup.CHOOSE_TYPE_MULTI) { + const o = this.options; + if (o.chooseType !== ButtonGroup.CHOOSE_TYPE_MULTI) { return { - type: "bi.vertical", + type: VerticalLayout.xtype, vgap: 5, items: [ { - type: "bi.button_group", - ref: (_ref) => { + type: ButtonGroup.xtype, + ref: _ref => { this.popup = _ref; }, items: this._formatItems(o.items), chooseType: o.chooseType, layouts: [ { - type: "bi.vertical" + type: VerticalLayout.xtype, } ], value: o.value, listeners: [ { - eventName: BI.Controller.EVENT_CHANGE, - action: function (type, val, obj) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if (type === BI.Events.CLICK) { - self.fireEvent(BI.TextValueComboPopup.EVENT_CHANGE, val, obj); + eventName: Controller.EVENT_CHANGE, + action: (type, val, obj) => { + this.fireEvent( + Controller.EVENT_CHANGE, + arguments + ); + if (type === Events.CLICK) { + this.fireEvent( + TextValueComboPopup.EVENT_CHANGE, + val, + obj + ); } - } + }, } - ] + ], } - ] + ], }; } + return { - type: "bi.vertical", - verticalAlign: BI.VerticalAlign.Stretch, - items: o.allowSelectAll ? [ - { - type: "bi.select_list", - logic: { - dynamic: true, - innerVgap: 5, - rowSize: ["", "fill"], - verticalAlign: BI.VerticalAlign.Stretch - }, - ref: (_ref) => { - this.popup = _ref; - }, - el: { + type: VerticalLayout.xtype, + verticalAlign: VerticalAlign.Stretch, + items: o.allowSelectAll + ? [ + { + type: SelectList.xtype, + logic: { + dynamic: true, + innerVgap: 5, + rowSize: ["", "fill"], + verticalAlign: VerticalAlign.Stretch, + }, + ref: _ref => { + this.popup = _ref; + }, el: { - chooseType: o.chooseType, - } - }, - items: this._formatItems(o.items), - value: { - type: BI.ButtonGroup.CHOOSE_TYPE_MULTI, - value: o.value - }, - height: "fill", - listeners: [ - { - eventName: BI.SelectList.EVENT_CHANGE, - action: function (val) { - self.fireEvent(BI.TextValueComboPopup.EVENT_CHANGE, val); - } - } - ] - }, { - type: "bi.center", - cls: "list-view-toolbar bi-high-light bi-split-top", - height: 24, - items: BI.createItems([ - { - type: "bi.text_button", - text: BI.i18nText("BI-Basic_Clears"), - handler: function () { - self.fireEvent(BI.TextValueComboPopup.EVENT_CLEAR); - } - }, { - type: "bi.text_button", - text: BI.i18nText("BI-Basic_OK"), - handler: function () { - self.fireEvent(BI.TextValueComboPopup.EVENT_CONFIRM); + el: { + chooseType: o.chooseType, + }, + }, + items: this._formatItems(o.items), + value: { + type: ButtonGroup.CHOOSE_TYPE_MULTI, + value: o.value, + }, + height: "fill", + listeners: [ + { + eventName: SelectList.EVENT_CHANGE, + action (val) { + this.fireEvent( + TextValueComboPopup.EVENT_CHANGE, + val + ); + }, } - } - ], { - once: false, - shadow: true, - isShadowShowingOnSelected: true - }) - } - ] : [ - { - type: "bi.list_pane", - logic: { - dynamic: true, - innerVgap: 5, - rowSize: ["", "fill"], - verticalAlign: BI.VerticalAlign.Stretch - }, - ref: (_ref) => { - this.popup = _ref; - }, - el: { - chooseType: o.chooseType, + ], }, - items: this._formatItems(o.items), - value: o.value, - height: "fill", - listeners: [ - { - eventName: BI.ListPane.EVENT_CHANGE, - action: function (val) { - self.fireEvent(BI.TextValueComboPopup.EVENT_CHANGE, val); + { + type: CenterLayout.xtype, + cls: "list-view-toolbar bi-high-light bi-split-top", + height: 24, + items: createItems( + [ + { + type: TextButton.xtype, + text: i18nText("BI-Basic_Clears"), + handler: () => { + this.fireEvent( + TextValueComboPopup.EVENT_CLEAR + ); + }, + }, + { + type: TextButton.xtype, + text: i18nText("BI-Basic_OK"), + handler: () => { + this.fireEvent( + TextValueComboPopup.EVENT_CONFIRM + ); + }, + } + ], + { + once: false, + shadow: true, + isShadowShowingOnSelected: true, + } + ), + } + ] + : [ + { + type: ListPane.xtype, + logic: { + dynamic: true, + innerVgap: 5, + rowSize: ["", "fill"], + verticalAlign: VerticalAlign.Stretch, + }, + ref: _ref => { + this.popup = _ref; + }, + el: { + chooseType: o.chooseType, + }, + items: this._formatItems(o.items), + value: o.value, + height: "fill", + listeners: [ + { + eventName: ListPane.EVENT_CHANGE, + action: val => { + this.fireEvent( + TextValueComboPopup.EVENT_CHANGE, + val + ); + }, } - } - ] - } - ], + ], + } + ], }; - }, + } - beforeMount: function () { - if (this.options.chooseType !== BI.ButtonGroup.CHOOSE_TYPE_MULTI) { + beforeMount() { + if (this.options.chooseType !== ButtonGroup.CHOOSE_TYPE_MULTI) { this.check(); } - }, + } - _formatItems: function (items) { - var o = this.options; - return BI.map(items, function (i, item) { - return BI.extend({ - type: o.chooseType !== BI.ButtonGroup.CHOOSE_TYPE_MULTI ? "bi.single_select_item" : "bi.multi_select_item", + _formatItems(items) { + const o = this.options; + + return map(items, (i, item) => extend( + { + type: + o.chooseType !== ButtonGroup.CHOOSE_TYPE_MULTI + ? SingleSelectItem.xtype + : MultiSelectItem.xtype, iconWrapperWidth: 36, textAlign: o.textAlign, - title: item.title || item.text - }, item); - }); - }, + title: item.title || item.text, + }, + item + )); + } - populate: function (items) { - BI.TextValueComboPopup.superclass.populate.apply(this, arguments); + populate(items) { + super.populate(...arguments); this.popup.populate(this._formatItems(items)); - }, + } - getValue: function () { - if (this.options.chooseType !== BI.ButtonGroup.CHOOSE_TYPE_MULTI) { + getValue() { + if (this.options.chooseType !== ButtonGroup.CHOOSE_TYPE_MULTI) { return this.popup.getValue(); } - var val = this.popup.getValue(); + const val = this.popup.getValue(); if (!this.options.allowSelectAll) { return val; } - if (val.type === BI.ButtonGroup.CHOOSE_TYPE_MULTI) { + if (val.type === ButtonGroup.CHOOSE_TYPE_MULTI) { return val.value; } else { return val.assist; } - }, + } - setValue: function (v) { - if (this.options.chooseType !== BI.ButtonGroup.CHOOSE_TYPE_MULTI) { + setValue(v) { + if (this.options.chooseType !== ButtonGroup.CHOOSE_TYPE_MULTI) { return this.popup.setValue(v); } if (!this.options.allowSelectAll) { this.popup.setValue(v); + return; } this.popup.setValue({ - type: BI.ButtonGroup.CHOOSE_TYPE_MULTI, - value: v + type: ButtonGroup.CHOOSE_TYPE_MULTI, + value: v, }); } - -}); -BI.TextValueComboPopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.TextValueComboPopup.EVENT_CLEAR = "EVENT_CLEAR"; -BI.TextValueComboPopup.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut("bi.text_value_combo_popup", BI.TextValueComboPopup); +} diff --git a/src/case/index.js b/src/case/index.js index 8892c93e2..29087bd9f 100644 --- a/src/case/index.js +++ b/src/case/index.js @@ -11,8 +11,10 @@ import { MultiSelectBar } from "./toolbar/toolbar.multiselect"; import * as layer from "./layer"; import * as linearSegment from "./linearsegment"; import { SelectList } from "./list/list.select"; +import * as combo from "./combo"; Object.assign(BI, { + ...combo, ...button, ...calendarItem, ...pager, From 842be683c23a6b0dc8161fbeb333bba238fd33a4 Mon Sep 17 00:00:00 2001 From: Treecat Date: Thu, 12 Jan 2023 11:44:59 +0800 Subject: [PATCH 084/300] =?UTF-8?q?KERNEL-14060=20refact:=20combo=E6=B2=A1?= =?UTF-8?q?=E6=9C=89=E5=AF=BC=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/case/index.js | 1 + 1 file changed, 1 insertion(+) diff --git a/src/case/index.js b/src/case/index.js index 29087bd9f..2643f6cf9 100644 --- a/src/case/index.js +++ b/src/case/index.js @@ -30,6 +30,7 @@ Object.assign(BI, { SelectList, }); +export * from "./combo"; export * from "./button"; export * from "./calendar"; export * from "./pager"; From e051b9edcb67d70e8150bc7fb8b1016bcb023b03 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Thu, 12 Jan 2023 11:53:22 +0800 Subject: [PATCH 085/300] =?UTF-8?q?=E6=97=A0JIRA=E4=BB=BB=E5=8A=A1=20fix:?= =?UTF-8?q?=20this=E6=8C=87=E5=90=91=E9=94=99=E8=AF=AF=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/widget/date/calendar/popup.year.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/widget/date/calendar/popup.year.js b/src/widget/date/calendar/popup.year.js index c7b8f0491..872f35a73 100644 --- a/src/widget/date/calendar/popup.year.js +++ b/src/widget/date/calendar/popup.year.js @@ -79,7 +79,7 @@ export class YearPopup extends Widget { }, cardCreator: bind(this._createYearCalendar, this), afterCardCreated: () => { - this.setValue(this.selectedYear); + this.navigation.setValue(this.selectedYear); }, }); From a2ca12a140abfa12d41116b0fafd01ba4721f2b6 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Thu, 12 Jan 2023 14:11:00 +0800 Subject: [PATCH 086/300] KERNEL-14092 refactor: widget/timeinterval --- src/case/calendar/calendar.date.item.js | 8 +- src/case/calendar/calendar.js | 65 +++-- src/case/calendar/calendar.year.js | 52 ++-- src/core/logic/index.js | 26 +- src/widget/dynamicdate/dynamicdate.trigger.js | 4 +- src/widget/timeinterval/dateinterval.js | 259 ++++++++++-------- src/widget/timeinterval/index.js | 3 + src/widget/timeinterval/timeinterval.js | 246 +++++++++-------- src/widget/timeinterval/timeperiods.js | 174 ++++++------ 9 files changed, 442 insertions(+), 395 deletions(-) create mode 100644 src/widget/timeinterval/index.js diff --git a/src/case/calendar/calendar.date.item.js b/src/case/calendar/calendar.date.item.js index 3322de754..b1b4ef5c5 100644 --- a/src/case/calendar/calendar.date.item.js +++ b/src/case/calendar/calendar.date.item.js @@ -1,9 +1,9 @@ +import { shortcut } from "@/core"; +import { BasicButton } from "@/base"; + /** * 专门为calendar的视觉加的button,作为私有button,不能配置任何属性,也不要用这个玩意 */ - -import { shortcut } from "@/core"; -import { BasicButton } from "@/base"; @shortcut() export class CalendarDateItem extends BasicButton { props() { @@ -17,7 +17,7 @@ export class CalendarDateItem extends BasicButton { render () { const { text, value, lgap, rgap, tgap, bgap } = this.options; - + return { type: "bi.absolute", items: [{ diff --git a/src/case/calendar/calendar.js b/src/case/calendar/calendar.js index da9a41442..b656a271e 100644 --- a/src/case/calendar/calendar.js +++ b/src/case/calendar/calendar.js @@ -1,12 +1,41 @@ +import { shortcut, Widget, getDate, each, range, extend, isLeapYear, Date, StartOfWeek, checkDateVoid, map, createWidget, createItems, LogicFactory, Controller, getShortDayName, getOffsetDate, isNotEmptyString, parseInt } from "@/core"; + /** * Created by GUY on 2015/8/28. - * @class BI.Calendar - * @extends BI.Widget + * @class Calendar + * @extends Widget */ -import { shortcut, Widget, getDate, each, range, extend, isLeapYear, Date, StartOfWeek, checkDateVoid, map, createWidget, createItems, LogicFactory, Controller, getShortDayName, getOffsetDate, isNotEmptyString, parseInt } from "@/core"; @shortcut() export class Calendar extends Widget { static xtype = "bi.calendar"; + + static getPageByDateJSON (json) { + const year = getDate().getFullYear(); + const month = getDate().getMonth(); + let page = (json.year - year) * 12; + page += json.month - 1 - month; + + return page; + } + + static getDateJSONByPage (v) { + const months = getDate().getMonth(); + let page = v; + + // 对当前page做偏移,使到当前年初 + page = page + months; + + let year = parseInt(page / 12); + if (page < 0 && page % 12 !== 0) { + year--; + } + const month = page >= 0 ? (page % 12) : ((12 + page % 12) % 12); + + return { + year: getDate().getFullYear() + year, + month: month + 1, + }; + } _defaultConfig () { const conf = super._defaultConfig(...arguments); @@ -222,33 +251,3 @@ export class Calendar extends Widget { }; } } - -extend(Calendar, { - getPageByDateJSON (json) { - const year = getDate().getFullYear(); - const month = getDate().getMonth(); - let page = (json.year - year) * 12; - page += json.month - 1 - month; - - return page; - }, - getDateJSONByPage (v) { - const months = getDate().getMonth(); - let page = v; - - // 对当前page做偏移,使到当前年初 - page = page + months; - - let year = parseInt(page / 12); - if (page < 0 && page % 12 !== 0) { - year--; - } - const month = page >= 0 ? (page % 12) : ((12 + page % 12) % 12); - - return { - year: getDate().getFullYear() + year, - month: month + 1, - }; - }, -}); - diff --git a/src/case/calendar/calendar.year.js b/src/case/calendar/calendar.year.js index 4c782da5b..c8ebc58b0 100644 --- a/src/case/calendar/calendar.year.js +++ b/src/case/calendar/calendar.year.js @@ -1,12 +1,33 @@ +import { shortcut, Widget, extend, parseDateTime, range, checkDateVoid, print, getDate, each, createWidget, createItems, LogicFactory, Controller, makeArray, map, isNotEmptyString } from "@/core"; + /** * Created by GUY on 2015/8/28. - * @class BI.YearCalendar - * @extends BI.Widget + * @class YearCalendar + * @extends Widget */ -import { shortcut, Widget, extend, parseDateTime, range, checkDateVoid, print, getDate, each, createWidget, createItems, LogicFactory, Controller, makeArray, map, isNotEmptyString } from "@/core"; @shortcut() export class YearCalendar extends Widget { static xtype = "bi.year_calendar"; + static INTERVAL = 12; + + // 获取显示的第一年 + static getStartYear (year) { + const cur = getDate().getFullYear(); + + return year - ((year - cur + 3) % YearCalendar.INTERVAL + 12) % YearCalendar.INTERVAL; + } + + static getEndYear (year) { + return YearCalendar.getStartYear(year) + YearCalendar.INTERVAL - 1; + } + + static getPageByYear (year) { + const cur = getDate().getFullYear(); + year = YearCalendar.getStartYear(year); + + return (year - cur + 3) / YearCalendar.INTERVAL; + } + _defaultConfig () { const conf = super._defaultConfig(...arguments); @@ -150,28 +171,3 @@ export class YearCalendar extends Widget { return this.years.getValue()[0]; } } - -// 类方法 -extend(YearCalendar, { - INTERVAL: 12, - - // 获取显示的第一年 - getStartYear (year) { - const cur = getDate().getFullYear(); - - return year - ((year - cur + 3) % YearCalendar.INTERVAL + 12) % YearCalendar.INTERVAL; - }, - - getEndYear (year) { - return YearCalendar.getStartYear(year) + YearCalendar.INTERVAL - 1; - }, - - getPageByYear (year) { - const cur = getDate().getFullYear(); - year = YearCalendar.getStartYear(year); - - return (year - cur + 3) / YearCalendar.INTERVAL; - }, -}); - - diff --git a/src/core/logic/index.js b/src/core/logic/index.js index 0397ce345..5b04dfe21 100644 --- a/src/core/logic/index.js +++ b/src/core/logic/index.js @@ -1,3 +1,5 @@ +import { map, isWidget } from "../2.base"; +import { Direction } from "../constant"; import { Logic } from "./logic"; import { VerticalLayoutLogic, HorizontalLayoutLogic, TableLayoutLogic, HorizontalFillLayoutLogic } from "./logic.layout"; @@ -33,21 +35,21 @@ export const LogicFactory = { createLogicTypeByDirection (direction) { switch (direction) { - case BI.Direction.Top: - case BI.Direction.Bottom: - case BI.Direction.Custom: - return BI.LogicFactory.Type.Vertical; - case BI.Direction.Left: - case BI.Direction.Right: - return BI.LogicFactory.Type.Horizontal; + case Direction.Top: + case Direction.Bottom: + case Direction.Custom: + return LogicFactory.Type.Vertical; + case Direction.Left: + case Direction.Right: + return LogicFactory.Type.Horizontal; default: } }, createLogicItemsByDirection (direction) { let items = Array.prototype.slice.call(arguments, 1); - items = BI.map(items, (i, item) => { - if (BI.isWidget(item)) { + items = map(items, (i, item) => { + if (isWidget(item)) { return { el: item, width: item.options.width, @@ -58,13 +60,13 @@ export const LogicFactory = { return item; }); switch (direction) { - case BI.Direction.Bottom: + case Direction.Bottom: items.reverse(); break; - case BI.Direction.Right: + case Direction.Right: items.reverse(); break; - case BI.Direction.Custom: + case Direction.Custom: items = items.slice(1); break; default: diff --git a/src/widget/dynamicdate/dynamicdate.trigger.js b/src/widget/dynamicdate/dynamicdate.trigger.js index 8e24b81d5..adad56bf7 100644 --- a/src/widget/dynamicdate/dynamicdate.trigger.js +++ b/src/widget/dynamicdate/dynamicdate.trigger.js @@ -303,16 +303,16 @@ export class DynamicDateTrigger extends Trigger { } setValue(v) { - let type, value; + let type, value, text; let date = getDate(); this.storeValue = v; if (isNotNull(v)) { type = v.type || DynamicDateCombo.Static; value = v.value || v; } - const text = this._getText(value); switch (type) { case DynamicDateCombo.Dynamic: + text = this._getText(value); date = DynamicDateHelper.getCalculation(value); this._setInnerValue(date, text); break; diff --git a/src/widget/timeinterval/dateinterval.js b/src/widget/timeinterval/dateinterval.js index 2da77de8b..a591d4a4d 100644 --- a/src/widget/timeinterval/dateinterval.js +++ b/src/widget/timeinterval/dateinterval.js @@ -1,27 +1,39 @@ -/** - * Created by Baron on 2015/10/19. - */ -BI.DateInterval = BI.inherit(BI.Single, { - constants: { +import { shortcut, extend, createWidget, i18nText, print, parseDateTime, checkDateVoid, checkDateLegal, isNotNull } from "@/core"; +import { Single, Label, Bubbles } from "@/base"; +import { DynamicDateCombo } from "../dynamicdate"; + +@shortcut() +export class DateInterval extends Single { + static xtype = "bi.date_interval" + + constants = { height: 24, width: 24, lgap: 15, offset: 0, - timeErrorCls: "time-error" - }, - _defaultConfig: function () { - var conf = BI.DateInterval.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { + timeErrorCls: "time-error", + }; + + static EVENT_VALID = "EVENT_VALID" + static EVENT_ERROR = "EVENT_ERROR" + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW" + + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { extraCls: "bi-date-interval", minDate: "1900-01-01", maxDate: "2099-12-31", height: 24, supportDynamic: true, }); - }, - - render: function () { - var self = this, o = this.options; + } + + render() { + const o = this.options; o.value = o.value || {}; this.left = this._createCombo(o.value.start, o.watermark?.start); this.right = this._createCombo(o.value.end, o.watermark?.end); @@ -30,164 +42,177 @@ BI.DateInterval = BI.inherit(BI.Single, { type: "bi.horizontal_fill", columnSize: ["fill", "", "fill"], items: [{ - el: self.left + el: this.left, }, { el: { - type: "bi.label", + type: Label.xtype, height: o.height, hgap: 5, text: "-", - ref: function (_ref) { - self.label = _ref; - } - } + ref: _ref => { + this.label = _ref; + }, + }, }, { - el: self.right - }] + el: this.right, + }], }; - }, + } - _createCombo: function (v, watermark) { - var self = this, o = this.options; - var combo = BI.createWidget({ - type: "bi.dynamic_date_combo", + _createCombo(v, watermark) { + const o = this.options; + const combo = createWidget({ + type: DynamicDateCombo.xtype, supportDynamic: o.supportDynamic, minDate: o.minDate, maxDate: o.maxDate, simple: o.simple, behaviors: o.behaviors, - watermark: watermark, + watermark, value: v, height: o.height, listeners: [{ - eventName: BI.DynamicDateCombo.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW, - action: function () { - self.fireEvent(BI.DateInterval.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); - } - }] + eventName: DynamicDateCombo.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW, + action: () => { + this.fireEvent(DateInterval.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW); + }, + }], }); - combo.on(BI.DynamicDateCombo.EVENT_ERROR, function () { - self._clearTitle(); - BI.Bubbles.hide("error"); - self.element.removeClass(self.constants.timeErrorCls); - self.fireEvent(BI.DateInterval.EVENT_ERROR); + combo.on(DynamicDateCombo.EVENT_ERROR, () => { + this._clearTitle(); + Bubbles.hide("error"); + this.element.removeClass(this.constants.timeErrorCls); + this.fireEvent(DateInterval.EVENT_ERROR); }); - combo.on(BI.DynamicDateCombo.EVENT_VALID, function () { - BI.Bubbles.hide("error"); - var smallDate = self.left.getKey(), bigDate = self.right.getKey(); - if (self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { - self._setTitle(BI.i18nText("BI-Time_Interval_Error_Text")); - self.element.addClass(self.constants.timeErrorCls); - BI.Bubbles.show("error", BI.i18nText("BI-Time_Interval_Error_Text"), self, { - offsetStyle: "center" + combo.on(DynamicDateCombo.EVENT_VALID, () => { + Bubbles.hide("error"); + const smallDate = this.left.getKey(), + bigDate = this.right.getKey(); + if (this._check(smallDate, bigDate) && this._compare(smallDate, bigDate)) { + this._setTitle(i18nText("BI-Time_Interval_Error_Text")); + this.element.addClass(this.constants.timeErrorCls); + Bubbles.show("error", i18nText("BI-Time_Interval_Error_Text"), this, { + offsetStyle: "center", }); - self.fireEvent(BI.DateInterval.EVENT_ERROR); + this.fireEvent(DateInterval.EVENT_ERROR); } else { - self._clearTitle(); - self.element.removeClass(self.constants.timeErrorCls); + this._clearTitle(); + this.element.removeClass(this.constants.timeErrorCls); } }); - combo.on(BI.DynamicDateCombo.EVENT_FOCUS, function () { - BI.Bubbles.hide("error"); - var smallDate = self.left.getKey(), bigDate = self.right.getKey(); - if (self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { - self._setTitle(BI.i18nText("BI-Time_Interval_Error_Text")); - self.element.addClass(self.constants.timeErrorCls); - BI.Bubbles.show("error", BI.i18nText("BI-Time_Interval_Error_Text"), self, { - offsetStyle: "center" + combo.on(DynamicDateCombo.EVENT_FOCUS, () => { + Bubbles.hide("error"); + const smallDate = this.left.getKey(), + bigDate = this.right.getKey(); + if (this._check(smallDate, bigDate) && this._compare(smallDate, bigDate)) { + this._setTitle(i18nText("BI-Time_Interval_Error_Text")); + this.element.addClass(this.constants.timeErrorCls); + Bubbles.show("error", i18nText("BI-Time_Interval_Error_Text"), this, { + offsetStyle: "center", }); - self.fireEvent(BI.DateInterval.EVENT_ERROR); + this.fireEvent(DateInterval.EVENT_ERROR); } else { - self._clearTitle(); - self.element.removeClass(self.constants.timeErrorCls); + this._clearTitle(); + this.element.removeClass(this.constants.timeErrorCls); } }); - // combo.on(BI.DynamicDateCombo.EVENT_BEFORE_POPUPVIEW, function () { - // self.left.hidePopupView(); - // self.right.hidePopupView(); + // combo.on(DynamicDateCombo.EVENT_BEFORE_POPUPVIEW, () => { + // this.left.hidePopupView(); + // this.right.hidePopupView(); // }); - combo.on(BI.DynamicDateCombo.EVENT_CONFIRM, function () { - BI.Bubbles.hide("error"); - var smallDate = self.left.getKey(), bigDate = self.right.getKey(); - if (self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { - self._setTitle(BI.i18nText("BI-Time_Interval_Error_Text")); - self.element.addClass(self.constants.timeErrorCls); - self.fireEvent(BI.DateInterval.EVENT_ERROR); - }else{ - self._clearTitle(); - self.element.removeClass(self.constants.timeErrorCls); - self.fireEvent(BI.DateInterval.EVENT_CHANGE); + combo.on(DynamicDateCombo.EVENT_CONFIRM, () => { + Bubbles.hide("error"); + const smallDate = this.left.getKey(), + bigDate = this.right.getKey(); + if (this._check(smallDate, bigDate) && this._compare(smallDate, bigDate)) { + this._setTitle(i18nText("BI-Time_Interval_Error_Text")); + this.element.addClass(this.constants.timeErrorCls); + this.fireEvent(DateInterval.EVENT_ERROR); + } else { + this._clearTitle(); + this.element.removeClass(this.constants.timeErrorCls); + this.fireEvent(DateInterval.EVENT_CHANGE); } }); + return combo; - }, - _dateCheck: function (date) { - return BI.print(BI.parseDateTime(date, "%Y-%x-%d"), "%Y-%x-%d") === date || - BI.print(BI.parseDateTime(date, "%Y-%X-%d"), "%Y-%X-%d") === date || - BI.print(BI.parseDateTime(date, "%Y-%x-%e"), "%Y-%x-%e") === date || - BI.print(BI.parseDateTime(date, "%Y-%X-%e"), "%Y-%X-%e") === date; - }, - _checkVoid: function (obj) { - var o = this.options; - return !BI.checkDateVoid(obj.year, obj.month, obj.day, o.minDate, o.maxDate)[0]; - }, - _check: function (smallDate, bigDate) { - var smallObj = smallDate.match(/\d+/g), bigObj = bigDate.match(/\d+/g); - return this._dateCheck(smallDate) && BI.checkDateLegal(smallDate) && this._checkVoid({ + } + + _dateCheck(date) { + return print(parseDateTime(date, "%Y-%x-%d"), "%Y-%x-%d") === date || + print(parseDateTime(date, "%Y-%X-%d"), "%Y-%X-%d") === date || + print(parseDateTime(date, "%Y-%x-%e"), "%Y-%x-%e") === date || + print(parseDateTime(date, "%Y-%X-%e"), "%Y-%X-%e") === date; + } + + _checkVoid(obj) { + const o = this.options; + + return !checkDateVoid(obj.year, obj.month, obj.day, o.minDate, o.maxDate)[0]; + } + + _check(smallDate, bigDate) { + const smallObj = smallDate.match(/\d+/g), + bigObj = bigDate.match(/\d+/g); + + return this._dateCheck(smallDate) && checkDateLegal(smallDate) && this._checkVoid({ year: smallObj[0], month: smallObj[1], - day: smallObj[2] - }) && this._dateCheck(bigDate) && BI.checkDateLegal(bigDate) && this._checkVoid({ + day: smallObj[2], + }) && this._dateCheck(bigDate) && checkDateLegal(bigDate) && this._checkVoid({ year: bigObj[0], month: bigObj[1], - day: bigObj[2] + day: bigObj[2], }); - }, - _compare: function (smallDate, bigDate) { - smallDate = BI.print(BI.parseDateTime(smallDate, "%Y-%X-%d"), "%Y-%X-%d"); - bigDate = BI.print(BI.parseDateTime(bigDate, "%Y-%X-%d"), "%Y-%X-%d"); - return BI.isNotNull(smallDate) && BI.isNotNull(bigDate) && smallDate > bigDate; - }, - _setTitle: function (v) { + } + + _compare(smallDate, bigDate) { + smallDate = print(parseDateTime(smallDate, "%Y-%X-%d"), "%Y-%X-%d"); + bigDate = print(parseDateTime(bigDate, "%Y-%X-%d"), "%Y-%X-%d"); + + return isNotNull(smallDate) && isNotNull(bigDate) && smallDate > bigDate; + } + + _setTitle(v) { this.left.setTitle(v); this.right.setTitle(v); this.label.setTitle(v); - }, - _clearTitle: function () { + } + + _clearTitle() { this.left.setTitle(""); this.right.setTitle(""); this.label.setTitle(""); - }, + } - setMinDate: function (minDate) { - var o = this.options; + setMinDate(minDate) { + const o = this.options; o.minDate = minDate; this.left.setMinDate(minDate); this.right.setMinDate(minDate); - }, + } - setMaxDate: function (maxDate) { - var o = this.options; + setMaxDate(maxDate) { + const o = this.options; o.maxDate = maxDate; this.left.setMaxDate(maxDate); this.right.setMaxDate(maxDate); - }, + } - setValue: function (date) { + setValue(date) { date = date || {}; this.left.setValue(date.start); this.right.setValue(date.end); - }, - getValue: function () { - return {start: this.left.getValue(), end: this.right.getValue()}; } -}); -BI.DateInterval.EVENT_VALID = "EVENT_VALID"; -BI.DateInterval.EVENT_ERROR = "EVENT_ERROR"; -BI.DateInterval.EVENT_CHANGE = "EVENT_CHANGE"; -BI.DateInterval.EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW"; -BI.shortcut("bi.date_interval", BI.DateInterval); + + getValue() { + return { + start: this.left.getValue(), + end: this.right.getValue(), + }; + } +} diff --git a/src/widget/timeinterval/index.js b/src/widget/timeinterval/index.js new file mode 100644 index 000000000..58eb61b77 --- /dev/null +++ b/src/widget/timeinterval/index.js @@ -0,0 +1,3 @@ +export { DateInterval } from "./dateinterval"; +export { TimeInterval } from "./timeinterval"; +export { TimePeriods } from "./timeperiods"; diff --git a/src/widget/timeinterval/timeinterval.js b/src/widget/timeinterval/timeinterval.js index c22c8e14e..23ca310e3 100644 --- a/src/widget/timeinterval/timeinterval.js +++ b/src/widget/timeinterval/timeinterval.js @@ -1,27 +1,37 @@ -/** - * Created by Baron on 2015/10/19. - */ -BI.TimeInterval = BI.inherit(BI.Single, { - constants: { +import { shortcut, extend, createWidget, i18nText, print, parseDateTime, checkDateVoid, checkDateLegal, isNotNull } from "@/core"; +import { Single, Label, Bubbles } from "@/base"; +import { DynamicDateTimeCombo } from "../dynamicdatetime"; + +@shortcut() +export class TimeInterval extends Single { + static xtype = "bi.time_interval" + + constants = { height: 24, width: 24, lgap: 15, offset: 0, - timeErrorCls: "time-error" - }, - _defaultConfig: function () { - var conf = BI.TimeInterval.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { + timeErrorCls: "time-error", + }; + + static EVENT_VALID = "EVENT_VALID" + static EVENT_ERROR = "EVENT_ERROR" + static EVENT_CHANGE = "EVENT_CHANGE" + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { extraCls: "bi-time-interval", minDate: "1900-01-01", maxDate: "2099-12-31", height: 24, - supportDynamic: true + supportDynamic: true, }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; o.value = o.value || {}; this.left = this._createCombo(o.value.start, o.watermark?.start); this.right = this._createCombo(o.value.end, o.watermark?.end); @@ -30,158 +40,172 @@ BI.TimeInterval = BI.inherit(BI.Single, { type: "bi.horizontal_fill", columnSize: ["fill", "", "fill"], items: [{ - el: self.left + el: this.left, }, { el: { - type: "bi.label", + type: Label.xtype, height: o.height, hgap: 5, text: "-", - ref: function (_ref) { - self.label = _ref; - } - } + ref: _ref => { + this.label = _ref; + }, + }, }, { - el: self.right - }] + el: this.right, + }], }; - }, + } - _createCombo: function (v, watermark) { - var self = this, o = this.options; - var combo = BI.createWidget({ - type: "bi.dynamic_date_time_combo", + _createCombo(v, watermark) { + const o = this.options; + const combo = createWidget({ + type: DynamicDateTimeCombo.xtype, simple: o.simple, supportDynamic: o.supportDynamic, minDate: o.minDate, maxDate: o.maxDate, behaviors: o.behaviors, - watermark: watermark, + watermark, value: v, height: o.height, }); - combo.on(BI.DynamicDateTimeCombo.EVENT_ERROR, function () { - self._clearTitle(); - BI.Bubbles.hide("error"); - self.element.removeClass(self.constants.timeErrorCls); - self.fireEvent(BI.TimeInterval.EVENT_ERROR); + combo.on(DynamicDateTimeCombo.EVENT_ERROR, () => { + this._clearTitle(); + Bubbles.hide("error"); + this.element.removeClass(this.constants.timeErrorCls); + this.fireEvent(TimeInterval.EVENT_ERROR); }); - combo.on(BI.DynamicDateTimeCombo.EVENT_VALID, function () { - BI.Bubbles.hide("error"); - var smallDate = self.left.getKey(), bigDate = self.right.getKey(); - if (self.left.isValid() && self.right.isValid() && self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { - self._setTitle(BI.i18nText("BI-Time_Interval_Error_Text")); - self.element.addClass(self.constants.timeErrorCls); - BI.Bubbles.show("error", BI.i18nText("BI-Time_Interval_Error_Text"), self, { - offsetStyle: "center" + combo.on(DynamicDateTimeCombo.EVENT_VALID, () => { + Bubbles.hide("error"); + const smallDate = this.left.getKey(), + bigDate = this.right.getKey(); + if (this.left.isValid() && this.right.isValid() && this._check(smallDate, bigDate) && this._compare(smallDate, bigDate)) { + this._setTitle(i18nText("BI-Time_Interval_Error_Text")); + this.element.addClass(this.constants.timeErrorCls); + Bubbles.show("error", i18nText("BI-Time_Interval_Error_Text"), this, { + offsetStyle: "center", }); - self.fireEvent(BI.TimeInterval.EVENT_ERROR); + this.fireEvent(TimeInterval.EVENT_ERROR); } else { - self._clearTitle(); - self.element.removeClass(self.constants.timeErrorCls); + this._clearTitle(); + this.element.removeClass(this.constants.timeErrorCls); } }); - combo.on(BI.DynamicDateTimeCombo.EVENT_FOCUS, function () { - BI.Bubbles.hide("error"); - var smallDate = self.left.getKey(), bigDate = self.right.getKey(); - if (self.left.isValid() && self.right.isValid() && self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { - self._setTitle(BI.i18nText("BI-Time_Interval_Error_Text")); - self.element.addClass(self.constants.timeErrorCls); - BI.Bubbles.show("error", BI.i18nText("BI-Time_Interval_Error_Text"), self, { - offsetStyle: "center" + combo.on(DynamicDateTimeCombo.EVENT_FOCUS, () => { + Bubbles.hide("error"); + const smallDate = this.left.getKey(), + bigDate = this.right.getKey(); + if (this.left.isValid() && this.right.isValid() && this._check(smallDate, bigDate) && this._compare(smallDate, bigDate)) { + this._setTitle(i18nText("BI-Time_Interval_Error_Text")); + this.element.addClass(this.constants.timeErrorCls); + Bubbles.show("error", i18nText("BI-Time_Interval_Error_Text"), this, { + offsetStyle: "center", }); - self.fireEvent(BI.TimeInterval.EVENT_ERROR); + this.fireEvent(TimeInterval.EVENT_ERROR); } else { - self._clearTitle(); - self.element.removeClass(self.constants.timeErrorCls); + this._clearTitle(); + this.element.removeClass(this.constants.timeErrorCls); } }); // 不知道干啥的,先注释掉 - // combo.on(BI.DynamicDateTimeCombo.EVENT_BEFORE_POPUPVIEW, function () { - // self.left.hidePopupView(); - // self.right.hidePopupView(); + // combo.on(DynamicDateTimeCombo.EVENT_BEFORE_POPUPVIEW, () => { + // this.left.hidePopupView(); + // this.right.hidePopupView(); // }); - combo.on(BI.DynamicDateTimeCombo.EVENT_CONFIRM, function () { - BI.Bubbles.hide("error"); - var smallDate = self.left.getKey(), bigDate = self.right.getKey(); - if (self.left.isValid() && self.right.isValid() && self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { - self._setTitle(BI.i18nText("BI-Time_Interval_Error_Text")); - self.element.addClass(self.constants.timeErrorCls); - self.fireEvent(BI.TimeInterval.EVENT_ERROR); - }else{ - self._clearTitle(); - self.element.removeClass(self.constants.timeErrorCls); - self.fireEvent(BI.TimeInterval.EVENT_CHANGE); + combo.on(DynamicDateTimeCombo.EVENT_CONFIRM, () => { + Bubbles.hide("error"); + const smallDate = this.left.getKey(), + bigDate = this.right.getKey(); + if (this.left.isValid() && this.right.isValid() && this._check(smallDate, bigDate) && this._compare(smallDate, bigDate)) { + this._setTitle(i18nText("BI-Time_Interval_Error_Text")); + this.element.addClass(this.constants.timeErrorCls); + this.fireEvent(TimeInterval.EVENT_ERROR); + } else { + this._clearTitle(); + this.element.removeClass(this.constants.timeErrorCls); + this.fireEvent(TimeInterval.EVENT_CHANGE); } }); + return combo; - }, - _dateCheck: function (date) { - return BI.print(BI.parseDateTime(date, "%Y-%x-%d %H:%M:%S"), "%Y-%x-%d %H:%M:%S") === date || - BI.print(BI.parseDateTime(date, "%Y-%X-%d %H:%M:%S"), "%Y-%X-%d %H:%M:%S") === date || - BI.print(BI.parseDateTime(date, "%Y-%x-%e %H:%M:%S"), "%Y-%x-%e %H:%M:%S") === date || - BI.print(BI.parseDateTime(date, "%Y-%X-%e %H:%M:%S"), "%Y-%X-%e %H:%M:%S") === date; - }, - _checkVoid: function (obj) { - var o = this.options; - return !BI.checkDateVoid(obj.year, obj.month, obj.day, o.minDate, o.maxDate)[0]; - }, - _check: function (smallDate, bigDate) { - var smallObj = smallDate.match(/\d+/g), bigObj = bigDate.match(/\d+/g); - return this._dateCheck(smallDate) && BI.checkDateLegal(smallDate) && this._checkVoid({ + } + + _dateCheck(date) { + return print(parseDateTime(date, "%Y-%x-%d %H:%M:%S"), "%Y-%x-%d %H:%M:%S") === date || + print(parseDateTime(date, "%Y-%X-%d %H:%M:%S"), "%Y-%X-%d %H:%M:%S") === date || + print(parseDateTime(date, "%Y-%x-%e %H:%M:%S"), "%Y-%x-%e %H:%M:%S") === date || + print(parseDateTime(date, "%Y-%X-%e %H:%M:%S"), "%Y-%X-%e %H:%M:%S") === date; + } + + _checkVoid(obj) { + const o = this.options; + + return !checkDateVoid(obj.year, obj.month, obj.day, o.minDate, o.maxDate)[0]; + } + + _check(smallDate, bigDate) { + const smallObj = smallDate.match(/\d+/g), + bigObj = bigDate.match(/\d+/g); + + return this._dateCheck(smallDate) && checkDateLegal(smallDate) && this._checkVoid({ year: smallObj[0], month: smallObj[1], - day: smallObj[2] - }) && this._dateCheck(bigDate) && BI.checkDateLegal(bigDate) && this._checkVoid({ + day: smallObj[2], + }) && this._dateCheck(bigDate) && checkDateLegal(bigDate) && this._checkVoid({ year: bigObj[0], month: bigObj[1], - day: bigObj[2] + day: bigObj[2], }); - }, - _compare: function (smallDate, bigDate) { - smallDate = BI.print(BI.parseDateTime(smallDate, "%Y-%X-%d %H:%M:%S"), "%Y-%X-%d %H:%M:%S"); - bigDate = BI.print(BI.parseDateTime(bigDate, "%Y-%X-%d %H:%M:%S"), "%Y-%X-%d %H:%M:%S"); - return BI.isNotNull(smallDate) && BI.isNotNull(bigDate) && smallDate > bigDate; - }, - _setTitle: function (v) { + } + + _compare(smallDate, bigDate) { + smallDate = print(parseDateTime(smallDate, "%Y-%X-%d %H:%M:%S"), "%Y-%X-%d %H:%M:%S"); + bigDate = print(parseDateTime(bigDate, "%Y-%X-%d %H:%M:%S"), "%Y-%X-%d %H:%M:%S"); + + return isNotNull(smallDate) && isNotNull(bigDate) && smallDate > bigDate; + } + + _setTitle(v) { this.left.setTitle(v); this.right.setTitle(v); this.label.setTitle(v); - }, - _clearTitle: function () { + } + + _clearTitle() { this.left.setTitle(""); this.right.setTitle(""); this.label.setTitle(""); - }, + } - setMinDate: function (minDate) { - var o = this.options; + setMinDate(minDate) { + const o = this.options; o.minDate = minDate; this.left.setMinDate(minDate); this.right.setMinDate(minDate); - }, + } - setMaxDate: function (maxDate) { - var o = this.options; + setMaxDate(maxDate) { + const o = this.options; o.maxDate = maxDate; this.left.setMaxDate(maxDate); this.right.setMaxDate(maxDate); - }, + } - setValue: function (date) { + setValue(date) { date = date || {}; this.left.setValue(date.start); this.right.setValue(date.end); - }, - getValue: function () { - return {start: this.left.getValue(), end: this.right.getValue()}; } -}); -BI.TimeInterval.EVENT_VALID = "EVENT_VALID"; -BI.TimeInterval.EVENT_ERROR = "EVENT_ERROR"; -BI.TimeInterval.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.time_interval", BI.TimeInterval); + + getValue() { + return { + start: this.left.getValue(), + end: this.right.getValue(), + }; + } +} diff --git a/src/widget/timeinterval/timeperiods.js b/src/widget/timeinterval/timeperiods.js index a8bb9e60b..1eb2cef6a 100644 --- a/src/widget/timeinterval/timeperiods.js +++ b/src/widget/timeinterval/timeperiods.js @@ -1,92 +1,90 @@ -/** - * 时间区间 - * qcc - * 2019/2/28 - */ +import { shortcut, extend } from "@/core"; +import { Single, Label } from "@/base"; +import { TimeCombo } from "../time"; + +@shortcut() +export class TimePeriods extends Single { + static xtype = "bi.time_periods" + + props = { + extraCls: "bi-time-interval", + value: {}, + }; + + static EVENT_CONFIRM = "EVENT_CONFIRM" + static EVENT_CHANGE = "EVENT_CHANGE" -!(function () { - BI.TimePeriods = BI.inherit(BI.Single, { - constants: { - height: 24, - width: 24, - hgap: 15, - offset: -15 - }, - props: { - extraCls: "bi-time-interval", - value: {} - }, - - render: function () { - var self = this, o = this.options; - return { - type: "bi.horizontal_fill", - columnSize: ["fill", "", "fill"], - items: [{ - el: BI.extend({ - ref: function (_ref) { - self.left = _ref; - } - }, this._createCombo(o.value.start, o.watermark?.start)) - }, { - el: { - type: "bi.label", - height: o.height, - hgap: 5, - text: "-", - ref: function (_ref) { - self.label = _ref; - } - } - }, { - el: BI.extend({ - ref: function (_ref) { - self.right = _ref; - } - }, this._createCombo(o.value.end, o.watermark?.end)) - }] - }; - }, + render() { + const o = this.options; + + return { + type: "bi.horizontal_fill", + columnSize: ["fill", "", "fill"], + items: [{ + el: extend({ + ref: _ref => { + this.left = _ref; + }, + }, this._createCombo(o.value.start, o.watermark?.start)), + }, { + el: { + type: Label.xtype, + height: o.height, + hgap: 5, + text: "-", + ref: _ref => { + this.label = _ref; + }, + }, + }, { + el: extend({ + ref: _ref => { + this.right = _ref; + }, + }, this._createCombo(o.value.end, o.watermark?.end)), + }], + }; + } + + _createCombo(v, watermark) { + const o = this.options; + + return { + type: TimeCombo.xtype, + value: v, + height: o.height, + watermark, + listeners: [{ + eventName: TimeCombo.EVENT_BEFORE_POPUPVIEW, + action: () => { + this.left.hidePopupView(); + this.right.hidePopupView(); + }, + }, { + eventName: TimeCombo.EVENT_CHANGE, + action: () => { + this.fireEvent(TimePeriods.EVENT_CHANGE); + }, + }, { + eventName: TimeCombo.EVENT_CONFIRM, + action: () => { + this.fireEvent(TimePeriods.EVENT_CONFIRM); + }, + }], + }; + } - _createCombo: function (v, watermark) { - var self = this; - var o = this.options; - return { - type: "bi.time_combo", - value: v, - height: o.height, - watermark: watermark, - listeners: [{ - eventName: BI.TimeCombo.EVENT_BEFORE_POPUPVIEW, - action: function () { - self.left.hidePopupView(); - self.right.hidePopupView(); - } - }, { - eventName: BI.TimeCombo.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.TimePeriods.EVENT_CHANGE); - } - }, { - eventName: BI.TimeCombo.EVENT_CONFIRM, - action: function () { - self.fireEvent(BI.TimePeriods.EVENT_CONFIRM); - } - }] - }; - }, + setValue(date) { + date = date || {}; + this.left.setValue(date.start); + this.right.setValue(date.end); + } - setValue: function (date) { - date = date || {}; - this.left.setValue(date.start); - this.right.setValue(date.end); - }, - getValue: function () { - return {start: this.left.getValue(), end: this.right.getValue()}; - } - }); - BI.TimePeriods.EVENT_CONFIRM = "EVENT_CONFIRM"; - BI.TimePeriods.EVENT_CHANGE = "EVENT_CHANGE"; - BI.shortcut("bi.time_periods", BI.TimePeriods); -})(); + getValue() { + return { + start: this.left.getValue(), + end: this.right.getValue(), + }; + } +} From 085b5c34e1824d956a88e38b46409a94353f3388 Mon Sep 17 00:00:00 2001 From: zsmj Date: Thu, 12 Jan 2023 14:29:45 +0800 Subject: [PATCH 087/300] =?UTF-8?q?KERNEL-14086=20feat:=20widget/singletre?= =?UTF-8?q?e=E3=80=81selecttree?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.js | 3 + .../__test__/multiselect.loader.nobar.test.js | 175 +++-- .../__test__/multiselect.loader.test.js | 2 +- .../__test__/multiselectcombo.test.js | 2 +- .../__test__/multiselectinsert.combo.test.js | 2 +- .../check/multiselect.check.pane.js | 154 +++-- .../multiselect/check/multiselect.display.js | 106 +-- src/widget/multiselect/loader.js | 337 +++++---- src/widget/multiselect/multiselect.combo.js | 610 +++++++++-------- .../multiselect/multiselect.combo.nobar.js | 620 +++++++++-------- .../multiselect/multiselect.insert.combo.js | 643 ++++++++++-------- .../multiselect.insert.combo.nobar.js | 635 +++++++++-------- .../multiselect/multiselect.insert.trigger.js | 190 +++--- src/widget/multiselect/multiselect.loader.js | 262 ++++--- .../multiselect/multiselect.loader.nobar.js | 315 +++++---- .../multiselect/multiselect.popup.view.js | 133 ++-- .../multiselect.popup.view.nobar.js | 127 ++-- src/widget/multiselect/multiselect.trigger.js | 48 +- .../search/multiselect.search.insert.pane.js | 142 ++-- .../search/multiselect.search.loader.js | 205 +++--- .../search/multiselect.search.pane.js | 120 ++-- .../trigger/button.checkselected.js | 14 +- .../multiselect/trigger/editor.multiselect.js | 7 +- .../trigger/editor/editor.patch.js | 324 +++++---- .../trigger/searcher.multiselect.insert.js | 277 ++++---- .../trigger/searcher.multiselect.js | 28 +- .../trigger/switcher.checkselected.js | 12 +- src/widget/multitree/multi.tree.combo.js | 4 +- .../multitree/multi.tree.insert.combo.js | 30 +- src/widget/multitree/multi.tree.list.combo.js | 24 +- .../trigger/searcher.list.multi.tree.js | 2 +- .../multitree/trigger/searcher.multi.tree.js | 2 +- 32 files changed, 3098 insertions(+), 2457 deletions(-) diff --git a/es6.js b/es6.js index 1a025d511..46d761847 100644 --- a/es6.js +++ b/es6.js @@ -43,10 +43,13 @@ const target = [ "createItems", "makeArrayByArray", "VerticalAlign", + "pushDistinct", + "endWith", "transformItems", "print", "Tree", "Func", + "Selection", ]; // 加载模块 diff --git a/src/widget/multiselect/__test__/multiselect.loader.nobar.test.js b/src/widget/multiselect/__test__/multiselect.loader.nobar.test.js index a7750bb26..904452922 100644 --- a/src/widget/multiselect/__test__/multiselect.loader.nobar.test.js +++ b/src/widget/multiselect/__test__/multiselect.loader.nobar.test.js @@ -4,15 +4,15 @@ * Created by windy on 2019/9/18 */ -describe("multi_select_no_bar_series", function () { - - var _getItemsByTimes, _itemsCreator, itemSelectorGetter, searchItemSelectorGetter, _hasNextByTimes, items; - before(function () { +describe("multi_select_no_bar_series", () => { + let _getItemsByTimes, _itemsCreator, itemSelectorGetter, searchItemSelectorGetter, _hasNextByTimes, items; + before(() => { _getItemsByTimes = function (items, times) { - var res = []; - for (var i = (times - 1) * 100; items[i] && i < times * 100; i++) { + const res = []; + for (let i = (times - 1) * 100; items[i] && i < times * 100; i++) { res.push(items[i]); } + return res; }; @@ -21,65 +21,60 @@ describe("multi_select_no_bar_series", function () { }; _itemsCreator = function (options, callback) { - var items = BI.map(BI.makeArray(100, null), function(idx, v) { + let items = BI.map(BI.makeArray(100, null), (idx, v) => { return { text: idx, value: idx, - title: idx + title: idx, }; }); - var keywords = (options.keywords || []).slice(); + const keywords = (options.keywords || []).slice(); if (options.keyword) { keywords.push(options.keyword); } - BI.each(keywords, function (i, kw) { - var search = BI.Func.getSearchResult(items, kw); + BI.each(keywords, (i, kw) => { + const search = BI.Func.getSearchResult(items, kw); items = search.match.concat(search.find); }); if (options.selectedValues) {// 过滤 - var filter = BI.makeObject(options.selectedValues, true); - items = BI.filter(items, function (i, ob) { - return !filter[ob.value]; - }); + const filter = BI.makeObject(options.selectedValues, true); + items = BI.filter(items, (i, ob) => !filter[ob.value]); } if (options.type == BI.MultiSelectCombo.REQ_GET_ALL_DATA) { callback({ - items: items + items, }); + return; } if (options.type == BI.MultiSelectCombo.REQ_GET_DATA_LENGTH) { - callback({count: items.length}); + callback({ count: items.length }); + return; } callback({ items: _getItemsByTimes(items, options.times), - hasNext: _hasNextByTimes(items, options.times) + hasNext: _hasNextByTimes(items, options.times), }); }; itemSelectorGetter = function (array) { - return BI.map(array, function (idx, num) { - return ".bi-multi-select-popup-view .bi-loader .bi-button-group .bi-multi-select-item:nth-child(" + num + ")"; - }); + return BI.map(array, (idx, num) => `.bi-multi-select-popup-view .bi-loader .bi-button-group .bi-multi-select-item:nth-child(${num})`); }; searchItemSelectorGetter = function (array) { - return BI.map(array, function (idx, num) { - return ".bi-multi-select-search-pane .bi-loader .bi-button-group .bi-multi-select-item:nth-child(" + num + ")"; - }); + return BI.map(array, (idx, num) => `.bi-multi-select-search-pane .bi-loader .bi-button-group .bi-multi-select-item:nth-child(${num})`); }; - - }) + }); /** * test_author_windy **/ - it("setValue", function () { - var widget = BI.Test.createWidget({ + it("setValue", () => { + const widget = BI.Test.createWidget({ type: "bi.multi_select_no_bar_combo", width: 220, - itemsCreator: _itemsCreator + itemsCreator: _itemsCreator, }); widget.setValue([1, 2]); expect(widget.getValue()).to.deep.equal([1, 2]); @@ -89,12 +84,12 @@ describe("multi_select_no_bar_series", function () { /** * test_author_windy **/ - it("getValue", function () { - var widget = BI.Test.createWidget({ + it("getValue", () => { + const widget = BI.Test.createWidget({ type: "bi.multi_select_no_bar_combo", width: 220, itemsCreator: _itemsCreator, - value: [1, 2, 3] + value: [1, 2, 3], }); expect(widget.getValue()).to.deep.equal([1, 2, 3]); widget.destroy(); @@ -103,22 +98,22 @@ describe("multi_select_no_bar_series", function () { /** * test_author_windy **/ - it("点选选值", function (done) { - var widget = BI.Test.createWidget({ + it("点选选值", done => { + const widget = BI.Test.createWidget({ type: "bi.multi_select_no_bar_combo", width: 220, - itemsCreator: _itemsCreator + itemsCreator: _itemsCreator, }); widget.element.find(".bi-multi-select-trigger").click(); // 为什么要delay 300呢,因为按钮有debounce - BI.delay(function () { + BI.delay(() => { // 点选1、2、3 - BI.each(itemSelectorGetter([1,2,3]), function (idx, selector) { + BI.each(itemSelectorGetter([1, 2, 3]), (idx, selector) => { widget.element.find(selector).click(); }); // 取消勾选1、2 - BI.delay(function () { - BI.each(itemSelectorGetter([1,2]), function (idx, selector) { + BI.delay(() => { + BI.each(itemSelectorGetter([1, 2]), (idx, selector) => { widget.element.find(selector).click(); }); expect(widget.getValue()).to.deep.equal([2]); @@ -131,19 +126,19 @@ describe("multi_select_no_bar_series", function () { /** * test_author_windy **/ - it("搜索选值", function (done) { - var widget = BI.Test.createWidget({ + it("搜索选值", done => { + const widget = BI.Test.createWidget({ type: "bi.multi_select_no_bar_combo", width: 220, - itemsCreator: _itemsCreator + itemsCreator: _itemsCreator, }); - BI.nextTick(function () { + BI.nextTick(() => { widget.element.find(".bi-multi-select-trigger .tip-text-style").click(); // 这边为啥要加呢,因为input的setValue中有nextTick - BI.nextTick(function () { - BI.Test.triggerKeyDown(widget.element.find(".bi-multi-select-trigger .bi-input"), "2", 50, function () { - BI.nextTick(function () { - BI.each(searchItemSelectorGetter([1,2]), function (idx, selector) { + BI.nextTick(() => { + BI.Test.triggerKeyDown(widget.element.find(".bi-multi-select-trigger .bi-input"), "2", 50, () => { + BI.nextTick(() => { + BI.each(searchItemSelectorGetter([1, 2]), (idx, selector) => { widget.element.find(selector).click(); }); expect(widget.getValue()).to.deep.equal([2, 12]); @@ -158,21 +153,21 @@ describe("multi_select_no_bar_series", function () { /** * test_author_windy **/ - it("查看已选", function (done) { - var widget = BI.Test.createWidget({ + it("查看已选", done => { + const widget = BI.Test.createWidget({ type: "bi.multi_select_no_bar_combo", width: 220, - itemsCreator: function (op, callback) { + itemsCreator(op, callback) { callback({ - items: items, - hasNext: false + items, + hasNext: false, }); }, - value: [1, 2] + value: [1, 2], }); - BI.nextTick(function () { + BI.nextTick(() => { widget.element.find(".bi-multi-select-check-selected-button").click(); - BI.delay(function () { + BI.delay(() => { expect(widget.element.find(".display-list-item").length).to.equal(2); widget.destroy(); done(); @@ -183,11 +178,11 @@ describe("multi_select_no_bar_series", function () { /** * test_author_windy **/ - it("setValue", function () { - var widget = BI.Test.createWidget({ + it("setValue", () => { + const widget = BI.Test.createWidget({ type: "bi.multi_select_insert_no_bar_combo", width: 220, - itemsCreator: _itemsCreator + itemsCreator: _itemsCreator, }); widget.setValue([1, 2]); expect(widget.getValue()).to.deep.equal([1, 2]); @@ -197,12 +192,12 @@ describe("multi_select_no_bar_series", function () { /** * test_author_windy **/ - it("getValue", function () { - var widget = BI.Test.createWidget({ + it("getValue", () => { + const widget = BI.Test.createWidget({ type: "bi.multi_select_insert_no_bar_combo", width: 220, itemsCreator: _itemsCreator, - value: [1, 2, 3] + value: [1, 2, 3], }); expect(widget.getValue()).to.deep.equal([1, 2, 3]); widget.destroy(); @@ -212,22 +207,22 @@ describe("multi_select_no_bar_series", function () { /** * test_author_windy **/ - it("点选选值1", function (done) { - var widget = BI.Test.createWidget({ + it("点选选值1", done => { + const widget = BI.Test.createWidget({ type: "bi.multi_select_insert_no_bar_combo", width: 220, - itemsCreator: _itemsCreator + itemsCreator: _itemsCreator, }); widget.element.find(".bi-multi-select-trigger").click(); // 为什么要delay 300呢,因为按钮有debounce - BI.delay(function () { + BI.delay(() => { // 点选1、2、3 - BI.each(itemSelectorGetter([1,2,3]), function (idx, selector) { + BI.each(itemSelectorGetter([1, 2, 3]), (idx, selector) => { widget.element.find(selector).click(); }); // 取消勾选1、2、3 - BI.delay(function () { - BI.each(itemSelectorGetter([1,2]), function (idx, selector) { + BI.delay(() => { + BI.each(itemSelectorGetter([1, 2]), (idx, selector) => { widget.element.find(selector).click(); }); expect(widget.getValue()).to.deep.equal([2]); @@ -240,19 +235,19 @@ describe("multi_select_no_bar_series", function () { /** * test_author_windy **/ - it("搜索选值1", function (done) { - var widget = BI.Test.createWidget({ + it("搜索选值1", done => { + const widget = BI.Test.createWidget({ type: "bi.multi_select_insert_no_bar_combo", width: 220, - itemsCreator: _itemsCreator + itemsCreator: _itemsCreator, }); - BI.nextTick(function () { + BI.nextTick(() => { widget.element.find(".bi-multi-select-trigger .tip-text-style").click(); // 这边为啥要加呢,因为input的setValue中有nextTick - BI.nextTick(function () { - BI.Test.triggerKeyDown(widget.element.find(".bi-multi-select-trigger .bi-input"), "2", 50, function () { - BI.nextTick(function () { - BI.each(searchItemSelectorGetter([1,2]), function (idx, selector) { + BI.nextTick(() => { + BI.Test.triggerKeyDown(widget.element.find(".bi-multi-select-trigger .bi-input"), "2", 50, () => { + BI.nextTick(() => { + BI.each(searchItemSelectorGetter([1, 2]), (idx, selector) => { widget.element.find(selector).click(); }); expect(widget.getValue()).to.deep.equal([2, 12]); @@ -267,18 +262,18 @@ describe("multi_select_no_bar_series", function () { /** * test_author_windy **/ - it("新增值1", function (done) { - var widget = BI.Test.createWidget({ + it("新增值1", done => { + const widget = BI.Test.createWidget({ type: "bi.multi_select_insert_no_bar_combo", width: 220, - itemsCreator: _itemsCreator + itemsCreator: _itemsCreator, }); - BI.nextTick(function () { + BI.nextTick(() => { widget.element.find(".bi-multi-select-trigger .tip-text-style").click(); // 这边为啥要加呢,因为input的setValue中有nextTick - BI.nextTick(function () { - BI.Test.triggerKeyDown(widget.element.find(".bi-multi-select-trigger .bi-input"), "z", 50, function () { - BI.nextTick(function () { + BI.nextTick(() => { + BI.Test.triggerKeyDown(widget.element.find(".bi-multi-select-trigger .bi-input"), "z", 50, () => { + BI.nextTick(() => { widget.element.find(".bi-text-button:contains(+点击新增\"z\")").click(); expect(widget.getValue()).to.deep.equal(["z"]); widget.destroy(); @@ -292,23 +287,23 @@ describe("multi_select_no_bar_series", function () { /** * test_author_windy **/ - it("查看已选1", function (done) { - var widget = BI.Test.createWidget({ + it("查看已选1", done => { + const widget = BI.Test.createWidget({ type: "bi.multi_select_insert_no_bar_combo", width: 220, itemsCreator: _itemsCreator, value: { type: 1, - value: [1, 2] - } + value: [1, 2], + }, }); - BI.nextTick(function () { + BI.nextTick(() => { widget.element.find(".bi-multi-select-check-selected-button").click(); - BI.delay(function () { + BI.delay(() => { expect(widget.element.find(".display-list-item").length).to.equal(2); widget.destroy(); done(); }, 300); }); }); -}); \ No newline at end of file +}); diff --git a/src/widget/multiselect/__test__/multiselect.loader.test.js b/src/widget/multiselect/__test__/multiselect.loader.test.js index 324598714..3e3f47411 100644 --- a/src/widget/multiselect/__test__/multiselect.loader.test.js +++ b/src/widget/multiselect/__test__/multiselect.loader.test.js @@ -2,4 +2,4 @@ * @author windy * @version 2.0 * Created by windy on 2019/9/18 - */ \ No newline at end of file + */ diff --git a/src/widget/multiselect/__test__/multiselectcombo.test.js b/src/widget/multiselect/__test__/multiselectcombo.test.js index 324598714..3e3f47411 100644 --- a/src/widget/multiselect/__test__/multiselectcombo.test.js +++ b/src/widget/multiselect/__test__/multiselectcombo.test.js @@ -2,4 +2,4 @@ * @author windy * @version 2.0 * Created by windy on 2019/9/18 - */ \ No newline at end of file + */ diff --git a/src/widget/multiselect/__test__/multiselectinsert.combo.test.js b/src/widget/multiselect/__test__/multiselectinsert.combo.test.js index 324598714..3e3f47411 100644 --- a/src/widget/multiselect/__test__/multiselectinsert.combo.test.js +++ b/src/widget/multiselect/__test__/multiselectinsert.combo.test.js @@ -2,4 +2,4 @@ * @author windy * @version 2.0 * Created by windy on 2019/9/18 - */ \ No newline at end of file + */ diff --git a/src/widget/multiselect/check/multiselect.check.pane.js b/src/widget/multiselect/check/multiselect.check.pane.js index 958375876..6043caf71 100644 --- a/src/widget/multiselect/check/multiselect.check.pane.js +++ b/src/widget/multiselect/check/multiselect.check.pane.js @@ -1,113 +1,121 @@ -/** - * - * @class BI.MultiSelectCheckPane - * @extends BI.Widget - */ -BI.MultiSelectCheckPane = BI.inherit(BI.Widget, { +import { + shortcut, + Widget, + extend, + emptyFn, + createWidget, + map, + i18nText, + VerticalAdaptLayout, VTapeLayout +} from "@/core"; +import { TextButton, Label } from "@/base"; +import { DisplaySelectedList } from "./multiselect.display"; - constants: { - height: 12, - lgap: 10, - tgap: 10, - bgap: 5 - }, +@shortcut() +export class MultiSelectCheckPane extends Widget { + static xtype = "bi.multi_select_check_pane"; - _defaultConfig: function () { - return BI.extend(BI.MultiSelectCheckPane.superclass._defaultConfig.apply(this, arguments), { + constants = { height: 12, lgap: 10, tgap: 10, bgap: 5 }; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-check-pane bi-background", items: [], - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, - onClickContinueSelect: BI.emptyFn + itemsCreator: emptyFn, + valueFormatter: emptyFn, + onClickContinueSelect: emptyFn, }); - }, + } - _init: function () { - BI.MultiSelectCheckPane.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, opts = this.options; + const self = this, + opts = this.options; this.storeValue = opts.value || {}; - this.display = BI.createWidget({ - type: "bi.display_selected_list", + this.display = createWidget({ + type: DisplaySelectedList.xtype, items: opts.items, - itemsCreator: function (op, callback) { - op = BI.extend(op || {}, { - selectedValues: self.storeValue.value + itemsCreator(op, callback) { + op = extend(op || {}, { + selectedValues: self.storeValue.value, }); if (self.storeValue.type === BI.Selection.Multi) { callback({ - items: BI.map(self.storeValue.value, function (i, v) { - var txt = opts.valueFormatter(v) || v; + items: map(self.storeValue.value, (i, v) => { + const txt = opts.valueFormatter(v) || v; return { text: txt, value: v, - title: txt + title: txt, }; - }) + }), }); return; } opts.itemsCreator(op, callback); - } + }, }); - this.continueSelect = BI.createWidget({ - type: "bi.text_button", - title: BI.i18nText("BI-Continue_Select"), - text: BI.i18nText("BI-Continue_Select"), - cls: "multi-select-check-selected bi-high-light" + this.continueSelect = createWidget({ + type: TextButton.xtype, + title: i18nText("BI-Continue_Select"), + text: i18nText("BI-Continue_Select"), + cls: "multi-select-check-selected bi-high-light", }); - this.continueSelect.on(BI.TextButton.EVENT_CHANGE, function () { + this.continueSelect.on(TextButton.EVENT_CHANGE, () => { opts.onClickContinueSelect(); }); - BI.createWidget({ - type: "bi.vtape", + createWidget({ + type: VTapeLayout.xtype, element: this, - items: [{ - height: this.constants.height, - el: { - type: "bi.vertical_adapt", - columnSize: ["auto", "auto"], - cls: "multi-select-continue-select", - items: [ - { - el: { - type: "bi.label", - title: BI.i18nText("BI-Selected_Data"), - text: BI.i18nText("BI-Selected_Data") + items: [ + { + height: this.constants.height, + el: { + type: VerticalAdaptLayout.xtype, + columnSize: ["auto", "auto"], + cls: "multi-select-continue-select", + items: [ + { + el: { + type: Label.xtype, + title: i18nText("BI-Selected_Data"), + text: i18nText("BI-Selected_Data"), + }, + lgap: this.constants.lgap, }, - lgap: this.constants.lgap - }, - { - el: this.continueSelect, - hgap: this.constants.lgap - }] + { + el: this.continueSelect, + hgap: this.constants.lgap, + } + ], + }, + tgap: this.constants.tgap, }, - tgap: this.constants.tgap - }, { - height: "fill", - el: this.display, - tgap: this.constants.bgap - }] + { + height: "fill", + el: this.display, + tgap: this.constants.bgap, + } + ], }); - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v || {}; - }, + } - empty: function () { + empty() { this.display.empty(); - }, - - populate: function () { - this.display.populate.apply(this.display, arguments); } -}); -BI.shortcut("bi.multi_select_check_pane", BI.MultiSelectCheckPane); + populate() { + this.display.populate(...arguments); + } +} diff --git a/src/widget/multiselect/check/multiselect.display.js b/src/widget/multiselect/check/multiselect.display.js index 30442583c..db52ee8b7 100644 --- a/src/widget/multiselect/check/multiselect.display.js +++ b/src/widget/multiselect/check/multiselect.display.js @@ -1,106 +1,112 @@ -/** - * - * - * 查看已选弹出层的展示面板 - * @class BI.DisplaySelectedList - * @extends BI.Widget - */ -BI.DisplaySelectedList = BI.inherit(BI.Pane, { +import { + shortcut, + extend, + emptyFn, + createWidget, + VerticalLayout, + createItems +} from "@/core"; +import { Pane, ButtonGroup, Loader, IconTextItem } from "@/base"; +import { ListPane } from "@/case"; - constants: { - height: 24, - lgap: 10 - }, +@shortcut() +export class DisplaySelectedList extends Pane { + static xtype = "bi.display_selected_list"; - _defaultConfig: function () { - return BI.extend(BI.DisplaySelectedList.superclass._defaultConfig.apply(this, arguments), { + constants = { height: 24, lgap: 10 }; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-display-list", - itemsCreator: BI.emptyFn, - items: [] + itemsCreator: emptyFn, + items: [], }); - }, + } - _init: function () { - BI.DisplaySelectedList.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, opts = this.options; + const self = this, + opts = this.options; this.hasNext = false; - var cacheItems = []; + let cacheItems = []; - this.button_group = BI.createWidget({ - type: "bi.list_pane", + this.button_group = createWidget({ + type: ListPane.xtype, element: this, el: { - type: "bi.loader", + type: Loader.xtype, isDefaultInit: false, logic: { dynamic: true, - scrolly: true + scrolly: true, }, items: this._createItems(opts.items), - chooseType: BI.ButtonGroup.CHOOSE_TYPE_MULTI, + chooseType: ButtonGroup.CHOOSE_TYPE_MULTI, layouts: [ { - type: "bi.vertical", - lgap: 10 + type: VerticalLayout.xtype, + lgap: 10, } - ] + ], }, - itemsCreator: function (options, callback) { + itemsCreator (options, callback) { if (options.times === 1) { cacheItems = []; } if (cacheItems.length > 0) { - var renderedItems = cacheItems.slice(0, 100); + const renderedItems = cacheItems.slice(0, 100); cacheItems = cacheItems.slice(100); self.hasNext = cacheItems.length > 0; callback(self._createItems(renderedItems)); + return; } - opts.itemsCreator(options, function (ob) { + opts.itemsCreator(options, ob => { self.hasNext = !!ob.hasNext; - var firstItemsCount = 100 + ob.items.length % 100; + const firstItemsCount = 100 + (ob.items.length % 100); if (ob.items.length > 100) { cacheItems = ob.items.slice(firstItemsCount); - self.hasNext = (firstItemsCount === ob.items.length) ? false : true; + self.hasNext = + firstItemsCount !== ob.items.length; } - callback(self._createItems(ob.items.slice(0, firstItemsCount))); + callback( + self._createItems(ob.items.slice(0, firstItemsCount)) + ); }); }, - hasNext: function () { + hasNext () { return self.hasNext; - } + }, }); - }, + } - _createItems: function (items) { - return BI.createItems(items, { - type: "bi.icon_text_item", + _createItems(items) { + return createItems(items, { + type: IconTextItem.xtype, cls: "cursor-default check-font icon-size-12 display-list-item bi-tips", once: true, invalid: true, selected: true, height: this.constants.height, logic: { - dynamic: true - } + dynamic: true, + }, }); - }, + } - empty: function () { + empty() { this.button_group.empty(); - }, + } - populate: function (items) { + populate(items) { if (arguments.length === 0) { this.button_group.populate(); } else { this.button_group.populate(this._createItems(items)); } } -}); - -BI.shortcut("bi.display_selected_list", BI.DisplaySelectedList); +} diff --git a/src/widget/multiselect/loader.js b/src/widget/multiselect/loader.js index c2c2d8de7..98b61d890 100644 --- a/src/widget/multiselect/loader.js +++ b/src/widget/multiselect/loader.js @@ -1,146 +1,192 @@ -/** - * 加载控件 - * - * Created by GUY on 2015/8/31. - * @class BI.Loader - * @extends BI.Widget - */ -BI.MultiSelectInnerLoader = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.MultiSelectInnerLoader.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + Widget, + extend, + emptyFn, + VerticalLayout, + createWidget, + Controller, + Events, + isEmpty, + nextTick, + bind, + isNumber, + isObject, + isFunction, + makeObject, + isArray, + each +} from "@/core"; +import { ButtonGroup, Loader } from "@/base"; + +@shortcut() +export class MultiSelectInnerLoader extends Widget { + static xtype = "bi.multi_select_inner_loader"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-inner-loader", direction: "top", isDefaultInit: true, // 是否默认初始化数据 logic: { dynamic: true, - scrolly: true + scrolly: true, }, // 下面是button_group的属性 el: { - type: "bi.button_group", - chooseType: BI.ButtonGroup.CHOOSE_TYPE_MULTI, + type: ButtonGroup.xtype, + chooseType: ButtonGroup.CHOOSE_TYPE_MULTI, behaviors: { - redmark: function () { + redmark() { return true; - } + }, }, - layouts: [{ - type: "bi.vertical" - }] + layouts: [ + { + type: VerticalLayout.xtype, + } + ], }, items: [], - itemsCreator: BI.emptyFn, - onLoaded: BI.emptyFn, + itemsCreator: emptyFn, + onLoaded: emptyFn, // 下面是分页信息 count: false, prev: false, next: {}, - hasPrev: BI.emptyFn, - hasNext: BI.emptyFn + hasPrev: emptyFn, + hasNext: emptyFn, }); - }, + } - _nextLoad: function () { - var self = this, o = this.options; + _nextLoad() { + const self = this, + o = this.options; this.next.setLoading(); if (this.cachItems && this.cachItems.length > 0) { this.next.setLoaded(); this.addItems(this.cachItems.slice(0, 100)); this.cachItems = this.cachItems.slice(100); + return; } - o.itemsCreator.apply(this, [{times: ++this.times}, function () { - self.next.setLoaded(); - self.addItems.apply(self, arguments); - }]); - }, - - render: function () { - var self = this, o = this.options; + o.itemsCreator.apply(this, [ + { times: ++this.times }, + function () { + self.next.setLoaded(); + self.addItems(...arguments); + } + ]); + } + + render() { + const self = this, + o = this.options; if (o.itemsCreator === false) { o.next = false; } - this.button_group = BI.createWidget(o.el, { - type: "bi.button_group", + this.button_group = createWidget(o.el, { + type: ButtonGroup.xtype, chooseType: 0, items: o.items, behaviors: {}, - layouts: [{ - type: "bi.vertical" - }], - value: o.value + layouts: [ + { + type: VerticalLayout.xtype, + } + ], + value: o.value, }); - this.button_group.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - if (type === BI.Events.CLICK) { - var node = self.cachGroup.getNodeByValue(value); - if (node) { - node.setSelected(obj.isSelected()); + this.button_group.on( + Controller.EVENT_CHANGE, + function (type, value, obj) { + if (type === Events.CLICK) { + const node = self.cachGroup.getNodeByValue(value); + if (node) { + node.setSelected(obj.isSelected()); + } + } + self.fireEvent(Controller.EVENT_CHANGE, arguments); + if (type === Events.CLICK) { + self.fireEvent(Loader.EVENT_CHANGE, obj); } } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if (type === BI.Events.CLICK) { - self.fireEvent(BI.Loader.EVENT_CHANGE, obj); - } - }); + ); - var renderEngine = BI.Widget._renderEngine; - BI.Widget.registerRenderEngine(BI.Element.renderEngine); - this.cachGroup = BI.createWidget(o.el, { - type: "bi.button_group", + const renderEngine = Widget._renderEngine; + Widget.registerRenderEngine(BI.Element.renderEngine); + this.cachGroup = createWidget(o.el, { + type: ButtonGroup.xtype, root: true, chooseType: 0, items: o.items, behaviors: {}, - layouts: [{ - type: "bi.vertical" - }], - value: o.value + layouts: [ + { + type: VerticalLayout.xtype, + } + ], + value: o.value, }); - BI.Widget.registerRenderEngine(renderEngine); + Widget.registerRenderEngine(renderEngine); if (o.next !== false) { - this.next = BI.createWidget(BI.extend({ - type: "bi.loading_bar" - }, o.next)); - this.next.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) { + this.next = createWidget( + extend( + { + type: "bi.loading_bar", + }, + o.next + ) + ); + this.next.on(Controller.EVENT_CHANGE, type => { + if (type === Events.CLICK) { self._nextLoad(); } }); } - BI.createWidget({ - type: "bi.vertical", + createWidget({ + type: VerticalLayout.xtype, element: this, - items: [this.button_group, this.next] + items: [this.button_group, this.next], }); - o.isDefaultInit && BI.isEmpty(o.items) && BI.nextTick(BI.bind(function () { - o.isDefaultInit && BI.isEmpty(o.items) && this._populate(); - }, this)); - }, + o.isDefaultInit && + isEmpty(o.items) && + nextTick( + bind(function () { + o.isDefaultInit && isEmpty(o.items) && this._populate(); + }, this) + ); + } - hasNext: function () { - var o = this.options; - if (BI.isNumber(o.count)) { + hasNext() { + const o = this.options; + if (isNumber(o.count)) { return this.count < o.count; } if (this.cachItems && this.cachItems.length > 0) { return true; } - return !!o.hasNext.apply(this, [{ - times: this.times, - count: this.count - }]); - }, - addItems: function (items) { + return !!o.hasNext.apply(this, [ + { + times: this.times, + count: this.count, + } + ]); + } + + addItems(items) { this.count += items.length; - if (BI.isObject(this.next)) { + if (isObject(this.next)) { if (this.hasNext()) { this.options.items = this.options.items.concat(items); this.next.setLoaded(); @@ -148,113 +194,124 @@ BI.MultiSelectInnerLoader = BI.inherit(BI.Widget, { this.next.setEnd(); } } - var renderEngine = BI.Widget._renderEngine; - BI.Widget.registerRenderEngine(BI.Element.renderEngine); - this.cachGroup.addItems.apply(this.cachGroup, arguments); - BI.Widget.registerRenderEngine(renderEngine); - this.button_group.addItems.apply(this.button_group, arguments); - }, - - _populate: function (items) { - var self = this, o = this.options; - if (arguments.length === 0 && (BI.isFunction(o.itemsCreator))) { - o.itemsCreator.apply(this, [{times: 1}, function (items, keyword) { - if (arguments.length === 0) { - throw new Error("参数不能为空"); + const renderEngine = Widget._renderEngine; + Widget.registerRenderEngine(BI.Element.renderEngine); + this.cachGroup.addItems(...arguments); + Widget.registerRenderEngine(renderEngine); + this.button_group.addItems(...arguments); + } + + _populate(items) { + const self = this, + o = this.options; + if (arguments.length === 0 && isFunction(o.itemsCreator)) { + o.itemsCreator.apply(this, [ + { times: 1 }, + function (items, keyword) { + if (arguments.length === 0) { + throw new Error("参数不能为空"); + } + self.populate(...arguments); + o.onLoaded(); } - self.populate.apply(self, arguments); - o.onLoaded(); - }]); + ]); + return false; } - this.options.items = (items || []).slice(0, 100 + (items || []).length % 100); + this.options.items = (items || []).slice( + 0, + 100 + ((items || []).length % 100) + ); this.times = 1; this.count = 0; this.count += items.length; - if (BI.isObject(this.next)) { + if (isObject(this.next)) { if (this.hasNext()) { this.next.setLoaded(); } else { this.next.invisible(); } } + return true; - }, + } - populate: function (items, keyword) { - if (this._populate.apply(this, arguments)) { + populate(items, keyword) { + if (this._populate(...arguments)) { this.cachItems = []; - var firstItemsCount = 100 + items.length % 100; + const firstItemsCount = 100 + (items.length % 100); if (items.length > firstItemsCount) { this.cachItems = items.slice(firstItemsCount); } - var renderEngine = BI.Widget._renderEngine; - BI.Widget.registerRenderEngine(BI.Element.renderEngine); + const renderEngine = Widget._renderEngine; + Widget.registerRenderEngine(BI.Element.renderEngine); this.cachGroup.populate.call(this.cachGroup, items, keyword); - BI.Widget.registerRenderEngine(renderEngine); - this.button_group.populate.call(this.button_group, items.slice(0, firstItemsCount), keyword); + Widget.registerRenderEngine(renderEngine); + this.button_group.populate.call( + this.button_group, + items.slice(0, firstItemsCount), + keyword + ); } - }, + } - setNotSelectedValue: function () { - this.button_group.setNotSelectedValue.apply(this.button_group, arguments); - this.cachGroup.setNotSelectedValue.apply(this.cachGroup, arguments); - }, + setNotSelectedValue() { + this.button_group.setNotSelectedValue(...arguments); + this.cachGroup.setNotSelectedValue(...arguments); + } - getNotSelectedValue: function () { + getNotSelectedValue() { return this.cachGroup.getNotSelectedValue(); - }, + } - setAllSelected: function (v) { + setAllSelected(v) { this.button_group.setAllSelected(v); this.cachGroup.setAllSelected(v); - }, + } - setValue: function (value) { - var map = BI.makeObject(BI.isArray(value) ? value : [value]); + setValue(value) { + const map = makeObject(isArray(value) ? value : [value]); this.cachGroup.setValueMap.call(this.cachGroup, map); this.button_group.setValueMap.call(this.button_group, map); - }, + } - getValue: function () { - return this.cachGroup.getValue.apply(this.cachGroup, arguments); - }, + getValue() { + return this.cachGroup.getValue(...arguments); + } - getAllButtons: function () { + getAllButtons() { return this.button_group.getAllButtons(); - }, + } - getAllLeaves: function () { + getAllLeaves() { return this.button_group.getAllLeaves(); - }, + } - getSelectedButtons: function () { + getSelectedButtons() { return this.button_group.getSelectedButtons(); - }, + } - getNotSelectedButtons: function () { + getNotSelectedButtons() { return this.button_group.getNotSelectedButtons(); - }, + } - getIndexByValue: function (value) { + getIndexByValue(value) { return this.button_group.getIndexByValue(value); - }, + } - getNodeById: function (id) { + getNodeById(id) { return this.button_group.getNodeById(id); - }, + } - getNodeByValue: function (value) { + getNodeByValue(value) { return this.button_group.getNodeByValue(value); - }, + } - empty: function () { + empty() { this.button_group.empty(); this.cachGroup.empty(); - BI.each([this.prev, this.next], function (i, ob) { + each([this.prev, this.next], (i, ob) => { ob && ob.setVisible(false); }); } -}); -BI.MultiSelectInnerLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multi_select_inner_loader", BI.MultiSelectInnerLoader); +} diff --git a/src/widget/multiselect/multiselect.combo.js b/src/widget/multiselect/multiselect.combo.js index 5651fa04f..a9efd6a3b 100644 --- a/src/widget/multiselect/multiselect.combo.js +++ b/src/widget/multiselect/multiselect.combo.js @@ -1,51 +1,98 @@ -/** - * - * @class BI.MultiSelectCombo - * @extends BI.Single - */ -BI.MultiSelectCombo = BI.inherit(BI.Single, { - - _defaultConfig: function () { - return BI.extend(BI.MultiSelectCombo.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + emptyFn, + isKey, + remove, + deepClone, + createWidget, + toPix, + bind, + last, + initial, + nextTick, + Events, + AbsoluteLayout, + VerticalAdaptLayout, + isNotNull, + makeObject, + map, + each, + Func, + concat, + values, + filter, + contains, + isNull +} from "@/core"; +import { Single, Combo } from "@/base"; +import { TriggerIconButton } from "@/case"; +import { MultiSelectTrigger } from "./multiselect.trigger"; +import { MultiSelectPopupView } from "./multiselect.popup.view"; +import { MultiSelectCheckSelectedSwitcher } from "./trigger/switcher.checkselected"; + +@shortcut() +export class MultiSelectCombo extends Single { + static xtype = "bi.multi_select_combo"; + + static REQ_GET_DATA_LENGTH = "1"; + static REQ_GET_ALL_DATA = "-1"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_CLICK_ITEM = "EVENT_CLICK_ITEM"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-combo", - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, + itemsCreator: emptyFn, + valueFormatter: emptyFn, itemHeight: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, height: 24, allowEdit: true, }); - }, - - _init: function () { - var self = this; - var o = this.options; - BI.MultiSelectCombo.superclass._init.apply(this, arguments); - var assertShowValue = function () { - if (BI.isKey(self._startValue)) { + } + + _init() { + const self = this; + const o = this.options; + super._init(...arguments); + const triggerBtn = createWidget({ + type: TriggerIconButton.xtype, + width: o.height, + height: o.height, + cls: "multi-select-trigger-icon-button", + }); + + function assertShowValue() { + if (isKey(self._startValue)) { if (self.storeValue.type === BI.Selection.All) { - BI.remove(self.storeValue.value, self._startValue); + remove(self.storeValue.value, self._startValue); self.storeValue.assist = self.storeValue.assist || []; BI.pushDistinct(self.storeValue.assist, self._startValue); } else { BI.pushDistinct(self.storeValue.value, self._startValue); - BI.remove(self.storeValue.assist, self._startValue); + remove(self.storeValue.assist, self._startValue); } } self.trigger.getSearcher().setState(self.storeValue); self.numberCounter.setButtonChecked(self.storeValue); - }; - this.storeValue = BI.deepClone(o.value) || {}; + } + + this.storeValue = deepClone(o.value) || {}; this._assertValue(this.storeValue); // 标记正在请求数据 this.requesting = false; - this.trigger = BI.createWidget({ - type: "bi.multi_select_trigger", + this.trigger = createWidget({ + type: MultiSelectTrigger.xtype, allowEdit: o.allowEdit, - height: BI.toPix(o.height, o.simple ? 1 : 2), + height: toPix(o.height, o.simple ? 1 : 2), text: o.text, defaultText: o.defaultText, masker: { @@ -58,114 +105,124 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { }, valueFormatter: o.valueFormatter, itemFormatter: o.itemFormatter, - itemsCreator: BI.bind(this._itemsCreator4Trigger, this), + itemsCreator: bind(this._itemsCreator4Trigger, this), itemHeight: o.itemHeight, value: this.storeValue, }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_FOCUS, function () { - self.fireEvent(BI.MultiSelectCombo.EVENT_FOCUS); + this.trigger.on(MultiSelectTrigger.EVENT_FOCUS, () => { + self.fireEvent(MultiSelectCombo.EVENT_FOCUS); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_BLUR, function () { - self.fireEvent(BI.MultiSelectCombo.EVENT_BLUR); + this.trigger.on(MultiSelectTrigger.EVENT_BLUR, () => { + self.fireEvent(MultiSelectCombo.EVENT_BLUR); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_START, function () { + this.trigger.on(MultiSelectTrigger.EVENT_START, function () { self._setStartValue(""); this.getSearcher().setValue(self.storeValue); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_STOP, function () { + this.trigger.on(MultiSelectTrigger.EVENT_STOP, () => { self._setStartValue(""); - self.fireEvent(BI.MultiSelectCombo.EVENT_STOP); + self.fireEvent(MultiSelectCombo.EVENT_STOP); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_SEARCHING, function (keywords) { - var last = BI.last(keywords); - keywords = BI.initial(keywords || []); - if (keywords.length > 0) { - self._joinKeywords(keywords, function () { - if (BI.endWith(last, BI.BlankSplitChar)) { - self.combo.setValue(self.storeValue); - assertShowValue(); - self.combo.populate(); - self._setStartValue(""); - } else { - self.combo.setValue(self.storeValue); - assertShowValue(); - } - self._dataChange = true; - }); + this.trigger.on( + MultiSelectTrigger.EVENT_SEARCHING, + keywords => { + const lastKeyword = last(keywords); + keywords = initial(keywords || []); + if (keywords.length > 0) { + self._joinKeywords(keywords, () => { + if (BI.endWith(lastKeyword, BI.BlankSplitChar)) { + self.combo.setValue(self.storeValue); + assertShowValue(); + self.combo.populate(); + self._setStartValue(""); + } else { + self.combo.setValue(self.storeValue); + assertShowValue(); + } + self._dataChange = true; + }); + } + self.fireEvent(MultiSelectCombo.EVENT_SEARCHING); } - self.fireEvent(BI.MultiSelectCombo.EVENT_SEARCHING); - }); + ); - this.trigger.on(BI.MultiSelectTrigger.EVENT_CHANGE, function (value, obj) { + this.trigger.on(MultiSelectTrigger.EVENT_CHANGE, function (value, obj) { if (obj instanceof BI.MultiSelectBar) { - self._joinAll(this.getValue(), function () { + self._joinAll(this.getValue(), () => { assertShowValue(); - self.fireEvent(BI.MultiSelectCombo.EVENT_CLICK_ITEM); + self.fireEvent(MultiSelectCombo.EVENT_CLICK_ITEM); }); } else { - self._join(this.getValue(), function () { + self._join(this.getValue(), () => { assertShowValue(); - self.fireEvent(BI.MultiSelectCombo.EVENT_CLICK_ITEM); + self.fireEvent(MultiSelectCombo.EVENT_CLICK_ITEM); }); } self._dataChange = true; }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW, function () { - // counter的值随点击项的改变而改变, 点击counter的时候不需要setValue(counter会请求刷新计数) - // 只需要更新查看面板的selectedValue用以请求已选数据 - self.numberCounter.updateSelectedValue(self.storeValue); - }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_COUNTER_CLICK, function () { + this.trigger.on( + MultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW, + () => { + // counter的值随点击项的改变而改变, 点击counter的时候不需要setValue(counter会请求刷新计数) + // 只需要更新查看面板的selectedValue用以请求已选数据 + self.numberCounter.updateSelectedValue(self.storeValue); + } + ); + this.trigger.on(MultiSelectTrigger.EVENT_COUNTER_CLICK, () => { if (!self.combo.isViewVisible()) { self.combo.showView(); } }); - this.combo = BI.createWidget({ - type: "bi.combo", - cls: (o.simple ? "bi-border-bottom" : "bi-border bi-border-radius"), + this.combo = createWidget({ + type: Combo.xtype, + cls: o.simple ? "bi-border-bottom" : "bi-border bi-border-radius", toggle: !o.allowEdit, container: o.container, el: this.trigger, adjustLength: 1, popup: { type: "bi.multi_select_popup_view", - ref: function () { + ref() { self.popup = this; self.trigger.setAdapter(this); self.numberCounter.setAdapter(this); }, - listeners: [{ - eventName: BI.MultiSelectPopupView.EVENT_CHANGE, - action: function () { - self._dataChange = true; - self.storeValue = this.getValue(); - self._adjust(function () { - assertShowValue(); - }); - self.fireEvent(BI.MultiSelectCombo.EVENT_CLICK_ITEM); - }, - }, { - eventName: BI.MultiSelectPopupView.EVENT_CLICK_CONFIRM, - action: function () { - self._defaultState(); + listeners: [ + { + eventName: MultiSelectPopupView.EVENT_CHANGE, + action() { + self._dataChange = true; + self.storeValue = this.getValue(); + self._adjust(() => { + assertShowValue(); + }); + self.fireEvent(MultiSelectCombo.EVENT_CLICK_ITEM); + }, }, - }, { - eventName: BI.MultiSelectPopupView.EVENT_CLICK_CLEAR, - action: function () { - self._dataChange = true; - self.setValue(); - self._defaultState(); + { + eventName: MultiSelectPopupView.EVENT_CLICK_CONFIRM, + action() { + self._defaultState(); + }, }, - }], + { + eventName: MultiSelectPopupView.EVENT_CLICK_CLEAR, + action() { + self._dataChange = true; + self.setValue(); + self._defaultState(); + }, + } + ], itemsCreator: o.itemsCreator, itemHeight: o.itemHeight, valueFormatter: o.valueFormatter, itemFormatter: o.itemFormatter, - onLoaded: function () { - BI.nextTick(function () { + onLoaded() { + nextTick(() => { self.combo.adjustWidth(); self.combo.adjustHeight(); self.numberCounter.adjustView(); @@ -174,39 +231,37 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { }, }, value: o.value, - hideChecker: function (e) { - return triggerBtn.element.find(e.target).length === 0 && self.numberCounter.element.find(e.target).length === 0; + hideChecker(e) { + return ( + triggerBtn.element.find(e.target).length === 0 && + self.numberCounter.element.find(e.target).length === 0 + ); }, }); - this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { + this.combo.on(Combo.EVENT_BEFORE_POPUPVIEW, function () { if (!this.isViewVisible()) { - self._dataChange = false;// 标记数据是否发生变化 + self._dataChange = false; // 标记数据是否发生变化 } this.setValue(self.storeValue); - BI.nextTick(function () { + nextTick(() => { self._populate(); }); }); // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; - this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { + this.combo.on(Combo.EVENT_AFTER_HIDEVIEW, () => { // important:关闭弹出时又可能没有退出编辑状态 self._stopEditing(); if (self.requesting === true) { self.wants2Quit = true; } else { - self._dataChange && self.fireEvent(BI.MultiSelectCombo.EVENT_CONFIRM); + self._dataChange && + self.fireEvent(MultiSelectCombo.EVENT_CONFIRM); } }); - var triggerBtn = BI.createWidget({ - type: "bi.trigger_icon_button", - width: o.height, - height: o.height, - cls: "multi-select-trigger-icon-button", - }); - triggerBtn.on(BI.TriggerIconButton.EVENT_CHANGE, function () { + triggerBtn.on(TriggerIconButton.EVENT_CHANGE, () => { self.numberCounter.hideView(); if (self.combo.isViewVisible()) { self.combo.hideView(); @@ -215,8 +270,8 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { } }); - this.numberCounter = BI.createWidget({ - type: "bi.multi_select_check_selected_switcher", + this.numberCounter = createWidget({ + type: MultiSelectCheckSelectedSwitcher.xtype, masker: { offset: { left: 0, @@ -226,259 +281,274 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { }, }, valueFormatter: o.valueFormatter, - itemsCreator: BI.bind(this._itemsCreator4Trigger, this), + itemsCreator: bind(this._itemsCreator4Trigger, this), value: this.storeValue, }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE, function () { - if (!self.combo.isViewVisible()) { - self.combo.showView(); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE, + () => { + if (!self.combo.isViewVisible()) { + self.combo.showView(); + } } - }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW, function () { - this.updateSelectedValue(self.storeValue); - }); - - this.numberCounter.on(BI.Events.VIEW, function (b) { - BI.nextTick(function () {// 自动调整宽度 - self.trigger.refreshPlaceHolderWidth((b === true ? self.numberCounter.element.outerWidth() + 8 : 0)); + ); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW, + function () { + this.updateSelectedValue(self.storeValue); + } + ); + + this.numberCounter.on(Events.VIEW, b => { + nextTick(() => { + // 自动调整宽度 + self.trigger.refreshPlaceHolderWidth( + b === true ? self.numberCounter.element.outerWidth() + 8 : 0 + ); }); }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_AFTER_HIDEVIEW, function () { - BI.nextTick(function () {// 收起时自动调整宽度 - self.trigger.refreshPlaceHolderWidth(0); - }); - }); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_AFTER_HIDEVIEW, + () => { + nextTick(() => { + // 收起时自动调整宽度 + self.trigger.refreshPlaceHolderWidth(0); + }); + } + ); - this.trigger.element.click(function (e) { + this.trigger.element.click(e => { if (self.trigger.element.find(e.target).length > 0) { self.numberCounter.hideView(); } }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.combo, - left: 0, - right: 0, - top: 0, - bottom: 0, - }, { - el: triggerBtn, - right: 0, - top: 0, - bottom: 0, - }, { - el: { - type: "bi.vertical_adapt", - items: [this.numberCounter], + items: [ + { + el: this.combo, + left: 0, + right: 0, + top: 0, + bottom: 0, }, - right: o.height, - top: 0, - height: o.height, - }], + { + el: triggerBtn, + right: 0, + top: 0, + bottom: 0, + }, + { + el: { + type: VerticalAdaptLayout.xtype, + items: [this.numberCounter], + }, + right: o.height, + top: 0, + height: o.height, + } + ], }); - }, + } - _itemsCreator4Trigger: function (op, callback) { - var self = this; - var o = this.options; + _itemsCreator4Trigger(op, callback) { + const self = this; + const o = this.options; o.itemsCreator(op, function (res) { - if (op.times === 1 && BI.isNotNull(op.keywords)) { + if (op.times === 1 && isNotNull(op.keywords)) { // 预防trigger内部把当前的storeValue改掉 - self.trigger.setValue(BI.deepClone(self.getValue())); + self.trigger.setValue(deepClone(self.getValue())); } callback.apply(self, arguments); }); - }, + } - _stopEditing: function () { + _stopEditing() { this.trigger.stopEditing(); this.numberCounter.hideView(); - }, + } - _defaultState: function () { + _defaultState() { this._stopEditing(); this.combo.hideView(); - }, + } - _assertValue: function (val) { + _assertValue(val) { val || (val = {}); val.type || (val.type = BI.Selection.Multi); val.value || (val.value = []); - }, + } - _makeMap: function (values) { - return BI.makeObject(values || []); - }, + _makeMap(values) { + return makeObject(values || []); + } - _joinKeywords: function (keywords, callback) { - var self = this; - var o = this.options; + _joinKeywords(keywords, callback) { + const self = this; + const o = this.options; this._assertValue(this.storeValue); this.requesting = true; - o.itemsCreator({ - type: BI.MultiSelectCombo.REQ_GET_ALL_DATA, - keywords: keywords, - }, function (ob) { - var values = BI.map(ob.items, "value"); - digest(values); - }); + o.itemsCreator( + { + type: MultiSelectCombo.REQ_GET_ALL_DATA, + keywords, + }, + ob => { + const values = map(ob.items, "value"); + digest(values); + } + ); function digest(items) { - var selectedMap = self._makeMap(items); - BI.each(keywords, function (i, val) { - if (BI.isNotNull(selectedMap[val])) { - self.storeValue.type === BI.Selection.Multi ? BI.pushDistinct(self.storeValue.value, val) : BI.remove(self.storeValue.value, val); + const selectedMap = self._makeMap(items); + each(keywords, (i, val) => { + if (isNotNull(selectedMap[val])) { + self.storeValue.type === BI.Selection.Multi + ? BI.pushDistinct(self.storeValue.value, val) + : remove(self.storeValue.value, val); } }); self._adjust(callback); } - }, + } - _joinAll: function (res, callback) { - var self = this; - var o = this.options; + _joinAll(res, callback) { + const tempMap = this._makeMap(this.storeValue.value); + const self = this; + const o = this.options; this._assertValue(res); this.requesting = true; if (this.storeValue.type === res.type) { - var result = BI.Func.getSearchResult(BI.map(this.storeValue.value, function (_i, v) { - return { - text: o.valueFormatter(v) || v, - value: v - }; - }), this.trigger.getKey()); - var change = false; - var map = this._makeMap(this.storeValue.value); - BI.each(BI.concat(result.match, result.find), function (i, obj) { - var v = obj.value; - if (BI.isNotNull(map[v])) { + const result = Func.getSearchResult( + map(this.storeValue.value, (_i, v) => { + return { + text: o.valueFormatter(v) || v, + value: v, + }; + }), + this.trigger.getKey() + ); + let change = false; + each(concat(result.match, result.find), (i, obj) => { + const v = obj.value; + if (isNotNull(tempMap[v])) { change = true; - self.storeValue.assist && self.storeValue.assist.push(map[v]); - delete map[v]; + self.storeValue.assist && + self.storeValue.assist.push(tempMap[v]); + delete tempMap[v]; } }); - change && (this.storeValue.value = BI.values(map)); + change && (this.storeValue.value = values(tempMap)); this._adjust(callback); + return; } - o.itemsCreator({ - type: BI.MultiSelectCombo.REQ_GET_ALL_DATA, - keywords: [this.trigger.getKey()], - selectedValues: BI.filter(this.storeValue.value, function (_i, v) { - return !BI.contains(res.value, v); - }), - }, function (ob) { - var items = BI.map(ob.items, "value"); - var selectedMap = self._makeMap(self.storeValue.value); - var notSelectedMap = self._makeMap(res.value); - var newItems = []; - BI.each(items, function (i, item) { - if (BI.isNotNull(selectedMap[items[i]])) { - self.storeValue.assist && self.storeValue.assist.push(selectedMap[items[i]]); - delete selectedMap[items[i]]; - } - if (BI.isNull(notSelectedMap[items[i]])) { - BI.remove(self.storeValue.assist, item); - newItems.push(item); - } - }); - self.storeValue.value = newItems.concat(BI.values(selectedMap)); - self._adjust(callback); - }); - }, + o.itemsCreator( + { + type: MultiSelectCombo.REQ_GET_ALL_DATA, + keywords: [this.trigger.getKey()], + selectedValues: filter(this.storeValue.value, (_i, v) => !contains(res.value, v)), + }, + ob => { + const items = map(ob.items, "value"); + const selectedMap = self._makeMap(self.storeValue.value); + const notSelectedMap = self._makeMap(res.value); + const newItems = []; + each(items, (i, item) => { + if (isNotNull(selectedMap[items[i]])) { + self.storeValue.assist && + self.storeValue.assist.push(selectedMap[items[i]]); + delete selectedMap[items[i]]; + } + if (isNull(notSelectedMap[items[i]])) { + remove(self.storeValue.assist, item); + newItems.push(item); + } + }); + self.storeValue.value = newItems.concat(values(selectedMap)); + self._adjust(callback); + } + ); + } - _adjust: function (callback) { - var self = this; - var o = this.options; + _adjust(callback) { + const self = this; adjust(); callback(); function adjust() { if (self.wants2Quit === true) { - self._dataChange && self.fireEvent(BI.MultiSelectCombo.EVENT_CONFIRM); + self._dataChange && + self.fireEvent(MultiSelectCombo.EVENT_CONFIRM); self.wants2Quit = false; } self.requesting = false; } - }, + } - _join: function (res, callback) { - var self = this; - var o = this.options; + _join(res, callback) { + const self = this; this._assertValue(res); this._assertValue(this.storeValue); if (this.storeValue.type === res.type) { - var map = this._makeMap(this.storeValue.value); - BI.each(res.value, function (i, v) { + const map = this._makeMap(this.storeValue.value); + each(res.value, (i, v) => { if (!map[v]) { BI.pushDistinct(self.storeValue.value, v); - BI.remove(self.storeValue.assist, v); + remove(self.storeValue.assist, v); map[v] = v; } }); - var change = false; - BI.each(res.assist, function (i, v) { - if (BI.isNotNull(map[v])) { + let change = false; + each(res.assist, (i, v) => { + if (isNotNull(map[v])) { change = true; - self.storeValue.assist && self.storeValue.assist.push(map[v]); + self.storeValue.assist && + self.storeValue.assist.push(map[v]); delete map[v]; } }); - change && (this.storeValue.value = BI.values(map)); + change && (this.storeValue.value = values(map)); self._adjust(callback); return; } this._joinAll(res, callback); - }, + } - _setStartValue: function (value) { + _setStartValue(value) { this._startValue = value; this.popup.setStartValue(value); - }, + } - _populate: function () { - this.combo.populate.apply(this.combo, arguments); - }, + _populate() { + this.combo.populate(...arguments); + } - showView: function () { + showView() { this.combo.showView(); - }, + } - hideView: function () { + hideView() { this.combo.hideView(); - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v || {}; this._assertValue(this.storeValue); this.combo.setValue(this.storeValue); this.numberCounter.setValue(this.storeValue); - }, - - getValue: function () { - return BI.deepClone(this.storeValue); - }, - - populate: function () { - this._populate.apply(this, arguments); - this.numberCounter.populateSwitcher.apply(this.numberCounter, arguments); - }, -}); - -BI.extend(BI.MultiSelectCombo, { - REQ_GET_DATA_LENGTH: 1, - REQ_GET_ALL_DATA: -1, -}); - -BI.MultiSelectCombo.EVENT_BLUR = "EVENT_BLUR"; -BI.MultiSelectCombo.EVENT_FOCUS = "EVENT_FOCUS"; -BI.MultiSelectCombo.EVENT_STOP = "EVENT_STOP"; -BI.MultiSelectCombo.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.MultiSelectCombo.EVENT_CLICK_ITEM = "EVENT_CLICK_ITEM"; -BI.MultiSelectCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; - -BI.shortcut("bi.multi_select_combo", BI.MultiSelectCombo); + } + + getValue() { + return deepClone(this.storeValue); + } + + populate() { + this._populate(...arguments); + this.numberCounter.populateSwitcher(...arguments); + } +} diff --git a/src/widget/multiselect/multiselect.combo.nobar.js b/src/widget/multiselect/multiselect.combo.nobar.js index d757ebbca..332858425 100644 --- a/src/widget/multiselect/multiselect.combo.nobar.js +++ b/src/widget/multiselect/multiselect.combo.nobar.js @@ -1,47 +1,95 @@ -/** - * - * @class BI.MultiSelectNoBarCombo - * @extends BI.Single - */ -BI.MultiSelectNoBarCombo = BI.inherit(BI.Single, { - - _defaultConfig: function () { - return BI.extend(BI.MultiSelectNoBarCombo.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + emptyFn, + isKey, + remove, + deepClone, + createWidget, + toPix, + bind, + last, + initial, + nextTick, + Events, + AbsoluteLayout, + VerticalAdaptLayout, + isNotNull, + makeObject, + map, + each, + Func, + concat, + values, + filter, + contains, + isNull, pushDistinct, Selection +} from "@/core"; +import { Single, Combo } from "@/base"; +import { MultiSelectBar, TriggerIconButton } from "@/case"; +import { MultiSelectTrigger } from "./multiselect.trigger"; +import { MultiSelectCheckSelectedSwitcher } from "./trigger/switcher.checkselected"; +import { MultiSelectNoBarPopupView } from "@/widget/multiselect/multiselect.popup.view.nobar"; + +@shortcut() +export class MultiSelectNoBarCombo extends Single { + static xtype = "bi.multi_select_no_bar_combo"; + + static REQ_GET_DATA_LENGTH = "1"; + static REQ_GET_ALL_DATA = "-1"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_CLICK_ITEM = "EVENT_CLICK_ITEM"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-combo-no-bar", - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, + itemsCreator: emptyFn, + valueFormatter: emptyFn, itemHeight: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, height: 24, }); - }, + } + + _init() { + const self = this, + o = this.options; + super._init(...arguments); + const triggerBtn = createWidget({ + type: TriggerIconButton.xtype, + width: o.height, + height: o.height, + cls: "multi-select-trigger-icon-button", + }); - _init: function () { - var self = this, o = this.options; - BI.MultiSelectNoBarCombo.superclass._init.apply(this, arguments); - var assertShowValue = function () { - if (BI.isKey(self._startValue)) { + function assertShowValue() { + if (isKey(self._startValue)) { if (self.storeValue.type === BI.Selection.All) { - BI.remove(self.storeValue.value, self._startValue); + remove(self.storeValue.value, self._startValue); self.storeValue.assist = self.storeValue.assist || []; - BI.pushDistinct(self.storeValue.assist, self._startValue); + pushDistinct(self.storeValue.assist, self._startValue); } else { - BI.pushDistinct(self.storeValue.value, self._startValue); - BI.remove(self.storeValue.assist, self._startValue); + pushDistinct(self.storeValue.value, self._startValue); + remove(self.storeValue.assist, self._startValue); } } self.trigger.getSearcher().setState(self.storeValue); self.numberCounter.setButtonChecked(self.storeValue); - }; + } + this.storeValue = { - type: BI.Selection.Multi, - value: BI.deepClone(o.value) || [] + type: Selection.Multi, + value: deepClone(o.value) || [], }; // 标记正在请求数据 this.requesting = false; - this.trigger = BI.createWidget({ - type: "bi.multi_select_trigger", - height: BI.toPix(o.height, o.simple ? 1 : 2), + this.trigger = createWidget({ + type: MultiSelectTrigger.xtype, + height: toPix(o.height, o.simple ? 1 : 2), text: o.text, defaultText: o.defaultText, masker: { @@ -53,163 +101,171 @@ BI.MultiSelectNoBarCombo = BI.inherit(BI.Single, { }, }, valueFormatter: o.valueFormatter, - itemsCreator: BI.bind(this._itemsCreator4Trigger, this), + itemsCreator: bind(this._itemsCreator4Trigger, this), itemFormatter: o.itemFormatter, itemHeight: o.itemHeight, value: { type: BI.Selection.Multi, - value: o.value - } + value: o.value, + }, }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_FOCUS, function () { - self.fireEvent(BI.MultiSelectNoBarCombo.EVENT_FOCUS); + this.trigger.on(MultiSelectTrigger.EVENT_FOCUS, () => { + self.fireEvent(MultiSelectNoBarCombo.EVENT_FOCUS); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_BLUR, function () { - self.fireEvent(BI.MultiSelectNoBarCombo.EVENT_BLUR); + this.trigger.on(MultiSelectTrigger.EVENT_BLUR, () => { + self.fireEvent(MultiSelectNoBarCombo.EVENT_BLUR); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_START, function () { + this.trigger.on(MultiSelectTrigger.EVENT_START, function () { self._setStartValue(""); this.getSearcher().setValue(self.storeValue); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_STOP, function () { + this.trigger.on(MultiSelectTrigger.EVENT_STOP, () => { self._setStartValue(""); - self.fireEvent(BI.MultiSelectNoBarCombo.EVENT_STOP); + self.fireEvent(MultiSelectNoBarCombo.EVENT_STOP); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_SEARCHING, function (keywords) { - var last = BI.last(keywords); - keywords = BI.initial(keywords || []); - if (keywords.length > 0) { - self._joinKeywords(keywords, function () { - if (BI.endWith(last, BI.BlankSplitChar)) { - self.combo.setValue(self.storeValue); - assertShowValue(); - self.combo.populate(); - self._setStartValue(""); - } else { - self.combo.setValue(self.storeValue); - assertShowValue(); - } - self._dataChange = true; - }); + this.trigger.on( + MultiSelectTrigger.EVENT_SEARCHING, + keywords => { + const lastKeyword = last(keywords); + keywords = initial(keywords || []); + if (keywords.length > 0) { + self._joinKeywords(keywords, () => { + if (BI.endWith(lastKeyword, BI.BlankSplitChar)) { + self.combo.setValue(self.storeValue); + assertShowValue(); + self.combo.populate(); + self._setStartValue(""); + } else { + self.combo.setValue(self.storeValue); + assertShowValue(); + } + self._dataChange = true; + }); + } } - }); + ); - this.trigger.on(BI.MultiSelectTrigger.EVENT_CHANGE, function (value, obj) { - if (obj instanceof BI.MultiSelectBar) { - self._joinAll(this.getValue(), function () { + this.trigger.on(MultiSelectTrigger.EVENT_CHANGE, function (value, obj) { + if (obj instanceof MultiSelectBar) { + self._joinAll(this.getValue(), () => { assertShowValue(); }); } else { - self._join(this.getValue(), function () { + self._join(this.getValue(), () => { assertShowValue(); }); } self._dataChange = true; - self.fireEvent(BI.MultiSelectNoBarCombo.EVENT_CLICK_ITEM); - }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW, function () { - // counter的值随点击项的改变而改变, 点击counter的时候不需要setValue(counter会请求刷新计数) - // 只需要更新查看面板的selectedValue用以请求已选数据 - self.numberCounter.updateSelectedValue(self.storeValue); + self.fireEvent(MultiSelectNoBarCombo.EVENT_CLICK_ITEM); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_COUNTER_CLICK, function () { + this.trigger.on( + MultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW, + () => { + // counter的值随点击项的改变而改变, 点击counter的时候不需要setValue(counter会请求刷新计数) + // 只需要更新查看面板的selectedValue用以请求已选数据 + self.numberCounter.updateSelectedValue(self.storeValue); + } + ); + this.trigger.on(MultiSelectTrigger.EVENT_COUNTER_CLICK, () => { if (!self.combo.isViewVisible()) { self.combo.showView(); } }); - this.combo = BI.createWidget({ - type: "bi.combo", - cls: (o.simple ? "bi-border-bottom" : "bi-border bi-border-radius"), + this.combo = createWidget({ + type: Combo.xtype, + cls: o.simple ? "bi-border-bottom" : "bi-border bi-border-radius", toggle: false, container: o.container, el: this.trigger, adjustLength: 1, popup: { - type: "bi.multi_select_no_bar_popup_view", - ref: function () { + type: MultiSelectNoBarPopupView.xtype, + ref() { self.popup = this; self.trigger.setAdapter(this); self.numberCounter.setAdapter(this); }, listeners: [ { - eventName: BI.MultiSelectPopupView.EVENT_CHANGE, - action: function () { + eventName: MultiSelectNoBarPopupView.EVENT_CHANGE, + action() { self._dataChange = true; self.storeValue = this.getValue(); - self._adjust(function () { + self._adjust(() => { assertShowValue(); }); - self.fireEvent(BI.MultiSelectNoBarCombo.EVENT_CLICK_ITEM); - } - }, { - eventName: BI.MultiSelectPopupView.EVENT_CLICK_CONFIRM, - action: function () { + self.fireEvent( + MultiSelectNoBarCombo.EVENT_CLICK_ITEM + ); + }, + }, + { + eventName: MultiSelectNoBarPopupView.EVENT_CLICK_CONFIRM, + action() { self._defaultState(); - } - }, { - eventName: BI.MultiSelectPopupView.EVENT_CLICK_CLEAR, - action: function () { + }, + }, + { + eventName: MultiSelectNoBarPopupView.EVENT_CLICK_CLEAR, + action() { self._dataChange = true; self.setValue(); self._defaultState(); - } + }, } ], itemsCreator: o.itemsCreator, itemHeight: o.itemHeight, valueFormatter: o.valueFormatter, itemFormatter: o.itemFormatter, - onLoaded: function () { - BI.nextTick(function () { + onLoaded() { + nextTick(() => { self.combo.adjustWidth(); self.combo.adjustHeight(); self.numberCounter.adjustView(); self.trigger.getSearcher().adjustView(); }); - } + }, }, value: { type: BI.Selection.Multi, - value: o.value + value: o.value, + }, + hideChecker(e) { + return ( + triggerBtn.element.find(e.target).length === 0 && + self.numberCounter.element.find(e.target).length === 0 + ); }, - hideChecker: function (e) { - return triggerBtn.element.find(e.target).length === 0 && self.numberCounter.element.find(e.target).length === 0; - } }); - this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { + this.combo.on(Combo.EVENT_BEFORE_POPUPVIEW, function () { if (!this.isViewVisible()) { - self._dataChange = false;// 标记数据是否发生变化 + self._dataChange = false; // 标记数据是否发生变化 } this.setValue(self.storeValue); - BI.nextTick(function () { + nextTick(() => { self._populate(); }); }); // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; - this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { + this.combo.on(Combo.EVENT_AFTER_HIDEVIEW, () => { // important:关闭弹出时又可能没有退出编辑状态 self._stopEditing(); if (self.requesting === true) { self.wants2Quit = true; } else { - self._dataChange && self.fireEvent(BI.MultiSelectNoBarCombo.EVENT_CONFIRM); + self._dataChange && + self.fireEvent(MultiSelectNoBarCombo.EVENT_CONFIRM); } }); - var triggerBtn = BI.createWidget({ - type: "bi.trigger_icon_button", - width: o.height, - height: o.height, - cls: "multi-select-trigger-icon-button" - }); - triggerBtn.on(BI.TriggerIconButton.EVENT_CHANGE, function () { + triggerBtn.on(TriggerIconButton.EVENT_CHANGE, () => { self.numberCounter.hideView(); if (self.combo.isViewVisible()) { self.combo.hideView(); @@ -218,8 +274,8 @@ BI.MultiSelectNoBarCombo = BI.inherit(BI.Single, { } }); - this.numberCounter = BI.createWidget({ - type: "bi.multi_select_check_selected_switcher", + this.numberCounter = createWidget({ + type: MultiSelectCheckSelectedSwitcher.xtype, masker: { offset: { left: 0, @@ -229,41 +285,54 @@ BI.MultiSelectNoBarCombo = BI.inherit(BI.Single, { }, }, valueFormatter: o.valueFormatter, - itemsCreator: BI.bind(this._itemsCreator4Trigger, this), + itemsCreator: bind(this._itemsCreator4Trigger, this), value: { type: BI.Selection.Multi, - value: o.value - } + value: o.value, + }, }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE, function () { - if (!self.combo.isViewVisible()) { - self.combo.showView(); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE, + () => { + if (!self.combo.isViewVisible()) { + self.combo.showView(); + } } - }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW, function () { - this.updateSelectedValue(self.storeValue); - }); - - this.numberCounter.on(BI.Events.VIEW, function (b) { - BI.nextTick(function () {// 自动调整宽度 - self.trigger.refreshPlaceHolderWidth((b === true ? self.numberCounter.element.outerWidth() + 8 : 0)); + ); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW, + function () { + this.updateSelectedValue(self.storeValue); + } + ); + + this.numberCounter.on(Events.VIEW, b => { + nextTick(() => { + // 自动调整宽度 + self.trigger.refreshPlaceHolderWidth( + b === true ? self.numberCounter.element.outerWidth() + 8 : 0 + ); }); }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_AFTER_HIDEVIEW, function () { - BI.nextTick(function () {// 收起时自动调整宽度 - self.trigger.refreshPlaceHolderWidth(0); - }); - }); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_AFTER_HIDEVIEW, + () => { + nextTick(() => { + // 收起时自动调整宽度 + self.trigger.refreshPlaceHolderWidth(0); + }); + } + ); - this.trigger.element.click(function (e) { + this.trigger.element.click(e => { if (self.trigger.element.find(e.target).length > 0) { self.numberCounter.hideView(); } }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, items: [ { @@ -271,238 +340,247 @@ BI.MultiSelectNoBarCombo = BI.inherit(BI.Single, { left: 0, right: 0, top: 0, - bottom: 0 - }, { + bottom: 0, + }, + { el: triggerBtn, right: 0, top: 0, - bottom: 0 - }, { + bottom: 0, + }, + { el: { - type: "bi.vertical_adapt", - items: [this.numberCounter] + type: VerticalAdaptLayout.xtype, + items: [this.numberCounter], }, right: o.height, top: 0, - height: o.height + height: o.height, } - ] + ], }); - }, + } - _addItem: function (assertShowValue, matched) { - var self = this; - var keyword = this.trigger.getSearcher().getKeyword(); - this._join({ - type: BI.Selection.Multi, - value: [keyword] - }, function () { - // 如果在不选的状态下直接把该值添加进来 - if (self.storeValue.type === BI.Selection.Multi) { - BI.pushDistinct(self.storeValue.value, keyword); + _addItem(assertShowValue, matched) { + const self = this; + const keyword = this.trigger.getSearcher().getKeyword(); + this._join( + { + type: BI.Selection.Multi, + value: [keyword], + }, + () => { + // 如果在不选的状态下直接把该值添加进来 + if (self.storeValue.type === BI.Selection.Multi) { + BI.pushDistinct(self.storeValue.value, keyword); + } + self.combo.setValue(self.storeValue); + self._setStartValue(keyword); + assertShowValue(); + self.populate(); + self._setStartValue(""); + self._dataChange = true; } - self.combo.setValue(self.storeValue); - self._setStartValue(keyword); - assertShowValue(); - self.populate(); - self._setStartValue(""); - self._dataChange = true; - }); - }, + ); + } - _itemsCreator4Trigger: function (op, callback) { - var self = this, o = this.options; + _itemsCreator4Trigger(op, callback) { + const self = this, + o = this.options; o.itemsCreator(op, function (res) { - if (op.times === 1 && BI.isNotNull(op.keywords)) { + if (op.times === 1 && isNotNull(op.keywords)) { // 预防trigger内部把当前的storeValue改掉 - self.trigger.setValue(BI.deepClone(self.storeValue)); + self.trigger.setValue(deepClone(self.storeValue)); } callback.apply(self, arguments); }); - }, + } - _stopEditing: function () { + _stopEditing() { this.trigger.stopEditing(); this.numberCounter.hideView(); - }, + } - _defaultState: function () { + _defaultState() { this._stopEditing(); this.combo.hideView(); - }, + } - _assertValue: function (val) { + _assertValue(val) { val || (val = {}); val.type || (val.type = BI.Selection.Multi); val.value || (val.value = []); - }, + } - _makeMap: function (values) { - return BI.makeObject(values || []); - }, + _makeMap(values) { + return makeObject(values || []); + } - _joinKeywords: function (keywords, callback) { - var self = this, o = this.options; + _joinKeywords(keywords, callback) { + const self = this, + o = this.options; this._assertValue(this.storeValue); this.requesting = true; - o.itemsCreator({ - type: BI.MultiSelectNoBarCombo.REQ_GET_ALL_DATA, - keywords: keywords - }, function (ob) { - var values = BI.map(ob.items, "value"); - digest(values); - }); + o.itemsCreator( + { + type: MultiSelectNoBarCombo.REQ_GET_ALL_DATA, + keywords, + }, + ob => { + const values = map(ob.items, "value"); + digest(values); + } + ); function digest(items) { - var selectedMap = self._makeMap(items); - BI.each(keywords, function (i, val) { - if (BI.isNotNull(selectedMap[val])) { - self.storeValue.type === BI.Selection.Multi ? BI.pushDistinct(self.storeValue.value, val) : BI.remove(self.storeValue.value, val); + const selectedMap = self._makeMap(items); + each(keywords, (i, val) => { + if (isNotNull(selectedMap[val])) { + self.storeValue.type === BI.Selection.Multi + ? BI.pushDistinct(self.storeValue.value, val) + : remove(self.storeValue.value, val); } }); self._adjust(callback); } - }, + } - _joinAll: function (res, callback) { - var self = this, o = this.options; + _joinAll(res, callback) { + const self = this, + o = this.options; this._assertValue(res); this.requesting = true; if (this.storeValue.type === res.type) { - var result = BI.Func.getSearchResult(BI.map(this.storeValue.value, function (_i, v) { - return { - text: o.valueFormatter(v) || v, - value: v - }; - }), this.trigger.getKey()); - var change = false; - var map = this._makeMap(this.storeValue.value); - BI.each(BI.concat(result.match, result.find), function (i, obj) { - var v = obj.value; - if (BI.isNotNull(map[v])) { + const result = Func.getSearchResult( + map(this.storeValue.value, (_i, v) => { + return { + text: o.valueFormatter(v) || v, + value: v, + }; + }), + this.trigger.getKey() + ); + let change = false; + const tempMap = this._makeMap(this.storeValue.value); + each(concat(result.match, result.find), (i, obj) => { + const v = obj.value; + if (isNotNull(tempMap[v])) { change = true; - self.storeValue.assist && self.storeValue.assist.push(map[v]); - delete map[v]; + self.storeValue.assist && + self.storeValue.assist.push(tempMap[v]); + delete tempMap[v]; } }); - change && (this.storeValue.value = BI.values(map)); + change && (this.storeValue.value = values(tempMap)); this._adjust(callback); + return; } - o.itemsCreator({ - type: BI.MultiSelectNoBarCombo.REQ_GET_ALL_DATA, - keywords: [this.trigger.getKey()], - selectedValues: BI.filter(this.storeValue.value, function (_i, v) { - return !BI.contains(res.value, v); - }), - }, function (ob) { - var items = BI.map(ob.items, "value"); - var selectedMap = self._makeMap(self.storeValue.value); - var notSelectedMap = self._makeMap(res.value); - var newItems = []; - BI.each(items, function (i, item) { - if (BI.isNotNull(selectedMap[items[i]])) { - self.storeValue.assist && self.storeValue.assist.push(selectedMap[items[i]]); - delete selectedMap[items[i]]; - } - if (BI.isNull(notSelectedMap[items[i]])) { - BI.remove(self.storeValue.assist, item); - newItems.push(item); - } - }); - self.storeValue.value = newItems.concat(BI.values(selectedMap)); - self._adjust(callback); - }); - }, + o.itemsCreator( + { + type: MultiSelectNoBarCombo.REQ_GET_ALL_DATA, + keywords: [this.trigger.getKey()], + selectedValues: filter(this.storeValue.value, (_i, v) => !contains(res.value, v)), + }, + ob => { + const items = map(ob.items, "value"); + const selectedMap = self._makeMap(self.storeValue.value); + const notSelectedMap = self._makeMap(res.value); + const newItems = []; + each(items, (i, item) => { + if (isNotNull(selectedMap[items[i]])) { + self.storeValue.assist && + self.storeValue.assist.push(selectedMap[items[i]]); + delete selectedMap[items[i]]; + } + if (isNull(notSelectedMap[items[i]])) { + remove(self.storeValue.assist, item); + newItems.push(item); + } + }); + self.storeValue.value = newItems.concat(values(selectedMap)); + self._adjust(callback); + } + ); + } - _adjust: function (callback) { - var self = this, o = this.options; + _adjust(callback) { + const self = this; adjust(); callback(); function adjust() { if (self.wants2Quit === true) { - self._dataChange && self.fireEvent(BI.MultiSelectNoBarCombo.EVENT_CONFIRM); + self._dataChange && + self.fireEvent(MultiSelectNoBarCombo.EVENT_CONFIRM); self.wants2Quit = false; } self.requesting = false; } - }, + } - _join: function (res, callback) { - var self = this, o = this.options; + _join(res, callback) { + const self = this; this._assertValue(res); this._assertValue(this.storeValue); if (this.storeValue.type === res.type) { - var map = this._makeMap(this.storeValue.value); - BI.each(res.value, function (i, v) { + const map = this._makeMap(this.storeValue.value); + each(res.value, (i, v) => { if (!map[v]) { - BI.pushDistinct(self.storeValue.value, v); - BI.remove(self.storeValue.assist, v); + pushDistinct(self.storeValue.value, v); + remove(self.storeValue.assist, v); map[v] = v; } }); - var change = false; - BI.each(res.assist, function (i, v) { - if (BI.isNotNull(map[v])) { + let change = false; + each(res.assist, (i, v) => { + if (isNotNull(map[v])) { change = true; - self.storeValue.assist && self.storeValue.assist.push(map[v]); + self.storeValue.assist && + self.storeValue.assist.push(map[v]); delete map[v]; } }); - change && (this.storeValue.value = BI.values(map)); + change && (this.storeValue.value = values(map)); self._adjust(callback); + return; } this._joinAll(res, callback); - }, + } - _setStartValue: function (value) { + _setStartValue(value) { this._startValue = value; this.popup.setStartValue(value); - }, + } - _populate: function () { - this.combo.populate.apply(this.combo, arguments); - }, + _populate() { + this.combo.populate(...arguments); + } - showView: function () { + showView() { this.combo.showView(); - }, + } - hideView: function () { + hideView() { this.combo.hideView(); - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = { type: BI.Selection.Multi, - value: v || [] + value: v || [], }; this.combo.setValue(this.storeValue); this.numberCounter.setValue(this.storeValue); - }, - - getValue: function () { - return BI.deepClone(this.storeValue.value); - }, - - populate: function () { - this._populate.apply(this, arguments); - this.numberCounter.populateSwitcher.apply(this.numberCounter, arguments); } -}); - -BI.extend(BI.MultiSelectNoBarCombo, { - REQ_GET_DATA_LENGTH: 1, - REQ_GET_ALL_DATA: -1 -}); -BI.MultiSelectNoBarCombo.EVENT_BLUR = "EVENT_BLUR"; -BI.MultiSelectNoBarCombo.EVENT_FOCUS = "EVENT_FOCUS"; -BI.MultiSelectNoBarCombo.EVENT_STOP = "EVENT_STOP"; -BI.MultiSelectNoBarCombo.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.MultiSelectNoBarCombo.EVENT_CLICK_ITEM = "EVENT_CLICK_ITEM"; -BI.MultiSelectNoBarCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; + getValue() { + return deepClone(this.storeValue.value); + } -BI.shortcut("bi.multi_select_no_bar_combo", BI.MultiSelectNoBarCombo); + populate() { + this._populate(...arguments); + this.numberCounter.populateSwitcher(...arguments); + } +} diff --git a/src/widget/multiselect/multiselect.insert.combo.js b/src/widget/multiselect/multiselect.insert.combo.js index c18aa6d90..4d9bb5b3c 100644 --- a/src/widget/multiselect/multiselect.insert.combo.js +++ b/src/widget/multiselect/multiselect.insert.combo.js @@ -1,46 +1,96 @@ -/** - * - * @class BI.MultiSelectInsertCombo - * @extends BI.Single - */ -BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { - - _defaultConfig: function () { - return BI.extend(BI.MultiSelectInsertCombo.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + emptyFn, + isKey, + remove, + deepClone, + createWidget, + toPix, + bind, + last, + initial, + i18nText, + nextTick, + Events, + AbsoluteLayout, + VerticalAdaptLayout, + isNotNull, + makeObject, + each, + Func, + map, + concat, + values, + filter, + contains, + isNull, endWith, pushDistinct, Selection +} from "@/core"; +import { Single, Combo, Msg } from "@/base"; +import { MultiSelectInsertTrigger } from "./multiselect.insert.trigger"; +import { MultiSelectPopupView } from "./multiselect.popup.view"; +import { MultiSelectBar, TriggerIconButton } from "@/case"; +import { MultiSelectCheckSelectedSwitcher } from "./trigger/switcher.checkselected"; + +@shortcut() +export class MultiSelectInsertCombo extends Single { + static xtype = "bi.multi_select_insert_combo"; + + static REQ_GET_DATA_LENGTH = "1"; + static REQ_GET_ALL_DATA = "-1"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_CLICK_ITEM = "EVENT_CLICK_ITEM"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_ADD_ITEM = "EVENT_ADD_ITEM"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-insert-combo", - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, + itemsCreator: emptyFn, + valueFormatter: emptyFn, height: 24, itemHeight: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - allowEdit: true + allowEdit: true, }); - }, - - _init: function () { - var self = this, o = this.options; - BI.MultiSelectInsertCombo.superclass._init.apply(this, arguments); - var assertShowValue = function () { - if (BI.isKey(self._startValue)) { - if (self.storeValue.type === BI.Selection.All) { - BI.remove(self.storeValue.value, self._startValue); + } + + _init() { + const self = this, + o = this.options; + super._init(...arguments); + const triggerBtn = createWidget({ + type: TriggerIconButton.xtype, + width: o.height, + height: o.height, + cls: "multi-select-trigger-icon-button", + }); + + function assertShowValue() { + if (isKey(self._startValue)) { + if (self.storeValue.type === Selection.All) { + remove(self.storeValue.value, self._startValue); self.storeValue.assist = self.storeValue.assist || []; - BI.pushDistinct(self.storeValue.assist, self._startValue); + pushDistinct(self.storeValue.assist, self._startValue); } else { - BI.pushDistinct(self.storeValue.value, self._startValue); - BI.remove(self.storeValue.assist, self._startValue); + pushDistinct(self.storeValue.value, self._startValue); + remove(self.storeValue.assist, self._startValue); } } self.trigger.getSearcher().setState(self.storeValue); self.numberCounter.setButtonChecked(self.storeValue); - }; - this.storeValue = BI.deepClone(o.value) || {}; + } + + this.storeValue = deepClone(o.value) || {}; // 标记正在请求数据 this.requesting = false; - this.trigger = BI.createWidget({ + this.trigger = createWidget({ type: "bi.multi_select_insert_trigger", allowEdit: o.allowEdit, - height: BI.toPix(o.height, o.simple ? 1 : 2), + height: toPix(o.height, o.simple ? 1 : 2), text: o.text, watermark: o.watermark, defaultText: o.defaultText, @@ -50,168 +100,188 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { left: 0, top: 0, right: 0, - bottom: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + 1 - } + bottom: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + 1, + }, }, valueFormatter: o.valueFormatter, - itemsCreator: BI.bind(this._itemsCreator4Trigger, this), + itemsCreator: bind(this._itemsCreator4Trigger, this), itemFormatter: o.itemFormatter, itemHeight: o.itemHeight, value: this.storeValue, }); - this.trigger.on(BI.MultiSelectInsertTrigger.EVENT_FOCUS, function () { - self.fireEvent(BI.MultiSelectInsertCombo.EVENT_FOCUS); + this.trigger.on(MultiSelectInsertTrigger.EVENT_FOCUS, () => { + self.fireEvent(MultiSelectInsertCombo.EVENT_FOCUS); }); - this.trigger.on(BI.MultiSelectInsertTrigger.EVENT_BLUR, function () { - self.fireEvent(BI.MultiSelectInsertCombo.EVENT_BLUR); + this.trigger.on(MultiSelectInsertTrigger.EVENT_BLUR, () => { + self.fireEvent(MultiSelectInsertCombo.EVENT_BLUR); }); - this.trigger.on(BI.MultiSelectInsertTrigger.EVENT_START, function () { + this.trigger.on(MultiSelectInsertTrigger.EVENT_START, function () { self._setStartValue(""); this.getSearcher().setValue(self.storeValue); }); - this.trigger.on(BI.MultiSelectInsertTrigger.EVENT_STOP, function () { + this.trigger.on(MultiSelectInsertTrigger.EVENT_STOP, () => { self._setStartValue(""); - self.fireEvent(BI.MultiSelectInsertCombo.EVENT_STOP); + self.fireEvent(MultiSelectInsertCombo.EVENT_STOP); }); - this.trigger.on(BI.MultiSelectInsertTrigger.EVENT_PAUSE, function () { + this.trigger.on(MultiSelectInsertTrigger.EVENT_PAUSE, function () { self._addItem(assertShowValue, true); - self.fireEvent(BI.MultiSelectInsertCombo.EVENT_ADD_ITEM, this.getSearcher().getKeyword()); + self.fireEvent( + MultiSelectInsertCombo.EVENT_ADD_ITEM, + this.getSearcher().getKeyword() + ); }); - this.trigger.on(BI.MultiSelectInsertTrigger.EVENT_SEARCHING, function (keywords) { - var last = BI.last(keywords); - keywords = BI.initial(keywords || []); - if (keywords.length > 0) { - self._joinKeywords(keywords, function () { - if (BI.endWith(last, BI.BlankSplitChar)) { - self.combo.setValue(self.storeValue); + this.trigger.on( + MultiSelectInsertTrigger.EVENT_SEARCHING, + function (keywords) { + const lastKeyword = last(keywords); + keywords = initial(keywords || []); + if (keywords.length > 0) { + self._joinKeywords(keywords, () => { + if (endWith(lastKeyword, BI.BlankSplitChar)) { + self.combo.setValue(self.storeValue); + assertShowValue(); + self.combo.populate(); + self._setStartValue(""); + } else { + self.combo.setValue(self.storeValue); + assertShowValue(); + } + self._dataChange = true; + }); + this.getSearcher().getKeywordsLength() > 2000 && + Msg.alert( + i18nText("BI-Basic_Prompt"), + i18nText("BI-Basic_Too_Much_Value_Get_Two_Thousand") + ); + } + self.fireEvent(MultiSelectInsertCombo.EVENT_SEARCHING); + } + ); + + this.trigger.on( + MultiSelectInsertTrigger.EVENT_CHANGE, + function (value, obj) { + if (obj instanceof MultiSelectBar) { + self._joinAll(this.getValue(), () => { assertShowValue(); - self.combo.populate(); - self._setStartValue(""); - } else { - self.combo.setValue(self.storeValue); + self.fireEvent(MultiSelectInsertCombo.EVENT_CLICK_ITEM); + }); + } else { + self._join(this.getValue(), () => { assertShowValue(); - } - self._dataChange = true; - }); - this.getSearcher().getKeywordsLength() > 2000 && BI.Msg.alert(BI.i18nText("BI-Basic_Prompt"), BI.i18nText("BI-Basic_Too_Much_Value_Get_Two_Thousand")); + self.fireEvent(MultiSelectInsertCombo.EVENT_CLICK_ITEM); + }); + } + self._dataChange = true; } - self.fireEvent(BI.MultiSelectInsertCombo.EVENT_SEARCHING); - }); - - this.trigger.on(BI.MultiSelectInsertTrigger.EVENT_CHANGE, function (value, obj) { - if (obj instanceof BI.MultiSelectBar) { - self._joinAll(this.getValue(), function () { - assertShowValue(); - self.fireEvent(BI.MultiSelectInsertCombo.EVENT_CLICK_ITEM); - }); - } else { - self._join(this.getValue(), function () { - assertShowValue(); - self.fireEvent(BI.MultiSelectInsertCombo.EVENT_CLICK_ITEM); - }); + ); + this.trigger.on( + MultiSelectInsertTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW, + () => { + // counter的值随点击项的改变而改变, 点击counter的时候不需要setValue(counter会请求刷新计数) + // 只需要更新查看面板的selectedValue用以请求已选数据 + self.numberCounter.updateSelectedValue(self.storeValue); } - self._dataChange = true; - }); - this.trigger.on(BI.MultiSelectInsertTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW, function () { - // counter的值随点击项的改变而改变, 点击counter的时候不需要setValue(counter会请求刷新计数) - // 只需要更新查看面板的selectedValue用以请求已选数据 - self.numberCounter.updateSelectedValue(self.storeValue); - }); - this.trigger.on(BI.MultiSelectInsertTrigger.EVENT_COUNTER_CLICK, function () { - if (!self.combo.isViewVisible()) { - self.combo.showView(); + ); + this.trigger.on( + MultiSelectInsertTrigger.EVENT_COUNTER_CLICK, + () => { + if (!self.combo.isViewVisible()) { + self.combo.showView(); + } } - }); + ); - this.combo = BI.createWidget({ - type: "bi.combo", - cls: (o.simple ? "bi-border-bottom" : "bi-border bi-border-radius"), + this.combo = createWidget({ + type: Combo.xtype, + cls: o.simple ? "bi-border-bottom" : "bi-border bi-border-radius", toggle: !o.allowEdit, el: this.trigger, adjustLength: 1, container: o.container, popup: { type: "bi.multi_select_popup_view", - ref: function () { + ref() { self.popup = this; self.trigger.setAdapter(this); self.numberCounter.setAdapter(this); }, listeners: [ { - eventName: BI.MultiSelectPopupView.EVENT_CHANGE, - action: function () { + eventName: MultiSelectPopupView.EVENT_CHANGE, + action() { self._dataChange = true; self.storeValue = this.getValue(); - self._adjust(function () { + self._adjust(() => { assertShowValue(); }); - self.fireEvent(BI.MultiSelectInsertCombo.EVENT_CLICK_ITEM); - } - }, { - eventName: BI.MultiSelectPopupView.EVENT_CLICK_CONFIRM, - action: function () { + self.fireEvent( + MultiSelectInsertCombo.EVENT_CLICK_ITEM + ); + }, + }, + { + eventName: MultiSelectPopupView.EVENT_CLICK_CONFIRM, + action() { self._defaultState(); - } - }, { - eventName: BI.MultiSelectPopupView.EVENT_CLICK_CLEAR, - action: function () { + }, + }, + { + eventName: MultiSelectPopupView.EVENT_CLICK_CLEAR, + action() { self._dataChange = true; self.setValue(); self._defaultState(); - } + }, } ], itemsCreator: o.itemsCreator, valueFormatter: o.valueFormatter, itemFormatter: o.itemFormatter, itemHeight: o.itemHeight, - onLoaded: function () { - BI.nextTick(function () { + onLoaded() { + nextTick(() => { self.combo.adjustWidth(); self.combo.adjustHeight(); self.numberCounter.adjustView(); self.trigger.getSearcher().adjustView(); }); - } + }, }, value: o.value, - hideChecker: function (e) { - return triggerBtn.element.find(e.target).length === 0 && - self.numberCounter.element.find(e.target).length === 0; - } + hideChecker(e) { + return ( + triggerBtn.element.find(e.target).length === 0 && + self.numberCounter.element.find(e.target).length === 0 + ); + }, }); - this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { + this.combo.on(Combo.EVENT_BEFORE_POPUPVIEW, function () { if (!this.isViewVisible()) { - self._dataChange = false;// 标记数据是否发生变化 + self._dataChange = false; // 标记数据是否发生变化 } this.setValue(self.storeValue); - BI.nextTick(function () { + nextTick(() => { self._populate(); }); }); // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; - this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { + this.combo.on(Combo.EVENT_AFTER_HIDEVIEW, () => { // important:关闭弹出时又可能没有退出编辑状态 self._stopEditing(); if (self.requesting === true) { self.wants2Quit = true; } else { - self._dataChange && self.fireEvent(BI.MultiSelectInsertCombo.EVENT_CONFIRM); + self._dataChange && + self.fireEvent(MultiSelectInsertCombo.EVENT_CONFIRM); } }); - var triggerBtn = BI.createWidget({ - type: "bi.trigger_icon_button", - width: o.height, - height: o.height, - cls: "multi-select-trigger-icon-button" - }); - triggerBtn.on(BI.TriggerIconButton.EVENT_CHANGE, function () { + triggerBtn.on(TriggerIconButton.EVENT_CHANGE, () => { self.numberCounter.hideView(); if (self.combo.isViewVisible()) { self.combo.hideView(); @@ -220,49 +290,62 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { } }); - this.numberCounter = BI.createWidget({ - type: "bi.multi_select_check_selected_switcher", + this.numberCounter = createWidget({ + type: MultiSelectCheckSelectedSwitcher.xtype, masker: { offset: { left: 0, top: 0, right: 0, - bottom: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + 1 - } + bottom: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + 1, + }, }, valueFormatter: o.valueFormatter, - itemsCreator: BI.bind(this._itemsCreator4Trigger, this), - value: o.value + itemsCreator: bind(this._itemsCreator4Trigger, this), + value: o.value, }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE, function () { - if (!self.combo.isViewVisible()) { - self.combo.showView(); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE, + () => { + if (!self.combo.isViewVisible()) { + self.combo.showView(); + } } - }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW, function () { - this.updateSelectedValue(self.storeValue); - }); - - this.numberCounter.on(BI.Events.VIEW, function (b) { - BI.nextTick(function () {// 自动调整宽度 - self.trigger.refreshPlaceHolderWidth((b === true ? self.numberCounter.element.outerWidth() + 8 : 0)); + ); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW, + function () { + this.updateSelectedValue(self.storeValue); + } + ); + + this.numberCounter.on(Events.VIEW, b => { + nextTick(() => { + // 自动调整宽度 + self.trigger.refreshPlaceHolderWidth( + b === true ? self.numberCounter.element.outerWidth() + 8 : 0 + ); }); }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_AFTER_HIDEVIEW, function () { - BI.nextTick(function () {// 收起时自动调整宽度 - self.trigger.refreshPlaceHolderWidth(0); - }); - }); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_AFTER_HIDEVIEW, + () => { + nextTick(() => { + // 收起时自动调整宽度 + self.trigger.refreshPlaceHolderWidth(0); + }); + } + ); - this.trigger.element.click(function (e) { + this.trigger.element.click(e => { if (self.trigger.element.find(e.target).length > 0) { self.numberCounter.hideView(); } }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, items: [ { @@ -270,230 +353,234 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { left: 0, right: 0, top: 0, - bottom: 0 - }, { + bottom: 0, + }, + { el: triggerBtn, right: 0, top: 0, - bottom: 0 - }, { + bottom: 0, + }, + { el: { - type: "bi.vertical_adapt", - items: [this.numberCounter] + type: VerticalAdaptLayout.xtype, + items: [this.numberCounter], }, right: o.height, top: 0, height: o.height, } - ] + ], }); - }, + } - _itemsCreator4Trigger: function (op, callback) { - var self = this, o = this.options; + _itemsCreator4Trigger(op, callback) { + const self = this, + o = this.options; o.itemsCreator(op, function (res) { - if (op.times === 1 && BI.isNotNull(op.keywords)) { + if (op.times === 1 && isNotNull(op.keywords)) { // 预防trigger内部把当前的storeValue改掉 - self.trigger.setValue(BI.deepClone(self.getValue())); + self.trigger.setValue(deepClone(self.getValue())); } callback.apply(self, arguments); }); - }, - - _addItem: function (assertShowValue) { - var self = this; - var keyword = this.trigger.getSearcher().getKeyword(); - this._join({ - type: BI.Selection.Multi, - value: [keyword] - }, function () { - // 如果在不选的状态下直接把该值添加进来 - if (self.storeValue.type === BI.Selection.Multi) { - BI.pushDistinct(self.storeValue.value, keyword); + } + + _addItem(assertShowValue) { + const self = this; + const keyword = this.trigger.getSearcher().getKeyword(); + this._join( + { + type: Selection.Multi, + value: [keyword], + }, + () => { + // 如果在不选的状态下直接把该值添加进来 + if (self.storeValue.type === Selection.Multi) { + pushDistinct(self.storeValue.value, keyword); + } + self.combo.setValue(self.storeValue); + self._setStartValue(keyword); + assertShowValue(); + self.populate(); + self._setStartValue(""); + self._dataChange = true; } - self.combo.setValue(self.storeValue); - self._setStartValue(keyword); - assertShowValue(); - self.populate(); - self._setStartValue(""); - self._dataChange = true; - }); - }, + ); + } - _stopEditing: function () { + _stopEditing() { this.trigger.stopEditing(); this.numberCounter.hideView(); - }, + } - _defaultState: function () { + _defaultState() { this._stopEditing(); this.combo.hideView(); - }, + } - _assertValue: function (val) { + _assertValue(val) { val || (val = {}); - val.type || (val.type = BI.Selection.Multi); + val.type || (val.type = Selection.Multi); val.value || (val.value = []); - }, + } - _makeMap: function (values) { - return BI.makeObject(values || []); - }, + _makeMap(values) { + return makeObject(values || []); + } - _joinKeywords: function (keywords, callback) { - var self = this, o = this.options; + _joinKeywords(keywords, callback) { + const self = this; this._assertValue(this.storeValue); this.requesting = true; digest(); function digest() { - BI.each(keywords, function (i, val) { - self.storeValue.type === BI.Selection.Multi ? BI.pushDistinct(self.storeValue.value, val) : BI.remove(self.storeValue.value, val); + each(keywords, (i, val) => { + self.storeValue.type === Selection.Multi + ? pushDistinct(self.storeValue.value, val) + : remove(self.storeValue.value, val); }); self._adjust(callback); } - }, + } - _joinAll: function (res, callback) { - var self = this, o = this.options; + _joinAll(res, callback) { + const self = this, + o = this.options; this._assertValue(res); this.requesting = true; if (this.storeValue.type === res.type) { - var result = BI.Func.getSearchResult(BI.map(this.storeValue.value, function (_i, v) { - return { - text: o.valueFormatter(v) || v, - value: v - }; - }), this.trigger.getKey()); - var change = false; - var map = this._makeMap(this.storeValue.value); - BI.each(BI.concat(result.match, result.find), function (i, obj) { - var v = obj.value; - if (BI.isNotNull(map[v])) { + const result = Func.getSearchResult( + map(this.storeValue.value, (_i, v) => { + return { + text: o.valueFormatter(v) || v, + value: v, + }; + }), + this.trigger.getKey() + ); + let change = false; + const tempMap = this._makeMap(this.storeValue.value); + each(concat(result.match, result.find), (i, obj) => { + const v = obj.value; + if (isNotNull(tempMap[v])) { change = true; - self.storeValue.assist && self.storeValue.assist.push(map[v]); - delete map[v]; + self.storeValue.assist && + self.storeValue.assist.push(tempMap[v]); + delete tempMap[v]; } }); - change && (this.storeValue.value = BI.values(map)); + change && (this.storeValue.value = values(tempMap)); this._adjust(callback); + return; } - o.itemsCreator({ - type: BI.MultiSelectInsertCombo.REQ_GET_ALL_DATA, - keywords: [this.trigger.getKey()], - selectedValues: BI.filter(this.storeValue.value, function (_i, v) { - return !BI.contains(res.value, v); - }), - }, function (ob) { - var items = BI.map(ob.items, "value"); - var selectedMap = self._makeMap(self.storeValue.value); - var notSelectedMap = self._makeMap(res.value); - var newItems = []; - BI.each(items, function (i, item) { - if (BI.isNotNull(selectedMap[items[i]])) { - self.storeValue.assist && self.storeValue.assist.push(selectedMap[items[i]]); - delete selectedMap[items[i]]; - } - if (BI.isNull(notSelectedMap[items[i]])) { - BI.remove(self.storeValue.assist, item); - newItems.push(item); - } - }); - self.storeValue.value = newItems.concat(BI.values(selectedMap)); - self._adjust(callback); - }); - }, + o.itemsCreator( + { + type: MultiSelectInsertCombo.REQ_GET_ALL_DATA, + keywords: [this.trigger.getKey()], + selectedValues: filter(this.storeValue.value, (_i, v) => !contains(res.value, v)), + }, + ob => { + const items = map(ob.items, "value"); + const selectedMap = self._makeMap(self.storeValue.value); + const notSelectedMap = self._makeMap(res.value); + const newItems = []; + each(items, (i, item) => { + if (isNotNull(selectedMap[items[i]])) { + self.storeValue.assist && + self.storeValue.assist.push(selectedMap[items[i]]); + delete selectedMap[items[i]]; + } + if (isNull(notSelectedMap[items[i]])) { + remove(self.storeValue.assist, item); + newItems.push(item); + } + }); + self.storeValue.value = newItems.concat(values(selectedMap)); + self._adjust(callback); + } + ); + } - _adjust: function (callback) { - var self = this, o = this.options; + _adjust(callback) { + const self = this; adjust(); callback(); function adjust() { if (self.wants2Quit === true) { - self._dataChange && self.fireEvent(BI.MultiSelectInsertCombo.EVENT_CONFIRM); + self._dataChange && + self.fireEvent(MultiSelectInsertCombo.EVENT_CONFIRM); self.wants2Quit = false; } self.requesting = false; } - }, + } - _join: function (res, callback) { - var self = this, o = this.options; + _join(res, callback) { + const self = this; this._assertValue(res); this._assertValue(this.storeValue); if (this.storeValue.type === res.type) { - var map = this._makeMap(this.storeValue.value); - BI.each(res.value, function (i, v) { + const map = this._makeMap(this.storeValue.value); + each(res.value, (i, v) => { if (!map[v]) { - BI.pushDistinct(self.storeValue.value, v); + pushDistinct(self.storeValue.value, v); // value更新的时候assist也需要更新 - BI.remove(self.storeValue.assist, v); + remove(self.storeValue.assist, v); map[v] = v; } }); - var change = false; - BI.each(res.assist, function (i, v) { - if (BI.isNotNull(map[v])) { + let change = false; + each(res.assist, (i, v) => { + if (isNotNull(map[v])) { change = true; - self.storeValue.assist && self.storeValue.assist.push(map[v]); + self.storeValue.assist && + self.storeValue.assist.push(map[v]); delete map[v]; } }); - change && (this.storeValue.value = BI.values(map)); + change && (this.storeValue.value = values(map)); self._adjust(callback); + return; } this._joinAll(res, callback); - }, + } - _setStartValue: function (value) { + _setStartValue(value) { this._startValue = value; this.popup.setStartValue(value); - }, + } - _populate: function () { - this.combo.populate.apply(this.combo, arguments); - }, + _populate() { + this.combo.populate(...arguments); + } - showView: function () { + showView() { this.combo.showView(); - }, + } - hideView: function () { + hideView() { this.combo.hideView(); - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v || {}; this._assertValue(this.storeValue); this.combo.setValue(this.storeValue); this.numberCounter.setValue(this.storeValue); - }, + } - getValue: function () { - return BI.deepClone(this.storeValue); - }, + getValue() { + return deepClone(this.storeValue); + } - populate: function () { - this._populate.apply(this, arguments); - this.numberCounter.populateSwitcher.apply(this.numberCounter, arguments); + populate() { + this._populate(...arguments); + this.numberCounter.populateSwitcher(...arguments); } -}); - -BI.extend(BI.MultiSelectInsertCombo, { - REQ_GET_DATA_LENGTH: 1, - REQ_GET_ALL_DATA: -1 -}); - -BI.MultiSelectInsertCombo.EVENT_FOCUS = "EVENT_FOCUS"; -BI.MultiSelectInsertCombo.EVENT_BLUR = "EVENT_BLUR"; -BI.MultiSelectInsertCombo.EVENT_STOP = "EVENT_STOP"; -BI.MultiSelectInsertCombo.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.MultiSelectInsertCombo.EVENT_CLICK_ITEM = "EVENT_CLICK_ITEM"; -BI.MultiSelectInsertCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.MultiSelectInsertCombo.EVENT_ADD_ITEM = "EVENT_ADD_ITEM"; - -BI.shortcut("bi.multi_select_insert_combo", BI.MultiSelectInsertCombo); +} diff --git a/src/widget/multiselect/multiselect.insert.combo.nobar.js b/src/widget/multiselect/multiselect.insert.combo.nobar.js index d3fbc3862..b6de5dd52 100644 --- a/src/widget/multiselect/multiselect.insert.combo.nobar.js +++ b/src/widget/multiselect/multiselect.insert.combo.nobar.js @@ -1,47 +1,92 @@ -/** - * - * @class BI.MultiSelectInsertCombo - * @extends BI.Single - */ -BI.MultiSelectInsertNoBarCombo = BI.inherit(BI.Single, { - - _defaultConfig: function () { - return BI.extend(BI.MultiSelectInsertNoBarCombo.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + emptyFn, + isKey, + remove, + deepClone, + createWidget, + toPix, + bind, + last, + initial, + i18nText, + nextTick, + Events, + AbsoluteLayout, + VerticalAdaptLayout, + isNotNull, + makeObject, + each, + Func, + map, + concat, + values, + filter, + contains, + isNull, endWith, pushDistinct, Selection +} from "@/core"; +import { Single, Combo, Msg } from "@/base"; +import { MultiSelectInsertTrigger } from "./multiselect.insert.trigger"; +import { MultiSelectBar, TriggerIconButton } from "@/case"; +import { MultiSelectCheckSelectedSwitcher } from "./trigger/switcher.checkselected"; +import { MultiSelectNoBarPopupView } from "./multiselect.popup.view.nobar"; + +@shortcut() +export class MultiSelectInsertNoBarCombo extends Single { + static xtype = "bi.multi_select_insert_no_bar_combo"; + + static REQ_GET_DATA_LENGTH = "1"; + static REQ_GET_ALL_DATA = "-1"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_ADD_ITEM = "EVENT_ADD_ITEM"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-insert-combo-no-bar", - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, + itemsCreator: emptyFn, + valueFormatter: emptyFn, itemHeight: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, height: 24, }); - }, - - _init: function () { - var self = this, o = this.options; - BI.MultiSelectInsertNoBarCombo.superclass._init.apply(this, arguments); - var assertShowValue = function () { - if (BI.isKey(self._startValue)) { - if (self.storeValue.type === BI.Selection.All) { - BI.remove(self.storeValue.value, self._startValue); + } + + _init() { + const self = this, + o = this.options; + super._init(...arguments); + const triggerBtn = createWidget({ + type: TriggerIconButton.xtype, + width: o.height, + height: o.height, + cls: "multi-select-trigger-icon-button", + }); + + function assertShowValue() { + if (isKey(self._startValue)) { + if (self.storeValue.type === Selection.All) { + remove(self.storeValue.value, self._startValue); self.storeValue.assist = self.storeValue.assist || []; - BI.pushDistinct(self.storeValue.assist, self._startValue); + pushDistinct(self.storeValue.assist, self._startValue); } else { - BI.pushDistinct(self.storeValue.value, self._startValue); - BI.remove(self.storeValue.assist, self._startValue); + pushDistinct(self.storeValue.value, self._startValue); + remove(self.storeValue.assist, self._startValue); } } self.trigger.getSearcher().setState(self.storeValue); self.numberCounter.setButtonChecked(self.storeValue); - }; + } + this.storeValue = { - type: BI.Selection.Multi, - value: BI.deepClone(o.value) || [] + type: Selection.Multi, + value: deepClone(o.value) || [], }; // 标记正在请求数据 this.requesting = false; - this.trigger = BI.createWidget({ - type: "bi.multi_select_insert_trigger", - height: BI.toPix(o.height, o.simple ? 1 : 2), + this.trigger = createWidget({ + type: MultiSelectInsertTrigger.xtype, + height: toPix(o.height, o.simple ? 1 : 2), text: o.text, // adapter: this.popup, masker: { @@ -49,161 +94,179 @@ BI.MultiSelectInsertNoBarCombo = BI.inherit(BI.Single, { left: 0, top: 0, right: 0, - bottom: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + 1 - } + bottom: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + 1, + }, }, valueFormatter: o.valueFormatter, - itemsCreator: BI.bind(this._itemsCreator4Trigger, this), + itemsCreator: bind(this._itemsCreator4Trigger, this), itemFormatter: o.itemFormatter, itemHeight: o.itemHeight, value: { - type: BI.Selection.Multi, - value: o.value - } + type: Selection.Multi, + value: o.value, + }, }); - this.trigger.on(BI.MultiSelectInsertTrigger.EVENT_START, function () { + this.trigger.on(MultiSelectInsertTrigger.EVENT_START, function () { self._setStartValue(""); this.getSearcher().setValue(self.storeValue); }); - this.trigger.on(BI.MultiSelectInsertTrigger.EVENT_STOP, function () { + this.trigger.on(MultiSelectInsertTrigger.EVENT_STOP, () => { self._setStartValue(""); }); - this.trigger.on(BI.MultiSelectInsertTrigger.EVENT_PAUSE, function () { + this.trigger.on(MultiSelectInsertTrigger.EVENT_PAUSE, function () { self._addItem(assertShowValue, true); - self.fireEvent(BI.MultiSelectInsertNoBarCombo.EVENT_ADD_ITEM, this.getSearcher().getKeyword()); + self.fireEvent( + MultiSelectInsertNoBarCombo.EVENT_ADD_ITEM, + this.getSearcher().getKeyword() + ); }); - this.trigger.on(BI.MultiSelectInsertTrigger.EVENT_SEARCHING, function (keywords) { - var last = BI.last(keywords); - keywords = BI.initial(keywords || []); - if (keywords.length > 0) { - self._joinKeywords(keywords, function () { - if (BI.endWith(last, BI.BlankSplitChar)) { - self.combo.setValue(self.storeValue); + this.trigger.on( + MultiSelectInsertTrigger.EVENT_SEARCHING, + function (keywords) { + const lastKeyword = last(keywords); + keywords = initial(keywords || []); + if (keywords.length > 0) { + self._joinKeywords(keywords, () => { + if (endWith(lastKeyword, BI.BlankSplitChar)) { + self.combo.setValue(self.storeValue); + assertShowValue(); + self.combo.populate(); + self._setStartValue(""); + } else { + self.combo.setValue(self.storeValue); + assertShowValue(); + } + self._dataChange = true; + }); + this.getSearcher().getKeywordsLength() > 2000 && + Msg.alert( + i18nText("BI-Basic_Prompt"), + i18nText("BI-Basic_Too_Much_Value_Get_Two_Thousand") + ); + } + } + ); + + this.trigger.on( + MultiSelectInsertTrigger.EVENT_CHANGE, + function (value, obj) { + if (obj instanceof MultiSelectBar) { + self._joinAll(this.getValue(), () => { assertShowValue(); - self.combo.populate(); - self._setStartValue(""); - } else { - self.combo.setValue(self.storeValue); + }); + } else { + self._join(this.getValue(), () => { assertShowValue(); - } - self._dataChange = true; - }); - this.getSearcher().getKeywordsLength() > 2000 && BI.Msg.alert(BI.i18nText("BI-Basic_Prompt"), BI.i18nText("BI-Basic_Too_Much_Value_Get_Two_Thousand")); + }); + } + self._dataChange = true; } - }); - - this.trigger.on(BI.MultiSelectInsertTrigger.EVENT_CHANGE, function (value, obj) { - if (obj instanceof BI.MultiSelectBar) { - self._joinAll(this.getValue(), function () { - assertShowValue(); - }); - } else { - self._join(this.getValue(), function () { - assertShowValue(); - }); + ); + this.trigger.on( + MultiSelectInsertTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW, + () => { + // counter的值随点击项的改变而改变, 点击counter的时候不需要setValue(counter会请求刷新计数) + // 只需要更新查看面板的selectedValue用以请求已选数据 + self.numberCounter.updateSelectedValue(self.storeValue); } - self._dataChange = true; - }); - this.trigger.on(BI.MultiSelectInsertTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW, function () { - // counter的值随点击项的改变而改变, 点击counter的时候不需要setValue(counter会请求刷新计数) - // 只需要更新查看面板的selectedValue用以请求已选数据 - self.numberCounter.updateSelectedValue(self.storeValue); - }); - this.trigger.on(BI.MultiSelectInsertTrigger.EVENT_COUNTER_CLICK, function () { - if (!self.combo.isViewVisible()) { - self.combo.showView(); + ); + this.trigger.on( + MultiSelectInsertTrigger.EVENT_COUNTER_CLICK, + () => { + if (!self.combo.isViewVisible()) { + self.combo.showView(); + } } - }); + ); - this.combo = BI.createWidget({ - type: "bi.combo", - cls: (o.simple ? "bi-border-bottom" : "bi-border bi-border-radius"), + this.combo = createWidget({ + type: Combo.xtype, + cls: o.simple ? "bi-border-bottom" : "bi-border bi-border-radius", toggle: false, container: o.container, el: this.trigger, adjustLength: 1, popup: { - type: "bi.multi_select_no_bar_popup_view", - ref: function () { + type: MultiSelectNoBarPopupView.xtype, + ref() { self.popup = this; self.trigger.setAdapter(this); self.numberCounter.setAdapter(this); }, listeners: [ { - eventName: BI.MultiSelectPopupView.EVENT_CHANGE, - action: function () { + eventName: MultiSelectNoBarPopupView.EVENT_CHANGE, + action() { self._dataChange = true; self.storeValue = this.getValue(); - self._adjust(function () { + self._adjust(() => { assertShowValue(); }); - } - }, { - eventName: BI.MultiSelectPopupView.EVENT_CLICK_CONFIRM, - action: function () { + }, + }, + { + eventName: MultiSelectNoBarPopupView.EVENT_CLICK_CONFIRM, + action() { self._defaultState(); - } - }, { - eventName: BI.MultiSelectPopupView.EVENT_CLICK_CLEAR, - action: function () { + }, + }, + { + eventName: MultiSelectNoBarPopupView.EVENT_CLICK_CLEAR, + action() { self._dataChange = true; self.setValue(); self._defaultState(); - } + }, } ], itemsCreator: o.itemsCreator, itemHeight: o.itemHeight, valueFormatter: o.valueFormatter, - onLoaded: function () { - BI.nextTick(function () { + onLoaded() { + nextTick(() => { self.combo.adjustWidth(); self.combo.adjustHeight(); self.numberCounter.adjustView(); self.trigger.getSearcher().adjustView(); }); - } + }, }, value: { - type: BI.Selection.Multi, - value: o.value + type: Selection.Multi, + value: o.value, + }, + hideChecker(e) { + return ( + triggerBtn.element.find(e.target).length === 0 && + self.numberCounter.element.find(e.target).length === 0 + ); }, - hideChecker: function (e) { - return triggerBtn.element.find(e.target).length === 0 && - self.numberCounter.element.find(e.target).length === 0; - } }); - this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { + this.combo.on(Combo.EVENT_BEFORE_POPUPVIEW, function () { if (!this.isViewVisible()) { - self._dataChange = false;// 标记数据是否发生变化 + self._dataChange = false; // 标记数据是否发生变化 } this.setValue(self.storeValue); - BI.nextTick(function () { + nextTick(() => { self._populate(); }); }); // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; - this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { + this.combo.on(Combo.EVENT_AFTER_HIDEVIEW, () => { // important:关闭弹出时又可能没有退出编辑状态 self._stopEditing(); if (self.requesting === true) { self.wants2Quit = true; } else { - self._dataChange && self.fireEvent(BI.MultiSelectInsertNoBarCombo.EVENT_CONFIRM); + self._dataChange && + self.fireEvent(MultiSelectInsertNoBarCombo.EVENT_CONFIRM); } }); - var triggerBtn = BI.createWidget({ - type: "bi.trigger_icon_button", - width: o.height, - height: o.height, - cls: "multi-select-trigger-icon-button" - }); - triggerBtn.on(BI.TriggerIconButton.EVENT_CHANGE, function () { + triggerBtn.on(TriggerIconButton.EVENT_CHANGE, () => { self.numberCounter.hideView(); if (self.combo.isViewVisible()) { self.combo.hideView(); @@ -212,52 +275,65 @@ BI.MultiSelectInsertNoBarCombo = BI.inherit(BI.Single, { } }); - this.numberCounter = BI.createWidget({ - type: "bi.multi_select_check_selected_switcher", + this.numberCounter = createWidget({ + type: MultiSelectCheckSelectedSwitcher.xtype, masker: { offset: { left: 0, top: 0, right: 0, - bottom: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + 1 - } + bottom: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + 1, + }, }, valueFormatter: o.valueFormatter, - itemsCreator: BI.bind(this._itemsCreator4Trigger, this), + itemsCreator: bind(this._itemsCreator4Trigger, this), value: { - type: BI.Selection.Multi, - value: o.value - } + type: Selection.Multi, + value: o.value, + }, }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE, function () { - if (!self.combo.isViewVisible()) { - self.combo.showView(); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE, + () => { + if (!self.combo.isViewVisible()) { + self.combo.showView(); + } } - }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW, function () { - this.updateSelectedValue(self.storeValue); - }); - - this.numberCounter.on(BI.Events.VIEW, function (b) { - BI.nextTick(function () {// 自动调整宽度 - self.trigger.refreshPlaceHolderWidth((b === true ? self.numberCounter.element.outerWidth() + 8 : 0)); + ); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW, + function () { + this.updateSelectedValue(self.storeValue); + } + ); + + this.numberCounter.on(Events.VIEW, b => { + nextTick(() => { + // 自动调整宽度 + self.trigger.refreshPlaceHolderWidth( + b === true ? self.numberCounter.element.outerWidth() + 8 : 0 + ); }); }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_AFTER_HIDEVIEW, function () { - BI.nextTick(function () {// 收起时自动调整宽度 - self.trigger.refreshPlaceHolderWidth(0); - }); - }); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_AFTER_HIDEVIEW, + () => { + nextTick(() => { + // 收起时自动调整宽度 + self.trigger.refreshPlaceHolderWidth(0); + }); + } + ); - this.trigger.element.click(function (e) { + this.trigger.element.click(e => { if (self.trigger.element.find(e.target).length > 0) { self.numberCounter.hideView(); } }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, items: [ { @@ -265,226 +341,235 @@ BI.MultiSelectInsertNoBarCombo = BI.inherit(BI.Single, { left: 0, right: 0, top: 0, - bottom: 0 - }, { + bottom: 0, + }, + { el: triggerBtn, right: 0, top: 0, - bottom: 0 - }, { + bottom: 0, + }, + { el: { - type: "bi.vertical_adapt", - items: [this.numberCounter] + type: VerticalAdaptLayout.xtype, + items: [this.numberCounter], }, right: o.height, top: 0, - height: o.height + height: o.height, } - ] + ], }); - }, + } - _itemsCreator4Trigger: function (op, callback) { - var self = this, o = this.options; + _itemsCreator4Trigger(op, callback) { + const self = this, + o = this.options; o.itemsCreator(op, function (res) { - if (op.times === 1 && BI.isNotNull(op.keywords)) { + if (op.times === 1 && isNotNull(op.keywords)) { // 预防trigger内部把当前的storeValue改掉 - self.trigger.setValue(BI.deepClone(self.storeValue)); + self.trigger.setValue(deepClone(self.storeValue)); } callback.apply(self, arguments); }); - }, - - _addItem: function (assertShowValue) { - var self = this; - var keyword = this.trigger.getSearcher().getKeyword(); - this._join({ - type: BI.Selection.Multi, - value: [keyword] - }, function () { - // 如果在不选的状态下直接把该值添加进来 - if (self.storeValue.type === BI.Selection.Multi) { - BI.pushDistinct(self.storeValue.value, keyword); + } + + _addItem(assertShowValue) { + const self = this; + const keyword = this.trigger.getSearcher().getKeyword(); + this._join( + { + type: Selection.Multi, + value: [keyword], + }, + () => { + // 如果在不选的状态下直接把该值添加进来 + if (self.storeValue.type === Selection.Multi) { + pushDistinct(self.storeValue.value, keyword); + } + self.combo.setValue(self.storeValue); + self._setStartValue(keyword); + assertShowValue(); + self.populate(); + self._setStartValue(""); + self._dataChange = true; } - self.combo.setValue(self.storeValue); - self._setStartValue(keyword); - assertShowValue(); - self.populate(); - self._setStartValue(""); - self._dataChange = true; - }); - }, + ); + } - _stopEditing: function () { + _stopEditing() { this.trigger.stopEditing(); this.numberCounter.hideView(); - }, + } - _defaultState: function () { + _defaultState() { this._stopEditing(); this.combo.hideView(); - }, + } - _assertValue: function (val) { + _assertValue(val) { val || (val = {}); - val.type || (val.type = BI.Selection.Multi); + val.type || (val.type = Selection.Multi); val.value || (val.value = []); - }, + } - _makeMap: function (values) { - return BI.makeObject(values || []); - }, + _makeMap(values) { + return makeObject(values || []); + } - _joinKeywords: function (keywords, callback) { - var self = this, o = this.options; + _joinKeywords(keywords, callback) { + const self = this; this._assertValue(this.storeValue); this.requesting = true; digest(); function digest() { - BI.each(keywords, function (i, val) { - self.storeValue.type === BI.Selection.Multi ? BI.pushDistinct(self.storeValue.value, val) : BI.remove(self.storeValue.value, val); + each(keywords, (i, val) => { + self.storeValue.type === Selection.Multi + ? pushDistinct(self.storeValue.value, val) + : remove(self.storeValue.value, val); }); self._adjust(callback); } - }, + } - _joinAll: function (res, callback) { - var self = this, o = this.options; + _joinAll(res, callback) { + const self = this, + o = this.options; this._assertValue(res); this.requesting = true; if (this.storeValue.type === res.type) { - var result = BI.Func.getSearchResult(BI.map(this.storeValue.value, function (_i, v) { - return { - text: o.valueFormatter(v) || v, - value: v - }; - }), this.trigger.getKey()); - var change = false; - var map = this._makeMap(this.storeValue.value); - BI.each(BI.concat(result.match, result.find), function (i, obj) { - var v = obj.value; - if (BI.isNotNull(map[v])) { + const result = Func.getSearchResult( + map(this.storeValue.value, (_i, v) => { + return { + text: o.valueFormatter(v) || v, + value: v, + }; + }), + this.trigger.getKey() + ); + let change = false; + const tempMap = this._makeMap(this.storeValue.value); + each(concat(result.match, result.find), (i, obj) => { + const v = obj.value; + if (isNotNull(tempMap[v])) { change = true; - self.storeValue.assist && self.storeValue.assist.push(map[v]); - delete map[v]; + self.storeValue.assist && + self.storeValue.assist.push(tempMap[v]); + delete tempMap[v]; } }); - change && (this.storeValue.value = BI.values(map)); + change && (this.storeValue.value = values(tempMap)); this._adjust(callback); + return; } - o.itemsCreator({ - type: BI.MultiSelectInsertNoBarCombo.REQ_GET_ALL_DATA, - keywords: [this.trigger.getKey()], - selectedValues: BI.filter(this.storeValue.value, function (_i, v) { - return !BI.contains(res.value, v); - }), - }, function (ob) { - var items = BI.map(ob.items, "value"); - var selectedMap = self._makeMap(self.storeValue.value); - var notSelectedMap = self._makeMap(res.value); - var newItems = []; - BI.each(items, function (i, item) { - if (BI.isNotNull(selectedMap[items[i]])) { - self.storeValue.assist && self.storeValue.assist.push(selectedMap[items[i]]); - delete selectedMap[items[i]]; - } - if (BI.isNull(notSelectedMap[items[i]])) { - BI.remove(self.storeValue.assist, item); - newItems.push(item); - } - }); - self.storeValue.value = newItems.concat(BI.values(selectedMap)); - self._adjust(callback); - }); - }, + o.itemsCreator( + { + type: MultiSelectInsertNoBarCombo.REQ_GET_ALL_DATA, + keywords: [this.trigger.getKey()], + selectedValues: filter(this.storeValue.value, (_i, v) => !contains(res.value, v)), + }, + ob => { + const items = map(ob.items, "value"); + const selectedMap = self._makeMap(self.storeValue.value); + const notSelectedMap = self._makeMap(res.value); + const newItems = []; + each(items, (i, item) => { + if (isNotNull(selectedMap[items[i]])) { + self.storeValue.assist && + self.storeValue.assist.push(selectedMap[items[i]]); + delete selectedMap[items[i]]; + } + if (isNull(notSelectedMap[items[i]])) { + remove(self.storeValue.assist, item); + newItems.push(item); + } + }); + self.storeValue.value = newItems.concat(values(selectedMap)); + self._adjust(callback); + } + ); + } - _adjust: function (callback) { - var self = this, o = this.options; + _adjust(callback) { + const self = this; adjust(); callback(); function adjust() { if (self.wants2Quit === true) { - self._dataChange && self.fireEvent(BI.MultiSelectInsertNoBarCombo.EVENT_CONFIRM); + self._dataChange && + self.fireEvent(MultiSelectInsertNoBarCombo.EVENT_CONFIRM); self.wants2Quit = false; } self.requesting = false; } - }, + } - _join: function (res, callback) { - var self = this, o = this.options; + _join(res, callback) { + const self = this; this._assertValue(res); this._assertValue(this.storeValue); if (this.storeValue.type === res.type) { - var map = this._makeMap(this.storeValue.value); - BI.each(res.value, function (i, v) { + const map = this._makeMap(this.storeValue.value); + each(res.value, (i, v) => { if (!map[v]) { self.storeValue.value.push(v); - BI.remove(self.storeValue.assist, v); + remove(self.storeValue.assist, v); map[v] = v; } }); - var change = false; - BI.each(res.assist, function (i, v) { - if (BI.isNotNull(map[v])) { + let change = false; + each(res.assist, (i, v) => { + if (isNotNull(map[v])) { change = true; - self.storeValue.assist && self.storeValue.assist.push(map[v]); + self.storeValue.assist && + self.storeValue.assist.push(map[v]); delete map[v]; } }); - change && (this.storeValue.value = BI.values(map)); + change && (this.storeValue.value = values(map)); self._adjust(callback); + return; } this._joinAll(res, callback); - }, + } - _setStartValue: function (value) { + _setStartValue(value) { this._startValue = value; this.popup.setStartValue(value); - }, + } - _populate: function () { - this.combo.populate.apply(this.combo, arguments); - }, + _populate() { + this.combo.populate(...arguments); + } - showView: function () { + showView() { this.combo.showView(); - }, + } - hideView: function () { + hideView() { this.combo.hideView(); - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = { - type: BI.Selection.Multi, - value: v || [] + type: Selection.Multi, + value: v || [], }; this.combo.setValue(this.storeValue); this.numberCounter.setValue(this.storeValue); - }, - - getValue: function () { - return BI.deepClone(this.storeValue.value); - }, - - populate: function () { - this._populate.apply(this, arguments); - this.numberCounter.populateSwitcher.apply(this.numberCounter, arguments); } -}); -BI.extend(BI.MultiSelectInsertNoBarCombo, { - REQ_GET_DATA_LENGTH: 1, - REQ_GET_ALL_DATA: -1 -}); - -BI.MultiSelectInsertNoBarCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.MultiSelectInsertNoBarCombo.EVENT_ADD_ITEM = "EVENT_ADD_ITEM"; + getValue() { + return deepClone(this.storeValue.value); + } -BI.shortcut("bi.multi_select_insert_no_bar_combo", BI.MultiSelectInsertNoBarCombo); + populate() { + this._populate(...arguments); + this.numberCounter.populateSwitcher(...arguments); + } +} diff --git a/src/widget/multiselect/multiselect.insert.trigger.js b/src/widget/multiselect/multiselect.insert.trigger.js index 4ed1b19ef..9b5fd3761 100644 --- a/src/widget/multiselect/multiselect.insert.trigger.js +++ b/src/widget/multiselect/multiselect.insert.trigger.js @@ -1,40 +1,55 @@ -/** - * - * 复选下拉框 - * @class BI.MultiSelectInsertTrigger - * @extends BI.Trigger - */ - -BI.MultiSelectInsertTrigger = BI.inherit(BI.Trigger, { - - constants: { - height: 14, - rgap: 4, - lgap: 4 - }, - - _defaultConfig: function () { - return BI.extend(BI.MultiSelectInsertTrigger.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + emptyFn, + createWidget, + Layout, + HTapeLayout, + AbsoluteLayout +} from "@/core"; +import { Trigger, Text } from "@/base"; +import { MultiSelectInsertSearcher } from "./trigger/searcher.multiselect.insert"; + +@shortcut() +export class MultiSelectInsertTrigger extends Trigger { + static xtype = "bi.multi_select_insert_trigger"; + + constants = { height: 14, rgap: 4, lgap: 4 }; + + static EVENT_TRIGGER_CLICK = "EVENT_TRIGGER_CLICK"; + static EVENT_COUNTER_CLICK = "EVENT_COUNTER_CLICK"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_START = "EVENT_START"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_BEFORE_COUNTER_POPUPVIEW = "EVENT_BEFORE_COUNTER_POPUPVIEW"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-trigger", - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, + itemsCreator: emptyFn, + valueFormatter: emptyFn, itemHeight: 24, searcher: {}, switcher: {}, adapter: null, masker: {}, - allowEdit: true + allowEdit: true, }); - }, + } - _init: function () { - BI.MultiSelectInsertTrigger.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, o = this.options; + const self = this, + o = this.options; - this.searcher = BI.createWidget(o.searcher, { - type: "bi.multi_select_insert_searcher", + this.searcher = createWidget(o.searcher, { + type: MultiSelectInsertSearcher.xtype, height: o.height, text: o.text, defaultText: o.defaultText, @@ -46,113 +61,106 @@ BI.MultiSelectInsertTrigger = BI.inherit(BI.Trigger, { popup: {}, adapter: o.adapter, masker: o.masker, - value: o.value - }); - this.searcher.on(BI.MultiSelectInsertSearcher.EVENT_START, function () { - self.fireEvent(BI.MultiSelectInsertTrigger.EVENT_START); + value: o.value, }); - this.searcher.on(BI.MultiSelectInsertSearcher.EVENT_PAUSE, function () { - self.fireEvent(BI.MultiSelectInsertTrigger.EVENT_PAUSE); + this.searcher.on(MultiSelectInsertSearcher.EVENT_START, () => { + self.fireEvent(MultiSelectInsertTrigger.EVENT_START); }); - this.searcher.on(BI.MultiSelectInsertSearcher.EVENT_SEARCHING, function () { - self.fireEvent(BI.MultiSelectInsertTrigger.EVENT_SEARCHING, arguments); + this.searcher.on(MultiSelectInsertSearcher.EVENT_PAUSE, () => { + self.fireEvent(MultiSelectInsertTrigger.EVENT_PAUSE); }); - this.searcher.on(BI.MultiSelectInsertSearcher.EVENT_STOP, function () { - self.fireEvent(BI.MultiSelectInsertTrigger.EVENT_STOP); + this.searcher.on( + MultiSelectInsertSearcher.EVENT_SEARCHING, + function () { + self.fireEvent( + MultiSelectInsertTrigger.EVENT_SEARCHING, + arguments + ); + } + ); + this.searcher.on(MultiSelectInsertSearcher.EVENT_STOP, () => { + self.fireEvent(MultiSelectInsertTrigger.EVENT_STOP); }); - this.searcher.on(BI.MultiSelectInsertSearcher.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiSelectInsertTrigger.EVENT_CHANGE, arguments); + this.searcher.on(MultiSelectInsertSearcher.EVENT_CHANGE, function () { + self.fireEvent(MultiSelectInsertTrigger.EVENT_CHANGE, arguments); }); - this.searcher.on(BI.MultiSelectInsertSearcher.EVENT_BLUR, function () { - self.fireEvent(BI.MultiSelectInsertTrigger.EVENT_BLUR); + this.searcher.on(MultiSelectInsertSearcher.EVENT_BLUR, () => { + self.fireEvent(MultiSelectInsertTrigger.EVENT_BLUR); }); - this.searcher.on(BI.MultiSelectInsertSearcher.EVENT_FOCUS, function () { - self.fireEvent(BI.MultiSelectInsertTrigger.EVENT_FOCUS); + this.searcher.on(MultiSelectInsertSearcher.EVENT_FOCUS, () => { + self.fireEvent(MultiSelectInsertTrigger.EVENT_FOCUS); }); - this.wrapNumberCounter = BI.createWidget({ - type: "bi.layout" + this.wrapNumberCounter = createWidget({ + type: Layout.xtype, }); - this.wrapper = BI.createWidget({ - type: "bi.htape", + this.wrapper = createWidget({ + type: HTapeLayout.xtype, element: this, items: [ { el: this.searcher, - width: "fill" - }, { + width: "fill", + }, + { el: this.wrapNumberCounter, - width: 0 - }, { - el: BI.createWidget(), - width: 24 + width: 0, + }, + { + el: createWidget(), + width: 24, } - ] + ], }); - !o.allowEdit && BI.createWidget({ - type: "bi.absolute", + !o.allowEdit && + createWidget({ + type: AbsoluteLayout.xtype, element: this, items: [ { el: { - type: "bi.text", - title: function () { + type: Text.xtype, + title() { return self.searcher.getState(); - } + }, }, left: 0, right: 24, top: 0, - bottom: 0 + bottom: 0, } - ] + ], }); - }, + } - /** - * 重新调整numberCounter的空白占位符 - */ - refreshPlaceHolderWidth: function (width) { + refreshPlaceHolderWidth(width) { this.wrapper.attr("items")[1].width = width; this.wrapper.resize(); - }, + } - getSearcher: function () { + getSearcher() { return this.searcher; - }, + } - stopEditing: function () { + stopEditing() { this.searcher.stopSearch(); - }, + } - setAdapter: function (adapter) { + setAdapter(adapter) { this.searcher.setAdapter(adapter); - }, + } - setValue: function (ob) { + setValue(ob) { this.searcher.setValue(ob); - }, + } - getKey: function () { + getKey() { return this.searcher.getKey(); - }, + } - getValue: function () { + getValue() { return this.searcher.getValue(); } -}); - -BI.MultiSelectInsertTrigger.EVENT_TRIGGER_CLICK = "EVENT_TRIGGER_CLICK"; -BI.MultiSelectInsertTrigger.EVENT_COUNTER_CLICK = "EVENT_COUNTER_CLICK"; -BI.MultiSelectInsertTrigger.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiSelectInsertTrigger.EVENT_START = "EVENT_START"; -BI.MultiSelectInsertTrigger.EVENT_STOP = "EVENT_STOP"; -BI.MultiSelectInsertTrigger.EVENT_PAUSE = "EVENT_PAUSE"; -BI.MultiSelectInsertTrigger.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.MultiSelectInsertTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW = "EVENT_BEFORE_COUNTER_POPUPVIEW"; -BI.MultiSelectInsertTrigger.EVENT_FOCUS = "EVENT_FOCUS"; -BI.MultiSelectInsertTrigger.EVENT_BLUR = "EVENT_BLUR"; - -BI.shortcut("bi.multi_select_insert_trigger", BI.MultiSelectInsertTrigger); +} diff --git a/src/widget/multiselect/multiselect.loader.js b/src/widget/multiselect/multiselect.loader.js index 2aa22aad5..ed92dfc69 100644 --- a/src/widget/multiselect/multiselect.loader.js +++ b/src/widget/multiselect/multiselect.loader.js @@ -1,75 +1,107 @@ -/** - * 多选加载数据面板 - * Created by guy on 15/11/2. - * @class BI.MultiSelectLoader - * @extends Widget - */ -BI.MultiSelectLoader = BI.inherit(BI.Widget, { - - _defaultConfig: function () { - return BI.extend(BI.MultiSelectLoader.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + Widget, + extend, + emptyFn, + createWidget, + isKey, + map, + contains, + remove, + Controller, + delay, + isNotNull, + Selection, Direction, LogicFactory, pushDistinct +} from "@/core"; +import { SelectList, MultiSelectBar, MultiSelectItem } from "@/case"; +import { MultiSelectInnerLoader } from "./loader"; + +@shortcut() +export class MultiSelectLoader extends Widget { + static xtype = "bi.multi_select_loader"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-loader", logic: { - dynamic: true + dynamic: true, }, el: { - height: 400 + height: 400, }, - valueFormatter: BI.emptyFn, - itemsCreator: BI.emptyFn, - itemFormatter: BI.emptyFn, - onLoaded: BI.emptyFn, + valueFormatter: emptyFn, + itemsCreator: emptyFn, + itemFormatter: emptyFn, + onLoaded: emptyFn, itemHeight: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, isDefaultInit: false, }); - }, + } - _init: function () { - BI.MultiSelectLoader.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, opts = this.options; - var hasNext = false; + const self = this, + opts = this.options; + let hasNext = false; this.storeValue = opts.value || {}; this._assertValue(this.storeValue); - this.button_group = BI.createWidget({ - type: "bi.select_list", + this.button_group = createWidget({ + type: SelectList.xtype, logic: opts.logic, toolbar: { - type: "bi.multi_select_bar", + type: MultiSelectBar.xtype, cls: "bi-list-item-active", - height: this.options.itemHeight || BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - iconWrapperWidth: 36 + height: + this.options.itemHeight || + BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, + iconWrapperWidth: 36, }, - el: BI.extend({ - onLoaded: opts.onLoaded, - el: { - type: "bi.multi_select_inner_loader", - isDefaultInit: opts.isDefaultInit, - } - }, opts.el), - itemsCreator: function (op, callback) { - var startValue = self._startValue; - self.storeValue && (op = BI.extend(op || {}, { - selectedValues: BI.isKey(startValue) && self.storeValue.type === BI.Selection.Multi - ? self.storeValue.value.concat(startValue) : self.storeValue.value + el: extend( + { + onLoaded: opts.onLoaded, + el: { + type: MultiSelectInnerLoader.xtype, + isDefaultInit: opts.isDefaultInit, + }, + }, + opts.el + ), + itemsCreator(op, callback) { + const startValue = self._startValue; + self.storeValue && + (op = extend(op || {}, { + selectedValues: + isKey(startValue) && + self.storeValue.type === Selection.Multi + ? self.storeValue.value.concat(startValue) + : self.storeValue.value, })); - opts.itemsCreator(op, function (ob) { + opts.itemsCreator(op, ob => { hasNext = ob.hasNext; - var firstItems = []; + let firstItems = []; if (op.times === 1 && self.storeValue) { - var json = BI.map(self.storeValue.value, function (i, v) { - var txt = opts.valueFormatter(v) || v; + const json = map(self.storeValue.value, (i, v) => { + const txt = opts.valueFormatter(v) || v; + return { text: txt, value: v, title: txt, - selected: self.storeValue.type === BI.Selection.Multi, + selected: + self.storeValue.type === Selection.Multi, }; }); - if (BI.isKey(self._startValue) && !BI.contains(self.storeValue.value, self._startValue)) { - var txt = opts.valueFormatter(startValue) || startValue; + if ( + isKey(self._startValue) && + !contains(self.storeValue.value, self._startValue) + ) { + const txt = + opts.valueFormatter(startValue) || startValue; json.unshift({ text: txt, value: startValue, @@ -79,108 +111,134 @@ BI.MultiSelectLoader = BI.inherit(BI.Widget, { } firstItems = self._createItems(json); } - callback(firstItems.concat(self._createItems(ob.items)), ob.keyword || ""); + callback( + firstItems.concat(self._createItems(ob.items)), + ob.keyword || "" + ); if (op.times === 1 && self.storeValue) { - BI.isKey(startValue) && (self.storeValue.type === BI.Selection.All ? BI.remove(self.storeValue.value, startValue) : BI.pushDistinct(self.storeValue.value, startValue)); + isKey(startValue) && + (self.storeValue.type === Selection.All + ? remove(self.storeValue.value, startValue) + : pushDistinct( + self.storeValue.value, + startValue + )); self.setValue(self.storeValue); } - (op.times === 1) && self._scrollToTop(); + op.times === 1 && self._scrollToTop(); }); }, - hasNext: function () { + hasNext() { return hasNext; }, - value: this.storeValue + value: this.storeValue, }); - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Top), BI.extend({ - scrolly: true, - vgap: 5 - }, opts.logic, { - items: BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Top, this.button_group) - })))); - this.button_group.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + createWidget( + extend( + { + element: this, + }, + LogicFactory.createLogic( + LogicFactory.createLogicTypeByDirection( + Direction.Top + ), + extend( + { + scrolly: true, + vgap: 5, + }, + opts.logic, + { + items: LogicFactory.createLogicItemsByDirection( + Direction.Top, + this.button_group + ), + } + ) + ) + ) + ); + this.button_group.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.button_group.on(BI.SelectList.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiSelectLoader.EVENT_CHANGE, arguments); + this.button_group.on(SelectList.EVENT_CHANGE, function () { + self.fireEvent(MultiSelectLoader.EVENT_CHANGE, arguments); }); - }, + } - _createItems: function (items) { - var allSelected = this.isAllSelected(); - var itemFormatter = this.options.itemFormatter; - return BI.map(items, (i, item) => { + _createItems(items) { + const allSelected = this.isAllSelected(); + const itemFormatter = this.options.itemFormatter; + + return map(items, (i, item) => { return { - type: "bi.multi_select_item", + type: MultiSelectItem.xtype, logic: this.options.logic, cls: "bi-list-item-active", - height: this.options.itemHeight || BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, + height: + this.options.itemHeight || + BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, selected: allSelected, iconWrapperWidth: 36, ...item, ...itemFormatter(item), }; }); - }, + } - _scrollToTop: function () { - var self = this; - BI.delay(function () { + _scrollToTop() { + const self = this; + delay(() => { self.button_group.element.scrollTop(0); }, 30); - }, + } - isAllSelected: function () { + isAllSelected() { return this.button_group.isAllSelected(); - }, + } - _assertValue: function (val) { + _assertValue(val) { val || (val = {}); - val.type || (val.type = BI.Selection.Multi); + val.type || (val.type = Selection.Multi); val.value || (val.value = []); - }, + } - setStartValue: function (v) { + setStartValue(v) { this._startValue = v; - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v || {}; this._assertValue(this.storeValue); this.button_group.setValue(this.storeValue); - }, + } - getValue: function () { + getValue() { return this.button_group.getValue(); - }, + } - getAllButtons: function () { + getAllButtons() { return this.button_group.getAllButtons(); - }, + } - empty: function () { + empty() { this.button_group.empty(); - }, + } - populate: function (items) { - // arguments.length为0时对arguments[0]赋值后不同环境对其length的取值不同(nashorn) - if (BI.isNotNull(items)) { - arguments[0] = this._createItems(items); + populate(...args) { + const items = args[0]; + if (isNotNull(items)) { + args[0] = this._createItems(items); } - this.button_group.populate.apply(this.button_group, arguments); - }, + this.button_group.populate(...args); + } - resetHeight: function (h) { + resetHeight(h) { this.button_group.resetHeight(h - 10); - }, + } - resetWidth: function (w) { + resetWidth(w) { this.button_group.resetWidth(w); } -}); - -BI.MultiSelectLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multi_select_loader", BI.MultiSelectLoader); +} diff --git a/src/widget/multiselect/multiselect.loader.nobar.js b/src/widget/multiselect/multiselect.loader.nobar.js index dde974df8..55a30caa6 100644 --- a/src/widget/multiselect/multiselect.loader.nobar.js +++ b/src/widget/multiselect/multiselect.loader.nobar.js @@ -1,185 +1,242 @@ -/** - * 多选加载数据面板 - * Created by guy on 15/11/2. - * @class BI.MultiSelectNoBarLoader - * @extends Widget - */ -BI.MultiSelectNoBarLoader = BI.inherit(BI.Widget, { - - _defaultConfig: function () { - return BI.extend(BI.MultiSelectNoBarLoader.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + Widget, + extend, + emptyFn, + createWidget, + isKey, + map, + contains, + remove, + Controller, + VerticalLayout, + delay, + isNotNull, + toPix, + Selection, + pushDistinct +} from "@/core"; +import { ButtonGroup, Loader } from "@/base"; +import { SelectList, ListPane, MultiSelectItem } from "@/case"; + +@shortcut() +export class MultiSelectNoBarLoader extends Widget { + static xtype = "bi.multi_select_no_bar_loader"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-loader", logic: { - dynamic: true + dynamic: true, }, el: { - height: 400 + height: 400, }, - valueFormatter: BI.emptyFn, - itemsCreator: BI.emptyFn, + valueFormatter: emptyFn, + itemsCreator: emptyFn, itemHeight: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - onLoaded: BI.emptyFn, - itemFormatter: BI.emptyFn, + onLoaded: emptyFn, + itemFormatter: emptyFn, }); - }, + } - _init: function () { - BI.MultiSelectNoBarLoader.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, opts = this.options; - var hasNext = false; + const self = this, + opts = this.options; + let hasNext = false; this.storeValue = opts.value || {}; this._assertValue(this.storeValue); - this.button_group = BI.createWidget(BI.extend({ - type: "bi.list_pane", - onLoaded: opts.onLoaded, - el: { - type: "bi.loader", - isDefaultInit: false, - logic: { - dynamic: true, - scrolly: true - }, - el: { - chooseType: BI.ButtonGroup.CHOOSE_TYPE_MULTI, - behaviors: { - redmark: function () { - return true; - } + this.button_group = createWidget( + extend( + { + type: ListPane.xtype, + onLoaded: opts.onLoaded, + el: { + type: Loader.xtype, + isDefaultInit: false, + logic: { + dynamic: true, + scrolly: true, + }, + el: { + chooseType: ButtonGroup.CHOOSE_TYPE_MULTI, + behaviors: { + redmark() { + return true; + }, + }, + layouts: [ + { + type: VerticalLayout.xtype, + } + ], + }, }, - layouts: [{ - type: "bi.vertical" - }] - } - }, - itemsCreator: function (op, callback) { - var startValue = self._startValue; - self.storeValue && (op = BI.extend(op || {}, { - selectedValues: BI.isKey(startValue) && self.storeValue.type === BI.Selection.Multi - ? self.storeValue.value.concat(startValue) : self.storeValue.value - })); - opts.itemsCreator(op, function (ob) { - hasNext = ob.hasNext; - var firstItems = []; - if (op.times === 1 && self.storeValue) { - var json = BI.map(self.storeValue.value, function (i, v) { - var txt = opts.valueFormatter(v) || v; - return { - text: txt, - value: v, - title: txt, - selected: self.storeValue.type === BI.Selection.Multi - }; + itemsCreator(op, callback) { + const startValue = self._startValue; + self.storeValue && + (op = extend(op || {}, { + selectedValues: + isKey(startValue) && + self.storeValue.type === Selection.Multi + ? self.storeValue.value.concat( + startValue + ) + : self.storeValue.value, + })); + opts.itemsCreator(op, ob => { + hasNext = ob.hasNext; + let firstItems = []; + if (op.times === 1 && self.storeValue) { + const json = map( + self.storeValue.value, + (i, v) => { + const txt = opts.valueFormatter(v) || v; + + return { + text: txt, + value: v, + title: txt, + selected: + self.storeValue.type === + Selection.Multi, + }; + } + ); + if ( + isKey(self._startValue) && + !contains( + self.storeValue.value, + self._startValue + ) + ) { + const txt = + opts.valueFormatter(startValue) || + startValue; + json.unshift({ + text: txt, + value: startValue, + title: txt, + selected: true, + }); + } + firstItems = self._createItems(json); + } + callback( + firstItems.concat(self._createItems(ob.items)), + ob.keyword || "" + ); + if (op.times === 1 && self.storeValue) { + isKey(startValue) && + (self.storeValue.type === Selection.All + ? remove( + self.storeValue.value, + startValue + ) + : pushDistinct( + self.storeValue.value, + startValue + )); + self.setValue(self.storeValue); + } + op.times === 1 && self._scrollToTop(); }); - if (BI.isKey(self._startValue) && !BI.contains(self.storeValue.value, self._startValue)) { - var txt = opts.valueFormatter(startValue) || startValue; - json.unshift({ - text: txt, - value: startValue, - title: txt, - selected: true - }); - } - firstItems = self._createItems(json); - } - callback(firstItems.concat(self._createItems(ob.items)), ob.keyword || ""); - if (op.times === 1 && self.storeValue) { - BI.isKey(startValue) && (self.storeValue.type === BI.Selection.All ? BI.remove(self.storeValue.value, startValue) : BI.pushDistinct(self.storeValue.value, startValue)); - self.setValue(self.storeValue); - } - (op.times === 1) && self._scrollToTop(); - }); - }, - hasNext: function () { - return hasNext; - }, - value: this.storeValue - }, opts.el)); + }, + hasNext() { + return hasNext; + }, + value: this.storeValue, + }, + opts.el + ) + ); - BI.createWidget({ - type: "bi.vertical", + createWidget({ + type: VerticalLayout.xtype, element: this, items: [this.button_group], - vgap: 5 + vgap: 5, }); - this.button_group.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.button_group.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.button_group.on(BI.SelectList.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiSelectNoBarLoader.EVENT_CHANGE, arguments); + this.button_group.on(SelectList.EVENT_CHANGE, function () { + self.fireEvent(MultiSelectNoBarLoader.EVENT_CHANGE, arguments); }); - }, + } - _createItems: function (items) { - return BI.map(items, (index, item) => { + _createItems(items) { + return map(items, (index, item) => { return { - type: "bi.multi_select_item", + type: MultiSelectItem.xtype, cls: "bi-list-item-active", logic: this.options.logic, - height: this.options.itemHeight || BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, + height: + this.options.itemHeight || + BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, iconWrapperWidth: 36, ...item, ...this.options.itemFormatter(item), }; }); - }, + } - _scrollToTop: function () { - var self = this; - BI.delay(function () { + _scrollToTop() { + const self = this; + delay(() => { self.button_group.element.scrollTop(0); }, 30); - }, + } - _assertValue: function (val) { + _assertValue(val) { val || (val = {}); - val.type || (val.type = BI.Selection.Multi); + val.type || (val.type = Selection.Multi); val.value || (val.value = []); - }, + } - setStartValue: function (v) { + setStartValue(v) { this._startValue = v; - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v || {}; this._assertValue(this.storeValue); this.button_group.setValue(this.storeValue.value); - }, + } - getValue: function () { + getValue() { return { - type: BI.Selection.Multi, - value: this.button_group.getValue() + type: Selection.Multi, + value: this.button_group.getValue(), }; - }, + } - getAllButtons: function () { + getAllButtons() { return this.button_group.getAllButtons(); - }, + } - empty: function () { + empty() { this.button_group.empty(); - }, + } - populate: function (items) { - if (BI.isNotNull(items)) { + populate(items) { + if (isNotNull(items)) { arguments[0] = this._createItems(items); } - this.button_group.populate.apply(this.button_group, arguments); - }, - - resetHeight: function (h) { - this.button_group.element.css({ "max-height": BI.toPix(h) }); - }, - - resetWidth: function () { + this.button_group.populate(...arguments); + } + resetHeight(h) { + this.button_group.element.css({ "max-height": toPix(h) }); } -}); -BI.MultiSelectNoBarLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multi_select_no_bar_loader", BI.MultiSelectNoBarLoader); + resetWidth() { + } +} diff --git a/src/widget/multiselect/multiselect.popup.view.js b/src/widget/multiselect/multiselect.popup.view.js index 1e11376d2..c16cbc196 100644 --- a/src/widget/multiselect/multiselect.popup.view.js +++ b/src/widget/multiselect/multiselect.popup.view.js @@ -1,100 +1,113 @@ -/** - * 带加载的多选下拉面板 - * @class BI.MultiSelectPopupView - * @extends Widget - */ -BI.MultiSelectPopupView = BI.inherit(BI.Widget, { - - _defaultConfig: function () { - return BI.extend(BI.MultiSelectPopupView.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + Widget, + extend, + emptyFn, + createWidget, + i18nText +} from "@/core"; +import { MultiPopupView } from "@/case"; +import { MultiSelectLoader } from "./multiselect.loader"; + +@shortcut() +export class MultiSelectPopupView extends Widget { + static xtype = "bi.multi_select_popup_view"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_CLICK_CONFIRM = "EVENT_CLICK_CONFIRM"; + static EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-popup-view", maxWidth: "auto", minWidth: 135, maxHeight: 400, - valueFormatter: BI.emptyFn, - itemsCreator: BI.emptyFn, - onLoaded: BI.emptyFn, + valueFormatter: emptyFn, + itemsCreator: emptyFn, + onLoaded: emptyFn, itemHeight: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, }); - }, + } - _init: function () { - BI.MultiSelectPopupView.superclass._init.apply(this, arguments); - var self = this, opts = this.options; + _init() { + super._init(...arguments); + const self = this, + opts = this.options; - this.loader = BI.createWidget({ - type: "bi.multi_select_loader", + this.loader = createWidget({ + type: MultiSelectLoader.xtype, itemsCreator: opts.itemsCreator, itemHeight: opts.itemHeight, valueFormatter: opts.valueFormatter, itemFormatter: opts.itemFormatter, onLoaded: opts.onLoaded, - value: opts.value + value: opts.value, }); - this.popupView = BI.createWidget({ - type: "bi.multi_popup_view", + this.popupView = createWidget({ + type: MultiPopupView.xtype, stopPropagation: false, maxWidth: opts.maxWidth, minWidth: opts.minWidth, maxHeight: opts.maxHeight, element: this, - buttons: [BI.i18nText("BI-Basic_Clears"), BI.i18nText("BI-Basic_OK")], + buttons: [i18nText("BI-Basic_Clears"), i18nText("BI-Basic_OK")], el: this.loader, - value: opts.value + value: opts.value, }); - this.popupView.on(BI.MultiPopupView.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiSelectPopupView.EVENT_CHANGE); + this.popupView.on(MultiPopupView.EVENT_CHANGE, () => { + self.fireEvent(MultiSelectPopupView.EVENT_CHANGE); }); - this.popupView.on(BI.MultiPopupView.EVENT_CLICK_TOOLBAR_BUTTON, function (index) { - switch (index) { - case 0: - self.fireEvent(BI.MultiSelectPopupView.EVENT_CLICK_CLEAR); - break; - case 1: - self.fireEvent(BI.MultiSelectPopupView.EVENT_CLICK_CONFIRM); - break; + this.popupView.on( + MultiPopupView.EVENT_CLICK_TOOLBAR_BUTTON, + index => { + switch (index) { + case 0: + self.fireEvent(MultiSelectPopupView.EVENT_CLICK_CLEAR); + break; + case 1: + self.fireEvent( + MultiSelectPopupView.EVENT_CLICK_CONFIRM + ); + break; + default: + break; + } } - }); - }, + ); + } - isAllSelected: function () { + isAllSelected() { return this.loader.isAllSelected(); - }, + } - setStartValue: function (v) { + setStartValue(v) { this.loader.setStartValue(v); - }, + } - setValue: function (v) { + setValue(v) { this.popupView.setValue(v); - }, + } - getValue: function () { + getValue() { return this.popupView.getValue(); - }, + } - populate: function (items) { - this.popupView.populate.apply(this.popupView, arguments); - }, + populate(items) { + this.popupView.populate(...arguments); + } - resetHeight: function (h) { + resetHeight(h) { this.popupView.resetHeight(h); - }, + } - resetWidth: function (w) { + resetWidth(w) { this.popupView.resetWidth(w); - }, + } - setDirection: function (direction, position) { + setDirection(direction, position) { this.popupView.setDirection(direction, position); - }, -}); - -BI.MultiSelectPopupView.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiSelectPopupView.EVENT_CLICK_CONFIRM = "EVENT_CLICK_CONFIRM"; -BI.MultiSelectPopupView.EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; - - -BI.shortcut("bi.multi_select_popup_view", BI.MultiSelectPopupView); + } +} diff --git a/src/widget/multiselect/multiselect.popup.view.nobar.js b/src/widget/multiselect/multiselect.popup.view.nobar.js index c0007f85a..5a8d150d7 100644 --- a/src/widget/multiselect/multiselect.popup.view.nobar.js +++ b/src/widget/multiselect/multiselect.popup.view.nobar.js @@ -1,96 +1,109 @@ -/** - * 带加载的多选下拉面板 - * @class BI.MultiSelectPopupView - * @extends Widget - */ -BI.MultiSelectNoBarPopupView = BI.inherit(BI.Widget, { +import { + shortcut, + Widget, + extend, + emptyFn, + createWidget, + i18nText +} from "@/core"; +import { MultiPopupView } from "@/case"; +import { MultiSelectNoBarLoader } from "./multiselect.loader.nobar"; - _defaultConfig: function () { - return BI.extend(BI.MultiSelectNoBarPopupView.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class MultiSelectNoBarPopupView extends Widget { + static xtype = "bi.multi_select_no_bar_popup_view"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_CLICK_CONFIRM = "EVENT_CLICK_CONFIRM"; + static EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-popup-view", maxWidth: "auto", minWidth: 135, maxHeight: 400, - valueFormatter: BI.emptyFn, - itemsCreator: BI.emptyFn, + valueFormatter: emptyFn, + itemsCreator: emptyFn, itemHeight: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - onLoaded: BI.emptyFn + onLoaded: emptyFn, }); - }, + } - _init: function () { - BI.MultiSelectNoBarPopupView.superclass._init.apply(this, arguments); - var self = this, opts = this.options; + _init() { + super._init(...arguments); + const self = this, + opts = this.options; - this.loader = BI.createWidget({ - type: "bi.multi_select_no_bar_loader", + this.loader = createWidget({ + type: MultiSelectNoBarLoader.xtype, itemsCreator: opts.itemsCreator, itemHeight: opts.itemHeight, valueFormatter: opts.valueFormatter, itemFormatter: opts.itemFormatter, onLoaded: opts.onLoaded, - value: opts.value + value: opts.value, }); - this.popupView = BI.createWidget({ - type: "bi.multi_popup_view", + this.popupView = createWidget({ + type: MultiPopupView.xtype, stopPropagation: false, maxWidth: opts.maxWidth, minWidth: opts.minWidth, maxHeight: opts.maxHeight, element: this, - buttons: [BI.i18nText("BI-Basic_Clears"), BI.i18nText("BI-Basic_OK")], + buttons: [i18nText("BI-Basic_Clears"), i18nText("BI-Basic_OK")], el: this.loader, - value: opts.value + value: opts.value, }); - this.popupView.on(BI.MultiPopupView.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiSelectNoBarPopupView.EVENT_CHANGE); + this.popupView.on(MultiPopupView.EVENT_CHANGE, () => { + self.fireEvent(MultiSelectNoBarPopupView.EVENT_CHANGE); }); - this.popupView.on(BI.MultiPopupView.EVENT_CLICK_TOOLBAR_BUTTON, function (index) { - switch (index) { - case 0: - self.fireEvent(BI.MultiSelectNoBarPopupView.EVENT_CLICK_CLEAR); - break; - case 1: - self.fireEvent(BI.MultiSelectNoBarPopupView.EVENT_CLICK_CONFIRM); - break; + this.popupView.on( + MultiPopupView.EVENT_CLICK_TOOLBAR_BUTTON, + index => { + switch (index) { + case 0: + self.fireEvent( + MultiSelectNoBarPopupView.EVENT_CLICK_CLEAR + ); + break; + case 1: + self.fireEvent( + MultiSelectNoBarPopupView.EVENT_CLICK_CONFIRM + ); + break; + } } - }); - }, + ); + } - setStartValue: function (v) { + setStartValue(v) { this.loader.setStartValue(v); - }, + } - setValue: function (v) { + setValue(v) { this.popupView.setValue(v); - }, + } - getValue: function () { + getValue() { return this.popupView.getValue(); - }, + } - populate: function (items) { - this.popupView.populate.apply(this.popupView, arguments); - }, + populate(items) { + this.popupView.populate(...arguments); + } - resetHeight: function (h) { + resetHeight(h) { this.popupView.resetHeight(h); - }, + } - resetWidth: function (w) { + resetWidth(w) { this.popupView.resetWidth(w); - }, + } - setDirection: function (direction, position) { + setDirection(direction, position) { this.popupView.setDirection(direction, position); - }, -}); - -BI.MultiSelectNoBarPopupView.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiSelectNoBarPopupView.EVENT_CLICK_CONFIRM = "EVENT_CLICK_CONFIRM"; -BI.MultiSelectNoBarPopupView.EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; - - -BI.shortcut("bi.multi_select_no_bar_popup_view", BI.MultiSelectNoBarPopupView); + } +} diff --git a/src/widget/multiselect/multiselect.trigger.js b/src/widget/multiselect/multiselect.trigger.js index f2affe91a..e938837c6 100644 --- a/src/widget/multiselect/multiselect.trigger.js +++ b/src/widget/multiselect/multiselect.trigger.js @@ -9,7 +9,7 @@ import { AbsoluteLayout } from "@/core"; import { Trigger, Text } from "@/base"; -import { MultiSelectSearcher } from "trigger/searcher.multiselect"; +import { MultiSelectSearcher } from "./trigger/searcher.multiselect"; @shortcut() export class MultiSelectTrigger extends Trigger { @@ -103,30 +103,30 @@ export class MultiSelectTrigger extends Trigger { }); !o.allowEdit && - createWidget({ - type: AbsoluteLayout.xtype, - element: this, - items: [ - { - el: { - type: Text.xtype, - title () { - /** 修正REPORT-73699引入,需要考虑到传递过来的值是方法的情况 */ - const state = self.searcher.getState(); - if (isFunction(state)) { - return state(); - } - - return state; - }, + createWidget({ + type: AbsoluteLayout.xtype, + element: this, + items: [ + { + el: { + type: Text.xtype, + title() { + /** 修正REPORT-73699引入,需要考虑到传递过来的值是方法的情况 */ + const state = self.searcher.getState(); + if (isFunction(state)) { + return state(); + } + + return state; }, - left: 0, - right: 24, - top: 0, - bottom: 0, - } - ], - }); + }, + left: 0, + right: 24, + top: 0, + bottom: 0, + } + ], + }); } refreshPlaceHolderWidth(width) { diff --git a/src/widget/multiselect/search/multiselect.search.insert.pane.js b/src/widget/multiselect/search/multiselect.search.insert.pane.js index d459dc73a..ce139fee6 100644 --- a/src/widget/multiselect/search/multiselect.search.insert.pane.js +++ b/src/widget/multiselect/search/multiselect.search.insert.pane.js @@ -1,99 +1,109 @@ -/** - * - * 在搜索框中输入文本弹出的面板 - * @class BI.MultiSelectSearchInsertPane - * @extends Widget - */ - -BI.MultiSelectSearchInsertPane = BI.inherit(BI.Widget, { - - constants: { - height: 24, - lgap: 10, - tgap: 5 - }, - - _defaultConfig: function () { - return BI.extend(BI.MultiSelectSearchInsertPane.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + Widget, + extend, + emptyFn, + createWidget, + i18nText, + Controller, VerticalFillLayout +} from "@/core"; +import { Label } from "@/base"; +import { MultiSelectSearchLoader } from "./multiselect.search.loader"; + +@shortcut() +export class MultiSelectSearchInsertPane extends Widget { + static xtype = "bi.multi_select_search_insert_pane"; + + constants = { height: 24, lgap: 10, tgap: 5 }; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-search-pane bi-card", - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, - keywordGetter: BI.emptyFn, - itemHeight: 24 + itemsCreator: emptyFn, + valueFormatter: emptyFn, + keywordGetter: emptyFn, + itemHeight: 24, }); - }, + } - _init: function () { - BI.MultiSelectSearchInsertPane.superclass._init.apply(this, arguments); - var self = this, o = this.options; + _init() { + super._init(...arguments); + const self = this, + o = this.options; - this.addNotMatchTip = BI.createWidget({ - type: "bi.label", - text: BI.i18nText("BI-Basic_Press_Enter_To_Add_Text", ""), + this.addNotMatchTip = createWidget({ + type: Label.xtype, + text: i18nText("BI-Basic_Press_Enter_To_Add_Text", ""), height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, cls: "bi-keyword-red-mark", hgap: 5, }); - this.loader = BI.createWidget({ - type: "bi.multi_select_search_loader", + this.loader = createWidget({ + type: MultiSelectSearchLoader.xtype, keywordGetter: o.keywordGetter, valueFormatter: o.valueFormatter, itemFormatter: o.itemFormatter, - itemsCreator: function (op, callback) { - o.itemsCreator.apply(self, [op, function (res) { - callback(res); - self.setKeyword(o.keywordGetter()); - }]); + itemsCreator(op, callback) { + o.itemsCreator.apply(self, [ + op, + function (res) { + callback(res); + self.setKeyword(o.keywordGetter()); + } + ]); }, itemHeight: o.itemHeight, - value: o.value + value: o.value, }); - this.loader.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.loader.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.resizer = BI.createWidget({ - type: "bi.vertical_fill", + this.resizer = createWidget({ + type: VerticalFillLayout.xtype, rowSize: ["", "fill"], element: this, - items: [{ - el: this.addNotMatchTip, - }, { - el: this.loader, - }], + items: [ + { + el: this.addNotMatchTip, + }, + { + el: this.loader, + } + ], }); - }, + } - setKeyword: function (keyword) { - this.addNotMatchTip.setText(BI.i18nText("BI-Basic_Press_Enter_To_Add_Text", keyword)); - }, + setKeyword(keyword) { + this.addNotMatchTip.setText( + i18nText("BI-Basic_Press_Enter_To_Add_Text", keyword) + ); + } - isAllSelected: function () { + isAllSelected() { return this.loader.isAllSelected(); - }, + } - hasMatched: function () { + hasMatched() { return false; - }, + } - setValue: function (v) { + setValue(v) { this.loader.setValue(v); - }, + } - getValue: function () { + getValue() { return this.loader.getValue(); - }, + } - empty: function () { + empty() { this.loader.empty(); - }, - - populate: function (items) { - this.loader.populate.apply(this.loader, arguments); } -}); - -BI.MultiSelectSearchInsertPane.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multi_select_search_insert_pane", BI.MultiSelectSearchInsertPane); + populate(items) { + this.loader.populate(...arguments); + } +} diff --git a/src/widget/multiselect/search/multiselect.search.loader.js b/src/widget/multiselect/search/multiselect.search.loader.js index 5f6d09f54..b52361dba 100644 --- a/src/widget/multiselect/search/multiselect.search.loader.js +++ b/src/widget/multiselect/search/multiselect.search.loader.js @@ -1,136 +1,160 @@ -/** - * 多选加载数据搜索loader面板 - * Created by guy on 15/11/4. - * @class BI.MultiSelectSearchLoader - * @extends Widget - */ -BI.MultiSelectSearchLoader = BI.inherit(BI.Widget, { - - _defaultConfig: function () { - return BI.extend(BI.MultiSelectSearchLoader.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + Widget, + extend, + emptyFn, + deepClone, + createWidget, + i18nText, + Controller, + VerticalLayout, + map, + isKey, + Func +} from "@/core"; +import { ButtonGroup, Loader } from "@/base"; +import { SelectList, MultiSelectBar, MultiSelectItem } from "@/case"; + +@shortcut() +export class MultiSelectSearchLoader extends Widget { + static xtype = "bi.multi_select_search_loader"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-search-loader", - itemsCreator: BI.emptyFn, - keywordGetter: BI.emptyFn, - valueFormatter: BI.emptyFn, - itemFormatter: BI.emptyFn, - itemHeight: 24 + itemsCreator: emptyFn, + keywordGetter: emptyFn, + valueFormatter: emptyFn, + itemFormatter: emptyFn, + itemHeight: 24, }); - }, + } - _init: function () { - BI.MultiSelectSearchLoader.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, opts = this.options; - var hasNext = false; - this.storeValue = BI.deepClone(opts.value); - this.button_group = BI.createWidget({ - type: "bi.select_list", + const self = this, + opts = this.options; + let hasNext = false; + this.storeValue = deepClone(opts.value); + this.button_group = createWidget({ + type: SelectList.xtype, toolbar: { - type: "bi.multi_select_bar", + type: MultiSelectBar.xtype, cls: "bi-list-item-active", - iconWrapperWidth: 36 + iconWrapperWidth: 36, }, element: this, logic: { - dynamic: false + dynamic: false, }, value: opts.value, el: { - tipText: BI.i18nText("BI-No_Select"), + tipText: i18nText("BI-No_Select"), el: { - type: "bi.loader", + type: Loader.xtype, isDefaultInit: false, logic: { dynamic: true, - scrolly: true + scrolly: true, }, el: { - chooseType: BI.ButtonGroup.CHOOSE_TYPE_MULTI, + chooseType: ButtonGroup.CHOOSE_TYPE_MULTI, behaviors: { - redmark: function () { + redmark() { return true; - } + }, }, layouts: [ { - type: "bi.vertical" + type: VerticalLayout.xtype, } - ] - } - } + ], + }, + }, }, - itemsCreator: function (op, callback) { - self.storeValue && (op = BI.extend(op || {}, { - selectedValues: self.storeValue.value + itemsCreator(op, callback) { + self.storeValue && + (op = extend(op || {}, { + selectedValues: self.storeValue.value, })); - opts.itemsCreator(op, function (ob) { - var keyword = ob.keyword = opts.keywordGetter(); + opts.itemsCreator(op, ob => { + const keyword = (ob.keyword = opts.keywordGetter()); hasNext = ob.hasNext; - var firstItems = []; + let firstItems = []; if (op.times === 1 && self.storeValue) { - var json = self._filterValues(self.storeValue); + const json = self._filterValues(self.storeValue); firstItems = self._createItems(json); } - var context = { + const context = { tipText: ob.tipText, }; - callback(firstItems.concat(self._createItems(ob.items)), keyword, context); + callback( + firstItems.concat(self._createItems(ob.items)), + keyword, + context + ); if (op.times === 1 && self.storeValue) { self.setValue(self.storeValue); } }); }, - hasNext: function () { + hasNext() { return hasNext; - } + }, }); - this.button_group.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.button_group.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.button_group.on(BI.SelectList.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiSelectSearchLoader.EVENT_CHANGE, arguments); + this.button_group.on(SelectList.EVENT_CHANGE, function () { + self.fireEvent(MultiSelectSearchLoader.EVENT_CHANGE, arguments); }); - }, + } + + _createItems(items) { + const allSelected = this.isAllSelected(); + const itemFormatter = this.options.itemFormatter; - _createItems: function (items) { - var allSelected = this.isAllSelected(); - var itemFormatter = this.options.itemFormatter; - - return BI.map(items, (index, item) => { + return map(items, (index, item) => { return { - type: "bi.multi_select_item", + type: MultiSelectItem.xtype, logic: { - dynamic: false + dynamic: false, }, - height: this.options.itemHeight || BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, + height: + this.options.itemHeight || + BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, selected: allSelected, cls: "bi-list-item-active", iconWrapperWidth: 36, ...item, - ...itemFormatter(item) + ...itemFormatter(item), }; }); - }, + } - isAllSelected: function () { + isAllSelected() { return this.button_group.isAllSelected(); - }, + } - _filterValues: function (src) { - var o = this.options; - var keyword = o.keywordGetter(); - var values = BI.deepClone(src.value) || []; - var newValues = BI.map(values, function (i, v) { + _filterValues(src) { + const o = this.options; + const keyword = o.keywordGetter(); + let values = deepClone(src.value) || []; + const newValues = map(values, (i, v) => { return { text: o.valueFormatter(v) || v, value: v, }; }); - if (BI.isKey(keyword)) { - var search = BI.Func.getSearchResult(newValues, keyword); + if (isKey(keyword)) { + const search = Func.getSearchResult(newValues, keyword); values = search.match.concat(search.find); } - return BI.map(values, function (i, v) { + + return map(values, (i, v) => { return { text: v.text, title: v.text, @@ -139,38 +163,35 @@ BI.MultiSelectSearchLoader = BI.inherit(BI.Widget, { ...o.itemFormatter(v), }; }); - }, + } - setValue: function (v) { + setValue(v) { // 暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 - this.storeValue = BI.deepClone(v); + this.storeValue = deepClone(v); this.button_group.setValue(v); - }, + } - getValue: function () { + getValue() { return this.button_group.getValue(); - }, + } - getAllButtons: function () { + getAllButtons() { return this.button_group.getAllButtons(); - }, + } - empty: function () { + empty() { this.button_group.empty(); - }, + } - populate: function (items) { - this.button_group.populate.apply(this.button_group, arguments); - }, + populate(items) { + this.button_group.populate(...arguments); + } - resetHeight: function (h) { + resetHeight(h) { this.button_group.resetHeight(h); - }, + } - resetWidth: function (w) { + resetWidth(w) { this.button_group.resetWidth(w); } -}); - -BI.MultiSelectSearchLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multi_select_search_loader", BI.MultiSelectSearchLoader); +} diff --git a/src/widget/multiselect/search/multiselect.search.pane.js b/src/widget/multiselect/search/multiselect.search.pane.js index 98c733348..0a8ead08b 100644 --- a/src/widget/multiselect/search/multiselect.search.pane.js +++ b/src/widget/multiselect/search/multiselect.search.pane.js @@ -1,86 +1,92 @@ -/** - * - * 在搜索框中输入文本弹出的面板 - * @class BI.MultiSelectSearchPane - * @extends Widget - */ +import { + shortcut, + Widget, + extend, + emptyFn, + createWidget, + Controller, + AbsoluteLayout +} from "@/core"; +import { MultiSelectSearchLoader } from "./multiselect.search.loader"; -BI.MultiSelectSearchPane = BI.inherit(BI.Widget, { +@shortcut() +export class MultiSelectSearchPane extends Widget { + static xtype = "bi.multi_select_search_pane"; - constants: { - height: 24, - lgap: 10, - tgap: 5 - }, + constants = { height: 24, lgap: 10, tgap: 5 }; - _defaultConfig: function () { - return BI.extend(BI.MultiSelectSearchPane.superclass._defaultConfig.apply(this, arguments), { + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-search-pane bi-card", - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, - keywordGetter: BI.emptyFn, + itemsCreator: emptyFn, + valueFormatter: emptyFn, + keywordGetter: emptyFn, itemHeight: 24, }); - }, + } - _init: function () { - BI.MultiSelectSearchPane.superclass._init.apply(this, arguments); - var self = this, o = this.options; + _init() { + super._init(...arguments); + const self = this, + o = this.options; - this.loader = BI.createWidget({ - type: "bi.multi_select_search_loader", + this.loader = createWidget({ + type: MultiSelectSearchLoader.xtype, keywordGetter: o.keywordGetter, valueFormatter: o.valueFormatter, itemFormatter: o.itemFormatter, - itemsCreator: function (op, callback) { - o.itemsCreator.apply(self, [op, function (res) { - callback(res); - }]); + itemsCreator(op, callback) { + o.itemsCreator.apply(self, [ + op, + function (res) { + callback(res); + } + ]); }, itemHeight: o.itemHeight, - value: o.value + value: o.value, }); - this.loader.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.loader.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.resizer = BI.createWidget({ - type: "bi.absolute", + this.resizer = createWidget({ + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.loader, - left: 0, - right: 0, - bottom: 0, - top: 0, - }], + items: [ + { + el: this.loader, + left: 0, + right: 0, + bottom: 0, + top: 0, + } + ], }); - }, + } - isAllSelected: function () { + isAllSelected() { return this.loader.isAllSelected(); - }, + } - hasMatched: function () { - }, + hasMatched() { + } - setValue: function (v) { + setValue(v) { this.loader.setValue(v); - }, + } - getValue: function () { + getValue() { return this.loader.getValue(); - }, + } - empty: function () { + empty() { this.loader.empty(); - }, - - populate: function (items) { - this.loader.populate.apply(this.loader, arguments); } -}); -BI.MultiSelectSearchPane.EVENT_CHANGE = "EVENT_CHANGE"; - -BI.shortcut("bi.multi_select_search_pane", BI.MultiSelectSearchPane); + populate(items) { + this.loader.populate(...arguments); + } +} diff --git a/src/widget/multiselect/trigger/button.checkselected.js b/src/widget/multiselect/trigger/button.checkselected.js index 97854a485..275013a86 100644 --- a/src/widget/multiselect/trigger/button.checkselected.js +++ b/src/widget/multiselect/trigger/button.checkselected.js @@ -7,7 +7,8 @@ import { i18nText, isNotNull, isNotEmptyString, - nextTick + nextTick, + Selection } from "@/core"; import { Single, TextButton } from "@/base"; import { MultiSelectCombo } from "../multiselect.combo"; @@ -67,13 +68,13 @@ export class MultiSelectCheckSelectedButton extends Single { _populate(ob) { const self = this, o = this.options; - if (ob.type === BI.Selection.All) { + if (ob.type === Selection.All) { o.itemsCreator( { type: MultiSelectCombo.REQ_GET_DATA_LENGTH, }, res => { - if (self.options.value.type !== BI.Selection.All) { + if (self.options.value.type !== Selection.All) { return; } if (isNotEmptyString(res.count)) { @@ -91,7 +92,7 @@ export class MultiSelectCheckSelectedButton extends Single { }); } ); - + return; } nextTick(() => { @@ -104,7 +105,7 @@ export class MultiSelectCheckSelectedButton extends Single { ob || (ob = {}); ob.type || (ob.type = BI.Selection.Multi); ob.value || (ob.value = []); - + return ob; } @@ -118,5 +119,6 @@ export class MultiSelectCheckSelectedButton extends Single { this._populate(this._assertValue(this.options.value)); } - getValue() {} + getValue() { + } } diff --git a/src/widget/multiselect/trigger/editor.multiselect.js b/src/widget/multiselect/trigger/editor.multiselect.js index ed8217cb6..f2e33a410 100644 --- a/src/widget/multiselect/trigger/editor.multiselect.js +++ b/src/widget/multiselect/trigger/editor.multiselect.js @@ -9,6 +9,7 @@ import { isEmptyArray } from "@/core"; import { StateEditor } from "@/case"; +import { SelectPatchEditor } from "./editor/editor.patch"; @shortcut() export class MultiSelectEditor extends Widget { @@ -31,7 +32,7 @@ export class MultiSelectEditor extends Widget { const self = this, o = this.options; this.editor = createWidget(o.el, { - type: "bi.select_patch_editor", + type: SelectPatchEditor.xtype, element: this, height: o.height, watermark: o.watermark, @@ -101,12 +102,10 @@ export class MultiSelectEditor extends Widget { if (isEmptyString(keywords[keywords.length - 1])) { keywords = keywords.slice(0, keywords.length - 1); } - + return isEmptyArray(keywords) ? "" : keywords[keywords.length - 1]; } - populate(items) {} - setWaterMark(v) { this.editor.setWaterMark(v); } diff --git a/src/widget/multiselect/trigger/editor/editor.patch.js b/src/widget/multiselect/trigger/editor/editor.patch.js index bec2ae7db..237109ef5 100644 --- a/src/widget/multiselect/trigger/editor/editor.patch.js +++ b/src/widget/multiselect/trigger/editor/editor.patch.js @@ -1,214 +1,248 @@ -/** - * @author windy - * @version 2.0 - * Created by windy on 2021/5/18 - */ -BI.SelectPatchEditor = BI.inherit(BI.Widget, { - - props: { - baseCls: "bi-patch-select-editor", - height: 24, - }, - - render: function () { - var self = this, o = this.options; - - var debounceInputChange = BI.debounce(BI.bind(this._dealChange, this), 300); - - return BI.extend({ - type: "bi.state_editor", - ref: function (_ref) { - self.editor = _ref; - }, - hgap: o.hgap, - vgap: o.vgap, - lgap: o.lgap, - rgap: o.rgap, - tgap: o.tgap, - bgap: o.bgap, - height: o.height, - watermark: o.watermark, - allowBlank: true, - value: o.value, - defaultText: o.defaultText, - text: o.text, - tipType: o.tipType, - warningTitle: o.warningTitle, - el: { - type: 'bi.textarea_editor', - scrolly: false, - validationChecker: function () { - return true; +import { + shortcut, + Widget, + debounce, + bind, + extend, + Controller, + contains, + isKey, + Events, + trim, replaceAll +} from "@/core"; +import { Editor, TextAreaEditor } from "@/base"; +import { StateEditor } from "@/case"; + +@shortcut() +export class SelectPatchEditor extends Widget { + static xtype = "bi.select_patch_editor"; + + props = { baseCls: "bi-patch-select-editor", height: 24 }; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + + render() { + const self = this, + o = this.options; + + const debounceInputChange = debounce(bind(this._dealChange, this), 300); + + return extend( + { + type: StateEditor.xtype, + ref(_ref) { + self.editor = _ref; }, - throttle: true, - }, - listeners: [{ - eventName: BI.Controller.EVENT_CHANGE, - action: function (type, v) { - if (BI.contains(v, "\n")) { - self._dealChange(type, v); - } else { - debounceInputChange(type, v); - } + hgap: o.hgap, + vgap: o.vgap, + lgap: o.lgap, + rgap: o.rgap, + tgap: o.tgap, + bgap: o.bgap, + height: o.height, + watermark: o.watermark, + allowBlank: true, + value: o.value, + defaultText: o.defaultText, + text: o.text, + tipType: o.tipType, + warningTitle: o.warningTitle, + el: { + type: TextAreaEditor.xtype, + scrolly: false, + validationChecker() { + return true; + }, + throttle: true, }, - }, { - eventName: BI.Editor.EVENT_KEY_DOWN, - action: function (keyCode) { - if (keyCode === BI.KeyCode.ENTER) { - self._clearSplitValue(); + listeners: [ + { + eventName: Controller.EVENT_CHANGE, + action(type, v) { + if (contains(v, "\n")) { + self._dealChange(type, v); + } else { + debounceInputChange(type, v); + } + }, + }, + { + eventName: Editor.EVENT_KEY_DOWN, + action(keyCode) { + if (keyCode === BI.KeyCode.ENTER) { + self._clearSplitValue(); + } + }, + }, + { + eventName: Editor.EVENT_FOCUS, + action() { + self.fireEvent( + SelectPatchEditor.EVENT_FOCUS, + arguments + ); + }, + }, + { + eventName: Editor.EVENT_BLUR, + action() { + self._start = false; + self.fireEvent( + SelectPatchEditor.EVENT_BLUR, + arguments + ); + }, } - }, - }, { - eventName: BI.Editor.EVENT_FOCUS, - action: function () { - self.fireEvent(BI.SelectPatchEditor.EVENT_FOCUS, arguments); - }, - }, { - eventName: BI.Editor.EVENT_BLUR, - action: function () { - self._start = false; - self.fireEvent(BI.SelectPatchEditor.EVENT_BLUR, arguments); - }, - }], - }, o.el); - }, + ], + }, + o.el + ); + } - _clearSplitValue: function () { + _clearSplitValue() { this.editor.setValue(""); - }, + } - _dealChange: function (type, v) { - var value = ""; + _dealChange(type, v) { + let value = ""; if (v !== this.editor.getValue()) { return; } - if (BI.isKey(v)) { + if (isKey(v)) { value = this._formatText(v); } - if (type === BI.Events.CHANGE) { + if (type === Events.CHANGE) { this._setValue(value); if (this._trimValue(value) !== "") { - if (!this._start || !BI.isKey(this._lastValue) || (this._pause === true && this._trimValue(this._lastValue) !== this._trimValue(value))) { + if ( + !this._start || + !isKey(this._lastValue) || + (this._pause === true && + this._trimValue(this._lastValue) !== + this._trimValue(value)) + ) { this._start = true; this._pause = false; - this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.STARTEDIT, this.getValue(), this); + this.fireEvent( + Controller.EVENT_CHANGE, + Events.STARTEDIT, + this.getValue(), + this + ); } } if (this._trimValue(this._lastValue) !== this._trimValue(value)) { - this.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.fireEvent(Controller.EVENT_CHANGE, arguments); } if (BI.endWith(value, BI.BlankSplitChar)) { this._pause = true; - this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.PAUSE, "", this); + this.fireEvent(Controller.EVENT_CHANGE, Events.PAUSE, "", this); } } - if (type === BI.Events.EMPTY || type === BI.Events.STOPEDIT) { - this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EMPTY); + if (type === Events.EMPTY || type === Events.STOPEDIT) { + this.fireEvent(Controller.EVENT_CHANGE, Events.EMPTY); } this._lastValue = value; - }, + } - _trimValue: function (v) { - return BI.trim(BI.replaceAll(v || "", BI.BlankSplitChar, "")); - }, + _trimValue(v) { + return trim(replaceAll(v || "", BI.BlankSplitChar, "")); + } - _formatText: function (v) { - return BI.replaceAll(v || "", "\n", BI.BlankSplitChar); - }, + _formatText(v) { + return replaceAll(v || "", "\n", BI.BlankSplitChar); + } - setWaterMark: function (v) { + setWaterMark(v) { this.editor.setWaterMark(v); - }, + } - doRedMark: function () { - this.editor.doRedMark.apply(this.editor, arguments); - }, + doRedMark() { + this.editor.doRedMark(...arguments); + } - unRedMark: function () { - this.editor.unRedMark.apply(this.editor, arguments); - }, + unRedMark() { + this.editor.unRedMark(...arguments); + } - doHighLight: function () { - this.editor.doHighLight.apply(this.editor, arguments); - }, + doHighLight() { + this.editor.doHighLight(...arguments); + } - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - }, + unHighLight() { + this.text.unHighLight(...arguments); + } - focus: function () { + focus() { this.editor.focus(); - }, + } - blur: function () { + blur() { this.editor.blur(); - }, + } - _setValue: function (v) { + _setValue(v) { this.editor.setValue(this._formatText(v)); - }, + } - _showInput: function () { + _showInput() { this.editor.visible(); this.text.invisible(); - }, + } - _showHint: function () { + _showHint() { this.editor.invisible(); this.text.visible(); - }, + } - isValid: function () { + isValid() { return this.editor.isValid(); - }, + } - setErrorText: function (text) { + setErrorText(text) { this.editor.setErrorText(text); - }, + } - getErrorText: function () { + getErrorText() { return this.editor.getErrorText(); - }, + } - isEditing: function () { + isEditing() { return this.editor.isEditing(); - }, + } - getLastValidValue: function () { + getLastValidValue() { return this.editor.getLastValidValue(); - }, + } - getLastChangedValue: function () { + getLastChangedValue() { return this.editor.getLastChangedValue(); - }, + } - setValue: function (v) { + setValue(v) { this._setValue(v); this._lastValue = this._trimValue(v); - }, + } - getValue: function () { - return BI.trim(this.editor.getValue()); - }, + getValue() { + return trim(this.editor.getValue()); + } - getState: function () { + getState() { return this.editor.getState(); - }, + } - setState: function (v) { + setState(v) { this.editor.setState(v); - }, + } - setTipType: function (v) { + setTipType(v) { this.editor.setTipType(v); - }, + } - getText: function () { + getText() { return this.editor.getText(); - }, -}); -BI.SelectPatchEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.SelectPatchEditor.EVENT_FOCUS = "EVENT_FOCUS"; -BI.SelectPatchEditor.EVENT_BLUR = "EVENT_BLUR"; - -BI.shortcut("bi.select_patch_editor", BI.SelectPatchEditor); + } +} diff --git a/src/widget/multiselect/trigger/searcher.multiselect.insert.js b/src/widget/multiselect/trigger/searcher.multiselect.insert.js index ec31d3d31..a2e043a6e 100644 --- a/src/widget/multiselect/trigger/searcher.multiselect.insert.js +++ b/src/widget/multiselect/trigger/searcher.multiselect.insert.js @@ -1,161 +1,196 @@ -/** - * searcher - * Created by guy on 15/11/3. - * @class BI.MultiSelectInsertSearcher - * @extends Widget - */ -BI.MultiSelectInsertSearcher = BI.inherit(BI.Widget, { - - _defaultConfig: function () { - return BI.extend(BI.MultiSelectInsertSearcher.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + Widget, + extend, + emptyFn, + i18nText, + createWidget, + isNotNull, + isEmptyArray, + size, + each +} from "@/core"; +import { MultiSelectEditor } from "./editor.multiselect"; +import { Searcher } from "@/base"; +import { MultiSelectSearchInsertPane } from "../search/multiselect.search.insert.pane"; + +@shortcut() +export class MultiSelectInsertSearcher extends Widget { + static xtype = "bi.multi_select_insert_searcher"; + + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_START = "EVENT_START"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-searcher", - itemsCreator: BI.emptyFn, + itemsCreator: emptyFn, itemHeight: 24, el: {}, popup: {}, - valueFormatter: BI.emptyFn, + valueFormatter: emptyFn, adapter: null, masker: {}, - watermark: BI.i18nText("BI-Basic_Search_And_Patch_Paste"), + watermark: i18nText("BI-Basic_Search_And_Patch_Paste"), }); - }, + } - _init: function () { - BI.MultiSelectInsertSearcher.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.editor = BI.createWidget(o.el, { - type: "bi.multi_select_editor", + _init() { + super._init(...arguments); + const self = this, + o = this.options; + this.editor = createWidget(o.el, { + type: MultiSelectEditor.xtype, watermark: o.watermark, height: o.height, text: o.text, defaultText: o.defaultText, listeners: [ { - eventName: BI.MultiSelectEditor.EVENT_FOCUS, - action: function () { - self.fireEvent(BI.MultiSelectInsertSearcher.EVENT_FOCUS); - } - }, { - eventName: BI.MultiSelectEditor.EVENT_BLUR, - action: function () { - self.fireEvent(BI.MultiSelectInsertSearcher.EVENT_BLUR); - } + eventName: MultiSelectEditor.EVENT_FOCUS, + action() { + self.fireEvent(MultiSelectInsertSearcher.EVENT_FOCUS); + }, + }, + { + eventName: MultiSelectEditor.EVENT_BLUR, + action() { + self.fireEvent(MultiSelectInsertSearcher.EVENT_BLUR); + }, } - ] + ], }); - this.searcher = BI.createWidget({ - type: "bi.searcher", + this.searcher = createWidget({ + type: Searcher.xtype, element: this, height: o.height, isAutoSearch: false, isAutoSync: false, - onSearch: function (op, callback) { + onSearch(op, callback) { callback(); }, el: this.editor, - popup: BI.extend({ - type: "bi.multi_select_search_insert_pane", - valueFormatter: o.valueFormatter, - itemFormatter: o.itemFormatter, - keywordGetter: function () { - return self.editor.getKeyword(); - }, - itemsCreator: function (op, callback) { - var keyword = self.editor.getKeyword(); - op.keywords = [keyword]; - this.setKeyword(keyword); - o.itemsCreator(op, function () { - if (keyword === self.editor.getValue()) { - callback.apply(null, arguments); - } - }); + popup: extend( + { + type: MultiSelectSearchInsertPane.xtype, + valueFormatter: o.valueFormatter, + itemFormatter: o.itemFormatter, + keywordGetter() { + return self.editor.getKeyword(); + }, + itemsCreator(op, callback) { + const keyword = self.editor.getKeyword(); + op.keywords = [keyword]; + this.setKeyword(keyword); + o.itemsCreator(op, function () { + if (keyword === self.editor.getValue()) { + callback(...arguments); + } + }); + }, + itemHeight: o.itemHeight, + value: o.value, }, - itemHeight: o.itemHeight, - value: o.value, - }, o.popup), + o.popup + ), adapter: o.adapter, - masker: o.masker + masker: o.masker, }); - this.searcher.on(BI.Searcher.EVENT_START, function () { - self.fireEvent(BI.MultiSelectInsertSearcher.EVENT_START); + this.searcher.on(Searcher.EVENT_START, () => { + self.fireEvent(MultiSelectInsertSearcher.EVENT_START); }); - this.searcher.on(BI.Searcher.EVENT_PAUSE, function () { - if (this.hasMatched()) { - - } - self.fireEvent(BI.MultiSelectInsertSearcher.EVENT_PAUSE); + this.searcher.on(Searcher.EVENT_PAUSE, () => { + self.fireEvent(MultiSelectInsertSearcher.EVENT_PAUSE); }); - this.searcher.on(BI.Searcher.EVENT_STOP, function () { - self.fireEvent(BI.MultiSelectInsertSearcher.EVENT_STOP); + this.searcher.on(Searcher.EVENT_STOP, () => { + self.fireEvent(MultiSelectInsertSearcher.EVENT_STOP); }); - this.searcher.on(BI.Searcher.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiSelectInsertSearcher.EVENT_CHANGE, arguments); + this.searcher.on(Searcher.EVENT_CHANGE, function () { + self.fireEvent(MultiSelectInsertSearcher.EVENT_CHANGE, arguments); }); - this.searcher.on(BI.Searcher.EVENT_SEARCHING, function () { - var keywords = this.getKeywords(); - self.fireEvent(BI.MultiSelectInsertSearcher.EVENT_SEARCHING, keywords.length > 2000 ? keywords.slice(0, 2000).concat([BI.BlankSplitChar]) : keywords.slice(0, 2000)); + this.searcher.on(Searcher.EVENT_SEARCHING, function () { + const keywords = this.getKeywords(); + self.fireEvent( + MultiSelectInsertSearcher.EVENT_SEARCHING, + keywords.length > 2000 + ? keywords.slice(0, 2000).concat([BI.BlankSplitChar]) + : keywords.slice(0, 2000) + ); }); - if (BI.isNotNull(o.value)) { + if (isNotNull(o.value)) { this.setState(o.value); } - }, + } - adjustView: function () { + adjustView() { this.searcher.adjustView(); - }, + } - isSearching: function () { + isSearching() { return this.searcher.isSearching(); - }, + } - stopSearch: function () { + stopSearch() { this.searcher.stopSearch(); - }, + } - getKeywordsLength: function () { - var keywords = this.editor.getKeywords(); + getKeywordsLength() { + const keywords = this.editor.getKeywords(); - return keywords[keywords.length - 1] === BI.BlankSplitChar ? keywords.length - 1 : keywords.length; - }, + return keywords[keywords.length - 1] === BI.BlankSplitChar + ? keywords.length - 1 + : keywords.length; + } - getKeyword: function () { - var keywords = this.editor.getKeywords().slice(0, 2000); + getKeyword() { + let keywords = this.editor.getKeywords().slice(0, 2000); if (keywords[keywords.length - 1] === BI.BlankSplitChar) { keywords = keywords.slice(0, keywords.length - 1); } - return BI.isEmptyArray(keywords) ? "" : keywords[keywords.length - 1]; - }, + return isEmptyArray(keywords) ? "" : keywords[keywords.length - 1]; + } - hasMatched: function () { + hasMatched() { return this.searcher.hasMatched(); - }, + } - hasChecked: function () { + hasChecked() { return this.searcher.getView() && this.searcher.getView().hasChecked(); - }, + } - setAdapter: function (adapter) { + setAdapter(adapter) { this.searcher.setAdapter(adapter); - }, + } - setState: function (ob) { - var o = this.options; + setState(ob) { + let state; + const o = this.options; ob || (ob = {}); ob.value || (ob.value = []); if (ob.type === BI.Selection.All) { if (ob.value.length === 0) { this.editor.setState(BI.Selection.All); - } else if (BI.size(ob.assist) <= 20) { - var state = ""; - BI.each(ob.assist, function (i, v) { + } else if (size(ob.assist) <= 20) { + state = ""; + each(ob.assist, (i, v) => { if (i === 0) { - state += "" + (v === null ? "" : (o.valueFormatter(v + "") || v)); + state += + `${ + v === null ? "" : o.valueFormatter(`${v}`) || v}`; } else { - state += "," + (v === null ? "" : (o.valueFormatter(v + "") || v)); + state += + `,${ + v === null ? "" : o.valueFormatter(`${v}`) || v}`; } }); this.editor.setState(state); @@ -165,13 +200,17 @@ BI.MultiSelectInsertSearcher = BI.inherit(BI.Widget, { } else { if (ob.value.length === 0) { this.editor.setState(BI.Selection.None); - } else if (BI.size(ob.value) <= 20) { - var state = ""; - BI.each(ob.value, function (i, v) { + } else if (size(ob.value) <= 20) { + state = ""; + each(ob.value, (i, v) => { if (i === 0) { - state += "" + (v === null ? "" : (o.valueFormatter(v + "") || v)); + state += + `${ + v === null ? "" : o.valueFormatter(`${v}`) || v}`; } else { - state += "," + (v === null ? "" : (o.valueFormatter(v + "") || v)); + state += + `,${ + v === null ? "" : o.valueFormatter(`${v}`) || v}`; } }); this.editor.setState(state); @@ -179,36 +218,26 @@ BI.MultiSelectInsertSearcher = BI.inherit(BI.Widget, { this.editor.setState(BI.Selection.Multi); } } - }, + } - getState: function () { + getState() { return this.editor.getState(); - }, + } - setValue: function (ob) { + setValue(ob) { this.setState(ob); this.searcher.setValue(ob); - }, + } - getKey: function () { + getKey() { return this.editor.getValue(); - }, + } - getValue: function () { + getValue() { return this.searcher.getValue(); - }, - - populate: function (items) { - this.searcher.populate.apply(this.searcher, arguments); - } -}); - -BI.MultiSelectInsertSearcher.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.MultiSelectInsertSearcher.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiSelectInsertSearcher.EVENT_START = "EVENT_START"; -BI.MultiSelectInsertSearcher.EVENT_STOP = "EVENT_STOP"; -BI.MultiSelectInsertSearcher.EVENT_PAUSE = "EVENT_PAUSE"; -BI.MultiSelectInsertSearcher.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.MultiSelectInsertSearcher.EVENT_FOCUS = "EVENT_FOCUS"; -BI.MultiSelectInsertSearcher.EVENT_BLUR = "EVENT_BLUR"; -BI.shortcut("bi.multi_select_insert_searcher", BI.MultiSelectInsertSearcher); + } + + populate(items) { + this.searcher.populate(...arguments); + } +} diff --git a/src/widget/multiselect/trigger/searcher.multiselect.js b/src/widget/multiselect/trigger/searcher.multiselect.js index a1a18c661..ef23281c3 100644 --- a/src/widget/multiselect/trigger/searcher.multiselect.js +++ b/src/widget/multiselect/trigger/searcher.multiselect.js @@ -9,8 +9,9 @@ import { size, each } from "@/core"; -import { MultiSelectEditor } from "editor.multiselect"; +import { MultiSelectEditor } from "./editor.multiselect"; import { Searcher } from "@/base"; +import { MultiSelectSearchPane } from "../search/multiselect.search.pane"; @shortcut() export class MultiSelectSearcher extends Widget { @@ -52,13 +53,13 @@ export class MultiSelectSearcher extends Widget { listeners: [ { eventName: MultiSelectEditor.EVENT_FOCUS, - action () { + action() { self.fireEvent(MultiSelectSearcher.EVENT_FOCUS); }, }, { eventName: MultiSelectEditor.EVENT_BLUR, - action () { + action() { self.fireEvent(MultiSelectSearcher.EVENT_BLUR); }, } @@ -71,19 +72,19 @@ export class MultiSelectSearcher extends Widget { height: o.height, isAutoSearch: false, isAutoSync: false, - onSearch (op, callback) { + onSearch(op, callback) { callback(); }, el: this.editor, popup: extend( { - type: "bi.multi_select_search_pane", + type: MultiSelectSearchPane.xtype, valueFormatter: o.valueFormatter, itemFormatter: o.itemFormatter, - keywordGetter () { + keywordGetter() { return self.editor.getValue(); }, - itemsCreator (op, callback) { + itemsCreator(op, callback) { const keyword = self.editor.getValue(); op.keywords = [keyword]; o.itemsCreator(op, () => { @@ -91,7 +92,7 @@ export class MultiSelectSearcher extends Widget { op.keywords = [keyword]; o.itemsCreator(op, function () { if (keyword === self.editor.getValue()) { - callback.apply(null, arguments); + callback(...arguments); } }); }); @@ -108,9 +109,7 @@ export class MultiSelectSearcher extends Widget { this.searcher.on(Searcher.EVENT_START, () => { self.fireEvent(MultiSelectSearcher.EVENT_START); }); - this.searcher.on(Searcher.EVENT_PAUSE, function () { - if (this.hasMatched()) { - } + this.searcher.on(Searcher.EVENT_PAUSE, () => { self.fireEvent(MultiSelectSearcher.EVENT_PAUSE); }); this.searcher.on(Searcher.EVENT_STOP, () => { @@ -165,6 +164,7 @@ export class MultiSelectSearcher extends Widget { } setState(ob) { + let state; const o = this.options; ob || (ob = {}); ob.value || (ob.value = []); @@ -172,7 +172,7 @@ export class MultiSelectSearcher extends Widget { if (ob.value.length === 0) { this.editor.setState(BI.Selection.All); } else if (size(ob.assist) <= 20) { - var state = ""; + state = ""; each(ob.assist, (i, v) => { if (i === 0) { state += @@ -192,7 +192,7 @@ export class MultiSelectSearcher extends Widget { if (ob.value.length === 0) { this.editor.setState(BI.Selection.None); } else if (size(ob.value) <= 20) { - var state = ""; + state = ""; each(ob.value, (i, v) => { if (i === 0) { state += @@ -229,6 +229,6 @@ export class MultiSelectSearcher extends Widget { } populate(items) { - this.searcher.populate.apply(this.searcher, arguments); + this.searcher.populate(...arguments); } } diff --git a/src/widget/multiselect/trigger/switcher.checkselected.js b/src/widget/multiselect/trigger/switcher.checkselected.js index b264f8220..89e4e4fb0 100644 --- a/src/widget/multiselect/trigger/switcher.checkselected.js +++ b/src/widget/multiselect/trigger/switcher.checkselected.js @@ -8,7 +8,8 @@ import { nextTick } from "@/core"; import { Switcher } from "@/base"; -import { MultiSelectCheckSelectedButton } from "button.checkselected"; +import { MultiSelectCheckSelectedButton } from "./button.checkselected"; +import { MultiSelectCheckPane } from "../check/multiselect.check.pane"; @shortcut() export class MultiSelectCheckSelectedSwitcher extends Widget { @@ -50,13 +51,13 @@ export class MultiSelectCheckSelectedSwitcher extends Widget { el: this.button, popup: extend( { - type: "bi.multi_select_check_pane", + type: MultiSelectCheckPane.xtype, valueFormatter: o.valueFormatter, itemsCreator: o.itemsCreator, - onClickContinueSelect () { + onClickContinueSelect() { self.switcher.hideView(); }, - ref (_ref) { + ref(_ref) { self.checkPane = _ref; }, value: o.value, @@ -114,7 +115,8 @@ export class MultiSelectCheckSelectedSwitcher extends Widget { this.button.setValue(v); } - getValue() {} + getValue() { + } populate(items) { this.switcher.populate.apply(this.switcher, arguments); diff --git a/src/widget/multitree/multi.tree.combo.js b/src/widget/multitree/multi.tree.combo.js index 571f86e03..7ae95930e 100644 --- a/src/widget/multitree/multi.tree.combo.js +++ b/src/widget/multitree/multi.tree.combo.js @@ -11,8 +11,8 @@ import { deepClone } from "@/core"; import { Single, Combo } from "@/base"; -import { MultiTreeSearcher } from "trigger/searcher.multi.tree"; -import { MultiTreePopup } from "multi.tree.popup"; +import { MultiTreeSearcher } from "./trigger/searcher.multi.tree"; +import { MultiTreePopup } from "./multi.tree.popup"; import { MultiSelectTrigger } from "../multiselect/multiselect.trigger"; import { TriggerIconButton } from "@/case"; import { MultiSelectCheckSelectedSwitcher } from "../multiselect/trigger/switcher.checkselected"; diff --git a/src/widget/multitree/multi.tree.insert.combo.js b/src/widget/multitree/multi.tree.insert.combo.js index 604fddd6d..12670343d 100644 --- a/src/widget/multitree/multi.tree.insert.combo.js +++ b/src/widget/multitree/multi.tree.insert.combo.js @@ -11,8 +11,8 @@ import { deepClone } from "@/core"; import { Single, Combo } from "@/base"; -import { MultiTreeSearchInsertPane } from "trigger/multi.tree.search.insert.pane"; -import { MultiTreePopup } from "multi.tree.popup"; +import { MultiTreeSearchInsertPane } from "./trigger/multi.tree.search.insert.pane"; +import { MultiTreePopup } from "./multi.tree.popup"; import { MultiSelectTrigger } from "../multiselect/multiselect.trigger"; import { TriggerIconButton } from "@/case"; import { MultiSelectCheckSelectedSwitcher } from "../multiselect/trigger/switcher.checkselected"; @@ -74,10 +74,10 @@ export class MultiTreeInsertCombo extends Single { listeners: [ { eventName: MultiTreeSearchInsertPane.EVENT_ADD_ITEM, - action () { + action() { self.storeValue.value[ self.trigger.getSearcher().getKeyword() - ] = {}; + ] = {}; self._assertShowValue(); // setValue以更新paras.value, 之后从search popup中拿到的就能有add的值了 self.combo.setValue(self.storeValue); @@ -88,8 +88,8 @@ export class MultiTreeInsertCombo extends Single { }, { eventName: - MultiTreeSearchInsertPane.EVENT_CLICK_TREE_NODE, - action () { + MultiTreeSearchInsertPane.EVENT_CLICK_TREE_NODE, + action() { self._dataChange = true; }, } @@ -108,7 +108,7 @@ export class MultiTreeInsertCombo extends Single { adjustLength: 1, popup: { type: "bi.multi_tree_popup_view", - ref () { + ref() { self.popup = this; self.trigger.setAdapter(this); self.numberCounter.setAdapter(this); @@ -116,7 +116,7 @@ export class MultiTreeInsertCombo extends Single { listeners: [ { eventName: MultiTreePopup.EVENT_AFTERINIT, - action () { + action() { self.numberCounter.adjustView(); isInit = true; if (want2showCounter === true) { @@ -126,7 +126,7 @@ export class MultiTreeInsertCombo extends Single { }, { eventName: MultiTreePopup.EVENT_CHANGE, - action () { + action() { change = true; const val = { type: BI.Selection.Multi, @@ -144,13 +144,13 @@ export class MultiTreeInsertCombo extends Single { }, { eventName: MultiTreePopup.EVENT_CLICK_CONFIRM, - action () { + action() { self.combo.hideView(); }, }, { eventName: MultiTreePopup.EVENT_CLICK_CLEAR, - action () { + action() { clear = true; self._dataChange = true; self.setValue(); @@ -159,7 +159,7 @@ export class MultiTreeInsertCombo extends Single { } ], itemsCreator: o.itemsCreator, - onLoaded () { + onLoaded() { nextTick(() => { self.numberCounter.adjustView(); self.trigger.getSearcher().adjustView(); @@ -169,7 +169,7 @@ export class MultiTreeInsertCombo extends Single { }, isNeedAdjustWidth: o.isNeedAdjustWidth, value: { value: o.value || {} }, - hideChecker (e) { + hideChecker(e) { return ( triggerBtn.element.find(e.target).length === 0 && self.numberCounter.element.find(e.target).length === 0 @@ -267,7 +267,7 @@ export class MultiTreeInsertCombo extends Single { if (isSearching()) { self._stopEditing(); self._dataChange && - self.fireEvent(MultiTreeInsertCombo.EVENT_CONFIRM); + self.fireEvent(MultiTreeInsertCombo.EVENT_CONFIRM); } else { if (isPopupView()) { self._stopEditing(); @@ -276,7 +276,7 @@ export class MultiTreeInsertCombo extends Single { self.storeValue = { value: {} }; } self._dataChange && - self.fireEvent(MultiTreeInsertCombo.EVENT_CONFIRM); + self.fireEvent(MultiTreeInsertCombo.EVENT_CONFIRM); } } clear = false; diff --git a/src/widget/multitree/multi.tree.list.combo.js b/src/widget/multitree/multi.tree.list.combo.js index 3d6e6d269..056fbd5fc 100644 --- a/src/widget/multitree/multi.tree.list.combo.js +++ b/src/widget/multitree/multi.tree.list.combo.js @@ -11,8 +11,8 @@ import { deepClone } from "@/core"; import { Single, Combo } from "@/base"; -import { MultiTreeSearchInsertPane } from "trigger/multi.tree.search.insert.pane"; -import { MultiTreePopup } from "multi.tree.popup"; +import { MultiTreeSearchInsertPane } from "./trigger/multi.tree.search.insert.pane"; +import { MultiTreePopup } from "./multi.tree.popup"; import { MultiSelectTrigger } from "../multiselect/multiselect.trigger"; import { TriggerIconButton, @@ -85,7 +85,7 @@ export class MultiTreeListCombo extends Single { listeners: [ { eventName: MultiTreeSearchInsertPane.EVENT_ADD_ITEM, - action () { + action() { self.storeValue.value.unshift([ self.trigger.getSearcher().getKeyword() ]); @@ -124,7 +124,7 @@ export class MultiTreeListCombo extends Single { adjustLength: 1, popup: { type: MultiTreePopup.xtype, - ref () { + ref() { self.popup = this; self.trigger.setAdapter(this); self.numberCounter.setAdapter(this); @@ -135,7 +135,7 @@ export class MultiTreeListCombo extends Single { listeners: [ { eventName: MultiTreePopup.EVENT_AFTERINIT, - action () { + action() { self.numberCounter.adjustView(); isInit = true; if (want2showCounter === true) { @@ -145,7 +145,7 @@ export class MultiTreeListCombo extends Single { }, { eventName: MultiTreePopup.EVENT_CHANGE, - action () { + action() { change = true; const val = { type: BI.Selection.Multi, @@ -163,13 +163,13 @@ export class MultiTreeListCombo extends Single { }, { eventName: MultiTreePopup.EVENT_CLICK_CONFIRM, - action () { + action() { self.combo.hideView(); }, }, { eventName: MultiTreePopup.EVENT_CLICK_CLEAR, - action () { + action() { clear = true; self._dataChange = true; self.setValue(); @@ -178,7 +178,7 @@ export class MultiTreeListCombo extends Single { } ], itemsCreator: o.itemsCreator, - onLoaded () { + onLoaded() { nextTick(() => { self.numberCounter.adjustView(); self.trigger.getSearcher().adjustView(); @@ -188,7 +188,7 @@ export class MultiTreeListCombo extends Single { }, isNeedAdjustWidth: o.isNeedAdjustWidth, value: this.storeValue, - hideChecker (e) { + hideChecker(e) { return ( triggerBtn.element.find(e.target).length === 0 && self.numberCounter.element.find(e.target).length === 0 @@ -286,7 +286,7 @@ export class MultiTreeListCombo extends Single { if (isSearching()) { self.trigger.stopEditing(); self._dataChange && - self.fireEvent(MultiTreeListCombo.EVENT_CONFIRM); + self.fireEvent(MultiTreeListCombo.EVENT_CONFIRM); } else { if (isPopupView()) { self._stopEditing(); @@ -295,7 +295,7 @@ export class MultiTreeListCombo extends Single { self.storeValue = { value: [] }; } self._dataChange && - self.fireEvent(MultiTreeListCombo.EVENT_CONFIRM); + self.fireEvent(MultiTreeListCombo.EVENT_CONFIRM); } } clear = false; diff --git a/src/widget/multitree/trigger/searcher.list.multi.tree.js b/src/widget/multitree/trigger/searcher.list.multi.tree.js index 0a853ca54..2356c0971 100644 --- a/src/widget/multitree/trigger/searcher.list.multi.tree.js +++ b/src/widget/multitree/trigger/searcher.list.multi.tree.js @@ -14,7 +14,7 @@ import { MultiSelectEditor } from "../../multiselect/trigger/editor.multiselect" import { MultiSelectSearcher } from "../../multiselect/trigger/searcher.multiselect"; import { Searcher } from "@/base"; import { SimpleStateEditor } from "@/case"; -import { MultiTreeSearchPane } from "multi.tree.search.pane"; +import { MultiTreeSearchPane } from "./multi.tree.search.pane"; @shortcut() export class MultiListTreeSearcher extends Widget { diff --git a/src/widget/multitree/trigger/searcher.multi.tree.js b/src/widget/multitree/trigger/searcher.multi.tree.js index 8a10023ea..cfc2a5201 100644 --- a/src/widget/multitree/trigger/searcher.multi.tree.js +++ b/src/widget/multitree/trigger/searcher.multi.tree.js @@ -13,7 +13,7 @@ import { } from "@/core"; import { MultiSelectEditor } from "../../multiselect/trigger/editor.multiselect"; import { MultiSelectSearcher } from "../../multiselect/trigger/searcher.multiselect"; -import { MultiTreeSearchPane } from "multi.tree.search.pane"; +import { MultiTreeSearchPane } from "./multi.tree.search.pane"; import { Searcher } from "@/base"; import { SimpleStateEditor } from "@/case"; From 4f4e84c4197f837227bad80a1bd1ed26cc274998 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Thu, 12 Jan 2023 14:44:29 +0800 Subject: [PATCH 088/300] =?UTF-8?q?KERNEL-14093=20refactor:=20widget/edito?= =?UTF-8?q?r=E3=80=81numbereditor=E3=80=81numberinterval?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/widget/editor/editor.search.js | 280 ++++----- src/widget/editor/editor.search.small.js | 34 +- src/widget/editor/editor.text.js | 198 +++--- src/widget/editor/editor.text.small.js | 34 +- src/widget/editor/index.js | 4 + src/widget/index.js | 29 +- src/widget/numbereditor/number.editor.js | 260 ++++---- src/widget/numberinterval/numberinterval.js | 570 +++++++++--------- .../singleeditor/single.editor.js | 120 ++-- 9 files changed, 789 insertions(+), 740 deletions(-) create mode 100644 src/widget/editor/index.js diff --git a/src/widget/editor/editor.search.js b/src/widget/editor/editor.search.js index bd40ae5a9..aef7cff33 100644 --- a/src/widget/editor/editor.search.js +++ b/src/widget/editor/editor.search.js @@ -1,26 +1,51 @@ -/** - * Created by roy on 15/9/14. - */ -BI.SearchEditor = BI.inherit(BI.Widget, { - _defaultConfig: function (config) { - var conf = BI.SearchEditor.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: "bi-search-editor bi-focus-shadow " + (config.simple ? "bi-border-bottom" : "bi-border bi-border-radius"), +import { shortcut, Widget, extend, i18nText, emptyFn, createWidget, toPix, isKey, Controller, Events, HTapeLayout, isEndWithBlank } from "@/core"; +import { IconButton, Editor, IconLabel } from "@/base"; + +@shortcut() +export class SearchEditor extends Widget { + static xtype = "bi.search_editor" + + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_FOCUS = "EVENT_FOCUS" + static EVENT_BLUR = "EVENT_BLUR" + static EVENT_CLICK = "EVENT_CLICK" + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" + static EVENT_SPACE = "EVENT_SPACE" + static EVENT_BACKSPACE = "EVENT_BACKSPACE" + static EVENT_CLEAR = "EVENT_CLEAR" + static EVENT_START = "EVENT_START" + static EVENT_PAUSE = "EVENT_PAUSE" + static EVENT_STOP = "EVENT_STOP" + static EVENT_CONFIRM = "EVENT_CONFIRM" + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM" + static EVENT_VALID = "EVENT_VALID" + static EVENT_ERROR = "EVENT_ERROR" + static EVENT_ENTER = "EVENT_ENTER" + static EVENT_RESTRICT = "EVENT_RESTRICT" + static EVENT_REMOVE = "EVENT_REMOVE" + static EVENT_EMPTY = "EVENT_EMPTY" + + _defaultConfig(config) { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `bi-search-editor bi-focus-shadow ${config.simple ? "bi-border-bottom" : "bi-border bi-border-radius"}`, height: 24, errorText: "", - watermark: BI.i18nText("BI-Basic_Search"), - validationChecker: BI.emptyFn, - quitChecker: BI.emptyFn, - value: "" - }); - }, - _init: function () { - BI.SearchEditor.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.editor = BI.createWidget(o.el, { - type: "bi.editor", + watermark: i18nText("BI-Basic_Search"), + validationChecker: emptyFn, + quitChecker: emptyFn, + value: "", + }); + } + + _init() { + super._init(...arguments); + const o = this.options; + this.editor = createWidget(o.el, { + type: Editor.xtype, simple: o.simple, - height: BI.toPix(o.height, o.simple ? 1 : 2), + height: toPix(o.height, o.simple ? 1 : 2), watermark: o.watermark, allowBlank: true, hgap: 1, @@ -30,189 +55,168 @@ BI.SearchEditor = BI.inherit(BI.Widget, { value: o.value, autoTrim: o.autoTrim, }); - this.clear = BI.createWidget({ - type: "bi.icon_button", + this.clear = createWidget({ + type: IconButton.xtype, stopEvent: true, cls: "close-font", - invisible: !BI.isKey(o.value) + invisible: !isKey(o.value), }); - this.clear.on(BI.IconButton.EVENT_CHANGE, function () { - self.setValue(""); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.STOPEDIT, self.getValue()); + this.clear.on(IconButton.EVENT_CHANGE, () => { + this.setValue(""); + this.fireEvent(Controller.EVENT_CHANGE, Events.STOPEDIT, this.getValue()); // 从有内容到无内容的清空也是一次change - self.fireEvent(BI.SearchEditor.EVENT_CHANGE); - self.fireEvent(BI.SearchEditor.EVENT_CLEAR); + this.fireEvent(SearchEditor.EVENT_CHANGE); + this.fireEvent(SearchEditor.EVENT_CLEAR); }); - BI.createWidget({ + createWidget({ element: this, - height: BI.toPix(o.height, o.simple ? 1 : 2), - type: "bi.htape", - items: [ - { - el: { - type: "bi.icon_label", - cls: "search-font" - }, - width: 24 + height: toPix(o.height, o.simple ? 1 : 2), + type: HTapeLayout.xtype, + items: [{ + el: { + type: IconLabel.xtype, + cls: "search-font", }, - { - el: self.editor - }, - { - el: this.clear, - width: 24 - } - ] + width: 24, + }, + { + el: this.editor, + }, + { + el: this.clear, + width: 24, + } + ], }); - this.editor.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.editor.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.editor.on(BI.Editor.EVENT_FOCUS, function () { - self.fireEvent(BI.SearchEditor.EVENT_FOCUS); + this.editor.on(Editor.EVENT_FOCUS, () => { + this.fireEvent(SearchEditor.EVENT_FOCUS); }); - this.editor.on(BI.Editor.EVENT_BLUR, function () { - self.fireEvent(BI.SearchEditor.EVENT_BLUR); + this.editor.on(Editor.EVENT_BLUR, () => { + this.fireEvent(SearchEditor.EVENT_BLUR); }); - this.editor.on(BI.Editor.EVENT_CLICK, function () { - self.fireEvent(BI.SearchEditor.EVENT_CLICK); + this.editor.on(Editor.EVENT_CLICK, () => { + this.fireEvent(SearchEditor.EVENT_CLICK); }); - this.editor.on(BI.Editor.EVENT_CHANGE, function () { - self._checkClear(); - self.fireEvent(BI.SearchEditor.EVENT_CHANGE); + this.editor.on(Editor.EVENT_CHANGE, () => { + this._checkClear(); + this.fireEvent(SearchEditor.EVENT_CHANGE); }); - this.editor.on(BI.Editor.EVENT_KEY_DOWN, function (v) { - self.fireEvent(BI.SearchEditor.EVENT_KEY_DOWN, v); + this.editor.on(Editor.EVENT_KEY_DOWN, v => { + this.fireEvent(SearchEditor.EVENT_KEY_DOWN, v); }); - this.editor.on(BI.Editor.EVENT_SPACE, function () { - self.fireEvent(BI.SearchEditor.EVENT_SPACE); + this.editor.on(Editor.EVENT_SPACE, () => { + this.fireEvent(SearchEditor.EVENT_SPACE); }); - this.editor.on(BI.Editor.EVENT_BACKSPACE, function () { - self.fireEvent(BI.SearchEditor.EVENT_BACKSPACE); + this.editor.on(Editor.EVENT_BACKSPACE, () => { + this.fireEvent(SearchEditor.EVENT_BACKSPACE); }); - this.editor.on(BI.Editor.EVENT_VALID, function () { - self.fireEvent(BI.SearchEditor.EVENT_VALID); + this.editor.on(Editor.EVENT_VALID, () => { + this.fireEvent(SearchEditor.EVENT_VALID); }); - this.editor.on(BI.Editor.EVENT_ERROR, function () { - self.fireEvent(BI.SearchEditor.EVENT_ERROR); + this.editor.on(Editor.EVENT_ERROR, () => { + this.fireEvent(SearchEditor.EVENT_ERROR); }); - this.editor.on(BI.Editor.EVENT_ENTER, function () { - self.fireEvent(BI.SearchEditor.EVENT_ENTER); + this.editor.on(Editor.EVENT_ENTER, () => { + this.fireEvent(SearchEditor.EVENT_ENTER); }); - this.editor.on(BI.Editor.EVENT_RESTRICT, function () { - self.fireEvent(BI.SearchEditor.EVENT_RESTRICT); + this.editor.on(Editor.EVENT_RESTRICT, () => { + this.fireEvent(SearchEditor.EVENT_RESTRICT); }); - this.editor.on(BI.Editor.EVENT_EMPTY, function () { - self._checkClear(); - self.fireEvent(BI.SearchEditor.EVENT_EMPTY); + this.editor.on(Editor.EVENT_EMPTY, () => { + this._checkClear(); + this.fireEvent(SearchEditor.EVENT_EMPTY); }); - this.editor.on(BI.Editor.EVENT_REMOVE, function () { - self.fireEvent(BI.SearchEditor.EVENT_REMOVE); + this.editor.on(Editor.EVENT_REMOVE, () => { + this.fireEvent(SearchEditor.EVENT_REMOVE); }); - this.editor.on(BI.Editor.EVENT_CONFIRM, function () { - self.fireEvent(BI.SearchEditor.EVENT_CONFIRM); + this.editor.on(Editor.EVENT_CONFIRM, () => { + this.fireEvent(SearchEditor.EVENT_CONFIRM); }); - this.editor.on(BI.Editor.EVENT_CHANGE_CONFIRM, function () { - self.fireEvent(BI.SearchEditor.EVENT_CHANGE_CONFIRM); + this.editor.on(Editor.EVENT_CHANGE_CONFIRM, () => { + this.fireEvent(SearchEditor.EVENT_CHANGE_CONFIRM); }); - this.editor.on(BI.Editor.EVENT_START, function () { - self.fireEvent(BI.SearchEditor.EVENT_START); + this.editor.on(Editor.EVENT_START, () => { + this.fireEvent(SearchEditor.EVENT_START); }); - this.editor.on(BI.Editor.EVENT_PAUSE, function () { - self.fireEvent(BI.SearchEditor.EVENT_PAUSE); + this.editor.on(Editor.EVENT_PAUSE, () => { + this.fireEvent(SearchEditor.EVENT_PAUSE); }); - this.editor.on(BI.Editor.EVENT_STOP, function () { - self.fireEvent(BI.SearchEditor.EVENT_STOP); + this.editor.on(Editor.EVENT_STOP, () => { + this.fireEvent(SearchEditor.EVENT_STOP); }); - }, + } - _checkClear: function () { + _checkClear() { if (!this.getValue()) { this.clear.invisible(); } else { this.clear.visible(); } - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.options.watermark = v; this.editor.setWaterMark(v); - }, + } - focus: function () { + focus() { this.editor.focus(); - }, + } - blur: function () { + blur() { this.editor.blur(); - }, + } - getValue: function () { + getValue() { if (this.isValid()) { return this.editor.getValue(); } - }, + } - getKeywords: function () { - var val = this.editor.getLastChangedValue(); - var keywords = val.match(/[\S]+/g); - if (BI.isEndWithBlank(val)) { + getKeywords() { + const val = this.editor.getLastChangedValue(); + const keywords = val.match(/[\S]+/g); + if (isEndWithBlank(val)) { return keywords.concat([" "]); } + return keywords; - }, + } - getLastValidValue: function () { + getLastValidValue() { return this.editor.getLastValidValue(); - }, + } - getLastChangedValue: function () { + getLastChangedValue() { return this.editor.getLastChangedValue(); - }, + } - setValue: function (v) { + setValue(v) { this.editor.setValue(v); - if (BI.isKey(v)) { + if (isKey(v)) { this.clear.visible(); } - }, + } - isEditing: function () { + isEditing() { return this.editor.isEditing(); - }, + } - isValid: function () { + isValid() { return this.editor.isValid(); - }, + } - showClearIcon: function () { + showClearIcon() { this.clear.visible(); - }, + } - hideClearIcon: function () { + hideClearIcon() { this.clear.invisible(); } -}); -BI.SearchEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.SearchEditor.EVENT_FOCUS = "EVENT_FOCUS"; -BI.SearchEditor.EVENT_BLUR = "EVENT_BLUR"; -BI.SearchEditor.EVENT_CLICK = "EVENT_CLICK"; -BI.SearchEditor.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.SearchEditor.EVENT_SPACE = "EVENT_SPACE"; -BI.SearchEditor.EVENT_BACKSPACE = "EVENT_BACKSPACE"; -BI.SearchEditor.EVENT_CLEAR = "EVENT_CLEAR"; - -BI.SearchEditor.EVENT_START = "EVENT_START"; -BI.SearchEditor.EVENT_PAUSE = "EVENT_PAUSE"; -BI.SearchEditor.EVENT_STOP = "EVENT_STOP"; -BI.SearchEditor.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.SearchEditor.EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; -BI.SearchEditor.EVENT_VALID = "EVENT_VALID"; -BI.SearchEditor.EVENT_ERROR = "EVENT_ERROR"; -BI.SearchEditor.EVENT_ENTER = "EVENT_ENTER"; -BI.SearchEditor.EVENT_RESTRICT = "EVENT_RESTRICT"; -BI.SearchEditor.EVENT_REMOVE = "EVENT_REMOVE"; -BI.SearchEditor.EVENT_EMPTY = "EVENT_EMPTY"; -BI.shortcut("bi.search_editor", BI.SearchEditor); +} diff --git a/src/widget/editor/editor.search.small.js b/src/widget/editor/editor.search.small.js index 145108f0d..890a1499f 100644 --- a/src/widget/editor/editor.search.small.js +++ b/src/widget/editor/editor.search.small.js @@ -1,20 +1,20 @@ -/** - * 小号搜索框 - * Created by GUY on 2015/9/29. - * @class BI.SmallSearchEditor - * @extends BI.SearchEditor - */ -BI.SmallSearchEditor = BI.inherit(BI.SearchEditor, { - _defaultConfig: function () { - var conf = BI.SmallSearchEditor.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-small-search-editor", - height: 20 +import { shortcut, extend } from "@/core"; +import { SearchEditor } from "./editor.search"; + +@shortcut() +export class SmallSearchEditor extends SearchEditor { + static xtype = "bi.small_search_editor" + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-small-search-editor`, + height: 20, }); - }, + } - _init: function () { - BI.SmallSearchEditor.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); } -}); -BI.shortcut("bi.small_search_editor", BI.SmallSearchEditor); \ No newline at end of file +} diff --git a/src/widget/editor/editor.text.js b/src/widget/editor/editor.text.js index 022b5f2ad..8841eb339 100644 --- a/src/widget/editor/editor.text.js +++ b/src/widget/editor/editor.text.js @@ -1,36 +1,57 @@ -/** - * guy - * @class BI.TextEditor - * @extends BI.Single - */ -BI.TextEditor = BI.inherit(BI.Widget, { - _defaultConfig: function (config) { - var conf = BI.TextEditor.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - extraCls: "bi-text-editor bi-focus-shadow " + (config.simple ? "bi-border-bottom" : "bi-border"), +import { shortcut, Widget, extend, emptyFn, createWidget, toPix, Controller } from "@/core"; +import { Editor } from "@/base"; + +@shortcut() +export class TextEditor extends Widget { + static xtype = "bi.text_editor" + + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_FOCUS = "EVENT_FOCUS" + static EVENT_BLUR = "EVENT_BLUR" + static EVENT_CLICK = "EVENT_CLICK" + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" + static EVENT_SPACE = "EVENT_SPACE" + static EVENT_BACKSPACE = "EVENT_BACKSPACE" + static EVENT_START = "EVENT_START" + static EVENT_PAUSE = "EVENT_PAUSE" + static EVENT_STOP = "EVENT_STOP" + static EVENT_CONFIRM = "EVENT_CONFIRM" + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM" + static EVENT_VALID = "EVENT_VALID" + static EVENT_ERROR = "EVENT_ERROR" + static EVENT_ENTER = "EVENT_ENTER" + static EVENT_RESTRICT = "EVENT_RESTRICT" + static EVENT_REMOVE = "EVENT_REMOVE" + static EVENT_EMPTY = "EVENT_EMPTY" + + _defaultConfig(config) { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + extraCls: `bi-text-editor bi-focus-shadow ${config.simple ? "bi-border-bottom" : "bi-border"}`, hgap: 4, vgap: 2, lgap: 0, rgap: 0, tgap: 0, bgap: 0, - validationChecker: BI.emptyFn, - quitChecker: BI.emptyFn, + validationChecker: emptyFn, + quitChecker: emptyFn, allowBlank: false, watermark: "", errorText: "", - height: 24 + height: 24, }); - }, + } - render: function () { - var self = this, o = this.options; - var border = o.simple ? 1 : 2; - this.editor = BI.createWidget({ - type: "bi.editor", + render() { + const o = this.options; + const border = o.simple ? 1 : 2; + this.editor = createWidget({ + type: Editor.xtype, element: this, - width: BI.toPix(o.width, border), - height: BI.toPix(o.height, border), + width: toPix(o.width, border), + height: toPix(o.height, border), simple: o.simple, hgap: o.hgap, vgap: o.vgap, @@ -50,121 +71,100 @@ BI.TextEditor = BI.inherit(BI.Widget, { autocomplete: o.autocomplete, autoTrim: o.autoTrim, }); - this.editor.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.editor.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.editor.on(BI.Editor.EVENT_FOCUS, function () { - self.fireEvent(BI.TextEditor.EVENT_FOCUS); + this.editor.on(Editor.EVENT_FOCUS, () => { + this.fireEvent(TextEditor.EVENT_FOCUS); }); - this.editor.on(BI.Editor.EVENT_BLUR, function () { - self.fireEvent(BI.TextEditor.EVENT_BLUR); + this.editor.on(Editor.EVENT_BLUR, () => { + this.fireEvent(TextEditor.EVENT_BLUR); }); - this.editor.on(BI.Editor.EVENT_CLICK, function () { - self.fireEvent(BI.TextEditor.EVENT_CLICK); + this.editor.on(Editor.EVENT_CLICK, () => { + this.fireEvent(TextEditor.EVENT_CLICK); }); - this.editor.on(BI.Editor.EVENT_CHANGE, function () { - self.fireEvent(BI.TextEditor.EVENT_CHANGE); + this.editor.on(Editor.EVENT_CHANGE, () => { + this.fireEvent(TextEditor.EVENT_CHANGE); }); - this.editor.on(BI.Editor.EVENT_KEY_DOWN, function (v) { - self.fireEvent(BI.TextEditor.EVENT_KEY_DOWN); + this.editor.on(Editor.EVENT_KEY_DOWN, v => { + this.fireEvent(TextEditor.EVENT_KEY_DOWN); }); - this.editor.on(BI.Editor.EVENT_SPACE, function (v) { - self.fireEvent(BI.TextEditor.EVENT_SPACE); + this.editor.on(Editor.EVENT_SPACE, v => { + this.fireEvent(TextEditor.EVENT_SPACE); }); - this.editor.on(BI.Editor.EVENT_BACKSPACE, function (v) { - self.fireEvent(BI.TextEditor.EVENT_BACKSPACE); + this.editor.on(Editor.EVENT_BACKSPACE, v => { + this.fireEvent(TextEditor.EVENT_BACKSPACE); }); - this.editor.on(BI.Editor.EVENT_VALID, function () { - self.element.removeClass("error"); - self.fireEvent(BI.TextEditor.EVENT_VALID); + this.editor.on(Editor.EVENT_VALID, () => { + this.element.removeClass("error"); + this.fireEvent(TextEditor.EVENT_VALID); }); - this.editor.on(BI.Editor.EVENT_CONFIRM, function () { - self.fireEvent(BI.TextEditor.EVENT_CONFIRM); + this.editor.on(Editor.EVENT_CONFIRM, () => { + this.fireEvent(TextEditor.EVENT_CONFIRM); }); - this.editor.on(BI.Editor.EVENT_CHANGE_CONFIRM, function () { - self.fireEvent(BI.TextEditor.EVENT_CHANGE_CONFIRM); + this.editor.on(Editor.EVENT_CHANGE_CONFIRM, () => { + this.fireEvent(TextEditor.EVENT_CHANGE_CONFIRM); }); - this.editor.on(BI.Editor.EVENT_REMOVE, function (v) { - self.fireEvent(BI.TextEditor.EVENT_REMOVE); + this.editor.on(Editor.EVENT_REMOVE, v => { + this.fireEvent(TextEditor.EVENT_REMOVE); }); - this.editor.on(BI.Editor.EVENT_START, function () { - self.fireEvent(BI.TextEditor.EVENT_START); + this.editor.on(Editor.EVENT_START, () => { + this.fireEvent(TextEditor.EVENT_START); }); - this.editor.on(BI.Editor.EVENT_PAUSE, function () { - self.fireEvent(BI.TextEditor.EVENT_PAUSE); + this.editor.on(Editor.EVENT_PAUSE, () => { + this.fireEvent(TextEditor.EVENT_PAUSE); }); - this.editor.on(BI.Editor.EVENT_STOP, function () { - self.fireEvent(BI.TextEditor.EVENT_STOP); + this.editor.on(Editor.EVENT_STOP, () => { + this.fireEvent(TextEditor.EVENT_STOP); }); - this.editor.on(BI.Editor.EVENT_ERROR, function () { - self.element.addClass("error"); - self.fireEvent(BI.TextEditor.EVENT_ERROR, arguments); + this.editor.on(Editor.EVENT_ERROR, (...args) => { + this.element.addClass("error"); + this.fireEvent(TextEditor.EVENT_ERROR, ...args); }); - this.editor.on(BI.Editor.EVENT_ENTER, function () { - self.fireEvent(BI.TextEditor.EVENT_ENTER); + this.editor.on(Editor.EVENT_ENTER, () => { + this.fireEvent(TextEditor.EVENT_ENTER); }); - this.editor.on(BI.Editor.EVENT_RESTRICT, function () { - self.fireEvent(BI.TextEditor.EVENT_RESTRICT); + this.editor.on(Editor.EVENT_RESTRICT, () => { + this.fireEvent(TextEditor.EVENT_RESTRICT); }); - this.editor.on(BI.Editor.EVENT_EMPTY, function () { - self.fireEvent(BI.TextEditor.EVENT_EMPTY); + this.editor.on(Editor.EVENT_EMPTY, () => { + this.fireEvent(TextEditor.EVENT_EMPTY); }); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.options.watermark = v; this.editor.setWaterMark(v); - }, + } - focus: function () { + focus() { this.editor.focus(); - }, + } - blur: function () { + blur() { this.editor.blur(); - }, + } - setErrorText: function (text) { + setErrorText(text) { this.editor.setErrorText(text); - }, + } - getErrorText: function () { + getErrorText() { return this.editor.getErrorText(); - }, + } - isValid: function () { + isValid() { return this.editor.isValid(); - }, + } - setValue: function (v) { + setValue(v) { this.editor.setValue(v); - }, + } - getValue: function () { + getValue() { return this.editor.getValue(); } -}); -BI.TextEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.TextEditor.EVENT_FOCUS = "EVENT_FOCUS"; -BI.TextEditor.EVENT_BLUR = "EVENT_BLUR"; -BI.TextEditor.EVENT_CLICK = "EVENT_CLICK"; -BI.TextEditor.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.TextEditor.EVENT_SPACE = "EVENT_SPACE"; -BI.TextEditor.EVENT_BACKSPACE = "EVENT_BACKSPACE"; - -BI.TextEditor.EVENT_START = "EVENT_START"; -BI.TextEditor.EVENT_PAUSE = "EVENT_PAUSE"; -BI.TextEditor.EVENT_STOP = "EVENT_STOP"; -BI.TextEditor.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.TextEditor.EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; -BI.TextEditor.EVENT_VALID = "EVENT_VALID"; -BI.TextEditor.EVENT_ERROR = "EVENT_ERROR"; -BI.TextEditor.EVENT_ENTER = "EVENT_ENTER"; -BI.TextEditor.EVENT_RESTRICT = "EVENT_RESTRICT"; -BI.TextEditor.EVENT_REMOVE = "EVENT_REMOVE"; -BI.TextEditor.EVENT_EMPTY = "EVENT_EMPTY"; - -BI.shortcut("bi.text_editor", BI.TextEditor); +} diff --git a/src/widget/editor/editor.text.small.js b/src/widget/editor/editor.text.small.js index cb7a9eb96..0d79c8c22 100644 --- a/src/widget/editor/editor.text.small.js +++ b/src/widget/editor/editor.text.small.js @@ -1,20 +1,20 @@ -/** - * 小号搜索框 - * Created by GUY on 2015/9/29. - * @class BI.SmallTextEditor - * @extends BI.SearchEditor - */ -BI.SmallTextEditor = BI.inherit(BI.TextEditor, { - _defaultConfig: function () { - var conf = BI.SmallTextEditor.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-small-text-editor", - height: 20 +import { shortcut, extend } from "@/core"; +import { TextEditor } from "./editor.text"; + +@shortcut() +export class SmallTextEditor extends TextEditor { + static xtype = "bi.small_text_editor" + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-small-text-editor`, + height: 20, }); - }, + } - _init: function () { - BI.SmallTextEditor.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); } -}); -BI.shortcut("bi.small_text_editor", BI.SmallTextEditor); \ No newline at end of file +} diff --git a/src/widget/editor/index.js b/src/widget/editor/index.js new file mode 100644 index 000000000..f5b7bed83 --- /dev/null +++ b/src/widget/editor/index.js @@ -0,0 +1,4 @@ +export { SearchEditor } from "./editor.search"; +export { SmallSearchEditor } from "./editor.search.small"; +export { TextEditor } from "./editor.text"; +export { SmallTextEditor } from "./editor.text.small"; diff --git a/src/widget/index.js b/src/widget/index.js index 6ce1b935c..499020348 100644 --- a/src/widget/index.js +++ b/src/widget/index.js @@ -6,11 +6,14 @@ import * as datetime from "./datetime"; import * as datetimepane from "./datetimepane"; import * as dynamicdatetime from "./dynamicdatetime"; import * as time from "./time"; +import * as editor from "./editor"; import { SelectTreeCombo } from "./selecttree/selecttree.combo"; import { SingleTreeCombo } from "./singletree/singletree.combo"; -import { MultiTreeCombo } from "/multitree/multi.tree.combo"; -import { MultiTreeInsertCombo } from "/multitree/multi.tree.insert.combo"; -import { MultiTreeListCombo } from "/multitree/multi.tree.list.combo"; +import { MultiTreeCombo } from "./multitree/multi.tree.combo"; +import { MultiTreeInsertCombo } from "./multitree/multi.tree.insert.combo"; +import { MultiTreeListCombo } from "./multitree/multi.tree.list.combo"; +import { NumberEditor } from "./numbereditor/number.editor"; +import { NumberInterval } from "./numberinterval/numberinterval"; Object.assign(BI, { Collapse, @@ -21,11 +24,14 @@ Object.assign(BI, { ...datetimepane, ...dynamicdatetime, ...time, + ...editor, SelectTreeCombo, SingleTreeCombo, MultiTreeCombo, MultiTreeInsertCombo, - MultiTreeListCombo + MultiTreeListCombo, + NumberEditor, + NumberInterval, }); export * from "./date/calendar"; @@ -35,11 +41,14 @@ export * from "./datetime"; export * from "./datetimepane"; export * from "./dynamicdatetime"; export * from "./time"; -export { SelectTreeCombo } from "./selecttree/selecttree.combo"; -export { SingleTreeCombo } from "./singletree/singletree.combo"; -export { MultiTreeCombo } from "/multitree/multi.tree.combo"; -export { MultiTreeInsertCombo } from "/multitree/multi.tree.insert.combo"; -export { MultiTreeListCombo } from "/multitree/multi.tree.list.combo"; +export * from "./editor"; export { - Collapse + Collapse, + NumberEditor, + NumberInterval, + SelectTreeCombo, + SingleTreeCombo, + MultiTreeCombo, + MultiTreeInsertCombo, + MultiTreeListCombo }; diff --git a/src/widget/numbereditor/number.editor.js b/src/widget/numbereditor/number.editor.js index 13f360baa..6e89f07df 100644 --- a/src/widget/numbereditor/number.editor.js +++ b/src/widget/numbereditor/number.editor.js @@ -1,202 +1,204 @@ -/** - * Created by windy on 2017/3/13. - * 数值微调器 - */ -BI.NumberEditor = BI.inherit(BI.Widget, { - _defaultConfig: function (conf) { - return BI.extend(BI.NumberEditor.superclass._defaultConfig.apply(this, arguments), { - baseCls: "bi-number-editor bi-focus-shadow " + (conf.simple ? "bi-border-bottom" : "bi-border bi-border-radius"), - validationChecker: BI.emptyFn, - valueFormatter: function (v) { +import { shortcut, Widget, extend, emptyFn, createWidget, toPix, parseFloat, HTapeLayout, GridLayout, isNumeric, clamp, MIN, MAX, KeyCode, add } from "@/core"; +import { SignEditor } from "@/case"; +import { TextEditor } from "../editor"; +import { IconButton } from "@/base"; + +@shortcut() +export class NumberEditor extends Widget { + static xtype = "bi.number_editor" + + static EVENT_CONFIRM = "EVENT_CONFIRM" + static EVENT_CHANGE = "EVENT_CHANGE" + + _defaultConfig(conf) { + return extend(super._defaultConfig(...arguments), { + baseCls: `bi-number-editor bi-focus-shadow ${conf.simple ? "bi-border-bottom" : "bi-border bi-border-radius"}`, + validationChecker: emptyFn, + valueFormatter (v) { return v; }, - valueParser: function (v) { + valueParser (v) { return v; }, value: 0, allowBlank: false, errorText: "", step: 1, - min: BI.MIN, - max: BI.MAX, + min: MIN, + max: MAX, watermark: "", }); - }, - - _init: function () { - BI.NumberEditor.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.editor = BI.createWidget({ - type: "bi.sign_editor", - height: BI.toPix(o.height, 2), + } + + _init() { + super._init(...arguments); + const o = this.options; + this.editor = createWidget({ + type: SignEditor.xtype, + height: toPix(o.height, 2), simple: o.simple, allowBlank: o.allowBlank, watermark: o.watermark, value: o.valueFormatter(o.value), - validationChecker: function (v) { + validationChecker: v => { // 不设置validationChecker就自动检测 - var parsedValue = o.valueParser(v); - if (o.validationChecker === BI.emptyFn && !self._checkValueInRange(parsedValue)) { + const parsedValue = o.valueParser(v); + if (o.validationChecker === emptyFn && !this._checkValueInRange(parsedValue)) { return false; } return o.validationChecker(parsedValue); }, errorText: o.errorText, - listeners: [ - { - eventName: BI.SignEditor.EVENT_QUICK_DOWN, - action: e => { - if ([BI.KeyCode.UP, BI.KeyCode.DOWN].includes(e.keyCode)) { - e.preventDefault(); - } - }, + listeners: [{ + eventName: SignEditor.EVENT_QUICK_DOWN, + action: e => { + if ([KeyCode.UP, KeyCode.DOWN].includes(e.keyCode)) { + e.preventDefault(); + } }, - { - eventName: BI.SignEditor.EVENT_KEY_DOWN, - action: (keycode) => { - if (keycode === BI.KeyCode.UP) { - this._finetuning(o.step); - - return; - } - if (keycode === BI.KeyCode.DOWN) { - this._finetuning(-o.step); - } - }, - } + }, + { + eventName: SignEditor.EVENT_KEY_DOWN, + action: keycode => { + if (keycode === KeyCode.UP) { + this._finetuning(o.step); + + return; + } + if (keycode === KeyCode.DOWN) { + this._finetuning(-o.step); + } + }, + } ], }); - this.editor.on(BI.TextEditor.EVENT_CHANGE, function () { + this.editor.on(TextEditor.EVENT_CHANGE, () => { // 大多数时候valueFormatter往往需要配合valueParser一起使用 - var value = this.getValue(); - var parsedValue = o.valueParser(value); - this.setValue(o.valueFormatter(parsedValue)); - self.fireEvent(BI.NumberEditor.EVENT_CHANGE); + const value = this.editor.getValue(); + const parsedValue = o.valueParser(value); + this.editor.setValue(o.valueFormatter(parsedValue)); + this.fireEvent(NumberEditor.EVENT_CHANGE); }); - this.editor.on(BI.TextEditor.EVENT_ERROR, function () { - o.value = BI.parseFloat(this.getLastValidValue()); - self._checkAdjustDisabled(o.value); - self.element.addClass("error"); + this.editor.on(TextEditor.EVENT_ERROR, () => { + o.value = parseFloat(this.editor.getLastValidValue()); + this._checkAdjustDisabled(o.value); + this.element.addClass("error"); }); - this.editor.on(BI.TextEditor.EVENT_VALID, function () { - o.value = BI.parseFloat(this.getValue()); - self._checkAdjustDisabled(o.value); - self.element.removeClass("error"); + this.editor.on(TextEditor.EVENT_VALID, () => { + o.value = parseFloat(this.editor.getValue()); + this._checkAdjustDisabled(o.value); + this.element.removeClass("error"); }); - this.editor.on(BI.TextEditor.EVENT_CONFIRM, function () { - self.fireEvent(BI.NumberEditor.EVENT_CONFIRM); + this.editor.on(TextEditor.EVENT_CONFIRM, () => { + this.fireEvent(NumberEditor.EVENT_CONFIRM); }); - this.topBtn = BI.createWidget({ - type: "bi.icon_button", + this.topBtn = createWidget({ + type: IconButton.xtype, forceNotSelected: true, trigger: "lclick,", debounce: false, - cls: (o.simple ? "solid-triangle-top-font " : "add-up-font bi-border-left ") + "top-button bi-list-item-active2 icon-size-12", + cls: `${o.simple ? "solid-triangle-top-font " : "add-up-font bi-border-left "}top-button bi-list-item-active2 icon-size-12`, }); - this.topBtn.on(BI.IconButton.EVENT_CHANGE, function () { - self._finetuning(o.step); - self.fireEvent(BI.NumberEditor.EVENT_CHANGE); - self.fireEvent(BI.NumberEditor.EVENT_CONFIRM); + this.topBtn.on(IconButton.EVENT_CHANGE, () => { + this._finetuning(o.step); + this.fireEvent(NumberEditor.EVENT_CHANGE); + this.fireEvent(NumberEditor.EVENT_CONFIRM); }); - this.bottomBtn = BI.createWidget({ - type: "bi.icon_button", + this.bottomBtn = createWidget({ + type: IconButton.xtype, trigger: "lclick,", forceNotSelected: true, debounce: false, - cls: (o.simple ? "solid-triangle-bottom-font " : "minus-down-font bi-border-left ") + "bottom-button bi-list-item-active2 icon-size-12", + cls: `${o.simple ? "solid-triangle-bottom-font " : "minus-down-font bi-border-left "}bottom-button bi-list-item-active2 icon-size-12`, }); - this.bottomBtn.on(BI.IconButton.EVENT_CHANGE, function () { - self._finetuning(-o.step); - self.fireEvent(BI.NumberEditor.EVENT_CHANGE); - self.fireEvent(BI.NumberEditor.EVENT_CONFIRM); + this.bottomBtn.on(IconButton.EVENT_CHANGE, () => { + this._finetuning(-o.step); + this.fireEvent(NumberEditor.EVENT_CHANGE); + this.fireEvent(NumberEditor.EVENT_CONFIRM); }); - BI.createWidget({ - type: "bi.htape", - height: BI.toPix(o.height, 2), + createWidget({ + type: HTapeLayout.xtype, + height: toPix(o.height, 2), element: this, items: [ this.editor, { el: { - type: "bi.grid", + type: GridLayout.xtype, columns: 1, rows: 2, - items: [ - { - column: 0, - row: 0, - el: this.topBtn, - }, { - column: 0, - row: 1, - el: this.bottomBtn, - } - ], + items: [{ + column: 0, + row: 0, + el: this.topBtn, + }, { + column: 0, + row: 1, + el: this.bottomBtn, + }], }, width: 23, } ], }); - }, + } - focus: function () { + focus() { this.editor.focus(); - }, + } - isEditing: function () { + isEditing() { return this.editor.isEditing(); - }, + } - _checkValueInRange: function (v) { - var o = this.options; + _checkValueInRange(v) { + const o = this.options; - return !!(BI.isNumeric(v) && BI.parseFloat(v) >= o.min && BI.parseFloat(v) <= o.max); - }, + return !!(isNumeric(v) && parseFloat(v) >= o.min && parseFloat(v) <= o.max); + } - _checkAdjustDisabled: function (v) { - if (this.options.validationChecker === BI.emptyFn) { - this.bottomBtn.setEnable(BI.parseFloat(v) > this.options.min); - this.topBtn.setEnable(BI.parseFloat(v) < this.options.max); + _checkAdjustDisabled(v) { + if (this.options.validationChecker === emptyFn) { + this.bottomBtn.setEnable(parseFloat(v) > this.options.min); + this.topBtn.setEnable(parseFloat(v) < this.options.max); } - }, - - // 微调 - _finetuning: function (add) { - const { max, min } = this.options; - let v = BI.parseFloat(this.getValue()); - v = BI.add(v, add); - v = BI.clamp(v, min, max); + } + + _finetuning(addValue) { + const { + max, + min, + } = this.options; + let v = parseFloat(this.getValue()); + v = add(v, addValue); + v = clamp(v, min, max); this.setValue(v); - }, + } - setUpEnable: function (v) { + setUpEnable(v) { this.topBtn.setEnable(!!v); - }, + } - setDownEnable: function (v) { + setDownEnable(v) { this.bottomBtn.setEnable(!!v); - }, + } - getLastValidValue: function () { + getLastValidValue() { return this.editor.getLastValidValue(); - }, + } - getLastChangedValue: function () { + getLastChangedValue() { return this.editor.getLastChangedValue(); - }, + } - getValue: function () { + getValue() { return this.options.value; - }, + } - setValue: function (v) { - var o = this.options; + setValue(v) { + const o = this.options; o.value = v; this.editor.setValue(o.valueFormatter(v)); this._checkAdjustDisabled(o.value); - }, - -}); -BI.NumberEditor.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.NumberEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.number_editor", BI.NumberEditor); + } +} diff --git a/src/widget/numberinterval/numberinterval.js b/src/widget/numberinterval/numberinterval.js index 0c3c488bd..ae0a22ae9 100644 --- a/src/widget/numberinterval/numberinterval.js +++ b/src/widget/numberinterval/numberinterval.js @@ -1,11 +1,13 @@ -// 小于号的值为:0,小于等于号的值为:1 -// closeMIn:最小值的符号,closeMax:最大值的符号 -/** - * Created by roy on 15/9/17. - * - */ -BI.NumberInterval = BI.inherit(BI.Single, { - constants: { +import { shortcut, extend, i18nText, createWidget, toPix, isNumeric, AbsoluteLayout, isEmptyString, isNotNull, isNull, isIE, getIEVersion } from "@/core"; +import { Single, Label, Bubbles } from "@/base"; +import { IconCombo } from "@/case"; +import { NumberIntervalSingleEidtor } from "./singleeditor/single.editor"; + +@shortcut() +export class NumberInterval extends Single { + static xtype = "bi.number_interval" + + constants = { typeError: "typeBubble", numberError: "numberBubble", signalError: "signalBubble", @@ -18,160 +20,174 @@ BI.NumberInterval = BI.inherit(BI.Single, { less: 0, less_equal: 1, numTip: "", - adjustYOffset: 2 - }, - _defaultConfig: function () { - var conf = BI.NumberInterval.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - extraCls: "bi-number-interval" + ((BI.isIE() && BI.getIEVersion() < 10) ? " hack" : ""), + adjustYOffset: 2, + }; + + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_CONFIRM = "EVENT_CONFIRM" + static EVENT_VALID = "EVENT_VALID" + static EVENT_ERROR = "EVENT_ERROR" + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + extraCls: `bi-number-interval${(isIE() && getIEVersion() < 10) ? " hack" : ""}`, height: 24, validation: "valid", closeMin: true, allowBlank: true, - watermark: BI.i18nText("BI-Basic_Unrestricted") + watermark: i18nText("BI-Basic_Unrestricted"), }); - }, - _init: function () { - var self = this, c = this.constants, o = this.options; - BI.NumberInterval.superclass._init.apply(this, arguments); - this.smallEditor = BI.createWidget({ + } + + _init() { + const self = this, + c = this.constants, + o = this.options; + super._init(...arguments); + this.smallEditor = createWidget({ type: "bi.number_interval_single_editor", - height: BI.toPix(o.height, o.simple ? 1 : 2), + height: toPix(o.height, o.simple ? 1 : 2), watermark: o.watermark, allowBlank: o.allowBlank, value: o.min, level: "warning", tipType: "success", - title: function () { + title () { return self.smallEditor && self.smallEditor.getValue(); }, - quitChecker: function () { + quitChecker () { return false; }, - validationChecker: function (v) { - if (!BI.isNumeric(v)) { + validationChecker (v) { + if (!isNumeric(v)) { self.smallEditorBubbleType = c.typeError; + return false; } + return true; }, - cls: "number-interval-small-editor bi-focus-shadow " + (o.simple ? "bi-border-bottom" : "bi-border bi-border-corner-left-radius") + cls: `number-interval-small-editor bi-focus-shadow ${o.simple ? "bi-border-bottom" : "bi-border bi-border-corner-left-radius"}`, }); - this.smallTip = BI.createWidget({ - type: "bi.label", + this.smallTip = createWidget({ + type: Label.xtype, text: o.numTip, - height: BI.toPix(o.height, o.simple ? 1 : 2), - invisible: true + height: toPix(o.height, o.simple ? 1 : 2), + invisible: true, }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this.smallEditor, items: [{ el: this.smallTip, top: 0, - right: 5 - }] + right: 5, + }], }); - this.bigEditor = BI.createWidget({ + this.bigEditor = createWidget({ type: "bi.number_interval_single_editor", - height: BI.toPix(o.height, o.simple ? 1 : 2), + height: toPix(o.height, o.simple ? 1 : 2), watermark: o.watermark, allowBlank: o.allowBlank, value: o.max, - title: function () { + title () { return self.bigEditor && self.bigEditor.getValue(); }, - quitChecker: function () { + quitChecker () { return false; }, - validationChecker: function (v) { - if (!BI.isNumeric(v)) { + validationChecker (v) { + if (!isNumeric(v)) { self.bigEditorBubbleType = c.typeError; + return false; } + return true; }, - cls: "number-interval-big-editor bi-focus-shadow" + (o.simple ? " bi-border-bottom" : " bi-border bi-border-corner-right-radius") + cls: `number-interval-big-editor bi-focus-shadow${o.simple ? " bi-border-bottom" : " bi-border bi-border-corner-right-radius"}`, }); - this.bigTip = BI.createWidget({ - type: "bi.label", + this.bigTip = createWidget({ + type: Label.xtype, text: o.numTip, - height: BI.toPix(o.height, o.simple ? 1 : 2), - invisible: true + height: toPix(o.height, o.simple ? 1 : 2), + invisible: true, }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this.bigEditor, items: [{ el: this.bigTip, top: 0, - right: 5 - }] + right: 5, + }], }); - this.smallCombo = BI.createWidget({ - type: "bi.icon_combo", - cls: "number-interval-small-combo" + (o.simple ? "" : " bi-border-top bi-border-bottom bi-border-right bi-border-corner-right-radius"), - height: BI.toPix(o.height, o.simple ? 0 : 2), - width: BI.toPix(c.width, c.border), + this.smallCombo = createWidget({ + type: IconCombo.xtype, + cls: `number-interval-small-combo${o.simple ? "" : " bi-border-top bi-border-bottom bi-border-right bi-border-corner-right-radius"}`, + height: toPix(o.height, o.simple ? 0 : 2), + width: toPix(c.width, c.border), items: [{ - text: "(" + BI.i18nText("BI-Less_Than") + ")", + text: `(${i18nText("BI-Less_Than")})`, iconCls: "less-font", - value: 0 + value: 0, }, { - text: "(" + BI.i18nText("BI-Less_And_Equal") + ")", + text: `(${i18nText("BI-Less_And_Equal")})`, value: 1, - iconCls: "less-equal-font" - }] + iconCls: "less-equal-font", + }], }); if (o.closeMin === true) { this.smallCombo.setValue(1); } else { this.smallCombo.setValue(0); } - this.bigCombo = BI.createWidget({ - type: "bi.icon_combo", - cls: "number-interval-big-combo" + (o.simple ? "" : " bi-border-top bi-border-bottom bi-border-left bi-border-corner-left-radius"), - height: BI.toPix(o.height, o.simple ? 0 : 2), - width: BI.toPix(c.width, c.border), + this.bigCombo = createWidget({ + type: IconCombo.xtype, + cls: `number-interval-big-combo${o.simple ? "" : " bi-border-top bi-border-bottom bi-border-left bi-border-corner-left-radius"}`, + height: toPix(o.height, o.simple ? 0 : 2), + width: toPix(c.width, c.border), items: [{ - text: "(" + BI.i18nText("BI-Less_Than") + ")", + text: `(${i18nText("BI-Less_Than")})`, iconCls: "less-font", - value: 0 + value: 0, }, { - text: "(" + BI.i18nText("BI-Less_And_Equal") + ")", + text: `(${i18nText("BI-Less_And_Equal")})`, value: 1, - iconCls: "less-equal-font" - }] + iconCls: "less-equal-font", + }], }); if (o.closeMax === true) { this.bigCombo.setValue(1); } else { this.bigCombo.setValue(0); } - this.label = BI.createWidget({ - type: "bi.label", - text: BI.i18nText("BI-Basic_Value"), + this.label = createWidget({ + type: Label.xtype, + text: i18nText("BI-Basic_Value"), textHeight: o.height, - // width: BI.toPix(o.width, o.simple ? 0 : c.border * 2), + // width: toPix(o.width, o.simple ? 0 : c.border * 2), hgap: 5, height: o.height, level: "warning", - tipType: "warning" + tipType: "warning", }); - this.left = BI.createWidget({ + this.left = createWidget({ type: "bi.horizontal_fill", columnSize: ["fill", ""], items: [{ - el: self.smallEditor + el: self.smallEditor, }, { el: self.smallCombo, - }] + }], }); - this.right = BI.createWidget({ + this.right = createWidget({ type: "bi.horizontal_fill", columnSize: ["", "fill"], items: [{ @@ -180,38 +196,38 @@ BI.NumberInterval = BI.inherit(BI.Single, { el: self.bigEditor, // BI-23883 间距考虑边框 // lgap: 1 - }] + }], }); - BI.createWidget({ + createWidget({ element: self, type: "bi.horizontal_fill", columnSize: ["fill", "", "fill"], items: [{ - el: self.left + el: self.left, }, { - el: self.label + el: self.label, }, { - el: self.right - }] + el: self.right, + }], }); - // BI.createWidget({ + // createWidget({ // element: self, - // type: "bi.horizontal_auto", + // type: HorizontalAutoLayout.xtype, // items: [ // self.label // ] // }); - // BI.createWidget({ + // createWidget({ // element: self, - // type: "bi.center", + // type: CenterLayout.xtype, // hgap: 15, // height: o.height, // items: [ // { - // type: "bi.absolute", + // type: AbsoluteLayout.xtype, // items: [{ // el: self.left, // left: -15, @@ -220,7 +236,7 @@ BI.NumberInterval = BI.inherit(BI.Single, { // bottom: 0 // }] // }, { - // type: "bi.absolute", + // type: AbsoluteLayout.xtype, // items: [{ // el: self.right, // left: 0, @@ -246,264 +262,274 @@ BI.NumberInterval = BI.inherit(BI.Single, { self._setEditorValueChangedEvent(self.smallEditor); self._checkValidation(); - }, + } - _checkValidation: function () { - var self = this, c = this.constants, o = this.options; + _checkValidation() { + const self = this, + c = this.constants, + o = this.options; self._setTitle(""); - BI.Bubbles.hide(c.typeError); - BI.Bubbles.hide(c.numberError); - BI.Bubbles.hide(c.signalError); + Bubbles.hide(c.typeError); + Bubbles.hide(c.numberError); + Bubbles.hide(c.signalError); if (!self.smallEditor.isValid() || !self.bigEditor.isValid()) { self.element.removeClass("number-error"); o.validation = "invalid"; + return c.typeError; } - if (BI.isEmptyString(self.smallEditor.getValue()) || BI.isEmptyString(self.bigEditor.getValue())) { + if (isEmptyString(self.smallEditor.getValue()) || isEmptyString(self.bigEditor.getValue())) { self.element.removeClass("number-error"); o.validation = "valid"; + return ""; } - var smallValue = parseFloat(self.smallEditor.getValue()), bigValue = parseFloat(self.bigEditor.getValue()), - bigComboValue = self.bigCombo.getValue(), smallComboValue = self.smallCombo.getValue(); + const smallValue = parseFloat(self.smallEditor.getValue()), + bigValue = parseFloat(self.bigEditor.getValue()), + bigComboValue = self.bigCombo.getValue(), + smallComboValue = self.smallCombo.getValue(); if (bigComboValue[0] === c.less_equal && smallComboValue[0] === c.less_equal) { if (smallValue > bigValue) { self.element.addClass("number-error"); o.validation = "invalid"; + return c.numberError; } self.element.removeClass("number-error"); o.validation = "valid"; + return ""; - } if (smallValue > bigValue) { self.element.addClass("number-error"); o.validation = "invalid"; + return c.numberError; } else if (smallValue === bigValue) { self.element.addClass("number-error"); o.validation = "invalid"; + return c.signalError; } self.element.removeClass("number-error"); o.validation = "valid"; + return ""; + } - - - - - }, - - _setTitle: function (v) { + _setTitle(v) { this.label.setTitle(v); - }, + } - _setFocusEvent: function (w) { - var self = this, c = this.constants; - w.on(BI.NumberIntervalSingleEidtor.EVENT_FOCUS, function () { + _setFocusEvent(w) { + const self = this, + c = this.constants; + w.on(NumberIntervalSingleEidtor.EVENT_FOCUS, () => { self._setTitle(""); switch (self._checkValidation()) { - case c.typeError: - BI.Bubbles.show(c.typeError, BI.i18nText("BI-Numerical_Interval_Input_Data"), self, { - offsetStyle: "left", - adjustYOffset: c.adjustYOffset - }); - break; - case c.numberError: - BI.Bubbles.show(c.numberError, BI.i18nText("BI-Numerical_Interval_Number_Value"), self, { - offsetStyle: "left", - adjustYOffset: c.adjustYOffset - }); - break; - case c.signalError: - BI.Bubbles.show(c.signalError, BI.i18nText("BI-Numerical_Interval_Signal_Value"), self, { - offsetStyle: "left", - adjustYOffset: c.adjustYOffset - }); - break; - default : - return; + case c.typeError: + Bubbles.show(c.typeError, i18nText("BI-Numerical_Interval_Input_Data"), self, { + offsetStyle: "left", + adjustYOffset: c.adjustYOffset, + }); + break; + case c.numberError: + Bubbles.show(c.numberError, i18nText("BI-Numerical_Interval_Number_Value"), self, { + offsetStyle: "left", + adjustYOffset: c.adjustYOffset, + }); + break; + case c.signalError: + Bubbles.show(c.signalError, i18nText("BI-Numerical_Interval_Signal_Value"), self, { + offsetStyle: "left", + adjustYOffset: c.adjustYOffset, + }); + break; + default: + return; } - }); - }, - _setBlurEvent: function (w) { - var c = this.constants, self = this; - w.on(BI.NumberIntervalSingleEidtor.EVENT_BLUR, function () { - BI.Bubbles.hide(c.typeError); - BI.Bubbles.hide(c.numberError); - BI.Bubbles.hide(c.signalError); + } + + _setBlurEvent(w) { + const c = this.constants, + self = this; + w.on(NumberIntervalSingleEidtor.EVENT_BLUR, () => { + Bubbles.hide(c.typeError); + Bubbles.hide(c.numberError); + Bubbles.hide(c.signalError); switch (self._checkValidation()) { - case c.typeError: - self._setTitle(BI.i18nText("BI-Numerical_Interval_Input_Data")); - break; - case c.numberError: - self._setTitle(BI.i18nText("BI-Numerical_Interval_Number_Value")); - break; - case c.signalError: - self._setTitle(BI.i18nText("BI-Numerical_Interval_Signal_Value")); - break; - default: - self._setTitle(""); + case c.typeError: + self._setTitle(i18nText("BI-Numerical_Interval_Input_Data")); + break; + case c.numberError: + self._setTitle(i18nText("BI-Numerical_Interval_Number_Value")); + break; + case c.signalError: + self._setTitle(i18nText("BI-Numerical_Interval_Signal_Value")); + break; + default: + self._setTitle(""); } }); - }, + } - _setErrorEvent: function (w) { - var c = this.constants, self = this; - w.on(BI.NumberIntervalSingleEidtor.EVENT_ERROR, function () { + _setErrorEvent(w) { + const c = this.constants, + self = this; + w.on(NumberIntervalSingleEidtor.EVENT_ERROR, () => { self._checkValidation(); - BI.Bubbles.show(c.typeError, BI.i18nText("BI-Numerical_Interval_Input_Data"), self, { + Bubbles.show(c.typeError, i18nText("BI-Numerical_Interval_Input_Data"), self, { offsetStyle: "left", - adjustYOffset: c.adjustYOffset + adjustYOffset: c.adjustYOffset, }); - self.fireEvent(BI.NumberInterval.EVENT_ERROR); + self.fireEvent(NumberInterval.EVENT_ERROR); }); - }, - + } - _setValidEvent: function (w) { - var self = this, c = this.constants; - w.on(BI.NumberIntervalSingleEidtor.EVENT_VALID, function () { + _setValidEvent(w) { + const self = this, + c = this.constants; + w.on(NumberIntervalSingleEidtor.EVENT_VALID, () => { switch (self._checkValidation()) { - case c.numberError: - BI.Bubbles.show(c.numberError, BI.i18nText("BI-Numerical_Interval_Number_Value"), self, { - offsetStyle: "left", - adjustYOffset: c.adjustYOffset - }); - self.fireEvent(BI.NumberInterval.EVENT_ERROR); - break; - case c.signalError: - BI.Bubbles.show(c.signalError, BI.i18nText("BI-Numerical_Interval_Signal_Value"), self, { - offsetStyle: "left", - adjustYOffset: c.adjustYOffset - }); - self.fireEvent(BI.NumberInterval.EVENT_ERROR); - break; - default: - self.fireEvent(BI.NumberInterval.EVENT_VALID); + case c.numberError: + Bubbles.show(c.numberError, i18nText("BI-Numerical_Interval_Number_Value"), self, { + offsetStyle: "left", + adjustYOffset: c.adjustYOffset, + }); + self.fireEvent(NumberInterval.EVENT_ERROR); + break; + case c.signalError: + Bubbles.show(c.signalError, i18nText("BI-Numerical_Interval_Signal_Value"), self, { + offsetStyle: "left", + adjustYOffset: c.adjustYOffset, + }); + self.fireEvent(NumberInterval.EVENT_ERROR); + break; + default: + self.fireEvent(NumberInterval.EVENT_VALID); } }); - }, - + } - _setEditorValueChangedEvent: function (w) { - var self = this, c = this.constants; - w.on(BI.NumberIntervalSingleEidtor.EVENT_CHANGE, function () { + _setEditorValueChangedEvent(w) { + const self = this, + c = this.constants; + w.on(NumberIntervalSingleEidtor.EVENT_CHANGE, () => { switch (self._checkValidation()) { - case c.typeError: - BI.Bubbles.show(c.typeError, BI.i18nText("BI-Numerical_Interval_Input_Data"), self, { - offsetStyle: "left", - adjustYOffset: c.adjustYOffset - }); - break; - case c.numberError: - BI.Bubbles.show(c.numberError, BI.i18nText("BI-Numerical_Interval_Number_Value"), self, { - offsetStyle: "left", - adjustYOffset: c.adjustYOffset - }); - break; - case c.signalError: - BI.Bubbles.show(c.signalError, BI.i18nText("BI-Numerical_Interval_Signal_Value"), self, { - offsetStyle: "left", - adjustYOffset: c.adjustYOffset - }); - break; - default : - break; + case c.typeError: + Bubbles.show(c.typeError, i18nText("BI-Numerical_Interval_Input_Data"), self, { + offsetStyle: "left", + adjustYOffset: c.adjustYOffset, + }); + break; + case c.numberError: + Bubbles.show(c.numberError, i18nText("BI-Numerical_Interval_Number_Value"), self, { + offsetStyle: "left", + adjustYOffset: c.adjustYOffset, + }); + break; + case c.signalError: + Bubbles.show(c.signalError, i18nText("BI-Numerical_Interval_Signal_Value"), self, { + offsetStyle: "left", + adjustYOffset: c.adjustYOffset, + }); + break; + default: + break; } - self.fireEvent(BI.NumberInterval.EVENT_CHANGE); + self.fireEvent(NumberInterval.EVENT_CHANGE); }); - w.on(BI.NumberIntervalSingleEidtor.EVENT_CONFIRM, function () { - self.fireEvent(BI.NumberInterval.EVENT_CONFIRM); + w.on(NumberIntervalSingleEidtor.EVENT_CONFIRM, () => { + self.fireEvent(NumberInterval.EVENT_CONFIRM); }); - }, + } - _setComboValueChangedEvent: function (w) { - var self = this, c = this.constants; - w.on(BI.IconCombo.EVENT_CHANGE, function () { + _setComboValueChangedEvent(w) { + const self = this, + c = this.constants; + w.on(IconCombo.EVENT_CHANGE, () => { switch (self._checkValidation()) { - case c.typeError: - self._setTitle(BI.i18nText("BI-Numerical_Interval_Input_Data")); - self.fireEvent(BI.NumberInterval.EVENT_ERROR); - break; - case c.numberError: - self._setTitle(BI.i18nText("BI-Numerical_Interval_Number_Value")); - self.fireEvent(BI.NumberInterval.EVENT_ERROR); - break; - case c.signalError: - self._setTitle(BI.i18nText("BI-Numerical_Interval_Signal_Value")); - self.fireEvent(BI.NumberInterval.EVENT_ERROR); - break; - default : - self.fireEvent(BI.NumberInterval.EVENT_CHANGE); - self.fireEvent(BI.NumberInterval.EVENT_CONFIRM); - self.fireEvent(BI.NumberInterval.EVENT_VALID); + case c.typeError: + self._setTitle(i18nText("BI-Numerical_Interval_Input_Data")); + self.fireEvent(NumberInterval.EVENT_ERROR); + break; + case c.numberError: + self._setTitle(i18nText("BI-Numerical_Interval_Number_Value")); + self.fireEvent(NumberInterval.EVENT_ERROR); + break; + case c.signalError: + self._setTitle(i18nText("BI-Numerical_Interval_Signal_Value")); + self.fireEvent(NumberInterval.EVENT_ERROR); + break; + default: + self.fireEvent(NumberInterval.EVENT_CHANGE); + self.fireEvent(NumberInterval.EVENT_CONFIRM); + self.fireEvent(NumberInterval.EVENT_VALID); } }); - }, + } - isStateValid: function () { + isStateValid() { return this.options.validation === "valid"; - }, + } - setMinEnable: function (b) { + setMinEnable(b) { this.smallEditor.setEnable(b); - }, + } - setCloseMinEnable: function (b) { + setCloseMinEnable(b) { this.smallCombo.setEnable(b); - }, + } - setMaxEnable: function (b) { + setMaxEnable(b) { this.bigEditor.setEnable(b); - }, + } - setCloseMaxEnable: function (b) { + setCloseMaxEnable(b) { this.bigCombo.setEnable(b); - }, + } - showNumTip: function () { + showNumTip() { this.smallTip.setVisible(true); this.bigTip.setVisible(true); - }, + } - hideNumTip: function () { + hideNumTip() { this.smallTip.setVisible(false); this.bigTip.setVisible(false); - }, + } - setNumTip: function (numTip) { + setNumTip(numTip) { this.smallTip.setText(numTip); this.bigTip.setText(numTip); - }, + } - getNumTip: function () { + getNumTip() { return this.smallTip.getText(); - }, + } - setValue: function (data) { + setValue(data) { data = data || {}; - var self = this, combo_value; - if (BI.isNumeric(data.min) || BI.isEmptyString(data.min)) { + const self = this; + let combo_value; + if (isNumeric(data.min) || isEmptyString(data.min)) { self.smallEditor.setValue(data.min); } - if (!BI.isNotNull(data.min)) { + if (!isNotNull(data.min)) { self.smallEditor.setValue(""); } - if (BI.isNumeric(data.max) || BI.isEmptyString(data.max)) { + if (isNumeric(data.max) || isEmptyString(data.max)) { self.bigEditor.setValue(data.max); } - if (!BI.isNotNull(data.max)) { + if (!isNotNull(data.max)) { self.bigEditor.setValue(""); } - if (!BI.isNull(data.closeMin)) { + if (!isNull(data.closeMin)) { if (data.closeMin === true) { combo_value = 1; } else { @@ -512,7 +538,7 @@ BI.NumberInterval = BI.inherit(BI.Single, { self.smallCombo.setValue(combo_value); } - if (!BI.isNull(data.closeMax)) { + if (!isNull(data.closeMax)) { if (data.closeMax === true) { combo_value = 1; } else { @@ -522,11 +548,13 @@ BI.NumberInterval = BI.inherit(BI.Single, { } this._checkValidation(); - }, - + } - getValue: function () { - var self = this, value = {}, minComboValue = self.smallCombo.getValue(), maxComboValue = self.bigCombo.getValue(); + getValue() { + const self = this, + value = {}, + minComboValue = self.smallCombo.getValue(), + maxComboValue = self.bigCombo.getValue(); value.min = self.smallEditor.getValue(); value.max = self.bigEditor.getValue(); if (minComboValue[0] === 0) { @@ -540,26 +568,22 @@ BI.NumberInterval = BI.inherit(BI.Single, { } else { value.closeMax = true; } + return value; - }, + } - focusMinEditor: function () { + focusMinEditor() { this.smallEditor.focus(); - }, + } - focusMaxEditor: function () { + focusMaxEditor() { this.bigEditor.focus(); - }, + } - destroyed: function () { - var c = this.constants; - BI.Bubbles.remove(c.typeError); - BI.Bubbles.remove(c.numberError); - BI.Bubbles.remove(c.signalError); + destroyed() { + const c = this.constants; + Bubbles.remove(c.typeError); + Bubbles.remove(c.numberError); + Bubbles.remove(c.signalError); } -}); -BI.NumberInterval.EVENT_CHANGE = "EVENT_CHANGE"; -BI.NumberInterval.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.NumberInterval.EVENT_VALID = "EVENT_VALID"; -BI.NumberInterval.EVENT_ERROR = "EVENT_ERROR"; -BI.shortcut("bi.number_interval", BI.NumberInterval); +} diff --git a/src/widget/numberinterval/singleeditor/single.editor.js b/src/widget/numberinterval/singleeditor/single.editor.js index ac7738d9f..80126ad53 100644 --- a/src/widget/numberinterval/singleeditor/single.editor.js +++ b/src/widget/numberinterval/singleeditor/single.editor.js @@ -1,19 +1,34 @@ -BI.NumberIntervalSingleEidtor = BI.inherit(BI.Single, { - props: { +import { shortcut, VerticalLayout } from "@/core"; +import { Single, Editor } from "@/base"; + +@shortcut() +export class NumberIntervalSingleEidtor extends Single { + static xtype = "bi.number_interval_single_editor" + + static EVENT_FOCUS = "EVENT_FOCUS" + static EVENT_BLUR = "EVENT_BLUR" + static EVENT_ERROR = "EVENT_ERROR" + static EVENT_VALID = "EVENT_VALID" + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM" + static EVENT_CONFIRM = "EVENT_CONFIRM" + + props = { baseCls: "bi-number-interval-single-editor", tipType: "success", - title: "" - }, + title: "", + }; - render: function () { - var self = this, o = this.options; + render() { + const self = this, + o = this.options; return { - type: "bi.vertical", + type: VerticalLayout.xtype, items: [{ - type: "bi.editor", + type: Editor.xtype, simple: o.simple, - ref: function (_ref) { + ref (_ref) { self.editor = _ref; }, height: o.height, @@ -23,67 +38,58 @@ BI.NumberIntervalSingleEidtor = BI.inherit(BI.Single, { quitChecker: o.quitChecker, validationChecker: o.validationChecker, listeners: [{ - eventName: BI.Editor.EVENT_ERROR, - action: function () { - self.fireEvent(BI.NumberIntervalSingleEidtor.EVENT_ERROR, arguments); - } + eventName: Editor.EVENT_ERROR, + action () { + self.fireEvent(NumberIntervalSingleEidtor.EVENT_ERROR, arguments); + }, }, { - eventName: BI.Editor.EVENT_FOCUS, - action: function () { - self.fireEvent(BI.NumberIntervalSingleEidtor.EVENT_FOCUS, arguments); - } + eventName: Editor.EVENT_FOCUS, + action () { + self.fireEvent(NumberIntervalSingleEidtor.EVENT_FOCUS, arguments); + }, }, { - eventName: BI.Editor.EVENT_BLUR, - action: function () { - self.fireEvent(BI.NumberIntervalSingleEidtor.EVENT_BLUR, arguments); - } + eventName: Editor.EVENT_BLUR, + action () { + self.fireEvent(NumberIntervalSingleEidtor.EVENT_BLUR, arguments); + }, }, { - eventName: BI.Editor.EVENT_VALID, - action: function () { - self.fireEvent(BI.NumberIntervalSingleEidtor.EVENT_VALID, arguments); - } + eventName: Editor.EVENT_VALID, + action () { + self.fireEvent(NumberIntervalSingleEidtor.EVENT_VALID, arguments); + }, }, { - eventName: BI.Editor.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.NumberIntervalSingleEidtor.EVENT_CHANGE, arguments); - } + eventName: Editor.EVENT_CHANGE, + action () { + self.fireEvent(NumberIntervalSingleEidtor.EVENT_CHANGE, arguments); + }, }, { - eventName: BI.Editor.EVENT_CONFIRM, - action: function () { - self.fireEvent(BI.NumberIntervalSingleEidtor.EVENT_CONFIRM, arguments); - } + eventName: Editor.EVENT_CONFIRM, + action () { + self.fireEvent(NumberIntervalSingleEidtor.EVENT_CONFIRM, arguments); + }, }, { - eventName: BI.Editor.EVENT_CHANGE_CONFIRM, - action: function () { - self.fireEvent(BI.NumberIntervalSingleEidtor.EVENT_CHANGE_CONFIRM, arguments); - } - }] - }] + eventName: Editor.EVENT_CHANGE_CONFIRM, + action () { + self.fireEvent(NumberIntervalSingleEidtor.EVENT_CHANGE_CONFIRM, arguments); + }, + }], + }], }; - }, + } - isValid: function () { + isValid() { return this.editor.isValid(); - }, + } - getValue: function () { + getValue() { return this.editor.getValue(); - }, + } - setValue: function (v) { + setValue(v) { return this.editor.setValue(v); - }, + } - focus: function () { + focus() { this.editor.focus(); } -}); - -BI.NumberIntervalSingleEidtor.EVENT_FOCUS = "EVENT_FOCUS"; -BI.NumberIntervalSingleEidtor.EVENT_BLUR = "EVENT_BLUR"; -BI.NumberIntervalSingleEidtor.EVENT_ERROR = "EVENT_ERROR"; -BI.NumberIntervalSingleEidtor.EVENT_VALID = "EVENT_VALID"; -BI.NumberIntervalSingleEidtor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.NumberIntervalSingleEidtor.EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; -BI.NumberIntervalSingleEidtor.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut("bi.number_interval_single_editor", BI.NumberIntervalSingleEidtor); \ No newline at end of file +} From 6a0b7a3c67e54c410c6dd0c6ef8210f1c3cbcff3 Mon Sep 17 00:00:00 2001 From: zsmj Date: Thu, 12 Jan 2023 14:45:27 +0800 Subject: [PATCH 089/300] update --- src/widget/index.js | 18 +++++++++++------- src/widget/multiselect/index.js | 0 2 files changed, 11 insertions(+), 7 deletions(-) create mode 100644 src/widget/multiselect/index.js diff --git a/src/widget/index.js b/src/widget/index.js index 6ce1b935c..f36868433 100644 --- a/src/widget/index.js +++ b/src/widget/index.js @@ -8,9 +8,10 @@ import * as dynamicdatetime from "./dynamicdatetime"; import * as time from "./time"; import { SelectTreeCombo } from "./selecttree/selecttree.combo"; import { SingleTreeCombo } from "./singletree/singletree.combo"; -import { MultiTreeCombo } from "/multitree/multi.tree.combo"; -import { MultiTreeInsertCombo } from "/multitree/multi.tree.insert.combo"; -import { MultiTreeListCombo } from "/multitree/multi.tree.list.combo"; +import { MultiTreeCombo } from "./multitree/multi.tree.combo"; +import { MultiTreeInsertCombo } from "./multitree/multi.tree.insert.combo"; +import { MultiTreeListCombo } from "./multitree/multi.tree.list.combo"; +import * as multiselect from "./multiselect"; Object.assign(BI, { Collapse, @@ -25,7 +26,8 @@ Object.assign(BI, { SingleTreeCombo, MultiTreeCombo, MultiTreeInsertCombo, - MultiTreeListCombo + MultiTreeListCombo, + ...multiselect, }); export * from "./date/calendar"; @@ -37,9 +39,11 @@ export * from "./dynamicdatetime"; export * from "./time"; export { SelectTreeCombo } from "./selecttree/selecttree.combo"; export { SingleTreeCombo } from "./singletree/singletree.combo"; -export { MultiTreeCombo } from "/multitree/multi.tree.combo"; -export { MultiTreeInsertCombo } from "/multitree/multi.tree.insert.combo"; -export { MultiTreeListCombo } from "/multitree/multi.tree.list.combo"; +export { MultiTreeCombo } from "./multitree/multi.tree.combo"; +export { MultiTreeInsertCombo } from "./multitree/multi.tree.insert.combo"; +export { MultiTreeListCombo } from "./multitree/multi.tree.list.combo"; +import * from "./multiselect"; + export { Collapse }; diff --git a/src/widget/multiselect/index.js b/src/widget/multiselect/index.js new file mode 100644 index 000000000..e69de29bb From 3bed68cbab523d145efb6360bb6698922a556b12 Mon Sep 17 00:00:00 2001 From: zsmj Date: Thu, 12 Jan 2023 14:48:05 +0800 Subject: [PATCH 090/300] update --- src/widget/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/widget/index.js b/src/widget/index.js index f36868433..d2284b0b8 100644 --- a/src/widget/index.js +++ b/src/widget/index.js @@ -42,7 +42,7 @@ export { SingleTreeCombo } from "./singletree/singletree.combo"; export { MultiTreeCombo } from "./multitree/multi.tree.combo"; export { MultiTreeInsertCombo } from "./multitree/multi.tree.insert.combo"; export { MultiTreeListCombo } from "./multitree/multi.tree.list.combo"; -import * from "./multiselect"; +export * from "./multiselect"; export { Collapse From 65791b56a14c7d3a7408ccafcfe7732f727d8866 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Thu, 12 Jan 2023 14:50:09 +0800 Subject: [PATCH 091/300] =?UTF-8?q?=E6=97=A0JIRA=E4=BB=BB=E5=8A=A1=20fix:?= =?UTF-8?q?=20TextValueCombo=E7=9A=84=E5=BC=95=E7=94=A8=E6=AD=A3=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/widget/dynamicdate/dynamicdate.param.item.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/widget/dynamicdate/dynamicdate.param.item.js b/src/widget/dynamicdate/dynamicdate.param.item.js index 7a2a9691a..a0fe36814 100644 --- a/src/widget/dynamicdate/dynamicdate.param.item.js +++ b/src/widget/dynamicdate/dynamicdate.param.item.js @@ -79,7 +79,7 @@ export class DynamicDateParamItem extends Widget { container: null, value: o.offset, listeners: [{ - eventName: BI.TextValueCombo.EVENT_CHANGE, + eventName: TextValueCombo.EVENT_CHANGE, action: () => { this.fireEvent(DynamicDateParamItem.EVENT_CHANGE); }, From 7c628d3401ec834332455c54523d55f1e11b0694 Mon Sep 17 00:00:00 2001 From: Treecat Date: Thu, 12 Jan 2023 15:06:19 +0800 Subject: [PATCH 092/300] =?UTF-8?q?KERNEL-14076=20fix:=20=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=20extend=20=E7=9A=84=E9=97=AE=E9=A2=98=E5=92=8C?= =?UTF-8?q?=E8=AF=86=E5=88=AB=E9=9D=99=E6=80=81=E5=8F=98=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.js | 76 ++++++++++++++++++++++++++++++++++++++++++++-------- es6.xtype.js | 3 +-- 2 files changed, 66 insertions(+), 13 deletions(-) diff --git a/es6.js b/es6.js index 5e5353d93..a3d0ce376 100644 --- a/es6.js +++ b/es6.js @@ -4,6 +4,22 @@ const prettier = require("prettier"); const { exec } = require("child_process"); const { search, initDepts, depts } = require("./es6.xtype"); +// const XTYPE_ONLY = false; +// const THIS_REPLACE = false; + +function objHaveFunction(obj) { + return Object.keys(obj).some(key => { + const value = obj[key]; + if (typeof value === "object") { + return objHaveFunction(value); + } else if (typeof value === "function") { + return true; + } + + return false; + }); +} + async function fix(path) { new Promise(res => { exec(`yarn eslint --fix ${path}`, () => { @@ -49,7 +65,7 @@ const target = [ // 加载模块 const loader = { - G: { "@/core": { shortcut: true } }, + // G: { "@/core": { shortcut: true } }, load(srcName, module) { const G = loader.G; if (target.indexOf(module) >= 0) { @@ -83,13 +99,15 @@ const loader = { }; async function handleFile(srcName) { - const G = loader.G; + // 全局状态回归 + const G = loader.G = { "@/core": { shortcut: true } }; const sourceCode = fs.readFileSync(srcName).toString(); const result = /BI\.(.*?)\s\=\sBI\.inherit\(/.exec(sourceCode); if (!result) { - console.log(`可能是已经es6过了 ${srcName}, 尝试替换 xtype`); + console.log(`已经es6过,替换 xtype => ${srcName}, `); + // 处理 xtype // 尝试对 xtype 进行替换 @@ -100,7 +118,7 @@ async function handleFile(srcName) { return `${clzName}.xtype`; } else { - console.log(`加载 ${matchedSentence}失败`); + console.log(`xtype 替换失败 ${matchedSentence} `); return matchedSentence; } @@ -123,6 +141,7 @@ async function handleFile(srcName) { // eslint-disable-next-line no-unused-vars const BI = { + [clzName]: clzName, inherit(_, options) { collection.methods = Object.keys(options) .filter(key => typeof options[key] === "function") @@ -135,6 +154,9 @@ async function handleFile(srcName) { return collection.static; }, + extend(targetClz, o) { + Object.assign(collection.static, o); + }, shortcut(xtype) { collection.xtype = xtype; }, @@ -151,12 +173,35 @@ async function handleFile(srcName) { loader.load(srcName, superName); Object.keys(collection.attr).forEach(key => { - A = `${key} = ${JSON.stringify(collection.attr[key])};`; + const value = collection.attr[key]; + if (typeof value === "function" || typeof value === "number") { + A += `\t${key} = ${value}\n`; + } else if (typeof value === "string") { + A += `\t${key} = "${value}"\n`; + } else if (typeof value === "object") { + if (objHaveFunction(value)) { + throw new Error("G"); + } else { + A += `\t${key} = ${JSON.stringify(value)}\n`; + } + } }); // 静态方法 Object.keys(collection.static).forEach(key => { - E += `\tstatic ${key} = "${collection.static[key]}"\n`; + // console.log(key, collection.static[key], typeof collection.static[key]) + const value = collection.static[key]; + if (typeof value === "function" || typeof value === "number") { + E += `\tstatic ${key} = ${value}\n`; + } else if (typeof value === "string") { + E += `\tstatic ${key} = "${value}"\n`; + } else if (typeof value === "object") { + if (objHaveFunction(value)) { + throw new Error("G"); + } else { + E += `\tstatic ${key} = ${JSON.stringify(value)}\n`; + } + } }); // 对函数进行替换 @@ -189,7 +234,7 @@ async function handleFile(srcName) { if (loadSuccess) { return target + end; } else { - console.log(`BI.xxx 加载 ${target}失败`); + console.log(`BI 变量替换失败 BI.${target}`); return matchedSentence; } @@ -203,7 +248,7 @@ async function handleFile(srcName) { return `${clzName}.xtype`; } else { - console.log(`加载 ${matchedSentence}失败`); + // console.log(`(没事) xtype 替换失败 ${matchedSentence} `); return matchedSentence; } @@ -221,8 +266,10 @@ async function handleFile(srcName) { Object.keys(G[moduleKey]).forEach(key => { i += `${key}, `; }); - const single = !/\//.test(moduleKey); - if (single) { + + // 必须以 . 开头 + const moduleInValid = /^[^@.]/.test(moduleKey); + if (moduleInValid) { moduleKey = `./${moduleKey}`; } @@ -246,6 +293,7 @@ ${M} const prettierCode = prettier.format(outputCode, { tabWidth: 4, + parser: 'babel', }); fs.writeFileSync(srcName, prettierCode); await fix(srcName); @@ -257,7 +305,13 @@ async function traverse(srcName) { if (srcName.indexOf("__test__") >= 0) return; if (srcName.endsWith(".js")) { - return await handleFile(srcName); + try { + return await handleFile(srcName); + } catch (error) { + console.log(`文件处理失败 ${srcName} \n${error}`); + + return; + } } else { const stat = fs.statSync(srcName); const flag = stat.isDirectory(); diff --git a/es6.xtype.js b/es6.xtype.js index 28c934c80..351134bf3 100644 --- a/es6.xtype.js +++ b/es6.xtype.js @@ -10,9 +10,8 @@ async function handle(filename) { let clzName; if (inheritRegResult) { clzName = inheritRegResult[1]; - // 把 } else { - const clzRegResult = /export\sclass\s(.*?)\sextend/.exec(code); + const clzRegResult = /export\s+class\s+(.*?)\s+/.exec(code); if (clzRegResult) { clzName = clzRegResult[1]; From 101b3352fa2775797b02ebaf36e8c3c25cc99791 Mon Sep 17 00:00:00 2001 From: zsmj Date: Thu, 12 Jan 2023 15:18:14 +0800 Subject: [PATCH 093/300] update --- src/widget/editor/editor.search.js | 280 +++++---- src/widget/index.js | 3 + src/widget/multiselect/index.js | 4 + src/widget/multiselectlist/index.js | 3 + .../multiselectlist/multiselectlist.insert.js | 528 ++++++++++------- .../multiselectlist.insert.nobar.js | 547 ++++++++++-------- src/widget/multiselectlist/multiselectlist.js | 534 +++++++++-------- 7 files changed, 1089 insertions(+), 810 deletions(-) create mode 100644 src/widget/multiselectlist/index.js diff --git a/src/widget/editor/editor.search.js b/src/widget/editor/editor.search.js index bd40ae5a9..48a7b8655 100644 --- a/src/widget/editor/editor.search.js +++ b/src/widget/editor/editor.search.js @@ -1,26 +1,69 @@ -/** - * Created by roy on 15/9/14. - */ -BI.SearchEditor = BI.inherit(BI.Widget, { - _defaultConfig: function (config) { - var conf = BI.SearchEditor.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: "bi-search-editor bi-focus-shadow " + (config.simple ? "bi-border-bottom" : "bi-border bi-border-radius"), +import { + shortcut, + Widget, + extend, + i18nText, + emptyFn, + createWidget, + toPix, + isKey, + Controller, + Events, + HTapeLayout, + isEndWithBlank +} from "@/core"; +import { IconButton, Editor, IconLabel } from "@/base"; + +@shortcut() +export class SearchEditor extends Widget { + static xtype = "bi.search_editor"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_CLICK = "EVENT_CLICK"; + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; + static EVENT_SPACE = "EVENT_SPACE"; + static EVENT_BACKSPACE = "EVENT_BACKSPACE"; + static EVENT_CLEAR = "EVENT_CLEAR"; + static EVENT_START = "EVENT_START"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; + static EVENT_VALID = "EVENT_VALID"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_ENTER = "EVENT_ENTER"; + static EVENT_RESTRICT = "EVENT_RESTRICT"; + static EVENT_REMOVE = "EVENT_REMOVE"; + static EVENT_EMPTY = "EVENT_EMPTY"; + + _defaultConfig(config) { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: + `bi-search-editor bi-focus-shadow ${ + config.simple + ? "bi-border-bottom" + : "bi-border bi-border-radius"}`, height: 24, errorText: "", - watermark: BI.i18nText("BI-Basic_Search"), - validationChecker: BI.emptyFn, - quitChecker: BI.emptyFn, - value: "" - }); - }, - _init: function () { - BI.SearchEditor.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.editor = BI.createWidget(o.el, { - type: "bi.editor", + watermark: i18nText("BI-Basic_Search"), + validationChecker: emptyFn, + quitChecker: emptyFn, + value: "", + }); + } + + _init() { + super._init(...arguments); + const self = this, + o = this.options; + this.editor = createWidget(o.el, { + type: Editor.xtype, simple: o.simple, - height: BI.toPix(o.height, o.simple ? 1 : 2), + height: toPix(o.height, o.simple ? 1 : 2), watermark: o.watermark, allowBlank: true, hgap: 1, @@ -30,189 +73,172 @@ BI.SearchEditor = BI.inherit(BI.Widget, { value: o.value, autoTrim: o.autoTrim, }); - this.clear = BI.createWidget({ - type: "bi.icon_button", + this.clear = createWidget({ + type: IconButton.xtype, stopEvent: true, cls: "close-font", - invisible: !BI.isKey(o.value) + invisible: !isKey(o.value), }); - this.clear.on(BI.IconButton.EVENT_CHANGE, function () { + this.clear.on(IconButton.EVENT_CHANGE, () => { self.setValue(""); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.STOPEDIT, self.getValue()); + self.fireEvent( + Controller.EVENT_CHANGE, + Events.STOPEDIT, + self.getValue() + ); // 从有内容到无内容的清空也是一次change - self.fireEvent(BI.SearchEditor.EVENT_CHANGE); - self.fireEvent(BI.SearchEditor.EVENT_CLEAR); + self.fireEvent(SearchEditor.EVENT_CHANGE); + self.fireEvent(SearchEditor.EVENT_CLEAR); }); - BI.createWidget({ + createWidget({ element: this, - height: BI.toPix(o.height, o.simple ? 1 : 2), - type: "bi.htape", + height: toPix(o.height, o.simple ? 1 : 2), + type: HTapeLayout.xtype, items: [ { el: { - type: "bi.icon_label", - cls: "search-font" + type: IconLabel.xtype, + cls: "search-font", }, - width: 24 + width: 24, }, { - el: self.editor + el: self.editor, }, { el: this.clear, - width: 24 + width: 24, } - ] + ], }); - this.editor.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.editor.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.editor.on(BI.Editor.EVENT_FOCUS, function () { - self.fireEvent(BI.SearchEditor.EVENT_FOCUS); + this.editor.on(Editor.EVENT_FOCUS, () => { + self.fireEvent(SearchEditor.EVENT_FOCUS); }); - this.editor.on(BI.Editor.EVENT_BLUR, function () { - self.fireEvent(BI.SearchEditor.EVENT_BLUR); + this.editor.on(Editor.EVENT_BLUR, () => { + self.fireEvent(SearchEditor.EVENT_BLUR); }); - this.editor.on(BI.Editor.EVENT_CLICK, function () { - self.fireEvent(BI.SearchEditor.EVENT_CLICK); + this.editor.on(Editor.EVENT_CLICK, () => { + self.fireEvent(SearchEditor.EVENT_CLICK); }); - this.editor.on(BI.Editor.EVENT_CHANGE, function () { + this.editor.on(Editor.EVENT_CHANGE, () => { self._checkClear(); - self.fireEvent(BI.SearchEditor.EVENT_CHANGE); + self.fireEvent(SearchEditor.EVENT_CHANGE); }); - this.editor.on(BI.Editor.EVENT_KEY_DOWN, function (v) { - self.fireEvent(BI.SearchEditor.EVENT_KEY_DOWN, v); + this.editor.on(Editor.EVENT_KEY_DOWN, v => { + self.fireEvent(SearchEditor.EVENT_KEY_DOWN, v); }); - this.editor.on(BI.Editor.EVENT_SPACE, function () { - self.fireEvent(BI.SearchEditor.EVENT_SPACE); + this.editor.on(Editor.EVENT_SPACE, () => { + self.fireEvent(SearchEditor.EVENT_SPACE); }); - this.editor.on(BI.Editor.EVENT_BACKSPACE, function () { - self.fireEvent(BI.SearchEditor.EVENT_BACKSPACE); + this.editor.on(Editor.EVENT_BACKSPACE, () => { + self.fireEvent(SearchEditor.EVENT_BACKSPACE); }); - - this.editor.on(BI.Editor.EVENT_VALID, function () { - self.fireEvent(BI.SearchEditor.EVENT_VALID); + this.editor.on(Editor.EVENT_VALID, () => { + self.fireEvent(SearchEditor.EVENT_VALID); }); - this.editor.on(BI.Editor.EVENT_ERROR, function () { - self.fireEvent(BI.SearchEditor.EVENT_ERROR); + this.editor.on(Editor.EVENT_ERROR, () => { + self.fireEvent(SearchEditor.EVENT_ERROR); }); - this.editor.on(BI.Editor.EVENT_ENTER, function () { - self.fireEvent(BI.SearchEditor.EVENT_ENTER); + this.editor.on(Editor.EVENT_ENTER, () => { + self.fireEvent(SearchEditor.EVENT_ENTER); }); - this.editor.on(BI.Editor.EVENT_RESTRICT, function () { - self.fireEvent(BI.SearchEditor.EVENT_RESTRICT); + this.editor.on(Editor.EVENT_RESTRICT, () => { + self.fireEvent(SearchEditor.EVENT_RESTRICT); }); - this.editor.on(BI.Editor.EVENT_EMPTY, function () { + this.editor.on(Editor.EVENT_EMPTY, () => { self._checkClear(); - self.fireEvent(BI.SearchEditor.EVENT_EMPTY); + self.fireEvent(SearchEditor.EVENT_EMPTY); }); - this.editor.on(BI.Editor.EVENT_REMOVE, function () { - self.fireEvent(BI.SearchEditor.EVENT_REMOVE); + this.editor.on(Editor.EVENT_REMOVE, () => { + self.fireEvent(SearchEditor.EVENT_REMOVE); }); - this.editor.on(BI.Editor.EVENT_CONFIRM, function () { - self.fireEvent(BI.SearchEditor.EVENT_CONFIRM); + this.editor.on(Editor.EVENT_CONFIRM, () => { + self.fireEvent(SearchEditor.EVENT_CONFIRM); }); - this.editor.on(BI.Editor.EVENT_CHANGE_CONFIRM, function () { - self.fireEvent(BI.SearchEditor.EVENT_CHANGE_CONFIRM); + this.editor.on(Editor.EVENT_CHANGE_CONFIRM, () => { + self.fireEvent(SearchEditor.EVENT_CHANGE_CONFIRM); }); - this.editor.on(BI.Editor.EVENT_START, function () { - self.fireEvent(BI.SearchEditor.EVENT_START); + this.editor.on(Editor.EVENT_START, () => { + self.fireEvent(SearchEditor.EVENT_START); }); - this.editor.on(BI.Editor.EVENT_PAUSE, function () { - self.fireEvent(BI.SearchEditor.EVENT_PAUSE); + this.editor.on(Editor.EVENT_PAUSE, () => { + self.fireEvent(SearchEditor.EVENT_PAUSE); }); - this.editor.on(BI.Editor.EVENT_STOP, function () { - self.fireEvent(BI.SearchEditor.EVENT_STOP); + this.editor.on(Editor.EVENT_STOP, () => { + self.fireEvent(SearchEditor.EVENT_STOP); }); - }, + } - _checkClear: function () { + _checkClear() { if (!this.getValue()) { this.clear.invisible(); } else { this.clear.visible(); } - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.options.watermark = v; this.editor.setWaterMark(v); - }, + } - focus: function () { + focus() { this.editor.focus(); - }, + } - blur: function () { + blur() { this.editor.blur(); - }, + } - getValue: function () { + getValue() { if (this.isValid()) { return this.editor.getValue(); } - }, + } - getKeywords: function () { - var val = this.editor.getLastChangedValue(); - var keywords = val.match(/[\S]+/g); - if (BI.isEndWithBlank(val)) { + getKeywords() { + const val = this.editor.getLastChangedValue(); + const keywords = val.match(/[\S]+/g); + if (isEndWithBlank(val)) { return keywords.concat([" "]); } + return keywords; - }, + } - getLastValidValue: function () { + getLastValidValue() { return this.editor.getLastValidValue(); - }, + } - getLastChangedValue: function () { + getLastChangedValue() { return this.editor.getLastChangedValue(); - }, + } - setValue: function (v) { + setValue(v) { this.editor.setValue(v); - if (BI.isKey(v)) { + if (isKey(v)) { this.clear.visible(); } - }, + } - isEditing: function () { + isEditing() { return this.editor.isEditing(); - }, + } - isValid: function () { + isValid() { return this.editor.isValid(); - }, + } - showClearIcon: function () { + showClearIcon() { this.clear.visible(); - }, + } - hideClearIcon: function () { + hideClearIcon() { this.clear.invisible(); } -}); -BI.SearchEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.SearchEditor.EVENT_FOCUS = "EVENT_FOCUS"; -BI.SearchEditor.EVENT_BLUR = "EVENT_BLUR"; -BI.SearchEditor.EVENT_CLICK = "EVENT_CLICK"; -BI.SearchEditor.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.SearchEditor.EVENT_SPACE = "EVENT_SPACE"; -BI.SearchEditor.EVENT_BACKSPACE = "EVENT_BACKSPACE"; -BI.SearchEditor.EVENT_CLEAR = "EVENT_CLEAR"; - -BI.SearchEditor.EVENT_START = "EVENT_START"; -BI.SearchEditor.EVENT_PAUSE = "EVENT_PAUSE"; -BI.SearchEditor.EVENT_STOP = "EVENT_STOP"; -BI.SearchEditor.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.SearchEditor.EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; -BI.SearchEditor.EVENT_VALID = "EVENT_VALID"; -BI.SearchEditor.EVENT_ERROR = "EVENT_ERROR"; -BI.SearchEditor.EVENT_ENTER = "EVENT_ENTER"; -BI.SearchEditor.EVENT_RESTRICT = "EVENT_RESTRICT"; -BI.SearchEditor.EVENT_REMOVE = "EVENT_REMOVE"; -BI.SearchEditor.EVENT_EMPTY = "EVENT_EMPTY"; -BI.shortcut("bi.search_editor", BI.SearchEditor); +} diff --git a/src/widget/index.js b/src/widget/index.js index d2284b0b8..4e3aaf496 100644 --- a/src/widget/index.js +++ b/src/widget/index.js @@ -12,6 +12,7 @@ import { MultiTreeCombo } from "./multitree/multi.tree.combo"; import { MultiTreeInsertCombo } from "./multitree/multi.tree.insert.combo"; import { MultiTreeListCombo } from "./multitree/multi.tree.list.combo"; import * as multiselect from "./multiselect"; +import * as multiselectlist from "./multiselectlist"; Object.assign(BI, { Collapse, @@ -28,6 +29,7 @@ Object.assign(BI, { MultiTreeInsertCombo, MultiTreeListCombo, ...multiselect, + ...multiselectlist, }); export * from "./date/calendar"; @@ -43,6 +45,7 @@ export { MultiTreeCombo } from "./multitree/multi.tree.combo"; export { MultiTreeInsertCombo } from "./multitree/multi.tree.insert.combo"; export { MultiTreeListCombo } from "./multitree/multi.tree.list.combo"; export * from "./multiselect"; +export * from "./multiselectlist"; export { Collapse diff --git a/src/widget/multiselect/index.js b/src/widget/multiselect/index.js index e69de29bb..9d15e06a0 100644 --- a/src/widget/multiselect/index.js +++ b/src/widget/multiselect/index.js @@ -0,0 +1,4 @@ +export { MultiSelectCombo } from "./multiselect.combo"; +export { MultiSelectNoBarCombo } from "./multiselect.combo.nobar"; +export { MultiSelectInsertCombo } from "./multiselect.insert.combo"; +export { MultiSelectInsertNoBarCombo } from "./multiselect.insert.combo.nobar"; diff --git a/src/widget/multiselectlist/index.js b/src/widget/multiselectlist/index.js new file mode 100644 index 000000000..416458b1f --- /dev/null +++ b/src/widget/multiselectlist/index.js @@ -0,0 +1,3 @@ +export * from "./multiselectlist.insert"; +export * from "./multiselectlist.insert.nobar"; +export * from "./multiselectlist"; diff --git a/src/widget/multiselectlist/multiselectlist.insert.js b/src/widget/multiselectlist/multiselectlist.insert.js index 8b6e8785f..71616ccb3 100644 --- a/src/widget/multiselectlist/multiselectlist.insert.js +++ b/src/widget/multiselectlist/multiselectlist.insert.js @@ -1,59 +1,105 @@ -/** - * Created by zcf_1 on 2017/5/2. - */ -BI.MultiSelectInsertList = BI.inherit(BI.Single, { - _defaultConfig: function () { - return BI.extend(BI.MultiSelectInsertList.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + emptyFn, + deepClone, + isKey, + Selection, + remove, + pushDistinct, + createWidget, + isNotEmptyString, + i18nText, + isEmptyArray, + last, + initial, + endWith, + AbsoluteLayout, + isEmptyString, + makeObject, + each, + Func, + map, + concat, + isNotNull, + values, + filter, + contains, + isNull, VerticalFillLayout +} from "@/core"; +import { Single, Searcher } from "@/base"; +import { MultiSelectBar } from "@/case"; +import { SelectPatchEditor } from "../multiselect/trigger/editor/editor.patch"; +import { MultiSelectLoader } from "../multiselect/multiselect.loader"; +import { MultiSelectSearchInsertPane } from "../multiselect/search/multiselect.search.insert.pane"; +import { SearchEditor } from "@/widget/editor/editor.search"; + + +@shortcut() +export class MultiSelectInsertList extends Single { + static xtype = "bi.multi_select_insert_list"; + + static REQ_GET_DATA_LENGTH = "1"; + static REQ_GET_ALL_DATA = "-1"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-insert-list", - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, + itemsCreator: emptyFn, + valueFormatter: emptyFn, searcherHeight: BI.SIZE_CONSANTS.TRIGGER_HEIGHT, itemHeight: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, }); - }, - _init: function () { - BI.MultiSelectInsertList.superclass._init.apply(this, arguments); + } - var self = this, o = this.options; - this.storeValue = this._assertValue(BI.deepClone(o.value) || {}); + _init() { + super._init(...arguments); - var assertShowValue = function () { - BI.isKey(self._startValue) && (self.storeValue.type === BI.Selection.All ? BI.remove(self.storeValue.value, self._startValue) : BI.pushDistinct(self.storeValue.value, self._startValue)); + const self = this, + o = this.options; + this.storeValue = this._assertValue(deepClone(o.value) || {}); + + function assertShowValue() { + isKey(self._startValue) && + (self.storeValue.type === Selection.All + ? remove(self.storeValue.value, self._startValue) + : pushDistinct(self.storeValue.value, self._startValue)); // self.trigger.setValue(self.storeValue); - }; + } - this.adapter = BI.createWidget({ - type: "bi.multi_select_loader", + this.adapter = createWidget({ + type: MultiSelectLoader.xtype, cls: "popup-multi-select-list bi-border-left bi-border-right bi-border-bottom", itemsCreator: o.itemsCreator, itemHeight: o.itemHeight, valueFormatter: o.valueFormatter, itemFormatter: o.itemFormatter, logic: { - dynamic: false + dynamic: false, }, // onLoaded: o.onLoaded, el: {}, isDefaultInit: true, - value: o.value + value: o.value, }); - this.adapter.on(BI.MultiSelectLoader.EVENT_CHANGE, function () { + this.adapter.on(MultiSelectLoader.EVENT_CHANGE, function () { self.storeValue = this.getValue(); assertShowValue(); - self.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE); + self.fireEvent(MultiSelectInsertList.EVENT_CHANGE); }); - this.searcherPane = BI.createWidget({ - type: "bi.multi_select_search_insert_pane", + this.searcherPane = createWidget({ + type: MultiSelectSearchInsertPane.xtype, cls: "bi-border-left bi-border-right bi-border-bottom", valueFormatter: o.valueFormatter, itemFormatter: o.itemFormatter, - keywordGetter: function () { + keywordGetter() { return self.trigger.getKeyword(); }, - itemsCreator: function (op, callback) { - var keyword = self.trigger.getKeyword(); - if (BI.isNotEmptyString(keyword)) { + itemsCreator(op, callback) { + const keyword = self.trigger.getKeyword(); + if (isNotEmptyString(keyword)) { op.keywords = [keyword]; this.setKeyword(op.keywords[0]); o.itemsCreator(op, callback); @@ -63,298 +109,338 @@ BI.MultiSelectInsertList = BI.inherit(BI.Single, { }); this.searcherPane.setVisible(false); - this.trigger = BI.createWidget({ - type: "bi.searcher", + this.trigger = createWidget({ + type: Searcher.xtype, el: { - type: "bi.select_patch_editor", + type: SelectPatchEditor.xtype, el: { - type: "bi.search_editor", - watermark: BI.i18nText("BI-Basic_Search_And_Patch_Paste"), + type: SearchEditor.xtype, + watermark: i18nText("BI-Basic_Search_And_Patch_Paste"), }, - ref: function (ref) { + ref(ref) { self.editor = ref; }, }, isAutoSearch: false, isAutoSync: false, - onSearch: function (op, callback) { + onSearch(op, callback) { callback(); }, adapter: this.adapter, popup: this.searcherPane, masker: false, - listeners: [{ - eventName: BI.Searcher.EVENT_START, - action: function () { - self._showSearcherPane(); - self._setStartValue(""); - this.setValue(BI.deepClone(self.storeValue)); - } - }, { - eventName: BI.Searcher.EVENT_STOP, - action: function () { - self._showAdapter(); - self._setStartValue(""); - self.adapter.setValue(self.storeValue); - // 需要刷新回到初始界面,否则搜索的结果不能放在最前面 - self.adapter.populate(); - } - }, { - eventName: BI.Searcher.EVENT_PAUSE, - action: function () { - var keywords = self._getKeywords(); - if (keywords[keywords.length - 1] === BI.BlankSplitChar) { - keywords = keywords.slice(0, keywords.length - 1); - } - var keyword = BI.isEmptyArray(keywords) ? "" : keywords[keywords.length - 1]; - self._join({ - type: BI.Selection.Multi, - value: [keyword] - }, function () { - if (self.storeValue.type === BI.Selection.Multi) { - BI.pushDistinct(self.storeValue.value, keyword); - } + listeners: [ + { + eventName: Searcher.EVENT_START, + action() { + self._showSearcherPane(); + self._setStartValue(""); + this.setValue(deepClone(self.storeValue)); + }, + }, + { + eventName: Searcher.EVENT_STOP, + action() { self._showAdapter(); + self._setStartValue(""); self.adapter.setValue(self.storeValue); - self._setStartValue(keyword); - assertShowValue(); + // 需要刷新回到初始界面,否则搜索的结果不能放在最前面 self.adapter.populate(); - self._setStartValue(""); - self.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE); - }); - self._showAdapter(); - } - }, { - eventName: BI.Searcher.EVENT_SEARCHING, - action: function () { - var keywords = self._getKeywords(); - var last = BI.last(keywords); - keywords = BI.initial(keywords || []); - if (keywords.length > 0) { - self._joinKeywords(keywords, function () { - if (BI.endWith(last, BI.BlankSplitChar)) { + }, + }, + { + eventName: Searcher.EVENT_PAUSE, + action() { + let keywords = self._getKeywords(); + if ( + keywords[keywords.length - 1] === BI.BlankSplitChar + ) { + keywords = keywords.slice(0, keywords.length - 1); + } + const keyword = isEmptyArray(keywords) + ? "" + : keywords[keywords.length - 1]; + self._join( + { + type: Selection.Multi, + value: [keyword], + }, + () => { + if (self.storeValue.type === Selection.Multi) { + pushDistinct( + self.storeValue.value, + keyword + ); + } + self._showAdapter(); self.adapter.setValue(self.storeValue); + self._setStartValue(keyword); assertShowValue(); self.adapter.populate(); self._setStartValue(""); - } else { - self.adapter.setValue(self.storeValue); - assertShowValue(); + self.fireEvent( + MultiSelectInsertList.EVENT_CHANGE + ); } - self.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE); - }); - self._getKeywordsLength() > 2000 && BI.Msg.alert(BI.i18nText("BI-Basic_Prompt"), BI.i18nText("BI-Basic_Too_Much_Value_Get_Two_Thousand")); - } - } - }, { - eventName: BI.Searcher.EVENT_CHANGE, - action: function (value, obj) { - if (obj instanceof BI.MultiSelectBar) { - self._joinAll(this.getValue(), function () { - assertShowValue(); - self.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE); - }); - } else { - self._join(this.getValue(), function () { - assertShowValue(); - self.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE); - }); - } + ); + self._showAdapter(); + }, + }, + { + eventName: Searcher.EVENT_SEARCHING, + action() { + let keywords = self._getKeywords(); + const lastKeyword = last(keywords); + keywords = initial(keywords || []); + if (keywords.length > 0) { + self._joinKeywords(keywords, () => { + if (endWith(lastKeyword, BI.BlankSplitChar)) { + self.adapter.setValue(self.storeValue); + assertShowValue(); + self.adapter.populate(); + self._setStartValue(""); + } else { + self.adapter.setValue(self.storeValue); + assertShowValue(); + } + self.fireEvent( + MultiSelectInsertList.EVENT_CHANGE + ); + }); + self._getKeywordsLength() > 2000 && + BI.Msg.alert( + i18nText("BI-Basic_Prompt"), + i18nText( + "BI-Basic_Too_Much_Value_Get_Two_Thousand" + ) + ); + } + }, + }, + { + eventName: Searcher.EVENT_CHANGE, + action(value, obj) { + if (obj instanceof MultiSelectBar) { + self._joinAll(this.getValue(), () => { + assertShowValue(); + self.fireEvent( + MultiSelectInsertList.EVENT_CHANGE + ); + }); + } else { + self._join(this.getValue(), () => { + assertShowValue(); + self.fireEvent( + MultiSelectInsertList.EVENT_CHANGE + ); + }); + } + }, } - }], - value: o.value + ], + value: o.value, }); - BI.createWidget({ - type: "bi.vertical_fill", + createWidget({ + type: VerticalFillLayout.xtype, rowSize: ["", "fill"], element: this, - items: [{ - el: this.trigger, - }, { - el: this.adapter, - }] + items: [ + { + el: this.trigger, + }, + { + el: this.adapter, + } + ], }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.searcherPane, - top: o.searcherHeight || BI.SIZE_CONSANTS.TRIGGER_HEIGHT, - bottom: 0, - left: 0, - right: 0 - }] + items: [ + { + el: this.searcherPane, + top: o.searcherHeight || BI.SIZE_CONSANTS.TRIGGER_HEIGHT, + bottom: 0, + left: 0, + right: 0, + } + ], }); - }, + } - _getKeywords: function () { - var val = this.editor.getValue(); - var keywords = val.split(/\u200b\s\u200b/); - if (BI.isEmptyString(keywords[keywords.length - 1])) { + _getKeywords() { + const val = this.editor.getValue(); + let keywords = val.split(/\u200b\s\u200b/); + if (isEmptyString(keywords[keywords.length - 1])) { keywords = keywords.slice(0, keywords.length - 1); } if (/\u200b\s\u200b$/.test(val)) { keywords = keywords.concat([BI.BlankSplitChar]); } - return keywords.length > 2000 ? keywords.slice(0, 2000).concat([BI.BlankSplitChar]) : keywords.slice(0, 2000); - }, + return keywords.length > 2000 + ? keywords.slice(0, 2000).concat([BI.BlankSplitChar]) + : keywords.slice(0, 2000); + } - _getKeywordsLength: function () { - var val = this.editor.getValue(); - var keywords = val.split(/\u200b\s\u200b/); + _getKeywordsLength() { + const val = this.editor.getValue(); + const keywords = val.split(/\u200b\s\u200b/); return keywords.length - 1; - }, + } - _showAdapter: function () { + _showAdapter() { this.adapter.setVisible(true); this.searcherPane.setVisible(false); - }, + } - _showSearcherPane: function () { + _showSearcherPane() { this.searcherPane.setVisible(true); this.adapter.setVisible(false); - }, + } - _defaultState: function () { + _defaultState() { this.trigger.stopEditing(); - }, + } - _assertValue: function (val) { + _assertValue(val) { val || (val = {}); - val.type || (val.type = BI.Selection.Multi); + val.type || (val.type = Selection.Multi); val.value || (val.value = []); + return val; - }, + } - _makeMap: function (values) { - return BI.makeObject(values || []); - }, + _makeMap(values) { + return makeObject(values || []); + } - _joinKeywords: function (keywords, callback) { - var self = this, o = this.options; + _joinKeywords(keywords, callback) { + const self = this; this._assertValue(this.storeValue); // 和复选下拉框同步,allData做缓存是会爆炸的 digest(); function digest() { - BI.each(keywords, function (i, val) { - self.storeValue.type === BI.Selection.Multi ? BI.pushDistinct(self.storeValue.value, val) : BI.remove(self.storeValue.value, val); + each(keywords, (i, val) => { + self.storeValue.type === Selection.Multi + ? pushDistinct(self.storeValue.value, val) + : remove(self.storeValue.value, val); }); callback(); } - }, + } - _joinAll: function (res, callback) { - var self = this, o = this.options; + _joinAll(res, callback) { + const self = this, + o = this.options; this._assertValue(res); if (this.storeValue.type === res.type) { - var result = BI.Func.getSearchResult(BI.map(this.storeValue.value, function (_i, v) { - return { - text: o.valueFormatter(v) || v, - value: v - }; - }), this.trigger.getKeyword()); - var change = false; - var map = this._makeMap(this.storeValue.value); - BI.each(BI.concat(result.match, result.find), function (i, obj) { - var v = obj.value; - if (BI.isNotNull(map[v])) { + const result = Func.getSearchResult( + map(this.storeValue.value, (_i, v) => { + return { + text: o.valueFormatter(v) || v, + value: v, + }; + }), + this.trigger.getKeyword() + ); + let change = false; + const tempMap = this._makeMap(this.storeValue.value); + each(concat(result.match, result.find), (i, obj) => { + const v = obj.value; + if (isNotNull(tempMap[v])) { change = true; - delete map[v]; + delete tempMap[v]; } }); - change && (this.storeValue.value = BI.values(map)); + change && (this.storeValue.value = values(tempMap)); callback(); + return; } - o.itemsCreator({ - type: BI.MultiSelectInsertList.REQ_GET_ALL_DATA, - keywords: [this.trigger.getKeyword()], - selectedValues: BI.filter(this.storeValue.value, function (_i, v) { - return !BI.contains(res.value, v); - }), - }, function (ob) { - var items = BI.map(ob.items, "value"); - var selectedMap = self._makeMap(self.storeValue.value); - var notSelectedMap = self._makeMap(res.value); - var newItems = []; - BI.each(items, function (i, item) { - if (BI.isNotNull(selectedMap[items[i]])) { - delete selectedMap[items[i]]; - } - if (BI.isNull(notSelectedMap[items[i]])) { - newItems.push(item); - } - }); - self.storeValue.value = newItems.concat(BI.values(selectedMap)); - callback(); - }); - }, + o.itemsCreator( + { + type: MultiSelectInsertList.REQ_GET_ALL_DATA, + keywords: [this.trigger.getKeyword()], + selectedValues: filter(this.storeValue.value, (_i, v) => !contains(res.value, v)), + }, + ob => { + const items = map(ob.items, "value"); + const selectedMap = self._makeMap(self.storeValue.value); + const notSelectedMap = self._makeMap(res.value); + const newItems = []; + each(items, (i, item) => { + if (isNotNull(selectedMap[items[i]])) { + delete selectedMap[items[i]]; + } + if (isNull(notSelectedMap[items[i]])) { + newItems.push(item); + } + }); + self.storeValue.value = newItems.concat(values(selectedMap)); + callback(); + } + ); + } - _join: function (res, callback) { - var self = this, o = this.options; + _join(res, callback) { + const self = this; this._assertValue(res); this._assertValue(this.storeValue); if (this.storeValue.type === res.type) { - var map = this._makeMap(this.storeValue.value); - BI.each(res.value, function (i, v) { + const map = this._makeMap(this.storeValue.value); + each(res.value, (i, v) => { if (!map[v]) { - BI.pushDistinct(self.storeValue.value, v); + pushDistinct(self.storeValue.value, v); map[v] = v; } }); - var change = false; - BI.each(res.assist, function (i, v) { - if (BI.isNotNull(map[v])) { + let change = false; + each(res.assist, (i, v) => { + if (isNotNull(map[v])) { change = true; delete map[v]; } }); - change && (this.storeValue.value = BI.values(map)); + change && (this.storeValue.value = values(map)); callback(); + return; } this._joinAll(res, callback); - }, + } - _setStartValue: function (value) { + _setStartValue(value) { this._startValue = value; this.adapter.setStartValue(value); - }, + } - isAllSelected: function () { + isAllSelected() { return this.adapter.isAllSelected(); - }, + } - resize: function () { + resize() { // this.trigger.getCounter().adjustView(); // this.trigger.adjustView(); - }, - setValue: function (v) { + } + + setValue(v) { this.storeValue = v || {}; this._assertValue(this.storeValue); this.adapter.setValue(this.storeValue); this.trigger.setValue(this.storeValue); - }, - - getValue: function () { - return BI.deepClone(this.storeValue); - }, - - populate: function () { - this.adapter.populate.apply(this.adapter, arguments); - this.trigger.populate.apply(this.trigger, arguments); } -}); -BI.extend(BI.MultiSelectInsertList, { - REQ_GET_DATA_LENGTH: 1, - REQ_GET_ALL_DATA: -1 -}); + getValue() { + return deepClone(this.storeValue); + } -BI.MultiSelectInsertList.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multi_select_insert_list", BI.MultiSelectInsertList); + populate() { + this.adapter.populate(...arguments); + this.trigger.populate(...arguments); + } +} diff --git a/src/widget/multiselectlist/multiselectlist.insert.nobar.js b/src/widget/multiselectlist/multiselectlist.insert.nobar.js index be87999ad..ac21aa3b4 100644 --- a/src/widget/multiselectlist/multiselectlist.insert.nobar.js +++ b/src/widget/multiselectlist/multiselectlist.insert.nobar.js @@ -1,61 +1,107 @@ -/** - * Created by zcf_1 on 2017/5/2. - */ -BI.MultiSelectInsertNoBarList = BI.inherit(BI.Single, { - _defaultConfig: function () { - return BI.extend(BI.MultiSelectInsertNoBarList.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + emptyFn, + Selection, + deepClone, + isKey, + remove, + pushDistinct, + createWidget, + isNotEmptyString, + i18nText, + isEmptyArray, + last, + initial, + endWith, + AbsoluteLayout, + isEmptyString, + makeObject, + each, + Func, + map, + concat, + isNotNull, + values, + filter, + contains, + isNull, VTapeLayout +} from "@/core"; +import { Single, Searcher, Msg } from "@/base"; +import { MultiSelectBar } from "@/case"; +import { SelectPatchEditor } from "../multiselect/trigger/editor/editor.patch"; +import { MultiSelectNoBarLoader } from "../multiselect/multiselect.loader.nobar"; +import { MultiSelectSearchInsertPane } from "../multiselect/search/multiselect.search.insert.pane"; +import { SearchEditor } from "../editor/editor.search"; + + +@shortcut() +export class MultiSelectInsertNoBarList extends Single { + static xtype = "bi.multi_select_insert_no_bar_list"; + + static REQ_GET_DATA_LENGTH = "1"; + static REQ_GET_ALL_DATA = "-1"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-insert-list", - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, + itemsCreator: emptyFn, + valueFormatter: emptyFn, searcherHeight: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, }); - }, - _init: function () { - BI.MultiSelectInsertNoBarList.superclass._init.apply(this, arguments); + } - var self = this, o = this.options; + _init() { + super._init(...arguments); + + const self = this, + o = this.options; this.storeValue = { - type: BI.Selection.Multi, - value: BI.deepClone(o.value) || [] + type: Selection.Multi, + value: deepClone(o.value) || [], }; - var assertShowValue = function () { - BI.isKey(self._startValue) && (self.storeValue.type === BI.Selection.All ? BI.remove(self.storeValue.value, self._startValue) : BI.pushDistinct(self.storeValue.value, self._startValue)); + function assertShowValue() { + isKey(self._startValue) && + (self.storeValue.type === Selection.All + ? remove(self.storeValue.value, self._startValue) + : pushDistinct(self.storeValue.value, self._startValue)); // self.trigger.setValue(self.storeValue); - }; + } - this.adapter = BI.createWidget({ - type: "bi.multi_select_no_bar_loader", + this.adapter = createWidget({ + type: MultiSelectNoBarLoader.xtype, cls: "popup-multi-select-list bi-border-left bi-border-right bi-border-bottom", itemsCreator: o.itemsCreator, itemHeight: o.itemHeight, valueFormatter: o.valueFormatter, logic: { - dynamic: false + dynamic: false, }, // onLoaded: o.onLoaded, el: {}, value: { - type: BI.Selection.Multi, - value: o.value || [] - } + type: Selection.Multi, + value: o.value || [], + }, }); - this.adapter.on(BI.MultiSelectLoader.EVENT_CHANGE, function () { + this.adapter.on(MultiSelectNoBarLoader.EVENT_CHANGE, function () { self.storeValue = this.getValue(); assertShowValue(); - self.fireEvent(BI.MultiSelectInsertNoBarList.EVENT_CHANGE); + self.fireEvent(MultiSelectInsertNoBarList.EVENT_CHANGE); }); - this.searcherPane = BI.createWidget({ - type: "bi.multi_select_search_insert_pane", + this.searcherPane = createWidget({ + type: MultiSelectSearchInsertPane.xtype, cls: "bi-border-left bi-border-right bi-border-bottom", valueFormatter: o.valueFormatter, - keywordGetter: function () { + keywordGetter() { return self.trigger.getKeyword(); }, - itemsCreator: function (op, callback) { - var keyword = self.trigger.getKeyword(); - if (BI.isNotEmptyString(keyword)) { + itemsCreator(op, callback) { + const keyword = self.trigger.getKeyword(); + if (isNotEmptyString(keyword)) { op.keywords = [keyword]; this.setKeyword(op.keywords[0]); o.itemsCreator(op, callback); @@ -64,303 +110,342 @@ BI.MultiSelectInsertNoBarList = BI.inherit(BI.Single, { }); this.searcherPane.setVisible(false); - this.trigger = BI.createWidget({ - type: "bi.searcher", + this.trigger = createWidget({ + type: Searcher.xtype, el: { - type: "bi.select_patch_editor", + type: SelectPatchEditor.xtype, el: { - type: "bi.search_editor", - watermark: BI.i18nText("BI-Basic_Search_And_Patch_Paste"), + type: SearchEditor.xtype, + watermark: i18nText("BI-Basic_Search_And_Patch_Paste"), }, - ref: function (ref) { + ref(ref) { self.editor = ref; }, - height: o.searcherHeight + height: o.searcherHeight, }, isAutoSearch: false, isAutoSync: false, - onSearch: function (op, callback) { + onSearch(op, callback) { callback(); }, adapter: this.adapter, popup: this.searcherPane, height: 200, masker: false, - listeners: [{ - eventName: BI.Searcher.EVENT_START, - action: function () { - self._showSearcherPane(); - self._setStartValue(""); - this.setValue(BI.deepClone(self.storeValue)); - } - }, { - eventName: BI.Searcher.EVENT_STOP, - action: function () { - self._showAdapter(); - self._setStartValue(""); - self.adapter.setValue(self.storeValue); - // 需要刷新回到初始界面,否则搜索的结果不能放在最前面 - self.adapter.populate(); - } - }, { - eventName: BI.Searcher.EVENT_PAUSE, - action: function () { - var keywords = self._getKeywords(); - if (keywords[keywords.length - 1] === BI.BlankSplitChar) { - keywords = keywords.slice(0, keywords.length - 1); - } - var keyword = BI.isEmptyArray(keywords) ? "" : keywords[keywords.length - 1]; - self._join({ - type: BI.Selection.Multi, - value: [keyword] - }, function () { - if (self.storeValue.type === BI.Selection.Multi) { - BI.pushDistinct(self.storeValue.value, keyword); - } + listeners: [ + { + eventName: Searcher.EVENT_START, + action() { + self._showSearcherPane(); + self._setStartValue(""); + this.setValue(deepClone(self.storeValue)); + }, + }, + { + eventName: Searcher.EVENT_STOP, + action() { self._showAdapter(); + self._setStartValue(""); self.adapter.setValue(self.storeValue); - self._setStartValue(keyword); - assertShowValue(); + // 需要刷新回到初始界面,否则搜索的结果不能放在最前面 self.adapter.populate(); - self._setStartValue(""); - self.fireEvent(BI.MultiSelectInsertNoBarList.EVENT_CHANGE); - }); - } - }, { - eventName: BI.Searcher.EVENT_SEARCHING, - action: function () { - var keywords = self._getKeywords(); - var last = BI.last(keywords); - keywords = BI.initial(keywords || []); - if (keywords.length > 0) { - self._joinKeywords(keywords, function () { - if (BI.endWith(last, BI.BlankSplitChar)) { + }, + }, + { + eventName: Searcher.EVENT_PAUSE, + action() { + let keywords = self._getKeywords(); + if ( + keywords[keywords.length - 1] === BI.BlankSplitChar + ) { + keywords = keywords.slice(0, keywords.length - 1); + } + const keyword = isEmptyArray(keywords) + ? "" + : keywords[keywords.length - 1]; + self._join( + { + type: Selection.Multi, + value: [keyword], + }, + () => { + if (self.storeValue.type === Selection.Multi) { + pushDistinct( + self.storeValue.value, + keyword + ); + } + self._showAdapter(); self.adapter.setValue(self.storeValue); + self._setStartValue(keyword); assertShowValue(); self.adapter.populate(); self._setStartValue(""); - } else { - self.adapter.setValue(self.storeValue); - assertShowValue(); + self.fireEvent( + MultiSelectInsertNoBarList.EVENT_CHANGE + ); } - self.fireEvent(BI.MultiSelectInsertNoBarList.EVENT_CHANGE); - }); - self._getKeywordsLength() > 2000 && BI.Msg.alert(BI.i18nText("BI-Basic_Prompt"), BI.i18nText("BI-Basic_Too_Much_Value_Get_Two_Thousand")); - } - } - }, { - eventName: BI.Searcher.EVENT_CHANGE, - action: function (value, obj) { - if (obj instanceof BI.MultiSelectBar) { - self._joinAll(this.getValue(), function () { - assertShowValue(); - self.fireEvent(BI.MultiSelectInsertNoBarList.EVENT_CHANGE); - }); - } else { - self._join(this.getValue(), function () { - assertShowValue(); - self.fireEvent(BI.MultiSelectInsertNoBarList.EVENT_CHANGE); - }); - } + ); + }, + }, + { + eventName: Searcher.EVENT_SEARCHING, + action() { + let keywords = self._getKeywords(); + const lastKeyword = last(keywords); + keywords = initial(keywords || []); + if (keywords.length > 0) { + self._joinKeywords(keywords, () => { + if (endWith(lastKeyword, BI.BlankSplitChar)) { + self.adapter.setValue(self.storeValue); + assertShowValue(); + self.adapter.populate(); + self._setStartValue(""); + } else { + self.adapter.setValue(self.storeValue); + assertShowValue(); + } + self.fireEvent( + MultiSelectInsertNoBarList.EVENT_CHANGE + ); + }); + self._getKeywordsLength() > 2000 && + Msg.alert( + i18nText("BI-Basic_Prompt"), + i18nText( + "BI-Basic_Too_Much_Value_Get_Two_Thousand" + ) + ); + } + }, + }, + { + eventName: Searcher.EVENT_CHANGE, + action(value, obj) { + if (obj instanceof MultiSelectBar) { + self._joinAll(this.getValue(), () => { + assertShowValue(); + self.fireEvent( + MultiSelectInsertNoBarList.EVENT_CHANGE + ); + }); + } else { + self._join(this.getValue(), () => { + assertShowValue(); + self.fireEvent( + MultiSelectInsertNoBarList.EVENT_CHANGE + ); + }); + } + }, } - }], + ], value: { - type: BI.Selection.Multi, - value: o.value || [] - } + type: Selection.Multi, + value: o.value || [], + }, }); - BI.createWidget({ - type: "bi.vtape", + createWidget({ + type: VTapeLayout.xtype, element: this, - items: [{ - el: this.trigger, - height: o.searcherHeight - }, { - el: this.adapter, - height: "fill" - }] + items: [ + { + el: this.trigger, + height: o.searcherHeight, + }, + { + el: this.adapter, + height: "fill", + } + ], }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.searcherPane, - top: o.searcherHeight, - bottom: 0, - left: 0, - right: 0 - }] + items: [ + { + el: this.searcherPane, + top: o.searcherHeight, + bottom: 0, + left: 0, + right: 0, + } + ], }); - }, + } - _getKeywords: function () { - var val = this.editor.getValue(); - var keywords = val.split(/\u200b\s\u200b/); - if (BI.isEmptyString(keywords[keywords.length - 1])) { + _getKeywords() { + const val = this.editor.getValue(); + let keywords = val.split(/\u200b\s\u200b/); + if (isEmptyString(keywords[keywords.length - 1])) { keywords = keywords.slice(0, keywords.length - 1); } if (/\u200b\s\u200b$/.test(val)) { keywords = keywords.concat([BI.BlankSplitChar]); } - return keywords.length > 2000 ? keywords.slice(0, 2000).concat([BI.BlankSplitChar]) : keywords.slice(0, 2000); - }, + return keywords.length > 2000 + ? keywords.slice(0, 2000).concat([BI.BlankSplitChar]) + : keywords.slice(0, 2000); + } - _getKeywordsLength: function () { - var val = this.editor.getValue(); - var keywords = val.split(/\u200b\s\u200b/); + _getKeywordsLength() { + const val = this.editor.getValue(); + const keywords = val.split(/\u200b\s\u200b/); return keywords.length - 1; - }, + } - _showAdapter: function () { + _showAdapter() { this.adapter.setVisible(true); this.searcherPane.setVisible(false); - }, + } - _showSearcherPane: function () { + _showSearcherPane() { this.searcherPane.setVisible(true); this.adapter.setVisible(false); - }, + } - _defaultState: function () { + _defaultState() { this.trigger.stopEditing(); - }, + } - _assertValue: function (val) { + _assertValue(val) { val || (val = {}); - val.type || (val.type = BI.Selection.Multi); + val.type || (val.type = Selection.Multi); val.value || (val.value = []); - }, + } - _makeMap: function (values) { - return BI.makeObject(values || []); - }, + _makeMap(values) { + return makeObject(values || []); + } - _joinKeywords: function (keywords, callback) { - var self = this, o = this.options; + _joinKeywords(keywords, callback) { + const self = this; this._assertValue(this.storeValue); // 和复选下拉框同步,allData做缓存是会爆炸的 digest(); - function digest (items) { - BI.each(keywords, function (i, val) { - self.storeValue.type === BI.Selection.Multi ? BI.pushDistinct(self.storeValue.value, val) : BI.remove(self.storeValue.value, val); + function digest(items) { + each(keywords, (i, val) => { + self.storeValue.type === Selection.Multi + ? pushDistinct(self.storeValue.value, val) + : remove(self.storeValue.value, val); }); callback(); } - }, + } - _joinAll: function (res, callback) { - var self = this, o = this.options; + _joinAll(res, callback) { + const self = this, + o = this.options; this._assertValue(res); if (this.storeValue.type === res.type) { - var result = BI.Func.getSearchResult(BI.map(this.storeValue.value, function (_i, v) { - return { - text: o.valueFormatter(v) || v, - value: v - }; - }), this.trigger.getKeyword()); - var change = false; - var map = this._makeMap(this.storeValue.value); - BI.each(BI.concat(result.match, result.find), function (i, obj) { - var v = obj.value; - if (BI.isNotNull(map[v])) { + const result = Func.getSearchResult( + map(this.storeValue.value, (_i, v) => { + return { + text: o.valueFormatter(v) || v, + value: v, + }; + }), + this.trigger.getKeyword() + ); + let change = false; + const tempMap = this._makeMap(this.storeValue.value); + each(concat(result.match, result.find), (i, obj) => { + const v = obj.value; + if (isNotNull(tempMap[v])) { change = true; - delete map[v]; + delete tempMap[v]; } }); - change && (this.storeValue.value = BI.values(map)); + change && (this.storeValue.value = values(tempMap)); callback(); + return; } - o.itemsCreator({ - type: BI.MultiSelectInsertNoBarList.REQ_GET_ALL_DATA, - keywords: [this.trigger.getKeyword()], - selectedValues: BI.filter(this.storeValue.value, function (_i, v) { - return !BI.contains(res.value, v); - }), - }, function (ob) { - var items = BI.map(ob.items, "value"); - var selectedMap = self._makeMap(self.storeValue.value); - var notSelectedMap = self._makeMap(res.value); - var newItems = []; - BI.each(items, function (i, item) { - if (BI.isNotNull(selectedMap[items[i]])) { - delete selectedMap[items[i]]; - } - if (BI.isNull(notSelectedMap[items[i]])) { - newItems.push(item); - } - }); - self.storeValue.value = newItems.concat(BI.values(selectedMap)); - callback(); - }); - }, + o.itemsCreator( + { + type: MultiSelectInsertNoBarList.REQ_GET_ALL_DATA, + keywords: [this.trigger.getKeyword()], + selectedValues: filter(this.storeValue.value, (_i, v) => !contains(res.value, v)), + }, + ob => { + const items = map(ob.items, "value"); + const selectedMap = self._makeMap(self.storeValue.value); + const notSelectedMap = self._makeMap(res.value); + const newItems = []; + each(items, (i, item) => { + if (isNotNull(selectedMap[items[i]])) { + delete selectedMap[items[i]]; + } + if (isNull(notSelectedMap[items[i]])) { + newItems.push(item); + } + }); + self.storeValue.value = newItems.concat(values(selectedMap)); + callback(); + } + ); + } - _join: function (res, callback) { - var self = this, o = this.options; + _join(res, callback) { + const self = this; this._assertValue(res); this._assertValue(this.storeValue); if (this.storeValue.type === res.type) { - var map = this._makeMap(this.storeValue.value); - BI.each(res.value, function (i, v) { + const map = this._makeMap(this.storeValue.value); + each(res.value, (i, v) => { if (!map[v]) { - BI.pushDistinct(self.storeValue.value, v); + pushDistinct(self.storeValue.value, v); map[v] = v; } }); - var change = false; - BI.each(res.assist, function (i, v) { - if (BI.isNotNull(map[v])) { + let change = false; + each(res.assist, (i, v) => { + if (isNotNull(map[v])) { change = true; delete map[v]; } }); - change && (this.storeValue.value = BI.values(map)); + change && (this.storeValue.value = values(map)); callback(); + return; } this._joinAll(res, callback); - }, + } - _setStartValue: function (value) { + _setStartValue(value) { this._startValue = value; this.adapter.setStartValue(value); - }, + } - isAllSelected: function () { + isAllSelected() { return this.adapter.isAllSelected(); - }, + } - resize: function () { + resize() { // this.trigger.getCounter().adjustView(); // this.trigger.adjustView(); - }, - setValue: function (v) { + } + + setValue(v) { this.storeValue = { - type: BI.Selection.Multi, - value: v || [] + type: Selection.Multi, + value: v || [], }; this.adapter.setValue(this.storeValue); this.trigger.setValue(this.storeValue); - }, - - getValue: function () { - return BI.deepClone(this.storeValue.value); - }, - - populate: function () { - this.adapter.populate.apply(this.adapter, arguments); - this.trigger.populate.apply(this.trigger, arguments); } -}); -BI.extend(BI.MultiSelectInsertNoBarList, { - REQ_GET_DATA_LENGTH: 1, - REQ_GET_ALL_DATA: -1 -}); + getValue() { + return deepClone(this.storeValue.value); + } -BI.MultiSelectInsertNoBarList.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multi_select_insert_no_bar_list", BI.MultiSelectInsertNoBarList); + populate() { + this.adapter.populate(...arguments); + this.trigger.populate(...arguments); + } +} diff --git a/src/widget/multiselectlist/multiselectlist.js b/src/widget/multiselectlist/multiselectlist.js index 7255963df..878bc5bc0 100644 --- a/src/widget/multiselectlist/multiselectlist.js +++ b/src/widget/multiselectlist/multiselectlist.js @@ -1,177 +1,233 @@ -/** - * Created by zcf_1 on 2017/5/2. - */ -BI.MultiSelectList = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.MultiSelectList.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + Widget, + extend, + emptyFn, + deepClone, + isKey, + Selection, + remove, + pushDistinct, + createWidget, + isNotEmptyString, + last, + initial, + endWith, + AbsoluteLayout, + isEmptyString, + makeObject, + map, + each, + isNotNull, + Func, + concat, + values, + filter, + contains, + isNull, VTapeLayout +} from "@/core"; +import { Searcher } from "@/base"; +import { MultiSelectBar } from "@/case"; +import { MultiSelectLoader } from "../multiselect/multiselect.loader"; +import { MultiSelectSearchPane } from "../multiselect/search/multiselect.search.pane"; +import { SelectPatchEditor } from "../multiselect/trigger/editor/editor.patch"; +import { SearchEditor } from "../editor/editor.search"; + + +@shortcut() +export class MultiSelectList extends Widget { + static xtype = "bi.multi_select_list"; + + static REQ_GET_DATA_LENGTH = "1"; + static REQ_GET_ALL_DATA = "-1"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-list", - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, + itemsCreator: emptyFn, + valueFormatter: emptyFn, searcherHeight: 24, itemHeight: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, }); - }, - _init: function () { - BI.MultiSelectList.superclass._init.apply(this, arguments); + } + + _init() { + super._init(...arguments); - var self = this, o = this.options; - this.storeValue = this._assertValue(BI.deepClone(o.value) || {}); + const self = this, + o = this.options; + this.storeValue = this._assertValue(deepClone(o.value) || {}); - var assertShowValue = function () { - BI.isKey(self._startValue) && (self.storeValue.type === BI.Selection.All ? BI.remove(self.storeValue.value, self._startValue) : BI.pushDistinct(self.storeValue.value, self._startValue)); + function assertShowValue() { + isKey(self._startValue) && + (self.storeValue.type === Selection.All + ? remove(self.storeValue.value, self._startValue) + : pushDistinct(self.storeValue.value, self._startValue)); // self.trigger.setValue(self.storeValue); - }; + } - this.adapter = BI.createWidget({ - type: "bi.multi_select_loader", + this.adapter = createWidget({ + type: MultiSelectLoader.xtype, cls: "popup-multi-select-list bi-border-left bi-border-right bi-border-bottom", itemsCreator: o.itemsCreator, valueFormatter: o.valueFormatter, itemHeight: o.itemHeight, logic: { - dynamic: false + dynamic: false, }, value: o.value, isDefaultInit: true, // onLoaded: o.onLoaded, - el: {} + el: {}, }); - this.adapter.on(BI.MultiSelectLoader.EVENT_CHANGE, function () { + this.adapter.on(MultiSelectLoader.EVENT_CHANGE, function () { self.storeValue = this.getValue(); - self._adjust(function () { + self._adjust(() => { assertShowValue(); - self.fireEvent(BI.MultiSelectList.EVENT_CHANGE); + self.fireEvent(MultiSelectList.EVENT_CHANGE); }); }); - this.searcherPane = BI.createWidget({ - type: "bi.multi_select_search_pane", + this.searcherPane = createWidget({ + type: MultiSelectSearchPane.xtype, cls: "bi-border-left bi-border-right bi-border-bottom", valueFormatter: o.valueFormatter, - keywordGetter: function () { + keywordGetter() { return self.trigger.getKeyword(); }, - itemsCreator: function (op, callback) { - var keyword = self.trigger.getKeyword(); - if (BI.isNotEmptyString(keyword)) { + itemsCreator(op, callback) { + const keyword = self.trigger.getKeyword(); + if (isNotEmptyString(keyword)) { op.keywords = [keyword]; o.itemsCreator(op, callback); } }, - itemHeight: o.itemHeight + itemHeight: o.itemHeight, }); this.searcherPane.setVisible(false); - this.trigger = BI.createWidget({ - type: "bi.searcher", + this.trigger = createWidget({ + type: Searcher.xtype, el: { - type: "bi.select_patch_editor", + type: SelectPatchEditor.xtype, el: { - type: "bi.search_editor", + type: SearchEditor.xtype, }, - ref: function (ref) { + ref(ref) { self.editor = ref; }, - height: o.searcherHeight + height: o.searcherHeight, }, isAutoSearch: false, isAutoSync: false, - onSearch: function (op, callback) { + onSearch(op, callback) { callback(); }, adapter: this.adapter, popup: this.searcherPane, height: 200, masker: false, - listeners: [{ - eventName: BI.Searcher.EVENT_START, - action: function () { - self._showSearcherPane(); - self._setStartValue(""); - this.setValue(BI.deepClone(self.storeValue)); - } - }, { - eventName: BI.Searcher.EVENT_STOP, - action: function () { - self._showAdapter(); - self._setStartValue(""); - self.adapter.setValue(self.storeValue); - // 需要刷新回到初始界面,否则搜索的结果不能放在最前面 - self.adapter.populate(); - } - }, { - eventName: BI.Searcher.EVENT_PAUSE, - action: function () { - self._showAdapter(); - self.fireEvent(BI.MultiSelectList.EVENT_CHANGE); + listeners: [ + { + eventName: Searcher.EVENT_START, + action() { + self._showSearcherPane(); + self._setStartValue(""); + this.setValue(deepClone(self.storeValue)); + }, + }, + { + eventName: Searcher.EVENT_STOP, + action() { + self._showAdapter(); + self._setStartValue(""); + self.adapter.setValue(self.storeValue); + // 需要刷新回到初始界面,否则搜索的结果不能放在最前面 + self.adapter.populate(); + }, + }, + { + eventName: Searcher.EVENT_PAUSE, + action() { + self._showAdapter(); + self.fireEvent(MultiSelectList.EVENT_CHANGE); + }, }, - }, { - eventName: BI.Searcher.EVENT_SEARCHING, - action: function () { - var keywords = this.getKeyword(); - var last = BI.last(keywords); - keywords = BI.initial(keywords || []); - if (keywords.length > 0) { - self._joinKeywords(keywords, function () { - if (BI.endWith(last, BI.BlankSplitChar)) { - self.adapter.setValue(self.storeValue); + { + eventName: Searcher.EVENT_SEARCHING, + action() { + let keywords = this.getKeyword(); + const lastKeyword = last(keywords); + keywords = initial(keywords || []); + if (keywords.length > 0) { + self._joinKeywords(keywords, () => { + if (endWith(lastKeyword, BI.BlankSplitChar)) { + self.adapter.setValue(self.storeValue); + assertShowValue(); + self.adapter.populate(); + self._setStartValue(""); + } else { + self.adapter.setValue(self.storeValue); + assertShowValue(); + } + self.fireEvent(MultiSelectList.EVENT_CHANGE); + }); + } + }, + }, + { + eventName: Searcher.EVENT_CHANGE, + action(value, obj) { + if (obj instanceof MultiSelectBar) { + self._joinAll(this.getValue(), () => { assertShowValue(); - self.adapter.populate(); - self._setStartValue(""); - } else { - self.adapter.setValue(self.storeValue); + self.fireEvent(MultiSelectList.EVENT_CHANGE); + }); + } else { + self._join(this.getValue(), () => { assertShowValue(); - } - self.fireEvent(BI.MultiSelectList.EVENT_CHANGE); - }); - } - } - }, { - eventName: BI.Searcher.EVENT_CHANGE, - action: function (value, obj) { - if (obj instanceof BI.MultiSelectBar) { - self._joinAll(this.getValue(), function () { - assertShowValue(); - self.fireEvent(BI.MultiSelectList.EVENT_CHANGE); - }); - } else { - self._join(this.getValue(), function () { - assertShowValue(); - self.fireEvent(BI.MultiSelectList.EVENT_CHANGE); - }); - } + self.fireEvent(MultiSelectList.EVENT_CHANGE); + }); + } + }, } - }] + ], }); - BI.createWidget({ - type: "bi.vtape", + createWidget({ + type: VTapeLayout.xtype, element: this, - items: [{ - el: this.trigger, - height: o.searcherHeight - }, { - el: this.adapter, - height: "fill" - }] + items: [ + { + el: this.trigger, + height: o.searcherHeight, + }, + { + el: this.adapter, + height: "fill", + } + ], }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.searcherPane, - top: o.searcherHeight, - bottom: 0, - left: 0, - right: 0 - }] + items: [ + { + el: this.searcherPane, + top: o.searcherHeight, + bottom: 0, + left: 0, + right: 0, + } + ], }); - }, + } - _getKeywords: function () { - var val = this.editor.getValue(); - var keywords = val.split(/\u200b\s\u200b/); - if (BI.isEmptyString(keywords[keywords.length - 1])) { + _getKeywords() { + const val = this.editor.getValue(); + let keywords = val.split(/\u200b\s\u200b/); + if (isEmptyString(keywords[keywords.length - 1])) { keywords = keywords.slice(0, keywords.length - 1); } if (/\u200b\s\u200b$/.test(val)) { @@ -179,193 +235,209 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { } return keywords; - }, + } - _showAdapter: function () { + _showAdapter() { this.adapter.setVisible(true); this.searcherPane.setVisible(false); - }, + } - _showSearcherPane: function () { + _showSearcherPane() { this.searcherPane.setVisible(true); this.adapter.setVisible(false); - }, + } - _defaultState: function () { + _defaultState() { this.trigger.stopEditing(); - }, + } - _assertValue: function (val) { + _assertValue(val) { val || (val = {}); - val.type || (val.type = BI.Selection.Multi); + val.type || (val.type = Selection.Multi); val.value || (val.value = []); + return val; - }, + } - _makeMap: function (values) { - return BI.makeObject(values || []); - }, + _makeMap(values) { + return makeObject(values || []); + } - _joinKeywords: function (keywords, callback) { - var self = this, o = this.options; + _joinKeywords(keywords, callback) { + const self = this, + o = this.options; this._assertValue(this.storeValue); // 和复选下拉框同步,allData做缓存是会爆炸的 - o.itemsCreator({ - type: BI.MultiSelectList.REQ_GET_ALL_DATA, - keywords: keywords - }, function (ob) { - var values = BI.map(ob.items, "value"); - digest(values); - }); + o.itemsCreator( + { + type: MultiSelectList.REQ_GET_ALL_DATA, + keywords, + }, + ob => { + const values = map(ob.items, "value"); + digest(values); + } + ); function digest(items) { - var selectedMap = self._makeMap(items); - BI.each(keywords, function (i, val) { - if (BI.isNotNull(selectedMap[val])) { - self.storeValue.type === BI.Selection.Multi ? BI.pushDistinct(self.storeValue.value, val) : BI.remove(self.storeValue.value, val); + const selectedMap = self._makeMap(items); + each(keywords, (i, val) => { + if (isNotNull(selectedMap[val])) { + self.storeValue.type === Selection.Multi + ? pushDistinct(self.storeValue.value, val) + : remove(self.storeValue.value, val); } }); self._adjust(callback); } - }, + } - _joinAll: function (res, callback) { - var self = this, o = this.options; + _joinAll(res, callback) { + const self = this, + o = this.options; this._assertValue(res); if (this.storeValue.type === res.type) { - var result = BI.Func.getSearchResult(BI.map(this.storeValue.value, function (_i, v) { - return { - text: o.valueFormatter(v) || v, - value: v - }; - }), this.trigger.getKeyword()); - var change = false; - var map = this._makeMap(this.storeValue.value); - BI.each(BI.concat(result.match, result.find), function (i, obj) { - var v = obj.value; - if (BI.isNotNull(map[v])) { + const result = Func.getSearchResult( + map(this.storeValue.value, (_i, v) => { + return { + text: o.valueFormatter(v) || v, + value: v, + }; + }), + this.trigger.getKeyword() + ); + let change = false; + const tempMap = this._makeMap(this.storeValue.value); + each(concat(result.match, result.find), (i, obj) => { + const v = obj.value; + if (isNotNull(tempMap[v])) { change = true; - delete map[v]; + delete tempMap[v]; } }); - change && (this.storeValue.value = BI.values(map)); + change && (this.storeValue.value = values(tempMap)); this._adjust(callback); + return; } - o.itemsCreator({ - type: BI.MultiSelectList.REQ_GET_ALL_DATA, - keywords: [this.trigger.getKeyword()], - selectedValues: BI.filter(this.storeValue.value, function (_i, v) { - return !BI.contains(res.value, v); - }), - }, function (ob) { - var items = BI.map(ob.items, "value"); - var selectedMap = self._makeMap(self.storeValue.value); - var notSelectedMap = self._makeMap(res.value); - var newItems = []; - BI.each(items, function (i, item) { - if (BI.isNotNull(selectedMap[items[i]])) { - delete selectedMap[items[i]]; - } - if (BI.isNull(notSelectedMap[items[i]])) { - newItems.push(item); - } - }); - self.storeValue.value = newItems.concat(BI.values(selectedMap)); - self._adjust(callback); - }); - }, + o.itemsCreator( + { + type: MultiSelectList.REQ_GET_ALL_DATA, + keywords: [this.trigger.getKeyword()], + selectedValues: filter(this.storeValue.value, (_i, v) => !contains(res.value, v)), + }, + ob => { + const items = map(ob.items, "value"); + const selectedMap = self._makeMap(self.storeValue.value); + const notSelectedMap = self._makeMap(res.value); + const newItems = []; + each(items, (i, item) => { + if (isNotNull(selectedMap[items[i]])) { + delete selectedMap[items[i]]; + } + if (isNull(notSelectedMap[items[i]])) { + newItems.push(item); + } + }); + self.storeValue.value = newItems.concat(values(selectedMap)); + self._adjust(callback); + } + ); + } - _adjust: function (callback) { - var self = this, o = this.options; + _adjust(callback) { + const self = this, + o = this.options; if (!this._count) { - o.itemsCreator({ - type: BI.MultiSelectList.REQ_GET_DATA_LENGTH - }, function (res) { - self._count = res.count; - adjust(); - callback(); - }); + o.itemsCreator( + { + type: MultiSelectList.REQ_GET_DATA_LENGTH, + }, + res => { + self._count = res.count; + adjust(); + callback(); + } + ); } else { adjust(); callback(); } function adjust() { - if (self.storeValue.type === BI.Selection.All && self.storeValue.value.length >= self._count) { + if ( + self.storeValue.type === Selection.All && + self.storeValue.value.length >= self._count + ) { self.storeValue = { - type: BI.Selection.Multi, - value: [] + type: Selection.Multi, + value: [], }; - } else if (self.storeValue.type === BI.Selection.Multi && self.storeValue.value.length >= self._count) { + } else if ( + self.storeValue.type === Selection.Multi && + self.storeValue.value.length >= self._count + ) { self.storeValue = { - type: BI.Selection.All, - value: [] + type: Selection.All, + value: [], }; } } - }, + } - _join: function (res, callback) { - var self = this, o = this.options; + _join(res, callback) { + const self = this; this._assertValue(res); this._assertValue(this.storeValue); if (this.storeValue.type === res.type) { - var map = this._makeMap(this.storeValue.value); - BI.each(res.value, function (i, v) { + const map = this._makeMap(this.storeValue.value); + each(res.value, (i, v) => { if (!map[v]) { - BI.pushDistinct(self.storeValue.value, v); + pushDistinct(self.storeValue.value, v); map[v] = v; } }); - var change = false; - BI.each(res.assist, function (i, v) { - if (BI.isNotNull(map[v])) { + let change = false; + each(res.assist, (i, v) => { + if (isNotNull(map[v])) { change = true; delete map[v]; } }); - change && (this.storeValue.value = BI.values(map)); + change && (this.storeValue.value = values(map)); self._adjust(callback); + return; } this._joinAll(res, callback); - }, + } - _setStartValue: function (value) { + _setStartValue(value) { this._startValue = value; this.adapter.setStartValue(value); - }, + } - isAllSelected: function () { + isAllSelected() { return this.adapter.isAllSelected(); - }, + } - resize: function () { - // this.trigger.getCounter().adjustView(); - // this.trigger.adjustView(); - }, - setValue: function (v) { + resize() { + + } + + setValue(v) { this.storeValue = v || {}; this._assertValue(this.storeValue); this.adapter.setValue(this.storeValue); this.trigger.setValue(this.storeValue); - }, - - getValue: function () { - return BI.deepClone(this.storeValue); - }, - - populate: function () { - this.adapter.populate.apply(this.adapter, arguments); - this.trigger.populate.apply(this.trigger, arguments); } -}); -BI.extend(BI.MultiSelectList, { - REQ_GET_DATA_LENGTH: 1, - REQ_GET_ALL_DATA: -1 -}); + getValue() { + return deepClone(this.storeValue); + } -BI.MultiSelectList.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multi_select_list", BI.MultiSelectList); + populate() { + this.adapter.populate(...arguments); + this.trigger.populate(...arguments); + } +} From c80b9f05ef148e9f31c149f972dbaec56f4c5afa Mon Sep 17 00:00:00 2001 From: zsmj Date: Thu, 12 Jan 2023 15:26:05 +0800 Subject: [PATCH 094/300] update --- src/case/list/list.select.js | 30 +++++++++++++++++++++++------- src/widget/editor/index.js | 0 2 files changed, 23 insertions(+), 7 deletions(-) create mode 100644 src/widget/editor/index.js diff --git a/src/case/list/list.select.js b/src/case/list/list.select.js index a6fb459db..e9fce794a 100644 --- a/src/case/list/list.select.js +++ b/src/case/list/list.select.js @@ -1,16 +1,32 @@ /* eslint-disable no-mixed-spaces-and-tabs */ -import { shortcut, Widget, extend, emptyFn, Controller, createWidget, Events, isNotNull, isEmptyString, isEmptyArray, Direction, get, LogicFactory, each, pixFormat } from "@/core"; +import { + shortcut, + Widget, + extend, + emptyFn, + Controller, + createWidget, + Events, + isNotNull, + isEmptyString, + isEmptyArray, + Direction, + get, + LogicFactory, + each, + pixFormat +} from "@/core"; import { ButtonGroup } from "@/base"; +import { MultiSelectBar } from "../toolbar/toolbar.multiselect"; +import { ListPane } from "../layer/pane.list"; + @shortcut() export class SelectList extends Widget { static xtype = "bi.select_list"; - - static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig() { return extend(super._defaultConfig(...arguments), { baseCls: "bi-select-list", @@ -23,11 +39,11 @@ export class SelectList extends Widget { hasNext: emptyFn, onLoaded: emptyFn, toolbar: { - type: "bi.multi_select_bar", + type: MultiSelectBar.xtype, iconWrapperWidth: 36, }, el: { - type: "bi.list_pane", + type: ListPane.xtype, }, }); } @@ -49,7 +65,7 @@ export class SelectList extends Widget { }); this.list = createWidget(o.el, { - type: "bi.list_pane", + type: ListPane.xtype, items: o.items, itemsCreator(op, callback) { op.times === 1 && this.toolbar.setVisible(false); diff --git a/src/widget/editor/index.js b/src/widget/editor/index.js new file mode 100644 index 000000000..e69de29bb From 499d1d02b4f9f75119c0e9c29dfde2ef78098962 Mon Sep 17 00:00:00 2001 From: Treecat Date: Thu, 12 Jan 2023 15:29:31 +0800 Subject: [PATCH 095/300] =?UTF-8?q?KERNEL-14076=20fix:=20=E4=BF=AE?= =?UTF-8?q?=E5=A4=8Dxtype?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/es6.js b/es6.js index 7667443e2..fbfede5a2 100644 --- a/es6.js +++ b/es6.js @@ -109,19 +109,20 @@ async function handleFile(srcName) { const sourceCode = fs.readFileSync(srcName).toString(); - const result = /BI\.(.*?)\s\=\sBI\.inherit\(/.exec(sourceCode); + const result = /BI\.(.*?)\s=\sBI\.inherit\(/.exec(sourceCode); if (!result) { - console.log(`已经es6过,替换 xtype => ${srcName}, `); + console.log(`已经es6过,替换 xtype => ${srcName}`); // 处理 xtype // 尝试对 xtype 进行替换 - const noXtypeCode = sourceCode.replace(/"bi\.(.*?)"/g, matchedSentence => { + const noXtypeCode = sourceCode.replace(/type:\s?"bi\.(.*?)"/g, v => { + const matchedSentence = v.replace(/type:\s?/, ""); const loadSuccess = loader.load(srcName, matchedSentence); if (loadSuccess) { const clzName = depts[matchedSentence].clzName; - return `${clzName}.xtype`; + return `type: ${clzName}.xtype`; } else { console.log(`xtype 替换失败 ${matchedSentence} `); From 3fb5b3a9bbd626b3ced4d119a24ae6506d2f6408 Mon Sep 17 00:00:00 2001 From: impact Date: Thu, 12 Jan 2023 15:32:32 +0800 Subject: [PATCH 096/300] =?UTF-8?q?KERNEL-14047=20refactor:=20case/colorch?= =?UTF-8?q?oose=20ES6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/case/colorchooser/colorchooser.custom.js | 69 +++-- src/case/colorchooser/colorchooser.js | 146 +++++----- .../colorchooser/colorchooser.popup.hex.js | 271 +++++++++--------- .../colorchooser.popup.hex.simple.js | 61 ++-- src/case/colorchooser/colorchooser.popup.js | 209 +++++++------- .../colorchooser/colorchooser.popup.simple.js | 61 ++-- src/case/colorchooser/colorchooser.simple.js | 65 +++-- src/case/colorchooser/colorchooser.trigger.js | 58 ++-- .../colorchooser/colorchooser.trigger.long.js | 73 ++--- .../colorpicker/button/button.colorpicker.js | 76 ++--- .../colorpicker/button/button.colorshow.js | 46 +-- .../colorchooser/colorpicker/button/index.js | 2 + .../colorpicker/colorpicker.hex.js | 165 +++++------ .../colorchooser/colorpicker/colorpicker.js | 195 +++++++------ .../colorpicker/editor.colorpicker.hex.js | 242 ++++++++-------- .../editor.colorpicker.hex.simple.js | 168 ++++++----- .../colorpicker/editor.colorpicker.js | 166 +++++------ .../colorpicker/editor.colorpicker.simple.js | 111 ++++--- src/case/colorchooser/colorpicker/index.js | 7 + .../colorchooser/farbtastic/farbtastic.js | 202 ++++++------- src/case/colorchooser/index.js | 11 + src/case/index.js | 5 +- src/core/structure/queue.js | 2 +- 23 files changed, 1261 insertions(+), 1150 deletions(-) create mode 100644 src/case/colorchooser/colorpicker/button/index.js create mode 100644 src/case/colorchooser/colorpicker/index.js create mode 100644 src/case/colorchooser/index.js diff --git a/src/case/colorchooser/colorchooser.custom.js b/src/case/colorchooser/colorchooser.custom.js index c34d92500..dd8bf8350 100644 --- a/src/case/colorchooser/colorchooser.custom.js +++ b/src/case/colorchooser/colorchooser.custom.js @@ -1,39 +1,47 @@ +import { shortcut, Widget, extend, createWidget } from "@/core"; +import { ColorPickerEditor } from "./colorpicker"; +import { Farbtastic } from "./farbtastic/farbtastic"; + /** * 自定义选色 * * Created by GUY on 2015/11/17. - * @class BI.CustomColorChooser - * @extends BI.Widget + * @class CustomColorChooser + * @extends Widget */ -BI.CustomColorChooser = BI.inherit(BI.Widget, { +@shortcut() +export class CustomColorChooser extends Widget { + static xtype = "bi.custom_color_chooser"; + + static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig: function () { - return BI.extend(BI.CustomColorChooser.superclass._defaultConfig.apply(this, arguments), { + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-custom-color-chooser", width: 292, - height: 265 + height: 265, }); - }, + } - _init: function () { - BI.CustomColorChooser.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.editor = BI.createWidget(o.editor, { + _init() { + super._init(...arguments); + const o = this.options; + this.editor = createWidget(o.editor, { type: "bi.simple_hex_color_picker_editor", - value: o.value + value: o.value, }); - this.editor.on(BI.ColorPickerEditor.EVENT_CHANGE, function () { - self.setValue(this.getValue()); + this.editor.on(ColorPickerEditor.EVENT_CHANGE, () => { + this.setValue(this.editor.getValue()); }); - this.farbtastic = BI.createWidget({ + this.farbtastic = createWidget({ type: "bi.farbtastic", - value: o.value + value: o.value, }); - this.farbtastic.on(BI.Farbtastic.EVENT_CHANGE, function () { - self.setValue(this.getValue()); + this.farbtastic.on(Farbtastic.EVENT_CHANGE, () => { + this.setValue(this.farbtastic.getValue()); }); - BI.createWidget({ + createWidget({ type: "bi.vtape", element: this, items: [{ @@ -42,30 +50,29 @@ BI.CustomColorChooser = BI.inherit(BI.Widget, { el: this.editor, left: 10, top: 0, - right: 10 + right: 10, }], - height: 50 + height: 50, }, { type: "bi.absolute", items: [{ el: this.farbtastic, left: 46, right: 46, - top: 7 + top: 7, }], - height: 215 - }] + height: 215, + }], }); - }, + } - setValue: function (color) { + setValue(color) { this.editor.setValue(color); this.farbtastic.setValue(color); - }, + } - getValue: function () { + getValue() { return this.editor.getValue(); } -}); -BI.CustomColorChooser.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.custom_color_chooser", BI.CustomColorChooser); +} + diff --git a/src/case/colorchooser/colorchooser.js b/src/case/colorchooser/colorchooser.js index 218ea56b0..20b410a68 100644 --- a/src/case/colorchooser/colorchooser.js +++ b/src/case/colorchooser/colorchooser.js @@ -1,27 +1,41 @@ +import { shortcut, Widget, extend, createWidget, toPix, isNotEmptyString } from "@/core"; +import { Combo } from "@/base"; +import { ColorChooserPopup } from "./colorchooser.popup"; + /** * 选色控件 * * Created by GUY on 2015/11/17. - * @class BI.ColorChooser - * @extends BI.Widget + * @class ColorChooser + * @extends Widget */ -BI.ColorChooser = BI.inherit(BI.Widget, { +@shortcut() +export class ColorChooser extends Widget { + static xtype = "bi.color_chooser"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_AFTER_POPUPVIEW = "EVENT_AFTER_POPUPVIEW"; - _defaultConfig: function () { - return BI.extend(BI.ColorChooser.superclass._defaultConfig.apply(this, arguments), { + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-color-chooser", value: "", height: 24, el: {}, - simple: false + simple: false, }); - }, + } - _init: function () { - var self = this, o = this.options; - BI.ColorChooser.superclass._init.apply(this, arguments); + _init() { + const o = this.options; + const fn = () => { + const color = this.colorPicker.getValue(); + this.setValue(color); + }; + + super._init(...arguments); o.value = (o.value || "").toLowerCase(); - this.combo = BI.createWidget({ + this.combo = createWidget({ type: "bi.combo", element: this, container: o.container, @@ -29,83 +43,77 @@ BI.ColorChooser = BI.inherit(BI.Widget, { destroyWhenHide: o.destroyWhenHide, isNeedAdjustWidth: false, isNeedAdjustHeight: false, - el: BI.extend({ + el: extend({ type: o.width <= 24 ? "bi.color_chooser_trigger" : "bi.long_color_chooser_trigger", simple: o.simple, - ref: function (_ref) { - self.trigger = _ref; + ref: _ref => { + this.trigger = _ref; }, value: o.value, - width: o.el.type ? o.width : BI.toPix(o.width, 2), - height: o.el.type ? o.height : BI.toPix(o.height, 2) + width: o.el.type ? o.width : toPix(o.width, 2), + height: o.el.type ? o.height : toPix(o.height, 2), }, o.el), - popup: () => ({ - el: BI.extend({ - type: "bi.hex_color_chooser_popup", - recommendColorsGetter: o.recommendColorsGetter, - ref: function (_ref) { - self.colorPicker = _ref; - }, - listeners: [{ - eventName: BI.ColorChooserPopup.EVENT_VALUE_CHANGE, - action: function () { - fn(); - if (!self._isRGBColor(self.colorPicker.getValue())) { - self.combo.hideView(); - } - } - }, { - eventName: BI.ColorChooserPopup.EVENT_CHANGE, - action: function () { - fn(); - self.combo.hideView(); - } - }] - }, o.popup), - value: o.value, - width: 300 - }), - value: o.value + popup: () => { + return { + el: extend({ + type: "bi.hex_color_chooser_popup", + recommendColorsGetter: o.recommendColorsGetter, + ref: _ref => { + this.colorPicker = _ref; + }, + listeners: [{ + eventName: ColorChooserPopup.EVENT_VALUE_CHANGE, + action: () => { + fn(); + if (!this._isRGBColor(this.colorPicker.getValue())) { + this.combo.hideView(); + } + }, + }, { + eventName: ColorChooserPopup.EVENT_CHANGE, + action: () => { + fn(); + this.combo.hideView(); + }, + }], + }, o.popup), + value: o.value, + width: 300, + }; + }, + value: o.value, }); - var fn = function () { - var color = self.colorPicker.getValue(); - self.setValue(color); - }; - - this.combo.on(BI.Combo.EVENT_BEFORE_HIDEVIEW, function () { - self.fireEvent(BI.ColorChooser.EVENT_CHANGE, arguments); + this.combo.on(Combo.EVENT_BEFORE_HIDEVIEW, (...args) => { + this.fireEvent(ColorChooser.EVENT_CHANGE, ...args); }); - this.combo.on(BI.Combo.EVENT_AFTER_POPUPVIEW, function () { - self.fireEvent(BI.ColorChooser.EVENT_AFTER_POPUPVIEW, arguments); + this.combo.on(Combo.EVENT_AFTER_POPUPVIEW, (...args) => { + this.fireEvent(ColorChooser.EVENT_AFTER_POPUPVIEW, ...args); }); - }, + } - _isRGBColor: function (color) { - return BI.isNotEmptyString(color) && color !== "transparent"; - }, + _isRGBColor(color) { + return isNotEmptyString(color) && color !== "transparent"; + } - isViewVisible: function () { + isViewVisible() { return this.combo.isViewVisible(); - }, + } - hideView: function () { + hideView() { this.combo.hideView(); - }, + } - showView: function () { + showView() { this.combo.showView(); - }, + } - setValue: function (color) { + setValue(color) { this.options.value = (color || "").toLowerCase(); this.combo.setValue(this.options.value); - }, + } - getValue: function () { + getValue() { return this.combo.getValue(); } -}); -BI.ColorChooser.EVENT_CHANGE = "EVENT_CHANGE"; -BI.ColorChooser.EVENT_AFTER_POPUPVIEW = "EVENT_AFTER_POPUPVIEW"; -BI.shortcut("bi.color_chooser", BI.ColorChooser); +} diff --git a/src/case/colorchooser/colorchooser.popup.hex.js b/src/case/colorchooser/colorchooser.popup.hex.js index b8c98cb36..ce0506e95 100644 --- a/src/case/colorchooser/colorchooser.popup.hex.js +++ b/src/case/colorchooser/colorchooser.popup.hex.js @@ -1,41 +1,52 @@ +import { shortcut, Widget, isNotNull, extend, isNotEmptyString, array2String, map, count, string2Array, filter, isArray, Cache, Queue } from "@/core"; +import { Combo } from "@/base"; +import { ColorChooserPopup } from "./colorchooser.popup"; +import { ColorPickerEditor, ColorPicker } from "./colorpicker"; + /** * @author windy * @version 2.0 * Created by windy on 2020/11/10 */ -BI.HexColorChooserPopup = BI.inherit(BI.Widget, { +@shortcut() +export class HexColorChooserPopup extends Widget { + static xtype = "bi.hex_color_chooser_popup"; + + static EVENT_VALUE_CHANGE = "EVENT_VALUE_CHANGE"; + static EVENT_CHANGE = "EVENT_CHANGE"; - props: { + props = { baseCls: "bi-color-chooser-popup", width: 300, recommendColorsGetter: BI.emptyFn, // 推荐色获取接口 - simple: false // 简单模式, popup中没有自动和透明 - }, + simple: false, // 简单模式, popup中没有自动和透明 + } - render: function () { - var self = this, o = this.options; - var hasRecommendColors = BI.isNotNull(o.recommendColorsGetter()); + render() { + const o = this.options; + const hasRecommendColors = isNotNull(o.recommendColorsGetter()); + return [{ type: "bi.vertical", items: [{ el: { type: "bi.vertical", hgap: 15, - items: [BI.extend({ + items: [extend({ type: o.simple ? "bi.simple_hex_color_picker_editor" : "bi.hex_color_picker_editor", value: o.value, height: o.simple ? 36 : 70, listeners: [{ - eventName: BI.ColorPickerEditor.EVENT_CHANGE, - action: function () { - self.setValue(this.getValue()); - self._dealStoreColors(); - self.fireEvent(BI.ColorChooserPopup.EVENT_VALUE_CHANGE, arguments); - } + eventName: ColorPickerEditor.EVENT_CHANGE, + action: (...args) => { + this.setValue(this.colorEditor.getValue()); + this._dealStoreColors(); + this.fireEvent(ColorChooserPopup.EVENT_VALUE_CHANGE, ...args); + }, }], - ref: function (_ref) { - self.colorEditor = _ref; - } + ref: _ref => { + this.colorEditor = _ref; + }, }, o.editor), { el: { type: "bi.hex_color_picker", @@ -44,19 +55,19 @@ BI.HexColorChooserPopup = BI.inherit(BI.Widget, { height: 22, value: o.value, listeners: [{ - eventName: BI.ColorPicker.EVENT_CHANGE, - action: function () { - self.setValue(this.getValue()[0]); - self._dealStoreColors(); - self.fireEvent(BI.ColorChooserPopup.EVENT_CHANGE, arguments); - } + eventName: ColorPicker.EVENT_CHANGE, + action: (...args) => { + this.setValue(this.storeColors.getValue()[0]); + this._dealStoreColors(); + this.fireEvent(ColorChooserPopup.EVENT_CHANGE, ...args); + }, }], - ref: function (_ref) { - self.storeColors = _ref; - } + ref: _ref => { + this.storeColors = _ref; + }, }, tgap: 10, - height: 22 + height: 22, }, { el: hasRecommendColors ? { type: "bi.vertical", @@ -64,7 +75,7 @@ BI.HexColorChooserPopup = BI.inherit(BI.Widget, { type: "bi.label", text: BI.i18nText("BI-Basic_Recommend_Color"), textAlign: "left", - height: 24 + height: 24, }, { type: "bi.hex_color_picker", cls: "bi-border-bottom bi-border-right", @@ -72,27 +83,27 @@ BI.HexColorChooserPopup = BI.inherit(BI.Widget, { height: 22, value: o.value, listeners: [{ - eventName: BI.ColorPicker.EVENT_CHANGE, - action: function () { - self.setValue(this.getValue()[0]); - self._dealStoreColors(); - self.fireEvent(BI.ColorChooserPopup.EVENT_CHANGE, arguments); - } + eventName: ColorPicker.EVENT_CHANGE, + action: (...args) => { + this.setValue(this.recommendColors.getValue()[0]); + this._dealStoreColors(); + this.fireEvent(ColorChooserPopup.EVENT_CHANGE, ...args); + }, }], - ref: function (_ref) { - self.recommendColors = _ref; - } - }] - } : {type: "bi.layout"}, + ref: _ref => { + this.recommendColors = _ref; + }, + }], + } : { type: "bi.layout" }, tgap: hasRecommendColors ? 10 : 0, - height: hasRecommendColors ? 47 : 0 + height: hasRecommendColors ? 47 : 0, }, { el: { type: "bi.layout", - cls: "bi-border-top" + cls: "bi-border-top", }, vgap: 10, - height: 1 + height: 1, }, { type: "bi.absolute", items: [{ @@ -101,25 +112,25 @@ BI.HexColorChooserPopup = BI.inherit(BI.Widget, { space: true, value: o.value, listeners: [{ - eventName: BI.ColorPicker.EVENT_CHANGE, - action: function () { - self.setValue(this.getValue()[0]); - self._dealStoreColors(); - self.fireEvent(BI.ColorChooserPopup.EVENT_CHANGE, arguments); - } + eventName: ColorPicker.EVENT_CHANGE, + action: (...args) => { + this.setValue(this.colorPicker.getValue()[0]); + this._dealStoreColors(); + this.fireEvent(ColorChooserPopup.EVENT_CHANGE, ...args); + }, }], - ref: function (_ref) { - self.colorPicker = _ref; - } + ref: _ref => { + this.colorPicker = _ref; + }, }, top: 0, left: 0, right: 0, - bottom: 1 + bottom: 1, }], - height: 80 - }] - } + height: 80, + }], + }, }, { el: { type: "bi.combo", @@ -133,7 +144,7 @@ BI.HexColorChooserPopup = BI.inherit(BI.Widget, { textAlign: "center", height: 24, textLgap: 10, - text: BI.i18nText("BI-Basic_More") + "..." + text: `${BI.i18nText("BI-Basic_More")}...`, }, popup: { type: "bi.popup_panel", @@ -143,9 +154,9 @@ BI.HexColorChooserPopup = BI.inherit(BI.Widget, { type: "bi.custom_color_chooser", value: o.value, editor: o.editor, - ref: function (_ref) { - self.customColorChooser = _ref; - } + ref: _ref => { + this.customColorChooser = _ref; + }, }, stopPropagation: false, bgap: -1, @@ -154,38 +165,41 @@ BI.HexColorChooserPopup = BI.inherit(BI.Widget, { minWidth: 227, listeners: [{ eventName: BI.PopupPanel.EVENT_CLICK_TOOLBAR_BUTTON, - action: function (index) { + action: (index, ...args) => { switch (index) { - case 0: - self.more.hideView(); - break; - case 1: - var color = self.customColorChooser.getValue(); - // farbtastic选择器没有透明和自动选项,点击保存不应该设置透明 - if (BI.isNotEmptyString(color)) { - self.setValue(color); - self._dealStoreColors(); - } - self.more.hideView(); - self.fireEvent(BI.ColorChooserPopup.EVENT_CHANGE, arguments); - break; + case 0: + this.more.hideView(); + break; + case 1: { + const color = this.customColorChooser.getValue(); + // farbtastic选择器没有透明和自动选项,点击保存不应该设置透明 + if (isNotEmptyString(color)) { + this.setValue(color); + this._dealStoreColors(); + } + this.more.hideView(); + this.fireEvent(ColorChooserPopup.EVENT_CHANGE, index, ...args); + break; } - } - }] + default: + break; + } + }, + }], }, listeners: [{ - eventName: BI.Combo.EVENT_AFTER_POPUPVIEW, - action: function () { - self.customColorChooser.setValue(self.getValue()); - } + eventName: Combo.EVENT_AFTER_POPUPVIEW, + action: () => { + this.customColorChooser.setValue(this.getValue()); + }, }], - ref: function (_ref) { - self.more = _ref; - } + ref: _ref => { + this.more = _ref; + }, }, tgap: 10, - height: 24 - }] + height: 24, + }], }, { type: "bi.absolute", items: [{ @@ -193,89 +207,86 @@ BI.HexColorChooserPopup = BI.inherit(BI.Widget, { type: "bi.layout", cls: "disable-mask", invisible: !o.disabled, - ref: function () { - self.mask = this; - } + ref: () => { + this.mask = this; + }, }, left: 0, right: 0, top: 0, - bottom: 0 - }] + bottom: 0, + }], }]; - }, + } // 这里就实现的不好了,setValue里面有个editor,editor的setValue会检测错误然后出bubble提示 - mounted: function () { - var o = this.options; - if (BI.isNotNull(o.value)) { + mounted() { + const o = this.options; + if (isNotNull(o.value)) { this.setValue(o.value); } - }, + } - _setEnable: function (enable) { - BI.ColorChooserPopup.superclass._setEnable.apply(this, arguments); + _setEnable(enable) { + super._setEnable(...arguments); this.mask.setVisible(!enable); - }, + } - _dealStoreColors: function () { - var color = this.getValue(); - var colors = this._getStoreColors(); - var que = new BI.Queue(12); + _dealStoreColors() { + const color = this.getValue(); + const colors = this._getStoreColors(); + const que = new Queue(12); que.fromArray(colors); que.remove(color); que.unshift(color); - var array = que.toArray(); - BI.Cache.setItem("colors", BI.array2String(array)); + const array = que.toArray(); + Cache.setItem("colors", array2String(array)); this.setStoreColors(array); - }, + } - _digestStoreColors: function (colors) { - var items = BI.map(colors.slice(0, 12), function (i, color) { + _digestStoreColors(colors) { + const items = map(colors.slice(0, 12), (i, color) => { return { - value: color + value: color, }; }); - BI.count(colors.length, 12, function (i) { + count(colors.length, 12, i => { items.push({ value: "empty", - disabled: true + disabled: true, }); }); + return items; - }, + } - _getStoreColors: function () { - var self = this, o = this.options; - var colorsArray = BI.string2Array(BI.Cache.getItem("colors") || ""); - return BI.filter(colorsArray, function (idx, color) { - return o.simple ? self._isRGBColor(color) : true; - }); - }, + _getStoreColors() { + const o = this.options; + const colorsArray = string2Array(Cache.getItem("colors") || ""); + + return filter(colorsArray, (idx, color) => o.simple ? this._isRGBColor(color) : true); + } - _isRGBColor: function (color) { - return BI.isNotEmptyString(color) && color !== "transparent"; - }, + _isRGBColor(color) { + return isNotEmptyString(color) && color !== "transparent"; + } - setStoreColors: function (colors) { - if (BI.isArray(colors)) { + setStoreColors(colors) { + if (isArray(colors)) { this.storeColors.populate([this._digestStoreColors(colors)]); // BI-66973 选中颜色的同时选中历史 this.storeColors.setValue(this.getValue()); } - }, + } - setValue: function (color) { + setValue(color) { this.colorEditor.setValue(color); this.colorPicker.setValue(color); this.storeColors.setValue(color); this.recommendColors && this.recommendColors.setValue(color); - }, + } - getValue: function () { + getValue() { return this.colorEditor.getValue(); } -}); -BI.HexColorChooserPopup.EVENT_VALUE_CHANGE = "EVENT_VALUE_CHANGE"; -BI.HexColorChooserPopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.hex_color_chooser_popup", BI.HexColorChooserPopup); +} diff --git a/src/case/colorchooser/colorchooser.popup.hex.simple.js b/src/case/colorchooser/colorchooser.popup.hex.simple.js index 628ad6f02..608017de2 100644 --- a/src/case/colorchooser/colorchooser.popup.hex.simple.js +++ b/src/case/colorchooser/colorchooser.popup.hex.simple.js @@ -1,50 +1,57 @@ +import { shortcut, Widget } from "@/core"; +import { ColorChooserPopup } from "./colorchooser.popup"; +import { SimpleColorChooserPopup } from "./colorchooser.popup.simple"; + /** * @author windy * @version 2.0 * Created by windy on 2020/11/10 */ -BI.SimpleHexColorChooserPopup = BI.inherit(BI.Widget, { +@shortcut() +export class SimpleHexColorChooserPopup extends Widget { + static xtype = "bi.simple_hex_color_chooser_popup"; + + static EVENT_VALUE_CHANGE = "EVENT_VALUE_CHANGE"; + static EVENT_CHANGE = "EVENT_CHANGE"; - props: { + props = { baseCls: "bi-color-chooser-popup", - }, + } + + render() { + const o = this.options; - render: function () { - var self = this, o = this.options; return { type: "bi.hex_color_chooser_popup", recommendColorsGetter: o.recommendColorsGetter, value: o.value, simple: true, // 是否有自动 listeners: [{ - eventName: BI.ColorChooserPopup.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.SimpleColorChooserPopup.EVENT_CHANGE, arguments); - } + eventName: ColorChooserPopup.EVENT_CHANGE, + action: (...args) => { + this.fireEvent(SimpleColorChooserPopup.EVENT_CHANGE, ...args); + }, }, { - eventName: BI.ColorChooserPopup.EVENT_VALUE_CHANGE, - action: function () { - self.fireEvent(BI.SimpleColorChooserPopup.EVENT_VALUE_CHANGE, arguments); - } + eventName: ColorChooserPopup.EVENT_VALUE_CHANGE, + action: (...args) => { + this.fireEvent(SimpleColorChooserPopup.EVENT_VALUE_CHANGE, ...args); + }, }], - ref: function (_ref) { - self.popup = _ref; - } - } - }, + ref: _ref => { + this.popup = _ref; + }, + }; + } - setStoreColors: function (colors) { + setStoreColors(colors) { this.popup.setStoreColors(colors); - }, + } - setValue: function (color) { + setValue(color) { this.popup.setValue(color); - }, + } - getValue: function () { + getValue() { return this.popup.getValue(); } -}); -BI.SimpleHexColorChooserPopup.EVENT_VALUE_CHANGE = "EVENT_VALUE_CHANGE"; -BI.SimpleHexColorChooserPopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.simple_hex_color_chooser_popup", BI.SimpleHexColorChooserPopup); \ No newline at end of file +} diff --git a/src/case/colorchooser/colorchooser.popup.js b/src/case/colorchooser/colorchooser.popup.js index c73fd91fc..7580e7a52 100644 --- a/src/case/colorchooser/colorchooser.popup.js +++ b/src/case/colorchooser/colorchooser.popup.js @@ -1,67 +1,76 @@ +import { shortcut, Widget, createWidget, Cache, string2Array, isNotNull, Queue, array2String, map, count, filter, isNotEmptyString, isArray } from "@/core"; +import { Combo } from "@/base"; +import { ColorPickerEditor, ColorPicker } from "./colorpicker"; + /** * 选色控件 * * Created by GUY on 2015/11/17. - * @class BI.ColorChooserPopup - * @extends BI.Widget + * @class ColorChooserPopup + * @extends Widget */ -BI.ColorChooserPopup = BI.inherit(BI.Widget, { +@shortcut() +export class ColorChooserPopup extends Widget { + static xtype = "bi.color_chooser_popup"; + + static EVENT_VALUE_CHANGE = "EVENT_VALUE_CHANGE"; + static EVENT_CHANGE = "EVENT_CHANGE"; - props: { + props = { baseCls: "bi-color-chooser-popup", width: 230, height: 145, - simple: false // 简单模式, popup中没有自动和透明 - }, + simple: false, // 简单模式, popup中没有自动和透明 + } - render: function () { - var self = this, o = this.options; - this.colorEditor = BI.createWidget(o.editor, { + render () { + const o = this.options; + this.colorEditor = createWidget(o.editor, { type: o.simple ? "bi.simple_color_picker_editor" : "bi.color_picker_editor", value: o.value, cls: "bi-header-background bi-border-bottom", - height: 30 + height: 30, }); - this.colorEditor.on(BI.ColorPickerEditor.EVENT_CHANGE, function () { - self.setValue(this.getValue()); - self._dealStoreColors(); - self.fireEvent(BI.ColorChooserPopup.EVENT_VALUE_CHANGE, arguments); + this.colorEditor.on(ColorPickerEditor.EVENT_CHANGE, (...args) => { + this.setValue(this.colorEditor.getValue()); + this._dealStoreColors(); + this.fireEvent(ColorChooserPopup.EVENT_VALUE_CHANGE, ...args); }); - this.storeColors = BI.createWidget({ + this.storeColors = createWidget({ type: "bi.color_picker", cls: "bi-border-bottom bi-border-right", items: [this._digestStoreColors(this._getStoreColors())], width: 210, height: 24, - value: o.value + value: o.value, }); - this.storeColors.on(BI.ColorPicker.EVENT_CHANGE, function () { - self.setValue(this.getValue()[0]); - self._dealStoreColors(); - self.fireEvent(BI.ColorChooserPopup.EVENT_CHANGE, arguments); + this.storeColors.on(ColorPicker.EVENT_CHANGE, (...args) => { + this.setValue(this.storeColors.getValue()[0]); + this._dealStoreColors(); + this.fireEvent(ColorChooserPopup.EVENT_CHANGE, ...args); }); - this.colorPicker = BI.createWidget({ + this.colorPicker = createWidget({ type: "bi.color_picker", width: 210, height: 50, - value: o.value + value: o.value, }); - this.colorPicker.on(BI.ColorPicker.EVENT_CHANGE, function () { - self.setValue(this.getValue()[0]); - self._dealStoreColors(); - self.fireEvent(BI.ColorChooserPopup.EVENT_CHANGE, arguments); + this.colorPicker.on(ColorPicker.EVENT_CHANGE, (...args) => { + this.setValue(this.colorPicker.getValue()[0]); + this._dealStoreColors(); + this.fireEvent(ColorChooserPopup.EVENT_CHANGE, ...args); }); - this.customColorChooser = BI.createWidget({ + this.customColorChooser = createWidget({ type: "bi.custom_color_chooser", - editor: o.editor + editor: o.editor, }); - var panel = BI.createWidget({ + const panel = createWidget({ type: "bi.popup_panel", buttons: [BI.i18nText("BI-Basic_Cancel"), BI.i18nText("BI-Basic_Save")], title: BI.i18nText("BI-Custom_Color"), @@ -70,10 +79,10 @@ BI.ColorChooserPopup = BI.inherit(BI.Widget, { bgap: -1, rgap: 1, lgap: 1, - minWidth: 227 + minWidth: 227, }); - this.more = BI.createWidget({ + this.more = createWidget({ type: "bi.combo", cls: "bi-border-top", container: null, @@ -85,25 +94,27 @@ BI.ColorChooserPopup = BI.inherit(BI.Widget, { textAlign: "center", height: 24, textLgap: 10, - text: BI.i18nText("BI-Basic_More") + "..." + text: `${BI.i18nText("BI-Basic_More")}...`, }, - popup: panel + popup: panel, }); - this.more.on(BI.Combo.EVENT_AFTER_POPUPVIEW, function () { - self.customColorChooser.setValue(self.getValue()); + this.more.on(Combo.EVENT_AFTER_POPUPVIEW, () => { + this.customColorChooser.setValue(this.getValue()); }); - panel.on(BI.PopupPanel.EVENT_CLICK_TOOLBAR_BUTTON, function (index) { + panel.on(BI.PopupPanel.EVENT_CLICK_TOOLBAR_BUTTON, (index, ...args) => { switch (index) { - case 0: - self.more.hideView(); - break; - case 1: - self.setValue(self.customColorChooser.getValue()); - self._dealStoreColors(); - self.more.hideView(); - self.fireEvent(BI.ColorChooserPopup.EVENT_CHANGE, arguments); - break; + case 0: + this.more.hideView(); + break; + case 1: + this.setValue(this.customColorChooser.getValue()); + this._dealStoreColors(); + this.more.hideView(); + this.fireEvent(ColorChooserPopup.EVENT_CHANGE, index, ...args); + break; + default: + break; } }); @@ -119,10 +130,10 @@ BI.ColorChooserPopup = BI.inherit(BI.Widget, { el: this.storeColors, left: 10, right: 10, - top: 5 - }] + top: 5, + }], }, - height: 29 + height: 29, }, { el: { type: "bi.absolute", @@ -131,107 +142,103 @@ BI.ColorChooserPopup = BI.inherit(BI.Widget, { left: 10, right: 10, top: 5, - bottom: 5 - }] + bottom: 5, + }], }, - height: 60 + height: 60, }, { el: this.more, - height: 24 - }] + height: 24, + }], }, left: 0, right: 0, top: 0, - bottom: 0 + bottom: 0, }, { el: { type: "bi.layout", cls: "disable-mask", invisible: !o.disabled, - ref: function () { - self.mask = this; - } + ref: () => { + this.mask = this; + }, }, left: 0, right: 0, top: 0, - bottom: 0 - }] + bottom: 0, + }], }; - }, + } // 这里就实现的不好了,setValue里面有个editor,editor的setValue会检测错误然后出bubble提示 - mounted: function () { - var self = this; - var o = this.options; - if (BI.isNotNull(o.value)) { + mounted () { + const o = this.options; + if (isNotNull(o.value)) { this.setValue(o.value); } - }, + } - _setEnable: function (enable) { - BI.ColorChooserPopup.superclass._setEnable.apply(this, arguments); + _setEnable (enable) { + super._setEnable(...arguments); this.mask.setVisible(!enable); - }, + } - _dealStoreColors: function () { - var color = this.getValue(); - var colors = this._getStoreColors(); - var que = new BI.Queue(8); + _dealStoreColors () { + const color = this.getValue(); + const colors = this._getStoreColors(); + const que = new Queue(8); que.fromArray(colors); que.remove(color); que.unshift(color); - var array = que.toArray(); - BI.Cache.setItem("colors", BI.array2String(array)); + const array = que.toArray(); + Cache.setItem("colors", array2String(array)); this.setStoreColors(array); - }, + } - _digestStoreColors: function (colors) { - var items = BI.map(colors, function (i, color) { + _digestStoreColors (colors) { + const items = map(colors, (i, color) => { return { - value: color + value: color, }; }); - BI.count(colors.length, 8, function (i) { + count(colors.length, 8, i => { items.push({ value: "", - disabled: true + disabled: true, }); }); + return items; - }, + } - _getStoreColors: function() { - var self = this, o = this.options; - var colorsArray = BI.string2Array(BI.Cache.getItem("colors") || ""); - return BI.filter(colorsArray, function (idx, color) { - return o.simple ? self._isRGBColor(color) : true; - }); - }, + _getStoreColors() { + const o = this.options; + const colorsArray = string2Array(Cache.getItem("colors") || ""); + + return filter(colorsArray, (idx, color) => o.simple ? this._isRGBColor(color) : true); + } - _isRGBColor: function (color) { - return BI.isNotEmptyString(color) && color !== "transparent"; - }, + _isRGBColor (color) { + return isNotEmptyString(color) && color !== "transparent"; + } - setStoreColors: function (colors) { - if (BI.isArray(colors)) { + setStoreColors (colors) { + if (isArray(colors)) { this.storeColors.populate([this._digestStoreColors(colors)]); // BI-66973 选中颜色的同时选中历史 this.storeColors.setValue(this.getValue()); } - }, + } - setValue: function (color) { + setValue (color) { this.colorEditor.setValue(color); this.colorPicker.setValue(color); this.storeColors.setValue(color); - }, + } - getValue: function () { + getValue () { return this.colorEditor.getValue(); } -}); -BI.ColorChooserPopup.EVENT_VALUE_CHANGE = "EVENT_VALUE_CHANGE"; -BI.ColorChooserPopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.color_chooser_popup", BI.ColorChooserPopup); +} diff --git a/src/case/colorchooser/colorchooser.popup.simple.js b/src/case/colorchooser/colorchooser.popup.simple.js index 54b34cec4..99a66d461 100644 --- a/src/case/colorchooser/colorchooser.popup.simple.js +++ b/src/case/colorchooser/colorchooser.popup.simple.js @@ -1,47 +1,52 @@ +import { shortcut, Widget, extend, createWidget } from "@/core"; +import { ColorChooserPopup } from "./colorchooser.popup"; + /** * 选色控件 * * Created by GUY on 2015/11/17. - * @class BI.SimpleColorChooserPopup - * @extends BI.Widget + * @class SimpleColorChooserPopup + * @extends Widget */ -BI.SimpleColorChooserPopup = BI.inherit(BI.Widget, { +@shortcut() +export class SimpleColorChooserPopup extends Widget { + static xtype = "bi.simple_color_chooser_popup"; + + static EVENT_VALUE_CHANGE = "EVENT_VALUE_CHANGE"; + static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig: function () { - return BI.extend(BI.SimpleColorChooserPopup.superclass._defaultConfig.apply(this, arguments), { - baseCls: "bi-color-chooser-popup" + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { + baseCls: "bi-color-chooser-popup", }); - }, + } - _init: function () { - BI.SimpleColorChooserPopup.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.popup = BI.createWidget({ - type: o.hex ? "bi.hex_color_chooser_popup" : "bi.color_chooser_popup", - value: o.value, + _init() { + super._init(...arguments); + const { hex, value } = this.options; + this.popup = createWidget({ + type: hex ? "bi.hex_color_chooser_popup" : "bi.color_chooser_popup", + value, element: this, - simple: true // 是否有自动 + simple: true, // 是否有自动 }); - this.popup.on(BI.ColorChooserPopup.EVENT_CHANGE, function () { - self.fireEvent(BI.SimpleColorChooserPopup.EVENT_CHANGE, arguments); + this.popup.on(ColorChooserPopup.EVENT_CHANGE, (...args) => { + this.fireEvent(SimpleColorChooserPopup.EVENT_CHANGE, ...args); }); - this.popup.on(BI.ColorChooserPopup.EVENT_VALUE_CHANGE, function () { - self.fireEvent(BI.SimpleColorChooserPopup.EVENT_VALUE_CHANGE, arguments); + this.popup.on(ColorChooserPopup.EVENT_VALUE_CHANGE, (...args) => { + this.fireEvent(SimpleColorChooserPopup.EVENT_VALUE_CHANGE, ...args); }); - }, + } - setStoreColors: function (colors) { + setStoreColors(colors) { this.popup.setStoreColors(colors); - }, + } - setValue: function (color) { + setValue(color) { this.popup.setValue(color); - }, + } - getValue: function () { + getValue() { return this.popup.getValue(); } -}); -BI.SimpleColorChooserPopup.EVENT_VALUE_CHANGE = "EVENT_VALUE_CHANGE"; -BI.SimpleColorChooserPopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.simple_color_chooser_popup", BI.SimpleColorChooserPopup); \ No newline at end of file +} diff --git a/src/case/colorchooser/colorchooser.simple.js b/src/case/colorchooser/colorchooser.simple.js index 28517ea6d..6cf9d9ded 100644 --- a/src/case/colorchooser/colorchooser.simple.js +++ b/src/case/colorchooser/colorchooser.simple.js @@ -1,24 +1,32 @@ +import { shortcut, Widget, extend, createWidget } from "@/core"; +import { ColorChooser } from "./colorchooser"; + /** * 简单选色控件,没有自动和透明 * * Created by GUY on 2015/11/17. - * @class BI.SimpleColorChooser - * @extends BI.Widget + * @class SimpleColorChooser + * @extends Widget */ -BI.SimpleColorChooser = BI.inherit(BI.Widget, { +@shortcut() +export class SimpleColorChooser extends Widget { + static xtype = "bi.simple_color_chooser"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_AFTER_POPUPVIEW = "EVENT_AFTER_POPUPVIEW"; - _defaultConfig: function () { - return BI.extend(BI.SimpleColorChooser.superclass._defaultConfig.apply(this, arguments), { + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-simple-color-chooser", - value: "#ffffff" + value: "#ffffff", }); - }, + } - _init: function () { - BI.SimpleColorChooser.superclass._init.apply(this, arguments); - var self = this, o = this.options; + _init() { + super._init(...arguments); + const o = this.options; - this.combo = BI.createWidget({ + this.combo = createWidget({ type: "bi.color_chooser", simple: o.simple, element: this, @@ -30,36 +38,33 @@ BI.SimpleColorChooser = BI.inherit(BI.Widget, { popup: { type: "bi.simple_hex_color_chooser_popup", recommendColorsGetter: o.recommendColorsGetter, - } + }, }); - this.combo.on(BI.ColorChooser.EVENT_CHANGE, function () { - self.fireEvent(BI.SimpleColorChooser.EVENT_CHANGE, arguments); + this.combo.on(ColorChooser.EVENT_CHANGE, (...args) => { + this.fireEvent(SimpleColorChooser.EVENT_CHANGE, ...args); }); - this.combo.on(BI.ColorChooser.EVENT_AFTER_POPUPVIEW, function () { - self.fireEvent(BI.SimpleColorChooser.EVENT_AFTER_POPUPVIEW, arguments); + this.combo.on(ColorChooser.EVENT_AFTER_POPUPVIEW, (...args) => { + this.fireEvent(SimpleColorChooser.EVENT_AFTER_POPUPVIEW, ...args); }); - }, + } - isViewVisible: function () { + isViewVisible() { return this.combo.isViewVisible(); - }, + } - hideView: function () { + hideView() { this.combo.hideView(); - }, + } - showView: function () { + showView() { this.combo.showView(); - }, + } - setValue: function (color) { + setValue(color) { this.combo.setValue(color); - }, + } - getValue: function () { + getValue() { return this.combo.getValue(); } -}); -BI.SimpleColorChooser.EVENT_CHANGE = "EVENT_CHANGE"; -BI.SimpleColorChooser.EVENT_AFTER_POPUPVIEW = "EVENT_AFTER_POPUPVIEW"; -BI.shortcut("bi.simple_color_chooser", BI.SimpleColorChooser); +} diff --git a/src/case/colorchooser/colorchooser.trigger.js b/src/case/colorchooser/colorchooser.trigger.js index af2039226..1187a8460 100644 --- a/src/case/colorchooser/colorchooser.trigger.js +++ b/src/case/colorchooser/colorchooser.trigger.js @@ -1,36 +1,44 @@ +import { shortcut, extend, createWidget, isNotNull } from "@/core"; +import { Trigger } from "@/base"; + /** * 选色控件 * * Created by GUY on 2015/11/17. - * @class BI.ColorChooserTrigger - * @extends BI.Trigger + * @class ColorChooserTrigger + * @extends Trigger */ -BI.ColorChooserTrigger = BI.inherit(BI.Trigger, { +@shortcut() +export class ColorChooserTrigger extends Trigger { + static xtype = "bi.color_chooser_trigger"; + + static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig: function (config) { - var conf = BI.ColorChooserTrigger.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-color-chooser-trigger bi-focus-shadow " + (config.simple ? "bi-border-bottom" : "bi-border bi-border-radius"), - height: 22 + _defaultConfig (config) { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-color-chooser-trigger bi-focus-shadow ${config.simple ? "bi-border-bottom" : "bi-border bi-border-radius"}`, + height: 22, }); - }, + } - _init: function () { - BI.ColorChooserTrigger.superclass._init.apply(this, arguments); - this.colorContainer = BI.createWidget({ + _init () { + super._init(...arguments); + this.colorContainer = createWidget({ type: "bi.layout", cls: "color-chooser-trigger-content" + (BI.isIE9Below && BI.isIE9Below() ? " hack" : "") }); - var down = BI.createWidget({ + const down = createWidget({ type: "bi.icon_button", disableSelected: true, cls: "icon-combo-down-icon trigger-triangle-font icon-size-12", width: 12, - height: 8 + height: 8, }); - BI.createWidget({ + createWidget({ type: "bi.absolute", element: this, items: [{ @@ -38,28 +46,26 @@ BI.ColorChooserTrigger = BI.inherit(BI.Trigger, { left: 2, right: 2, top: 2, - bottom: 2 + bottom: 2, }, { el: down, right: -1, - bottom: 1 - }] + bottom: 1, + }], }); - if (BI.isNotNull(this.options.value)) { + if (isNotNull(this.options.value)) { this.setValue(this.options.value); } - }, + } - setValue: function (color) { - BI.ColorChooserTrigger.superclass.setValue.apply(this, arguments); + setValue (color) { + super.setValue(...arguments); if (color === "") { this.colorContainer.element.css("background-color", "").removeClass("trans-color-background").addClass("auto-color-background"); } else if (color === "transparent") { this.colorContainer.element.css("background-color", "").removeClass("auto-color-background").addClass("trans-color-background"); } else { - this.colorContainer.element.css({"background-color": color}).removeClass("auto-color-background").removeClass("trans-color-background"); + this.colorContainer.element.css({ "background-color": color }).removeClass("auto-color-background").removeClass("trans-color-background"); } } -}); -BI.ColorChooserTrigger.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.color_chooser_trigger", BI.ColorChooserTrigger); +} diff --git a/src/case/colorchooser/colorchooser.trigger.long.js b/src/case/colorchooser/colorchooser.trigger.long.js index 773b3d326..8210e111e 100644 --- a/src/case/colorchooser/colorchooser.trigger.long.js +++ b/src/case/colorchooser/colorchooser.trigger.long.js @@ -1,59 +1,66 @@ +import { shortcut, extend, createWidget } from "@/core"; +import { Trigger } from "@/base"; + /** * 选色控件 * * Created by GUY on 2015/11/17. - * @class BI.LongColorChooserTrigger - * @extends BI.Trigger + * @class LongColorChooserTrigger + * @extends Trigger */ -BI.LongColorChooserTrigger = BI.inherit(BI.Trigger, { +@shortcut() +export class LongColorChooserTrigger extends Trigger { + static xtype = "bi.long_color_chooser_trigger"; + + static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig: function (config) { - var conf = BI.LongColorChooserTrigger.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-color-chooser-trigger bi-focus-shadow " + (config.simple ? "bi-border-bottom" : "bi-border bi-border-radius"), - height: 24 + _defaultConfig (config) { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-color-chooser-trigger bi-focus-shadow ${config.simple ? "bi-border-bottom" : "bi-border bi-border-radius"}`, + height: 24, }); - }, + } - _init: function () { - BI.LongColorChooserTrigger.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.colorContainer = BI.createWidget({ + _init () { + super._init(...arguments); + this.colorContainer = createWidget({ type: "bi.htape", cls: "color-chooser-trigger-content", items: [{ type: "bi.icon_change_button", - ref: function (_ref) { - self.changeIcon = _ref; + ref: _ref => { + this.changeIcon = _ref; }, disableSelected: true, iconCls: "auto-color-icon", width: 24, iconWidth: 16, - iconHeight: 16 + iconHeight: 16, }, { el: { type: "bi.label", - ref: function (_ref) { - self.label = _ref; + ref: _ref => { + this.label = _ref; }, textAlign: "left", hgap: 5, height: 18, - text: BI.i18nText("BI-Basic_Auto") - } - }] + text: BI.i18nText("BI-Basic_Auto"), + }, + }], }); - var down = BI.createWidget({ + const down = createWidget({ type: "bi.icon_button", disableSelected: true, cls: "icon-combo-down-icon trigger-triangle-font icon-size-12", width: 12, - height: 8 + height: 8, }); - BI.createWidget({ + createWidget({ type: "bi.absolute", element: this, items: [{ @@ -61,20 +68,20 @@ BI.LongColorChooserTrigger = BI.inherit(BI.Trigger, { left: 2, right: 2, top: 2, - bottom: 2 + bottom: 2, }, { el: down, right: 3, - bottom: 3 - }] + bottom: 3, + }], }); if (this.options.value) { this.setValue(this.options.value); } - }, + } - setValue: function (color) { - BI.LongColorChooserTrigger.superclass.setValue.apply(this, arguments); + setValue (color) { + super.setValue(...arguments); if (color === "") { this.colorContainer.element.css("background-color", ""); this.changeIcon.setVisible(true); @@ -88,11 +95,9 @@ BI.LongColorChooserTrigger = BI.inherit(BI.Trigger, { this.changeIcon.setIcon("trans-color-icon"); this.label.setText(BI.i18nText("BI-Transparent_Color")); } else { - this.colorContainer.element.css({"background-color": color}); + this.colorContainer.element.css({ "background-color": color }); this.changeIcon.setVisible(false); this.label.setVisible(false); } } -}); -BI.LongColorChooserTrigger.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.long_color_chooser_trigger", BI.LongColorChooserTrigger); +} diff --git a/src/case/colorchooser/colorpicker/button/button.colorpicker.js b/src/case/colorchooser/colorpicker/button/button.colorpicker.js index d3ebf5300..e690eb1f3 100644 --- a/src/case/colorchooser/colorpicker/button/button.colorpicker.js +++ b/src/case/colorchooser/colorpicker/button/button.colorpicker.js @@ -1,66 +1,72 @@ +import { shortcut, isNotNull, extend } from "@/core"; +import { BasicButton, Maskers } from "@/base"; + /** * 简单选色控件按钮 * * Created by GUY on 2015/11/16. - * @class BI.ColorPickerButton - * @extends BI.BasicButton + * @class ColorPickerButton + * @extends BasicButton */ -BI.ColorPickerButton = BI.inherit(BI.BasicButton, { +@shortcut() +export class ColorPickerButton extends BasicButton { + static xtype = "bi.color_picker_button"; + + static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig: function () { - var conf = BI.ColorPickerButton.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-color-picker-button bi-background bi-border-top bi-border-left" + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-color-picker-button bi-background bi-border-top bi-border-left`, }); - }, + } - _init: function () { - BI.ColorPickerButton.superclass._init.apply(this, arguments); - var self = this, o = this.options; - if (BI.isNotNull(o.value)) { - if (o.value === '') { + _init() { + super._init(...arguments); + const o = this.options; + if (isNotNull(o.value)) { + if (o.value === "") { this.element.addClass("auto-color-no-square-normal-background"); } else if (o.value === "transparent") { this.element.addClass("trans-color-background"); } else { this.element.css("background-color", o.value); } - var name = this.getName(); - this.element.hover(function () { - self._createMask(); - if (self.isEnabled()) { - BI.Maskers.show(name); + const name = this.getName(); + this.element.hover(() => { + this._createMask(); + if (this.isEnabled()) { + Maskers.show(name); } - }, function () { - if (!self.isSelected()) { - BI.Maskers.hide(name); + }, () => { + if (!this.isSelected()) { + Maskers.hide(name); } }); } - }, + } - _createMask: function () { - var o = this.options, name = this.getName(); - if (this.isEnabled() && !BI.Maskers.has(name)) { - var w = BI.Maskers.make(name, this, { + _createMask() { + const o = this.options, name = this.getName(); + if (this.isEnabled() && !Maskers.has(name)) { + const w = Maskers.make(name, this, { offset: { left: -1, top: -1, right: -1, - bottom: -1 - } + bottom: -1, + }, }); w.element.addClass("color-picker-button-mask").css("background-color", o.value); } - }, + } - setSelected: function (b) { - BI.ColorPickerButton.superclass.setSelected.apply(this, arguments); + setSelected(b) { + super.setSelected(...arguments); if (b) { this._createMask(); } - BI.Maskers[b ? "show" : "hide"](this.getName()); + Maskers[b ? "show" : "hide"](this.getName()); } -}); -BI.ColorPickerButton.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.color_picker_button", BI.ColorPickerButton); \ No newline at end of file +} diff --git a/src/case/colorchooser/colorpicker/button/button.colorshow.js b/src/case/colorchooser/colorpicker/button/button.colorshow.js index c9b2da438..104dfabf2 100644 --- a/src/case/colorchooser/colorpicker/button/button.colorshow.js +++ b/src/case/colorchooser/colorpicker/button/button.colorshow.js @@ -1,24 +1,32 @@ +import { shortcut } from "@/core"; +import { BasicButton } from "@/base"; + /** * @author windy * @version 2.0 * Created by windy on 2021/7/28 */ -BI.ColorChooserShowButton = BI.inherit(BI.BasicButton, { +@shortcut() +export class ColorChooserShowButton extends BasicButton { + static xtype = "bi.color_picker_show_button"; + + static EVENT_CHANGE = "EVENT_CHANGE"; - props: { - baseCls: 'bi-color-chooser-show-button bi-border bi-list-item-effect bi-border-radius', - }, + props = { + baseCls: "bi-color-chooser-show-button bi-border bi-list-item-effect bi-border-radius", + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; + return { - type: 'bi.htape', + type: "bi.htape", items: [ { el: { type: "bi.icon_label", - ref: function (_ref) { - self.icon = _ref; + ref: _ref => { + this.icon = _ref; }, iconWidth: 16, iconHeight: 16, @@ -26,20 +34,18 @@ BI.ColorChooserShowButton = BI.inherit(BI.BasicButton, { hgap: 20, width: 16, }, { - type: 'bi.label', - textAlign: 'left', + type: "bi.label", + textAlign: "left", text: o.text, } - ] + ], }; - }, + } - doClick: function () { - BI.ColorChooserShowButton.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick(...arguments); if (this.isValid()) { - this.fireEvent(BI.ColorChooserShowButton.EVENT_CHANGE, this); + this.fireEvent(ColorChooserShowButton.EVENT_CHANGE, this); } - }, -}); -BI.ColorChooserShowButton.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.color_picker_show_button", BI.ColorChooserShowButton); + } +} diff --git a/src/case/colorchooser/colorpicker/button/index.js b/src/case/colorchooser/colorpicker/button/index.js new file mode 100644 index 000000000..59b5c9378 --- /dev/null +++ b/src/case/colorchooser/colorpicker/button/index.js @@ -0,0 +1,2 @@ +export { ColorPickerButton } from "./button.colorpicker"; +export { ColorChooserShowButton } from "./button.colorshow"; \ No newline at end of file diff --git a/src/case/colorchooser/colorpicker/colorpicker.hex.js b/src/case/colorchooser/colorpicker/colorpicker.hex.js index 8154b9c23..5a1b4162b 100644 --- a/src/case/colorchooser/colorpicker/colorpicker.hex.js +++ b/src/case/colorchooser/colorpicker/colorpicker.hex.js @@ -1,166 +1,173 @@ +import { shortcut, Widget, extend, each } from "@/core"; +import { ButtonGroup } from "@/base"; + /** * @author windy * @version 2.0 * Created by windy on 2021/7/28 */ -BI.HexColorPicker = BI.inherit(BI.Widget, { +@shortcut() +export class HexColorPicker extends Widget { + static xtype = "bi.hex_color_picker"; + + static EVENT_CHANGE = "EVENT_CHANGE"; - props: { + props = { baseCls: "bi-hex-color-picker", items: null, - }, + } - _items: [ + _items = [ [ { - "value": "#999999" + value: "#999999", }, { - "value": "#FFFFFF" + value: "#FFFFFF", }, { - "value": "#FFE5E5" + value: "#FFE5E5", }, { - "value": "#FFF1E5" + value: "#FFF1E5", }, { - "value": "#FFF9E5" + value: "#FFF9E5", }, { - "value": "#E9F5E9" + value: "#E9F5E9", }, { - "value": "#EAEEFF" + value: "#EAEEFF", }, { - "value": "#EFEBF7" + value: "#EFEBF7", }, { - "value": "#FCE8EF" + value: "#FCE8EF", } ], [ { - "value": "#737373" + value: "#737373", }, { - "value": "#F2F2F2" + value: "#F2F2F2", }, { - "value": "#FFA6A6" + value: "#FFA6A6", }, { - "value": "#FFD0A6" + value: "#FFD0A6", }, { - "value": "#FFEDA6" + value: "#FFEDA6", }, { - "value": "#B3DCB2" + value: "#B3DCB2", }, { - "value": "#B9C6FF" + value: "#B9C6FF", }, { - "value": "#CABAE6" + value: "#CABAE6", }, { - "value": "#F8B1C9" + value: "#F8B1C9", } ], [ { - "value": "#4C4C4C" + value: "#4C4C4C", }, { - "value": "#D9D9D9" + value: "#D9D9D9", }, { - "value": "#FF5959" + value: "#FF5959", }, { - "value": "#FFA759" + value: "#FFA759", }, { - "value": "#FFDD59" + value: "#FFDD59", }, { - "value": "#7EBE70" + value: "#7EBE70", }, { - "value": "#7B95FF" + value: "#7B95FF", }, { - "value": "#9C7FD0" + value: "#9C7FD0", }, { - "value": "#F06D99" + value: "#F06D99", } ], [ { - "value": "#262626" + value: "#262626", }, { - "value": "#BFBFBF" + value: "#BFBFBF", }, { - "value": "#FF0000" + value: "#FF0000", }, { - "value": "#FF7800" + value: "#FF7800", }, { - "value": "#FFCB00" + value: "#FFCB00", }, { - "value": "#259B23" + value: "#259B23", }, { - "value": "#355CFF" + value: "#355CFF", }, { - "value": "#673AB7" + value: "#673AB7", }, { - "value": "#E91E63" + value: "#E91E63", } ], [ { - "value": "#000000" + value: "#000000", }, { - "value": "#A6A6A6" + value: "#A6A6A6", }, { - "value": "#A80000" + value: "#A80000", }, { - "value": "#B65600" + value: "#B65600", }, { - "value": "#CEB000" + value: "#CEB000", }, { - "value": "#0E550C" + value: "#0E550C", }, { - "value": "#09269C" + value: "#09269C", }, { - "value": "#3A1A73" + value: "#3A1A73", }, { - "value": "#B30072" + value: "#B30072", } ] - ], + ] + + render() { + const o = this.options; - render: function () { - var self = this, o = this.options; - return { type: "bi.button_group", items: this._digest(o.items || this._items), @@ -172,52 +179,50 @@ BI.HexColorPicker = BI.inherit(BI.Widget, { value: o.value, listeners: [ { - eventName: BI.ButtonGroup.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.HexColorPicker.EVENT_CHANGE, arguments); - } + eventName: ButtonGroup.EVENT_CHANGE, + action: (...args) => { + this.fireEvent(HexColorPicker.EVENT_CHANGE, ...args); + }, } ], - ref: function (_ref) { - self.colors = _ref; - } + ref: _ref => { + this.colors = _ref; + }, }; - }, + } - _digest: function (items) { - var o = this.options; - var blocks = []; - BI.each(items, function (idx, row) { - var bRow = []; - BI.each(row, function (idx, item) { - bRow.push(BI.extend({ + _digest(items) { + const o = this.options; + const blocks = []; + each(items, (idx, row) => { + const bRow = []; + each(row, (idx, item) => { + bRow.push(extend({ type: "bi.color_picker_button", once: false, - cls: o.space ? 'bi-border-right' : '', + cls: o.space ? "bi-border-right" : "", }, item)); if (o.space && idx < row.length - 1) { - bRow.push({ type: 'bi.layout' }); + bRow.push({ type: "bi.layout" }); } }); blocks.push(bRow); }); return blocks; - }, + } - populate: function (items) { - var args = [].slice.call(arguments); + populate(items) { + const args = [].slice.call(arguments); args[0] = this._digest(items); this.colors.populate.apply(this.colors, args); - }, + } - setValue: function (color) { + setValue(color) { this.colors.setValue(color); - }, + } - getValue: function () { + getValue() { return this.colors.getValue(); } -}); -BI.HexColorPicker.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.hex_color_picker", BI.HexColorPicker); +} diff --git a/src/case/colorchooser/colorpicker/colorpicker.js b/src/case/colorchooser/colorpicker/colorpicker.js index 54a827400..fa4bd5c9d 100644 --- a/src/case/colorchooser/colorpicker/colorpicker.js +++ b/src/case/colorchooser/colorpicker/colorpicker.js @@ -1,190 +1,195 @@ +import { shortcut, Widget, extend, createItems, createWidget } from "@/core"; +import { ButtonGroup } from "@/base"; + /** * 简单选色控件 * * Created by GUY on 2015/11/16. - * @class BI.ColorPicker - * @extends BI.Widget + * @class ColorPicker + * @extends Widget */ -BI.ColorPicker = BI.inherit(BI.Widget, { +@shortcut() +export class ColorPicker extends Widget { + static xtype = "bi.color_picker"; + + static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig: function () { - return BI.extend(BI.ColorPicker.superclass._defaultConfig.apply(this, arguments), { + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-color-picker", - items: null + items: null, }); - }, + } - _items: [ + _items = [ [{ - value: "#ffffff" + value: "#ffffff", }, { - value: "#f2f2f2" + value: "#f2f2f2", }, { - value: "#e5e5e5" + value: "#e5e5e5", }, { - value: "#d9d9d9" + value: "#d9d9d9", }, { - value: "#cccccc" + value: "#cccccc", }, { - value: "#bfbfbf" + value: "#bfbfbf", }, { - value: "#b2b2b2" + value: "#b2b2b2", }, { - value: "#a6a6a6" + value: "#a6a6a6", }, { - value: "#999999" + value: "#999999", }, { - value: "#8c8c8c" + value: "#8c8c8c", }, { - value: "#808080" + value: "#808080", }, { - value: "#737373" + value: "#737373", }, { - value: "#666666" + value: "#666666", }, { - value: "#4d4d4d" + value: "#4d4d4d", }, { - value: "#333333" + value: "#333333", }, { - value: "#000000" + value: "#000000", }], [{ - value: "#d8b5a6" + value: "#d8b5a6", }, { - value: "#ff9e9a" + value: "#ff9e9a", }, { - value: "#ffc17d" + value: "#ffc17d", }, { - value: "#f5e56b" + value: "#f5e56b", }, { - value: "#d8e698" + value: "#d8e698", }, { - value: "#e0ebaf" + value: "#e0ebaf", }, { - value: "#c3d825" + value: "#c3d825", }, { - value: "#bbe2e7" + value: "#bbe2e7", }, { - value: "#85d3cd" + value: "#85d3cd", }, { - value: "#bde1e6" + value: "#bde1e6", }, { - value: "#a0d8ef" + value: "#a0d8ef", }, { - value: "#89c3eb" + value: "#89c3eb", }, { - value: "#bbc8e6" + value: "#bbc8e6", }, { - value: "#bbbcde" + value: "#bbbcde", }, { - value: "#d6b4cc" + value: "#d6b4cc", }, { - value: "#fbc0d3" + value: "#fbc0d3", }], [{ - value: "#bb9581" + value: "#bb9581", }, { - value: "#f37d79" + value: "#f37d79", }, { - value: "#fba74f" + value: "#fba74f", }, { - value: "#ffdb4f" + value: "#ffdb4f", }, { - value: "#c7dc68" + value: "#c7dc68", }, { - value: "#b0ca71" + value: "#b0ca71", }, { - value: "#99ab4e" + value: "#99ab4e", }, { - value: "#84b9cb" + value: "#84b9cb", }, { - value: "#00a3af" + value: "#00a3af", }, { - value: "#2ca9e1" + value: "#2ca9e1", }, { - value: "#0095d9" + value: "#0095d9", }, { - value: "#4c6cb3" + value: "#4c6cb3", }, { - value: "#8491c3" + value: "#8491c3", }, { - value: "#a59aca" + value: "#a59aca", }, { - value: "#cc7eb1" + value: "#cc7eb1", }, { - value: "#e89bb4" + value: "#e89bb4", }], [{ - value: "#9d775f" + value: "#9d775f", }, { - value: "#dd4b4b" + value: "#dd4b4b", }, { - value: "#ef8b07" + value: "#ef8b07", }, { - value: "#fcc800" + value: "#fcc800", }, { - value: "#aacf53" + value: "#aacf53", }, { - value: "#82ae46" + value: "#82ae46", }, { - value: "#69821b" + value: "#69821b", }, { - value: "#59b9c6" + value: "#59b9c6", }, { - value: "#2a83a2" + value: "#2a83a2", }, { - value: "#007bbb" + value: "#007bbb", }, { - value: "#19448e" + value: "#19448e", }, { - value: "#274a78" + value: "#274a78", }, { - value: "#4a488e" + value: "#4a488e", }, { - value: "#7058a3" + value: "#7058a3", }, { - value: "#884898" + value: "#884898", }, { - value: "#d47596" + value: "#d47596", }] - ], + ] - _init: function () { - BI.ColorPicker.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.colors = BI.createWidget({ + _init() { + super._init(...arguments); + const o = this.options; + this.colors = createWidget({ type: "bi.button_group", element: this, - items: BI.createItems(o.items || this._items, { + items: createItems(o.items || this._items, { type: "bi.color_picker_button", - once: false + once: false, }), layouts: [{ - type: "bi.grid" + type: "bi.grid", }], - value: o.value + value: o.value, }); - this.colors.on(BI.ButtonGroup.EVENT_CHANGE, function () { - self.fireEvent(BI.ColorPicker.EVENT_CHANGE, arguments); + this.colors.on(ButtonGroup.EVENT_CHANGE, (...args) => { + this.fireEvent(ColorPicker.EVENT_CHANGE, ...args); }); - }, + } - populate: function (items) { - var args = [].slice.call(arguments); - args[0] = BI.createItems(items, { + populate(items) { + const args = [].slice.call(arguments); + args[0] = createItems(items, { type: "bi.color_picker_button", - once: false + once: false, }); this.colors.populate.apply(this.colors, args); - }, + } - setValue: function (color) { + setValue(color) { this.colors.setValue(color); - }, + } - getValue: function () { + getValue() { return this.colors.getValue(); } -}); -BI.ColorPicker.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.color_picker", BI.ColorPicker); \ No newline at end of file +} diff --git a/src/case/colorchooser/colorpicker/editor.colorpicker.hex.js b/src/case/colorchooser/colorpicker/editor.colorpicker.hex.js index 22c66a250..7b626a37c 100644 --- a/src/case/colorchooser/colorpicker/editor.colorpicker.hex.js +++ b/src/case/colorchooser/colorpicker/editor.colorpicker.hex.js @@ -1,36 +1,37 @@ +import { shortcut, Widget, createItems, map, isNumeric, range, extend, isEmptyString, isNull, DOM } from "@/core"; +import { ColorPickerEditor } from "./editor.colorpicker"; +import { ColorChooserShowButton } from "./button"; + +const RGB_WIDTH = 32, HEX_WIDTH = 70, HEX_PREFIX_POSITION = 1; + /** * 简单选色控件 * * Created by GUY on 2015/11/16. - * @class BI.ColorPickerEditor - * @extends BI.Widget + * @class HexColorPickerEditor + * @extends Widget */ -BI.HexColorPickerEditor = BI.inherit(BI.Widget, { - - constants: { - RGB_WIDTH: 32, - HEX_WIDTH: 70, - HEX_PREFIX_POSITION: 1 - }, - - props: { +@shortcut() +export class HexColorPickerEditor extends Widget { + static xtype = "bi.hex_color_picker_editor"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + props = { baseCls: "bi-color-picker-editor", - height: 30 - }, + height: 30, + } - render: function () { - var self = this, o = this.options, c = this.constants; + render() { this.storeValue = {}; - var RGB = BI.createItems([{ text: "R" }, { text: "G" }, { text: "B" }], { + const RGB = createItems([{ text: "R" }, { text: "G" }, { text: "B" }], { type: "bi.label", cls: "color-picker-editor-label", - height: 20 + height: 20, }); - var checker = function (v) { - return BI.isNumeric(v) && (v | 0) >= 0 && (v | 0) <= 255; - }; - var Ws = BI.map(BI.range(0, 3), function () { + const checker = v => isNumeric(v) && (v | 0) >= 0 && (v | 0) <= 255; + const Ws = map(range(0, 3), () => { return { type: "bi.small_text_editor", cls: "color-picker-editor-input bi-border-radius", @@ -38,20 +39,20 @@ BI.HexColorPickerEditor = BI.inherit(BI.Widget, { errorText: BI.i18nText("BI-Color_Picker_Error_Text"), allowBlank: true, value: 255, - width: c.RGB_WIDTH, + width: RGB_WIDTH, height: 24, listeners: [ { eventName: BI.TextEditor.EVENT_CHANGE, - action: function () { - self._checkEditors(); - if (checker(self.storeValue.r) && checker(self.storeValue.g) && checker(self.storeValue.b)) { - self.colorShow.element.css("background-color", self.getValue()); - self.fireEvent(BI.ColorPickerEditor.EVENT_CHANGE); + action: () => { + this._checkEditors(); + if (checker(this.storeValue.r) && checker(this.storeValue.g) && checker(this.storeValue.b)) { + this.colorShow.element.css("background-color", this.getValue()); + this.fireEvent(ColorPickerEditor.EVENT_CHANGE); } - } + }, } - ] + ], }; }); @@ -64,8 +65,8 @@ BI.HexColorPickerEditor = BI.inherit(BI.Widget, { tgap: 10, items: [ { - type: 'bi.vertical_adapt', - columnSize: ["fill", 'fill'], + type: "bi.vertical_adapt", + columnSize: ["fill", "fill"], height: 24, items: [ { @@ -76,16 +77,16 @@ BI.HexColorPickerEditor = BI.inherit(BI.Widget, { text: BI.i18nText("BI-Transparent_Color"), listeners: [ { - eventName: BI.ColorChooserShowButton.EVENT_CHANGE, - action: function () { - self.setValue("transparent"); - self.fireEvent(BI.ColorPickerEditor.EVENT_CHANGE); - } + eventName: ColorChooserShowButton.EVENT_CHANGE, + action: () => { + this.setValue("transparent"); + this.fireEvent(ColorPickerEditor.EVENT_CHANGE); + }, } ], - ref: function (_ref) { - self.transparent = _ref; - } + ref: _ref => { + this.transparent = _ref; + }, }, { el: { type: "bi.color_picker_show_button", @@ -95,24 +96,24 @@ BI.HexColorPickerEditor = BI.inherit(BI.Widget, { text: BI.i18nText("BI-Basic_Auto"), listeners: [ { - eventName: BI.ColorChooserShowButton.EVENT_CHANGE, - action: function () { - self.setValue(""); - self.fireEvent(BI.ColorPickerEditor.EVENT_CHANGE); - } + eventName: ColorChooserShowButton.EVENT_CHANGE, + action: () => { + this.setValue(""); + this.fireEvent(ColorPickerEditor.EVENT_CHANGE); + }, } ], - ref: function (_ref) { - self.none = _ref; - } + ref: _ref => { + this.none = _ref; + }, }, lgap: 10, } - ] + ], }, { el: { type: "bi.vertical_adapt", - columnSize: [22, 10, 'fill', 12, c.RGB_WIDTH, 12, c.RGB_WIDTH, 12, c.RGB_WIDTH], + columnSize: [22, 10, "fill", 12, RGB_WIDTH, 12, RGB_WIDTH, 12, RGB_WIDTH], rgap: 5, items: [ @@ -122,107 +123,106 @@ BI.HexColorPickerEditor = BI.inherit(BI.Widget, { cls: "color-picker-editor-display bi-card bi-border", height: 22, width: 22, - ref: function (_ref) { - self.colorShow = _ref; - } + ref: _ref => { + this.colorShow = _ref; + }, }, - width: 18 + width: 18, }, { type: "bi.label", text: "#", - width: 10 + width: 10, }, { type: "bi.small_text_editor", - ref: function (_ref) { - self.hexEditor = _ref; + ref: _ref => { + this.hexEditor = _ref; }, cls: "color-picker-editor-input bi-border-radius", validationChecker: this._hexChecker, allowBlank: true, errorText: BI.i18nText("BI-Color_Picker_Error_Text_Hex"), - width: c.HEX_WIDTH, + width: HEX_WIDTH, height: 24, listeners: [ { eventName: "EVENT_CHANGE", - action: function () { - self._checkHexEditor(); - if (checker(self.storeValue.r) && checker(self.storeValue.g) && checker(self.storeValue.b)) { - self.colorShow.element.css("background-color", self.getValue()); - self.fireEvent(BI.ColorPickerEditor.EVENT_CHANGE); + action: () => { + this._checkHexEditor(); + if (checker(this.storeValue.r) && checker(this.storeValue.g) && checker(this.storeValue.b)) { + this.colorShow.element.css("background-color", this.getValue()); + this.fireEvent(ColorPickerEditor.EVENT_CHANGE); } - - } + }, } - ] + ], }, RGB[0], { - el: BI.extend(Ws[0], { - ref: function (_ref) { - self.R = _ref; - } + el: extend(Ws[0], { + ref: _ref => { + this.R = _ref; + }, }), - width: c.RGB_WIDTH + width: RGB_WIDTH, }, RGB[1], { - el: BI.extend(Ws[1], { - ref: function (_ref) { - self.G = _ref; - } + el: extend(Ws[1], { + ref: _ref => { + this.G = _ref; + }, }), - width: c.RGB_WIDTH + width: RGB_WIDTH, }, RGB[2], { - el: BI.extend(Ws[2], { - ref: function (_ref) { - self.B = _ref; - } + el: extend(Ws[2], { + ref: _ref => { + this.B = _ref; + }, }), rgap: -5, - width: c.RGB_WIDTH + width: RGB_WIDTH, } - ] - } + ], + }, } - ] + ], }, left: 0, right: 0, top: 0, - bottom: 0 + bottom: 0, } - ] + ], }; - }, + } - _hexChecker: function (v) { + _hexChecker(v) { return /^[0-9a-fA-F]{6}$/.test(v); - }, + } - _checkEditors: function () { - if (BI.isEmptyString(this.R.getValue())) { + _checkEditors() { + if (isEmptyString(this.R.getValue())) { this.R.setValue(0); } - if (BI.isEmptyString(this.G.getValue())) { + if (isEmptyString(this.G.getValue())) { this.G.setValue(0); } - if (BI.isEmptyString(this.B.getValue())) { + if (isEmptyString(this.B.getValue())) { this.B.setValue(0); } this.storeValue = { r: this.R.getValue() || 0, g: this.G.getValue() || 0, - b: this.B.getValue() || 0 + b: this.B.getValue() || 0, }; - this.hexEditor.setValue(this.getValue().slice(this.constants.HEX_PREFIX_POSITION)); - }, + this.hexEditor.setValue(this.getValue().slice(HEX_PREFIX_POSITION)); + } - _isEmptyRGB: function () { - return BI.isEmptyString(this.storeValue.r) && BI.isEmptyString(this.storeValue.g) && BI.isEmptyString(this.storeValue.b); - }, + _isEmptyRGB() { + return isEmptyString(this.storeValue.r) && isEmptyString(this.storeValue.g) && isEmptyString(this.storeValue.b); + } - _checkHexEditor: function () { - if (BI.isEmptyString(this.hexEditor.getValue())) { + _checkHexEditor() { + if (isEmptyString(this.hexEditor.getValue())) { this.hexEditor.setValue("000000"); } - var json = BI.DOM.rgb2json(BI.DOM.hex2rgb("#" + this.hexEditor.getValue())); + const json = DOM.rgb2json(DOM.hex2rgb(`#${this.hexEditor.getValue()}`)); this.storeValue = { r: json.r || 0, g: json.g || 0, @@ -231,9 +231,9 @@ BI.HexColorPickerEditor = BI.inherit(BI.Widget, { this.R.setValue(this.storeValue.r); this.G.setValue(this.storeValue.g); this.B.setValue(this.storeValue.b); - }, + } - _showPreColor: function (color) { + _showPreColor(color) { if (color === "") { this.colorShow.element.css("background-color", "").removeClass("trans-color-background").addClass("auto-color-square-normal-background"); } else if (color === "transparent") { @@ -241,18 +241,18 @@ BI.HexColorPickerEditor = BI.inherit(BI.Widget, { } else { this.colorShow.element.css({ "background-color": color }).removeClass("auto-color-square-normal-background").removeClass("trans-color-background"); } - }, + } - _setEnable: function (enable) { - BI.ColorPickerEditor.superclass._setEnable.apply(this, arguments); + _setEnable(enable) { + super._setEnable(...arguments); if (enable === true) { this.element.removeClass("base-disabled disabled"); } else if (enable === false) { this.element.addClass("base-disabled disabled"); } - }, + } - setValue: function (color) { + setValue(color) { if (color === "transparent") { this.transparent.setSelected(true); this.none.setSelected(false); @@ -264,8 +264,9 @@ BI.HexColorPickerEditor = BI.inherit(BI.Widget, { this.storeValue = { r: "", g: "", - b: "" + b: "", }; + return; } if (!color) { @@ -276,28 +277,27 @@ BI.HexColorPickerEditor = BI.inherit(BI.Widget, { } this.transparent.setSelected(false); this._showPreColor(color); - var json = BI.DOM.rgb2json(BI.DOM.hex2rgb(color)); + const json = DOM.rgb2json(DOM.hex2rgb(color)); this.storeValue = { - r: BI.isNull(json.r) ? "" : json.r, - g: BI.isNull(json.g) ? "" : json.g, - b: BI.isNull(json.b) ? "" : json.b + r: isNull(json.r) ? "" : json.r, + g: isNull(json.g) ? "" : json.g, + b: isNull(json.b) ? "" : json.b, }; this.R.setValue(this.storeValue.r); this.G.setValue(this.storeValue.g); this.B.setValue(this.storeValue.b); - this.hexEditor.setValue(color.slice(this.constants.HEX_PREFIX_POSITION)); - }, + this.hexEditor.setValue(color.slice(HEX_PREFIX_POSITION)); + } - getValue: function () { + getValue() { if (this._isEmptyRGB() && this.transparent.isSelected()) { return "transparent"; } - return BI.DOM.rgb2hex(BI.DOM.json2rgb({ + + return DOM.rgb2hex(DOM.json2rgb({ r: this.storeValue.r, g: this.storeValue.g, - b: this.storeValue.b + b: this.storeValue.b, })); } -}); -BI.HexColorPickerEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.hex_color_picker_editor", BI.HexColorPickerEditor); +} diff --git a/src/case/colorchooser/colorpicker/editor.colorpicker.hex.simple.js b/src/case/colorchooser/colorpicker/editor.colorpicker.hex.simple.js index 749806355..f055be894 100644 --- a/src/case/colorchooser/colorpicker/editor.colorpicker.hex.simple.js +++ b/src/case/colorchooser/colorpicker/editor.colorpicker.hex.simple.js @@ -1,34 +1,34 @@ +import { shortcut, Widget, extend, isEmptyObject, createItems, isNull, isNumeric, map, isEmptyString, range, DOM } from "@/core"; +import { SimpleColorPickerEditor } from "./editor.colorpicker.simple"; +import { ColorPickerEditor } from "./editor.colorpicker"; + +const RGB_WIDTH = 32, HEX_WIDTH = 70, HEX_PREFIX_POSITION = 1; + /** * @author windy * @version 2.0 * Created by windy on 2020/11/10 */ -BI.SimpleHexColorPickerEditor = BI.inherit(BI.Widget, { +@shortcut() +export class SimpleHexColorPickerEditor extends Widget { + static xtype = "bi.simple_hex_color_picker_editor"; - constants: { - RGB_WIDTH: 32, - HEX_WIDTH: 70, - HEX_PREFIX_POSITION: 1 - }, + static EVENT_CHANGE = "EVENT_CHANGE"; - props: { + props = { baseCls: "bi-color-picker-editor", - height: 36 - }, - - render: function () { - var self = this, o = this.options, c = this.constants; + height: 36, + } - var RGB = BI.createItems([{ text: "R" }, { text: "G" }, { text: "B" }], { + render () { + const RGB = createItems([{ text: "R" }, { text: "G" }, { text: "B" }], { type: "bi.label", cls: "color-picker-editor-label", - height: 20 + height: 20, }); - var checker = function (v) { - return BI.isNumeric(v) && (v | 0) >= 0 && (v | 0) <= 255; - }; - var Ws = BI.map(BI.range(0, 3), function () { + const checker = v => isNumeric(v) && (v | 0) >= 0 && (v | 0) <= 255; + const Ws = map(range(0, 3), () => { return { type: "bi.small_text_editor", cls: "color-picker-editor-input bi-border-radius", @@ -36,20 +36,20 @@ BI.SimpleHexColorPickerEditor = BI.inherit(BI.Widget, { errorText: BI.i18nText("BI-Color_Picker_Error_Text"), allowBlank: true, value: 255, - width: c.RGB_WIDTH, + width: RGB_WIDTH, height: 24, listeners: [ { eventName: BI.TextEditor.EVENT_CHANGE, - action: function () { - self._checkEditors(); - if (self.R.isValid() && self.G.isValid() && self.B.isValid()) { - self.colorShow.element.css("background-color", self.getValue()); - self.fireEvent(BI.SimpleColorPickerEditor.EVENT_CHANGE); + action: () => { + this._checkEditors(); + if (this.R.isValid() && this.G.isValid() && this.B.isValid()) { + this.colorShow.element.css("background-color", this.getValue()); + this.fireEvent(SimpleColorPickerEditor.EVENT_CHANGE); } - } + }, } - ] + ], }; }); @@ -61,7 +61,7 @@ BI.SimpleHexColorPickerEditor = BI.inherit(BI.Widget, { el: { type: "bi.vertical_adapt", rgap: 5, - columnSize: [22, 10, 'fill', 12, c.RGB_WIDTH, 12, c.RGB_WIDTH, 12, c.RGB_WIDTH], + columnSize: [22, 10, "fill", 12, RGB_WIDTH, 12, RGB_WIDTH, 12, RGB_WIDTH], items: [ { el: { @@ -69,91 +69,91 @@ BI.SimpleHexColorPickerEditor = BI.inherit(BI.Widget, { cls: "color-picker-editor-display bi-card bi-border", height: 22, width: 22, - ref: function (_ref) { - self.colorShow = _ref; - } + ref: _ref => { + this.colorShow = _ref; + }, }, width: 18, }, { type: "bi.label", text: "#", - width: 10 + width: 10, }, { type: "bi.small_text_editor", - ref: function (_ref) { - self.hexEditor = _ref; + ref: _ref => { + this.hexEditor = _ref; }, cls: "color-picker-editor-input bi-border-radius", validationChecker: this._hexChecker, allowBlank: true, errorText: BI.i18nText("BI-Color_Picker_Error_Text_Hex"), - width: c.HEX_WIDTH, + width: HEX_WIDTH, height: 24, listeners: [ { eventName: "EVENT_CHANGE", - action: function () { - self._checkHexEditor(); - if (checker(self.storeValue.r) && checker(self.storeValue.g) && checker(self.storeValue.b)) { - self.colorShow.element.css("background-color", self.getValue()); - self.fireEvent(BI.ColorPickerEditor.EVENT_CHANGE); + action: () => { + this._checkHexEditor(); + if (checker(this.storeValue.r) && checker(this.storeValue.g) && checker(this.storeValue.b)) { + this.colorShow.element.css("background-color", this.getValue()); + this.fireEvent(ColorPickerEditor.EVENT_CHANGE); } - } + }, } - ] + ], }, RGB[0], { - el: BI.extend(Ws[0], { - ref: function (_ref) { - self.R = _ref; - } + el: extend(Ws[0], { + ref: _ref => { + this.R = _ref; + }, }), - width: c.RGB_WIDTH + width: RGB_WIDTH, }, RGB[1], { - el: BI.extend(Ws[1], { - ref: function (_ref) { - self.G = _ref; - } + el: extend(Ws[1], { + ref: _ref => { + this.G = _ref; + }, }), - width: c.RGB_WIDTH + width: RGB_WIDTH, }, RGB[2], { - el: BI.extend(Ws[2], { - ref: function (_ref) { - self.B = _ref; - } + el: extend(Ws[2], { + ref: _ref => { + this.B = _ref; + }, }), rgap: -5, - width: c.RGB_WIDTH + width: RGB_WIDTH, } - ] - } + ], + }, } - ] + ], }; - }, + } - _hexChecker: function (v) { + _hexChecker (v) { return /^[0-9a-fA-F]{6}$/.test(v); - }, + } - _checkEditors: function () { - if (BI.isEmptyString(this.R.getValue())) { + _checkEditors () { + if (isEmptyString(this.R.getValue())) { this.R.setValue(0); } - if (BI.isEmptyString(this.G.getValue())) { + if (isEmptyString(this.G.getValue())) { this.G.setValue(0); } - if (BI.isEmptyString(this.B.getValue())) { + if (isEmptyString(this.B.getValue())) { this.B.setValue(0); } - this.hexEditor.setValue(this.getValue().slice(this.constants.HEX_PREFIX_POSITION)); - }, + this.hexEditor.setValue(this.getValue().slice(HEX_PREFIX_POSITION)); + } - _checkHexEditor: function () { - if (BI.isEmptyString(this.hexEditor.getValue())) { + _checkHexEditor () { + if (isEmptyString(this.hexEditor.getValue())) { this.hexEditor.setValue("000000"); } - var json = BI.DOM.rgb2json(BI.DOM.hex2rgb("#" + this.hexEditor.getValue())); + const json = DOM.rgb2json(DOM.hex2rgb(`#${this.hexEditor.getValue()}`)); this.storeValue = { r: json.r || 0, g: json.g || 0, @@ -162,24 +162,22 @@ BI.SimpleHexColorPickerEditor = BI.inherit(BI.Widget, { this.R.setValue(this.storeValue.r); this.G.setValue(this.storeValue.g); this.B.setValue(this.storeValue.b); - }, + } - setValue: function (color) { + setValue (color) { this.colorShow.element.css({ "background-color": color }); - var json = BI.DOM.rgb2json(BI.DOM.hex2rgb(color)); - this.R.setValue(BI.isNull(json.r) ? "" : json.r); - this.G.setValue(BI.isNull(json.g) ? "" : json.g); - this.B.setValue(BI.isNull(json.b) ? "" : json.b); - this.hexEditor.setValue(BI.isEmptyObject(json) ? "" : color.slice(this.constants.HEX_PREFIX_POSITION)); - }, + const json = DOM.rgb2json(DOM.hex2rgb(color)); + this.R.setValue(isNull(json.r) ? "" : json.r); + this.G.setValue(isNull(json.g) ? "" : json.g); + this.B.setValue(isNull(json.b) ? "" : json.b); + this.hexEditor.setValue(isEmptyObject(json) ? "" : color.slice(HEX_PREFIX_POSITION)); + } - getValue: function () { - return BI.DOM.rgb2hex(BI.DOM.json2rgb({ + getValue () { + return DOM.rgb2hex(DOM.json2rgb({ r: this.R.getValue(), g: this.G.getValue(), - b: this.B.getValue() + b: this.B.getValue(), })); } -}); -BI.SimpleHexColorPickerEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.simple_hex_color_picker_editor", BI.SimpleHexColorPickerEditor); +} diff --git a/src/case/colorchooser/colorpicker/editor.colorpicker.js b/src/case/colorchooser/colorpicker/editor.colorpicker.js index 982d333c3..f413ff94d 100644 --- a/src/case/colorchooser/colorpicker/editor.colorpicker.js +++ b/src/case/colorchooser/colorpicker/editor.colorpicker.js @@ -1,60 +1,62 @@ +import { shortcut, Widget, extend, createWidgets, createItems, createWidget, each, isEmptyString, isNumeric, isNull, DOM } from "@/core"; +import { IconButton } from "@/base"; + +const RGB_WIDTH = 32; + /** * 简单选色控件 * * Created by GUY on 2015/11/16. - * @class BI.ColorPickerEditor - * @extends BI.Widget + * @class ColorPickerEditor + * @extends Widget */ -BI.ColorPickerEditor = BI.inherit(BI.Widget, { +@shortcut() +export class ColorPickerEditor extends Widget { + static xtype = "bi.color_picker_editor"; - constants: { - RGB_WIDTH: 32 - }, + static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig: function () { - return BI.extend(BI.ColorPickerEditor.superclass._defaultConfig.apply(this, arguments), { + _defaultConfig () { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-color-picker-editor", // width: 200, - height: 30 + height: 30, }); - }, + } - _init: function () { - BI.ColorPickerEditor.superclass._init.apply(this, arguments); - var self = this, o = this.options, c = this.constants; + _init () { + super._init(...arguments); this.storeValue = {}; - this.colorShow = BI.createWidget({ + this.colorShow = createWidget({ type: "bi.layout", cls: "color-picker-editor-display bi-card bi-border", height: 16, - width: 16 + width: 16, }); - var RGB = BI.createWidgets(BI.createItems([{ text: "R" }, { text: "G" }, { text: "B" }], { + const RGB = createWidgets(createItems([{ text: "R" }, { text: "G" }, { text: "B" }], { type: "bi.label", cls: "color-picker-editor-label", width: 20, - height: 20 + height: 20, })); - var checker = function (v) { - return BI.isNumeric(v) && (v | 0) >= 0 && (v | 0) <= 255; - }; - var Ws = BI.createWidgets([{}, {}, {}], { + const checker = v => isNumeric(v) && (v | 0) >= 0 && (v | 0) <= 255; + const Ws = createWidgets([{}, {}, {}], { type: "bi.small_text_editor", cls: "color-picker-editor-input bi-border-radius", validationChecker: checker, errorText: BI.i18nText("BI-Color_Picker_Error_Text"), allowBlank: true, value: 255, - width: c.RGB_WIDTH, - height: 20 + width: RGB_WIDTH, + height: 20, }); - BI.each(Ws, function (i, w) { - w.on(BI.TextEditor.EVENT_CHANGE, function () { - self._checkEditors(); - if (checker(self.storeValue.r) && checker(self.storeValue.g) && checker(self.storeValue.b)) { - self.colorShow.element.css("background-color", self.getValue()); - self.fireEvent(BI.ColorPickerEditor.EVENT_CHANGE); + each(Ws, (i, w) => { + w.on(BI.TextEditor.EVENT_CHANGE, () => { + this._checkEditors(); + if (checker(this.storeValue.r) && checker(this.storeValue.g) && checker(this.storeValue.b)) { + this.colorShow.element.css("background-color", this.getValue()); + this.fireEvent(ColorPickerEditor.EVENT_CHANGE); } }); }); @@ -62,37 +64,37 @@ BI.ColorPickerEditor = BI.inherit(BI.Widget, { this.G = Ws[1]; this.B = Ws[2]; - this.none = BI.createWidget({ + this.none = createWidget({ type: "bi.icon_button", cls: "auto-color-icon", width: 16, height: 16, iconWidth: 16, iconHeight: 16, - title: BI.i18nText("BI-Basic_Auto") + title: BI.i18nText("BI-Basic_Auto"), }); - this.none.on(BI.IconButton.EVENT_CHANGE, function () { - var value = self.getValue(); - self.setValue(""); - (value !== "") && self.fireEvent(BI.ColorPickerEditor.EVENT_CHANGE); + this.none.on(IconButton.EVENT_CHANGE, () => { + const value = this.getValue(); + this.setValue(""); + (value !== "") && this.fireEvent(ColorPickerEditor.EVENT_CHANGE); }); - this.transparent = BI.createWidget({ + this.transparent = createWidget({ type: "bi.icon_button", cls: "trans-color-icon", width: 16, height: 16, iconWidth: 16, iconHeight: 16, - title: BI.i18nText("BI-Transparent_Color") + title: BI.i18nText("BI-Transparent_Color"), }); - this.transparent.on(BI.IconButton.EVENT_CHANGE, function () { - var value = self.getValue(); - self.setValue("transparent"); - (value !== "transparent") && self.fireEvent(BI.ColorPickerEditor.EVENT_CHANGE); + this.transparent.on(IconButton.EVENT_CHANGE, () => { + const value = this.getValue(); + this.setValue("transparent"); + (value !== "transparent") && this.fireEvent(ColorPickerEditor.EVENT_CHANGE); }); - BI.createWidget({ + createWidget({ type: "bi.absolute", element: this, items: [ @@ -102,67 +104,67 @@ BI.ColorPickerEditor = BI.inherit(BI.Widget, { items: [ { el: this.colorShow, - width: 16 + width: 16, }, { el: RGB[0], - width: 20 + width: 20, }, { el: this.R, - width: c.RGB_WIDTH + width: RGB_WIDTH, }, { el: RGB[1], - width: 20 + width: 20, }, { el: this.G, - width: c.RGB_WIDTH + width: RGB_WIDTH, }, { el: RGB[2], - width: 20 + width: 20, }, { el: this.B, - width: c.RGB_WIDTH + width: RGB_WIDTH, }, { el: this.transparent, width: 16, - lgap: 5 + lgap: 5, }, { el: this.none, width: 16, - lgap: 5 + lgap: 5, } - ] + ], }, left: 10, right: 10, top: 0, - bottom: 0 + bottom: 0, } - ] + ], }); - }, + } - _checkEditors: function () { - if (BI.isEmptyString(this.R.getValue())) { + _checkEditors () { + if (isEmptyString(this.R.getValue())) { this.R.setValue(0); } - if (BI.isEmptyString(this.G.getValue())) { + if (isEmptyString(this.G.getValue())) { this.G.setValue(0); } - if (BI.isEmptyString(this.B.getValue())) { + if (isEmptyString(this.B.getValue())) { this.B.setValue(0); } this.storeValue = { r: this.R.getValue() || 0, g: this.G.getValue() || 0, - b: this.B.getValue() || 0 + b: this.B.getValue() || 0, }; - }, + } - _isEmptyRGB: function () { - return BI.isEmptyString(this.storeValue.r) && BI.isEmptyString(this.storeValue.g) && BI.isEmptyString(this.storeValue.b); - }, + _isEmptyRGB () { + return isEmptyString(this.storeValue.r) && isEmptyString(this.storeValue.g) && isEmptyString(this.storeValue.b); + } - _showPreColor: function (color) { + _showPreColor (color) { if (color === "") { this.colorShow.element.css("background-color", "").removeClass("trans-color-background").addClass("auto-color-normal-background"); } else if (color === "transparent") { @@ -170,18 +172,18 @@ BI.ColorPickerEditor = BI.inherit(BI.Widget, { } else { this.colorShow.element.css({ "background-color": color }).removeClass("auto-color-normal-background").removeClass("trans-color-background"); } - }, + } - _setEnable: function (enable) { - BI.ColorPickerEditor.superclass._setEnable.apply(this, arguments); + _setEnable (enable) { + super._setEnable(...arguments); if (enable === true) { this.element.removeClass("base-disabled disabled"); } else if (enable === false) { this.element.addClass("base-disabled disabled"); } - }, + } - setValue: function (color) { + setValue (color) { if (color === "transparent") { this.transparent.setSelected(true); this.none.setSelected(false); @@ -192,8 +194,9 @@ BI.ColorPickerEditor = BI.inherit(BI.Widget, { this.storeValue = { r: "", g: "", - b: "" + b: "", }; + return; } if (!color) { @@ -204,27 +207,26 @@ BI.ColorPickerEditor = BI.inherit(BI.Widget, { } this.transparent.setSelected(false); this._showPreColor(color); - var json = BI.DOM.rgb2json(BI.DOM.hex2rgb(color)); + const json = DOM.rgb2json(DOM.hex2rgb(color)); this.storeValue = { - r: BI.isNull(json.r) ? "" : json.r, - g: BI.isNull(json.g) ? "" : json.g, - b: BI.isNull(json.b) ? "" : json.b + r: isNull(json.r) ? "" : json.r, + g: isNull(json.g) ? "" : json.g, + b: isNull(json.b) ? "" : json.b, }; this.R.setValue(this.storeValue.r); this.G.setValue(this.storeValue.g); this.B.setValue(this.storeValue.b); - }, + } - getValue: function () { + getValue() { if (this._isEmptyRGB() && this.transparent.isSelected()) { return "transparent"; } - return BI.DOM.rgb2hex(BI.DOM.json2rgb({ + + return DOM.rgb2hex(DOM.json2rgb({ r: this.storeValue.r, g: this.storeValue.g, - b: this.storeValue.b + b: this.storeValue.b, })); } -}); -BI.ColorPickerEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.color_picker_editor", BI.ColorPickerEditor); +} diff --git a/src/case/colorchooser/colorpicker/editor.colorpicker.simple.js b/src/case/colorchooser/colorpicker/editor.colorpicker.simple.js index 63b7576b4..590cd1c37 100644 --- a/src/case/colorchooser/colorpicker/editor.colorpicker.simple.js +++ b/src/case/colorchooser/colorpicker/editor.colorpicker.simple.js @@ -1,59 +1,60 @@ +import { shortcut, Widget, extend, isNull, createWidget, isNumeric, createItems, createWidgets, each, isEmptyString, DOM } from "@/core"; + +const RGB_WIDTH = 32; + /** * 简单选色控件 * * Created by GUY on 2015/11/16. - * @class BI.SimpleColorPickerEditor - * @extends BI.Widget + * @class SimpleColorPickerEditor + * @extends Widget */ -BI.SimpleColorPickerEditor = BI.inherit(BI.Widget, { +@shortcut() +export class SimpleColorPickerEditor extends Widget { + static xtype = "bi.simple_color_picker_editor"; - constants: { - RGB_WIDTH: 32 - }, + static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig: function () { - return BI.extend(BI.SimpleColorPickerEditor.superclass._defaultConfig.apply(this, arguments), { + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-color-picker-editor", // width: 200, - height: 30 + height: 30, }); - }, + } - _init: function () { - BI.SimpleColorPickerEditor.superclass._init.apply(this, arguments); - var self = this, o = this.options, c = this.constants; - this.colorShow = BI.createWidget({ + _init() { + super._init(...arguments); + this.colorShow = createWidget({ type: "bi.layout", cls: "color-picker-editor-display bi-card bi-border", height: 16, - width: 16 + width: 16, }); - var RGB = BI.createWidgets(BI.createItems([{ text: "R" }, { text: "G" }, { text: "B" }], { + const RGB = createWidgets(createItems([{ text: "R" }, { text: "G" }, { text: "B" }], { type: "bi.label", cls: "color-picker-editor-label", width: 20, - height: 20 + height: 20, })); - var checker = function (v) { - return BI.isNumeric(v) && (v | 0) >= 0 && (v | 0) <= 255; - }; - var Ws = BI.createWidgets([{}, {}, {}], { + const checker = v => isNumeric(v) && (v | 0) >= 0 && (v | 0) <= 255; + const Ws = createWidgets([{}, {}, {}], { type: "bi.small_text_editor", cls: "color-picker-editor-input bi-border-radius", validationChecker: checker, errorText: BI.i18nText("BI-Color_Picker_Error_Text"), allowBlank: true, value: 255, - width: c.RGB_WIDTH, - height: 20 + width: RGB_WIDTH, + height: 20, }); - BI.each(Ws, function (i, w) { - w.on(BI.TextEditor.EVENT_CHANGE, function () { - self._checkEditors(); - if (self.R.isValid() && self.G.isValid() && self.B.isValid()) { - self.colorShow.element.css("background-color", self.getValue()); - self.fireEvent(BI.SimpleColorPickerEditor.EVENT_CHANGE); + each(Ws, (i, w) => { + w.on(BI.TextEditor.EVENT_CHANGE, () => { + this._checkEditors(); + if (this.R.isValid() && this.G.isValid() && this.B.isValid()) { + this.colorShow.element.css("background-color", this.getValue()); + this.fireEvent(SimpleColorPickerEditor.EVENT_CHANGE); } }); }); @@ -61,7 +62,7 @@ BI.SimpleColorPickerEditor = BI.inherit(BI.Widget, { this.G = Ws[1]; this.B = Ws[2]; - BI.createWidget({ + createWidget({ type: "bi.vertical_adapt", element: this, items: [ @@ -69,57 +70,55 @@ BI.SimpleColorPickerEditor = BI.inherit(BI.Widget, { el: this.colorShow, width: 16, lgap: 20, - rgap: 15 + rgap: 15, }, { el: RGB[0], - width: 20 + width: 20, }, { el: this.R, - width: c.RGB_WIDTH + width: RGB_WIDTH, }, { el: RGB[1], - width: 20 + width: 20, }, { el: this.G, - width: c.RGB_WIDTH + width: RGB_WIDTH, }, { el: RGB[2], - width: 20 + width: 20, }, { el: this.B, - width: c.RGB_WIDTH + width: RGB_WIDTH, } - ] + ], }); - }, + } - _checkEditors: function () { - if (BI.isEmptyString(this.R.getValue())) { + _checkEditors() { + if (isEmptyString(this.R.getValue())) { this.R.setValue(0); } - if (BI.isEmptyString(this.G.getValue())) { + if (isEmptyString(this.G.getValue())) { this.G.setValue(0); } - if (BI.isEmptyString(this.B.getValue())) { + if (isEmptyString(this.B.getValue())) { this.B.setValue(0); } - }, + } - setValue: function (color) { + setValue(color) { this.colorShow.element.css({ "background-color": color }); - var json = BI.DOM.rgb2json(BI.DOM.hex2rgb(color)); - this.R.setValue(BI.isNull(json.r) ? "" : json.r); - this.G.setValue(BI.isNull(json.g) ? "" : json.g); - this.B.setValue(BI.isNull(json.b) ? "" : json.b); - }, + const json = DOM.rgb2json(DOM.hex2rgb(color)); + this.R.setValue(isNull(json.r) ? "" : json.r); + this.G.setValue(isNull(json.g) ? "" : json.g); + this.B.setValue(isNull(json.b) ? "" : json.b); + } - getValue: function () { - return BI.DOM.rgb2hex(BI.DOM.json2rgb({ + getValue() { + return DOM.rgb2hex(DOM.json2rgb({ r: this.R.getValue(), g: this.G.getValue(), - b: this.B.getValue() + b: this.B.getValue(), })); } -}); -BI.SimpleColorPickerEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.simple_color_picker_editor", BI.SimpleColorPickerEditor); +} diff --git a/src/case/colorchooser/colorpicker/index.js b/src/case/colorchooser/colorpicker/index.js new file mode 100644 index 000000000..73724cae8 --- /dev/null +++ b/src/case/colorchooser/colorpicker/index.js @@ -0,0 +1,7 @@ +export { ColorPicker } from "./colorpicker"; +export { HexColorPicker } from "./colorpicker.hex"; +export { ColorPickerEditor } from "./editor.colorpicker"; +export { HexColorPickerEditor } from "./editor.colorpicker.hex"; +export { SimpleHexColorPickerEditor } from "./editor.colorpicker.hex.simple"; +export { SimpleColorPickerEditor } from "./editor.colorpicker.simple"; +export * from "./button"; diff --git a/src/case/colorchooser/farbtastic/farbtastic.js b/src/case/colorchooser/farbtastic/farbtastic.js index 0bf1061b0..9a57fbaf8 100644 --- a/src/case/colorchooser/farbtastic/farbtastic.js +++ b/src/case/colorchooser/farbtastic/farbtastic.js @@ -1,98 +1,101 @@ -BI.Farbtastic = BI.inherit(BI.BasicButton, { +import { shortcut, isKey, DOM } from "@/core"; +import { BasicButton } from "@/base"; - constants: { - RADIUS: 84, - SQUARE: 100, - WIDTH: 194 - }, +const RADIUS = 84, SQUARE = 100, WIDTH = 194; - props: { +@shortcut() +export class Farbtastic extends BasicButton { + static xtype = "bi.farbtastic"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + props = { baseCls: "bi-farbtastic", width: 195, height: 195, stopPropagation: true, - value: "#000000" - }, + value: "#000000", + } - render: function () { - var self = this; + render() { this._defaultState(); + return { type: "bi.absolute", items: [{ el: { type: "bi.layout", cls: "", - ref: function (_ref) { - self.colorWrapper = _ref; - } + ref: _ref => { + this.colorWrapper = _ref; + }, }, top: 47, left: 47, width: 101, - height: 101 + height: 101, }, { el: { type: "bi.layout", cls: "wheel", - ref: function (_ref) { - self.wheel = _ref; - } + ref: _ref => { + this.wheel = _ref; + }, }, left: 0, right: 0, top: 0, - bottom: 0 + bottom: 0, }, { el: { type: "bi.layout", cls: "overlay", - ref: function (_ref) { - self.overlay = _ref; - } + ref: _ref => { + this.overlay = _ref; + }, }, top: 47, left: 47, width: 101, - height: 101 + height: 101, }, { el: { type: "bi.layout", cls: "marker", - ref: function (_ref) { - self.hMarker = _ref; + ref: _ref => { + this.hMarker = _ref; }, scrollable: false, width: 17, - height: 17 - } + height: 17, + }, }, { el: { type: "bi.layout", cls: "marker", - ref: function (_ref) { - self.slMarker = _ref; + ref: _ref => { + this.slMarker = _ref; }, scrollable: false, width: 17, - height: 17 - } - }] + height: 17, + }, + }], }; - }, + } - created: function () { - var o = this.options; - if (BI.isKey(o.value)) { + created() { + const o = this.options; + if (isKey(o.value)) { this.setValue(o.value); } - }, + } - _defaultState: function () { + _defaultState() { this.hsl = [0, 0, 0]; - }, + } - _unpack: function (color) { + _unpack(color) { if (color.length === 7) { return [parseInt("0x" + color.substring(1, 3)) / 255, parseInt("0x" + color.substring(3, 5)) / 255, @@ -102,81 +105,84 @@ BI.Farbtastic = BI.inherit(BI.BasicButton, { parseInt("0x" + color.substring(2, 3)) / 15, parseInt("0x" + color.substring(3, 4)) / 15]; } - }, + } - _pack: function (rgb) { - var r = Math.round(rgb[0] * 255); - var g = Math.round(rgb[1] * 255); - var b = Math.round(rgb[2] * 255); + _pack(rgb) { + const r = Math.round(rgb[0] * 255); + const g = Math.round(rgb[1] * 255); + const b = Math.round(rgb[2] * 255); + return "#" + (r < 16 ? "0" : "") + r.toString(16) + - (g < 16 ? "0" : "") + g.toString(16) + - (b < 16 ? "0" : "") + b.toString(16); - }, + (g < 16 ? "0" : "") + g.toString(16) + + (b < 16 ? "0" : "") + b.toString(16); + } - _setColor: function (color) { - var unpack = this._unpack(color); + _setColor(color) { + const unpack = this._unpack(color); if (this.value !== color && unpack) { this.value = color; this.rgb = unpack; this.hsl = this._RGBToHSL(this.rgb); this._updateDisplay(); } - }, + } - _setHSL: function (hsl) { + _setHSL(hsl) { this.hsl = hsl; this.rgb = this._HSLToRGB(hsl); this.value = this._pack(this.rgb); this._updateDisplay(); + return this; - }, + } - _HSLToRGB: function (hsl) { - return BI.DOM.hsl2rgb(hsl); - }, + _HSLToRGB(hsl) { + return DOM.hsl2rgb(hsl); + } - _RGBToHSL: function (rgb) { - return BI.DOM.rgb2hsl(rgb); - }, + _RGBToHSL(rgb) { + return DOM.rgb2hsl(rgb); + } - _updateDisplay: function () { - var angle = this.hsl[0] * 6.28; + _updateDisplay() { + const angle = this.hsl[0] * 6.28; this.hMarker.element.css({ - left: Math.round(Math.sin(angle) * this.constants.RADIUS + this.constants.WIDTH / 2) + "px", - top: Math.round(-Math.cos(angle) * this.constants.RADIUS + this.constants.WIDTH / 2) + "px" + left: `${Math.round(Math.sin(angle) * RADIUS + WIDTH / 2)}px`, + top: `${Math.round(-Math.cos(angle) * RADIUS + WIDTH / 2)}px`, }); this.slMarker.element.css({ - left: Math.round(this.constants.SQUARE * (.5 - this.hsl[1]) + this.constants.WIDTH / 2) + "px", - top: Math.round(this.constants.SQUARE * (.5 - this.hsl[2]) + this.constants.WIDTH / 2) + "px" + left: `${Math.round(SQUARE * (.5 - this.hsl[1]) + WIDTH / 2)}px`, + top: `${Math.round(SQUARE * (.5 - this.hsl[2]) + WIDTH / 2)}px`, }); // Saturation/Luminance gradient this.colorWrapper.element.css("backgroundColor", this._pack(this._HSLToRGB([this.hsl[0], 1, 0.5]))); - }, + } - _absolutePosition: function (el) { - var r = {x: el.offsetLeft, y: el.offsetTop}; + _absolutePosition(el) { + const r = { x: el.offsetLeft, y: el.offsetTop }; // Resolve relative to offsetParent if (el.offsetParent) { - var tmp = this._absolutePosition(el.offsetParent); + const tmp = this._absolutePosition(el.offsetParent); r.x += tmp.x; r.y += tmp.y; } + return r; - }, + } - _widgetCoords: function (event) { - var x, y; - var el = event.target || event.srcElement; - var reference = this.wheel.element[0]; + _widgetCoords(event) { + let x, y; + const el = event.target || event.srcElement; + const reference = this.wheel.element[0]; if (typeof event.offsetX !== "undefined") { // Use offset coordinates and find common offsetParent - var pos = {x: event.offsetX, y: event.offsetY}; + const pos = { x: event.offsetX, y: event.offsetY }; // Send the coordinates upwards through the offsetParent chain. - var e = el; + let e = el; while (e) { e.mouseX = pos.x; e.mouseY = pos.y; @@ -186,8 +192,8 @@ BI.Farbtastic = BI.inherit(BI.BasicButton, { } // Look for the coordinates starting from the wheel widget. - var e = reference; - var offset = {x: 0, y: 0}; + e = reference; + const offset = { x: 0, y: 0 }; while (e) { if (typeof e.mouseX !== "undefined") { x = e.mouseX - offset.x; @@ -208,46 +214,46 @@ BI.Farbtastic = BI.inherit(BI.BasicButton, { } } else { // Use absolute coordinates - var pos = this._absolutePosition(reference); + const pos = this._absolutePosition(reference); x = (event.pageX || 0) - pos.x; y = (event.pageY || 0) - pos.y; } + // Subtract distance to middle - return {x: x - this.constants.WIDTH / 2, y: y - this.constants.WIDTH / 2}; - }, + return { x: x - WIDTH / 2, y: y - WIDTH / 2 }; + } - _doMouseMove: function (event) { - var pos = this._widgetCoords(event); + _doMouseMove(event) { + const pos = this._widgetCoords(event); // Set new HSL parameters if (this.circleDrag) { - var hue = Math.atan2(pos.x, -pos.y) / 6.28; + let hue = Math.atan2(pos.x, -pos.y) / 6.28; if (hue < 0) hue += 1; this._setHSL([hue, this.hsl[1], this.hsl[2]]); } else { - var sat = Math.max(0, Math.min(1, -(pos.x / this.constants.SQUARE) + .5)); - var lum = Math.max(0, Math.min(1, -(pos.y / this.constants.SQUARE) + .5)); + const sat = Math.max(0, Math.min(1, -(pos.x / SQUARE) + .5)); + const lum = Math.max(0, Math.min(1, -(pos.y / SQUARE) + .5)); this._setHSL([this.hsl[0], sat, lum]); } - this.fireEvent(BI.Farbtastic.EVENT_CHANGE, this.getValue(), this); - }, + this.fireEvent(Farbtastic.EVENT_CHANGE, this.getValue(), this); + } - doClick: function (event) { - var pos = this._widgetCoords(event); - this.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > this.constants.SQUARE; + doClick(event) { + const pos = this._widgetCoords(event); + this.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > SQUARE; // Process this._doMouseMove(event); + return false; - }, + } - setValue: function (color) { + setValue(color) { this._setColor(color); - }, + } - getValue: function () { + getValue() { return this.value; } -}); -BI.Farbtastic.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.farbtastic", BI.Farbtastic); +} diff --git a/src/case/colorchooser/index.js b/src/case/colorchooser/index.js new file mode 100644 index 000000000..582eac086 --- /dev/null +++ b/src/case/colorchooser/index.js @@ -0,0 +1,11 @@ +export { ColorChooser } from "./colorchooser"; +export { CustomColorChooser } from "./colorchooser.custom"; +export { ColorChooserPopup } from "./colorchooser.popup"; +export { HexColorChooserPopup } from "./colorchooser.popup.hex"; +export { SimpleHexColorChooserPopup } from "./colorchooser.popup.hex.simple"; +export { SimpleColorChooserPopup } from "./colorchooser.popup.simple"; +export { SimpleColorChooser } from "./colorchooser.simple"; +export { ColorChooserTrigger } from "./colorchooser.trigger"; +export { LongColorChooserTrigger } from "./colorchooser.trigger.long"; +export { Farbtastic } from "./farbtastic/farbtastic"; +export * from "./colorpicker"; diff --git a/src/case/index.js b/src/case/index.js index 647534575..70d85ee9e 100644 --- a/src/case/index.js +++ b/src/case/index.js @@ -10,8 +10,9 @@ import * as segment from "./segment"; import { MultiSelectBar } from "./toolbar/toolbar.multiselect"; import * as layer from "./layer"; import * as linearSegment from "./linearsegment"; +import * as colorchooser from "./colorchooser"; import { SelectList } from "./list/list.select"; -import * as combo from "./combo"; + Object.assign(BI, { ...combo, @@ -27,6 +28,7 @@ Object.assign(BI, { MultiSelectBar, ...layer, ...linearSegment, + ...colorchooser, SelectList, }); @@ -44,6 +46,7 @@ export * from "./segment"; export * from "./layer"; export * from "./linearsegment"; export * from "./checkbox"; +export * from "./colorchooser"; export { MultiSelectBar, SelectList diff --git a/src/core/structure/queue.js b/src/core/structure/queue.js index 9cdf8b596..b42e25492 100644 --- a/src/core/structure/queue.js +++ b/src/core/structure/queue.js @@ -75,7 +75,7 @@ export class Queue { } fromArray(array) { - array.each(v => this.push(v)); + array.forEach(v => this.push(v)); } clear() { From 80db0a5eee7379944cf06aa4c48056c9fb643313 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Thu, 12 Jan 2023 15:38:47 +0800 Subject: [PATCH 097/300] =?UTF-8?q?=E6=97=A0JIRA=E4=BB=BB=E5=8A=A1=20fix:?= =?UTF-8?q?=20=E4=BF=AE=E5=A4=8Dpane.list=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/base/combination/group.button.js | 51 ++++++++++++++-------------- src/case/layer/pane.list.js | 3 +- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/src/base/combination/group.button.js b/src/base/combination/group.button.js index 01b54e98c..814ce099e 100644 --- a/src/base/combination/group.button.js +++ b/src/base/combination/group.button.js @@ -31,7 +31,7 @@ export class ButtonGroup extends Widget { const behaviors = {}; each(optionsBehaviors, (key, rule) => { behaviors[key] = BI.BehaviorFactory.createBehavior(key, { - rule: rule, + rule, }); }); this.behaviors = behaviors; @@ -65,25 +65,26 @@ export class ButtonGroup extends Widget { args[0] = buttons; each(this.behaviors, (i, behavior) => { - behavior.doBehavior.apply(behavior, args); + behavior.doBehavior(...args); }); each(buttons, (i, btn) => { - btn.on(Controller.EVENT_CHANGE, (type, value, obj, ...arg) => { + btn.on(Controller.EVENT_CHANGE, (...arg) => { + const [type, value, obj] = arg; if (type === BI.Events.CLICK) { switch (chooseType) { - case ButtonGroup.CHOOSE_TYPE_SINGLE: - this.setValue(btn.getValue()); - break; - case ButtonGroup.CHOOSE_TYPE_NONE: - this.setValue([]); - break; - default: - break; + case ButtonGroup.CHOOSE_TYPE_SINGLE: + this.setValue(btn.getValue()); + break; + case ButtonGroup.CHOOSE_TYPE_NONE: + this.setValue([]); + break; + default: + break; } - this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...arg); + this.fireEvent(Controller.EVENT_CHANGE, ...arg); this.fireEvent(ButtonGroup.EVENT_CHANGE, value, obj); } else { - this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...arg); + this.fireEvent(Controller.EVENT_CHANGE, ...arg); } }); btn.on(BI.Events.DESTROY, () => { @@ -98,15 +99,13 @@ export class ButtonGroup extends Widget { const { layouts: optionsLayouts } = this.options; const layouts = isArray(optionsLayouts) ? optionsLayouts : [optionsLayouts]; for (let i = layouts.length - 1; i > 0; i--) { - btns = map(btns, (k, it) => { - return extend({}, layouts[i], { - items: [ - extend({}, layouts[i].el, { - el: it, - }) - ], - }); - }); + btns = map(btns, (k, it) => extend({}, layouts[i], { + items: [ + extend({}, layouts[i].el, { + el: it, + }) + ], + })); } return btns; @@ -154,12 +153,12 @@ export class ButtonGroup extends Widget { const args = Array.prototype.slice.call(arguments); args.unshift(this.buttons); each(this.behaviors, (i, behavior) => { - behavior.doBehavior.apply(behavior, args); + behavior.doBehavior(...args); }); } prependItems(items) { - const btns = this._btnsCreator.apply(this, arguments); + const btns = this._btnsCreator(...arguments); this.buttons = concat(btns, this.buttons); if (this._isSimpleLayout() && this.layouts && this.layouts.prependItems) { @@ -173,7 +172,7 @@ export class ButtonGroup extends Widget { } addItems(items) { - const btns = this._btnsCreator.apply(this, arguments); + const btns = this._btnsCreator(...arguments); this.buttons = concat(this.buttons, btns); // 如果是一个简单的layout @@ -209,7 +208,7 @@ export class ButtonGroup extends Widget { this.empty(); this.options.items = items; - this.buttons = this._btnsCreator.apply(this, arguments); + this.buttons = this._btnsCreator(...arguments); if (this._isSimpleLayout()) { items = this._packageSimpleItems(this.buttons); } else { diff --git a/src/case/layer/pane.list.js b/src/case/layer/pane.list.js index 69d6f4df1..8fa7e5f4c 100644 --- a/src/case/layer/pane.list.js +++ b/src/case/layer/pane.list.js @@ -69,7 +69,8 @@ export class ListPane extends Pane { }], }); - this.button_group.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { + this.button_group.on(Controller.EVENT_CHANGE, (...args) => { + const [type, value, obj] = args; this.fireEvent(Controller.EVENT_CHANGE, ...args); if (type === Events.CLICK) { this.fireEvent(ListPane.EVENT_CHANGE, value, obj); From bac72939090fe9e4d79fcd72273080ac884a47b6 Mon Sep 17 00:00:00 2001 From: impact Date: Thu, 12 Jan 2023 15:39:14 +0800 Subject: [PATCH 098/300] =?UTF-8?q?KERNEL-14047=20refactor:=20=E4=BF=AE?= =?UTF-8?q?=E5=A4=8Dindex?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/case/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/case/index.js b/src/case/index.js index 70d85ee9e..bc43a3dff 100644 --- a/src/case/index.js +++ b/src/case/index.js @@ -12,7 +12,7 @@ import * as layer from "./layer"; import * as linearSegment from "./linearsegment"; import * as colorchooser from "./colorchooser"; import { SelectList } from "./list/list.select"; - +import * as combo from "./combo"; Object.assign(BI, { ...combo, From d43a9786e47db24724dbad74a354713170072693 Mon Sep 17 00:00:00 2001 From: zsmj Date: Thu, 12 Jan 2023 16:13:17 +0800 Subject: [PATCH 099/300] update --- src/widget/index.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/widget/index.js b/src/widget/index.js index 327f708f8..5d238bd4f 100644 --- a/src/widget/index.js +++ b/src/widget/index.js @@ -44,7 +44,7 @@ export * from "./datepane"; export * from "./datetime"; export * from "./datetimepane"; export * from "./dynamicdatetime"; -export * from "./time +export * from "./time"; export * from "./editor"; export { SelectTreeCombo } from "./selecttree/selecttree.combo"; export { SingleTreeCombo } from "./singletree/singletree.combo"; @@ -53,7 +53,7 @@ export { MultiTreeInsertCombo } from "./multitree/multi.tree.insert.combo"; export { MultiTreeListCombo } from "./multitree/multi.tree.list.combo"; export * from "./multiselect"; export * from "./multiselectlist"; - + export { Collapse, NumberEditor, From fb82d5c0273675fdc951df4dc82266033e6cce8b Mon Sep 17 00:00:00 2001 From: zsmj Date: Thu, 12 Jan 2023 16:13:32 +0800 Subject: [PATCH 100/300] update --- src/core/1.lodash.js | 443 ++++++++++++++++++++++++------------------- 1 file changed, 243 insertions(+), 200 deletions(-) diff --git a/src/core/1.lodash.js b/src/core/1.lodash.js index 1fdf1bbc4..269718d61 100644 --- a/src/core/1.lodash.js +++ b/src/core/1.lodash.js @@ -1,3 +1,4 @@ +/* eslint-disable */ /** * @license * Lodash (Custom Build) @@ -7,7 +8,7 @@ * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ -;(function() { +;(function () { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; @@ -191,7 +192,7 @@ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ - var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); + var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; @@ -269,10 +270,11 @@ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { + var nodeUtil = (function () { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} + } catch (e) { + } }()); /* Node.js helper references. */ @@ -296,10 +298,14 @@ */ function apply(func, thisArg, args) { switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); + case 0: + return func.call(thisArg); + case 1: + return func.call(thisArg, args[0]); + case 2: + return func.call(thisArg, args[0], args[1]); + case 3: + return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } @@ -546,7 +552,7 @@ */ function baseFindKey(collection, predicate, eachFunc) { var result; - eachFunc(collection, function(value, key, collection) { + eachFunc(collection, function (value, key, collection) { if (predicate(value, key, collection)) { result = key; return false; @@ -612,7 +618,7 @@ * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { - return function(object) { + return function (object) { return object == null ? undefined : object[key]; }; } @@ -625,7 +631,7 @@ * @returns {Function} Returns the new accessor function. */ function basePropertyOf(object) { - return function(key) { + return function (key) { return object == null ? undefined : object[key]; }; } @@ -644,7 +650,7 @@ * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { - eachFunc(collection, function(value, index, collection) { + eachFunc(collection, function (value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); @@ -699,7 +705,7 @@ * @returns {Function} Returns the new capped function. */ function baseUnary(func) { - return function(value) { + return function (value) { return func(value); }; } @@ -715,7 +721,7 @@ * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { - return arrayMap(props, function(key) { + return arrayMap(props, function (key) { return object[key]; }); } @@ -745,7 +751,8 @@ var index = -1, length = strSymbols.length; - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) { + } return index; } @@ -761,7 +768,8 @@ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) { + } return index; } @@ -845,7 +853,7 @@ var index = -1, result = Array(map.size); - map.forEach(function(value, key) { + map.forEach(function (value, key) { result[++index] = [key, value]; }); return result; @@ -860,7 +868,7 @@ * @returns {Function} Returns the new function. */ function overArg(func, transform) { - return function(arg) { + return function (arg) { return func(transform(arg)); }; } @@ -915,7 +923,7 @@ var index = -1, result = Array(set.size); - set.forEach(function(value) { + set.forEach(function (value) { result[++index] = value; }); return result; @@ -1024,7 +1032,7 @@ var idCounter = 0; /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { + var maskSrcKey = (function () { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); @@ -1061,12 +1069,13 @@ symIterator = Symbol ? Symbol.iterator : undefined, symToStringTag = Symbol ? Symbol.toStringTag : undefined; - var defineProperty = (function() { + var defineProperty = (function () { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; - } catch (e) {} + } catch (e) { + } }()); /* Built-in method references for those with the same name as other `lodash` methods. */ @@ -1247,9 +1256,11 @@ * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ - var baseCreate = (function() { - function object() {} - return function(proto) { + var baseCreate = (function () { + function object() { + } + + return function (proto) { if (!isObject(proto)) { return {}; } @@ -1992,7 +2003,7 @@ * @returns {Function} Returns `accumulator`. */ function baseAggregator(collection, setter, iteratee, accumulator) { - baseEach(collection, function(value, key, collection) { + baseEach(collection, function (value, key, collection) { setter(accumulator, value, iteratee(value), collection); }); return accumulator; @@ -2154,7 +2165,7 @@ stack.set(value, result); if (isSet(value)) { - value.forEach(function(subValue) { + value.forEach(function (subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); @@ -2162,7 +2173,7 @@ } if (isMap(value)) { - value.forEach(function(subValue, key) { + value.forEach(function (subValue, key) { result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); @@ -2174,7 +2185,7 @@ : (isFlat ? keysIn : keys); var props = isArr ? undefined : keysFunc(value); - arrayEach(props || value, function(subValue, key) { + arrayEach(props || value, function (subValue, key) { if (props) { key = subValue; subValue = value[key]; @@ -2199,7 +2210,9 @@ if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } - return setTimeout(function() { func.apply(undefined, args); }, wait); + return setTimeout(function () { + func.apply(undefined, args); + }, wait); } /** @@ -2230,8 +2243,7 @@ if (comparator) { includes = arrayIncludesWith; isCommon = false; - } - else if (values.length >= LARGE_ARRAY_SIZE) { + } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); @@ -2250,8 +2262,7 @@ } } result.push(value); - } - else if (!includes(values, computed, comparator)) { + } else if (!includes(values, computed, comparator)) { result.push(value); } } @@ -2279,7 +2290,7 @@ */ function baseEvery(collection, predicate) { var result = true; - baseEach(collection, function(value, index, collection) { + baseEach(collection, function (value, index, collection) { result = !!predicate(value, index, collection); return result; }); @@ -2325,7 +2336,7 @@ */ function baseFilter(collection, predicate) { var result = []; - baseEach(collection, function(value, index, collection) { + baseEach(collection, function (value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } @@ -2426,7 +2437,7 @@ * @returns {Array} Returns the function names. */ function baseFunctions(object, props) { - return arrayFilter(props, function(key) { + return arrayFilter(props, function (key) { return isFunction(object[key]); }); } @@ -2595,7 +2606,7 @@ * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { - baseForOwn(object, function(value, key, object) { + baseForOwn(object, function (value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; @@ -2929,7 +2940,7 @@ var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; - baseEach(collection, function(value, key, collection) { + baseEach(collection, function (value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; @@ -2947,7 +2958,7 @@ if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } - return function(object) { + return function (object) { return object === source || baseIsMatch(object, source, matchData); }; } @@ -2964,7 +2975,7 @@ if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } - return function(object) { + return function (object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) @@ -2987,12 +2998,11 @@ if (object === source) { return; } - baseFor(source, function(srcValue, key) { + baseFor(source, function (srcValue, key) { if (isObject(srcValue)) { stack || (stack = new Stack); baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } - else { + } else { var newValue = customizer ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) : undefined; @@ -3044,32 +3054,25 @@ if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; - } - else if (isArrayLikeObject(objValue)) { + } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); - } - else if (isBuff) { + } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true); - } - else if (isTyped) { + } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true); - } - else { + } else { newValue = []; } - } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { + } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); - } - else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { + } else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { newValue = initCloneObject(srcValue); } - } - else { + } else { isCommon = false; } } @@ -3095,14 +3098,14 @@ var index = -1; iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(baseIteratee)); - var result = baseMap(collection, function(value, key, collection) { - var criteria = arrayMap(iteratees, function(iteratee) { + var result = baseMap(collection, function (value, key, collection) { + var criteria = arrayMap(iteratees, function (iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); - return baseSortBy(result, function(object, other) { + return baseSortBy(result, function (object, other) { return compareMultiple(object, other, orders); }); } @@ -3117,7 +3120,7 @@ * @returns {Object} Returns the new object. */ function basePick(object, paths) { - return basePickBy(object, paths, function(value, path) { + return basePickBy(object, paths, function (value, path) { return hasIn(object, path); }); } @@ -3155,7 +3158,7 @@ * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { - return function(object) { + return function (object) { return baseGet(object, path); }; } @@ -3256,7 +3259,7 @@ * @param {*} data The metadata. * @returns {Function} Returns `func`. */ - var baseSetData = !metaMap ? identity : function(func, data) { + var baseSetData = !metaMap ? identity : function (func, data) { metaMap.set(func, data); return func; }; @@ -3269,7 +3272,7 @@ * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ - var baseSetToString = !defineProperty ? identity : function(func, string) { + var baseSetToString = !defineProperty ? identity : function (func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, @@ -3320,7 +3323,7 @@ function baseSome(collection, predicate) { var result; - baseEach(collection, function(value, index, collection) { + baseEach(collection, function (value, index, collection) { result = predicate(value, index, collection); return !result; }); @@ -3371,8 +3374,7 @@ if (comparator) { isCommon = false; includes = arrayIncludesWith; - } - else if (length >= LARGE_ARRAY_SIZE) { + } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); @@ -3380,8 +3382,7 @@ isCommon = false; includes = cacheHas; seen = new SetCache; - } - else { + } else { seen = iteratee ? [] : result; } outer: @@ -3401,8 +3402,7 @@ seen.push(computed); } result.push(value); - } - else if (!includes(seen, computed, comparator)) { + } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } @@ -3441,7 +3441,7 @@ if (result instanceof LazyWrapper) { result = result.value(); } - return arrayReduce(actions, function(result, action) { + return arrayReduce(actions, function (result, action) { return action.func.apply(action.thisArg, arrayPush([result], action.args)); }, result); } @@ -3830,7 +3830,7 @@ * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { - return function(collection, iteratee) { + return function (collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; @@ -3846,7 +3846,7 @@ * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { - return baseRest(function(object, sources) { + return baseRest(function (object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, @@ -3880,7 +3880,7 @@ * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { - return function(collection, iteratee) { + return function (collection, iteratee) { if (collection == null) { return collection; } @@ -3908,7 +3908,7 @@ * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { + return function (object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), @@ -3942,6 +3942,7 @@ var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } + return wrapper; } @@ -3954,20 +3955,28 @@ * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { - return function() { + return function () { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { - case 0: return new Ctor; - case 1: return new Ctor(args[0]); - case 2: return new Ctor(args[0], args[1]); - case 3: return new Ctor(args[0], args[1], args[2]); - case 4: return new Ctor(args[0], args[1], args[2], args[3]); - case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); - case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); - case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + case 0: + return new Ctor; + case 1: + return new Ctor(args[0]); + case 2: + return new Ctor(args[0], args[1]); + case 3: + return new Ctor(args[0], args[1], args[2]); + case 4: + return new Ctor(args[0], args[1], args[2], args[3]); + case 5: + return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: + return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: + return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); @@ -4012,6 +4021,7 @@ var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } + return wrapper; } @@ -4023,12 +4033,14 @@ * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { - return function(collection, predicate, fromIndex) { + return function (collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = baseIteratee(predicate, 3); collection = keys(collection); - predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + predicate = function (key) { + return iteratee(iterable[key], key, iterable); + }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; @@ -4105,6 +4117,7 @@ } return fn.apply(thisBinding, args); } + return wrapper; } @@ -4117,7 +4130,7 @@ * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { - return function(object, iteratee) { + return function (object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } @@ -4154,6 +4167,7 @@ } return apply(fn, isBind ? thisArg : this, args); } + return wrapper; } @@ -4165,7 +4179,7 @@ * @returns {Function} Returns the new range function. */ function createRange(fromRight) { - return function(start, end, step) { + return function (start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined; } @@ -4232,7 +4246,7 @@ * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ - var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + var createSet = !(Set && (1 / setToArray(new Set([, -0]))[1]) == INFINITY) ? noop : function (values) { return new Set(values); }; @@ -4405,7 +4419,7 @@ } // Recursively compare arrays (susceptible to call stack limits). if (seen) { - if (!arraySome(other, function(othValue, othIndex) { + if (!arraySome(other, function (othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); @@ -4627,7 +4641,7 @@ * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ - var getData = !metaMap ? noop : function(func) { + var getData = !metaMap ? noop : function (func) { return metaMap.get(func); }; @@ -4727,7 +4741,8 @@ try { value[symToStringTag] = undefined; var unmasked = true; - } catch (e) {} + } catch (e) { + } var result = nativeObjectToString.call(value); if (unmasked) { @@ -4747,12 +4762,12 @@ * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + var getSymbols = !nativeGetSymbols ? stubArray : function (object) { if (object == null) { return []; } object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { + return arrayFilter(nativeGetSymbols(object), function (symbol) { return propertyIsEnumerable.call(object, symbol); }); }; @@ -4764,7 +4779,7 @@ * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ - var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var getSymbolsIn = !nativeGetSymbols ? stubArray : function (object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); @@ -4788,18 +4803,23 @@ (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { - getTag = function(value) { + getTag = function (value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { - case dataViewCtorString: return dataViewTag; - case mapCtorString: return mapTag; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag; - case weakMapCtorString: return weakMapTag; + case dataViewCtorString: + return dataViewTag; + case mapCtorString: + return mapTag; + case promiseCtorString: + return promiseTag; + case setCtorString: + return setTag; + case weakMapCtorString: + return weakMapTag; } } return result; @@ -4825,10 +4845,18 @@ size = data.size; switch (data.type) { - case 'drop': start += size; break; - case 'dropRight': end -= size; break; - case 'take': end = nativeMin(end, start + size); break; - case 'takeRight': start = nativeMax(start, end - size); break; + case 'drop': + start += size; + break; + case 'dropRight': + end -= size; + break; + case 'take': + end = nativeMin(end, start + size); + break; + case 'takeRight': + start = nativeMax(start, end - size); + break; } } return { 'start': start, 'end': end }; @@ -4934,9 +4962,15 @@ case dataViewTag: return cloneDataView(object, isDeep); - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + case float32Tag: + case float64Tag: + case int8Tag: + case int16Tag: + case int32Tag: + case uint8Tag: + case uint8ClampedTag: + case uint16Tag: + case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: @@ -5134,7 +5168,7 @@ * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { - return function(object) { + return function (object) { if (object == null) { return false; } @@ -5152,7 +5186,7 @@ * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { - var result = memoize(func, function(key) { + var result = memoize(func, function (key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } @@ -5275,7 +5309,7 @@ */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { + return function () { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), @@ -5382,7 +5416,7 @@ var count = 0, lastCalled = 0; - return function() { + return function () { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); @@ -5405,12 +5439,12 @@ * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ - var stringToPath = memoizeCapped(function(string) { + var stringToPath = memoizeCapped(function (string) { var result = []; if (string.charCodeAt(0) === 46 /* . */) { result.push(''); } - string.replace(rePropName, function(match, number, quote, subString) { + string.replace(rePropName, function (match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); }); return result; @@ -5442,10 +5476,12 @@ if (func != null) { try { return funcToString.call(func); - } catch (e) {} + } catch (e) { + } try { return (func + ''); - } catch (e) {} + } catch (e) { + } } return ''; } @@ -5459,7 +5495,7 @@ * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { - arrayEach(wrapFlags, function(pair) { + arrayEach(wrapFlags, function (pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { details.push(value); @@ -5481,7 +5517,7 @@ } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); - result.__index__ = wrapper.__index__; + result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } @@ -5617,7 +5653,7 @@ * _.difference([2, 1], [2, 3]); * // => [1] */ - var difference = baseRest(function(array, values) { + var difference = baseRest(function (array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; @@ -5885,7 +5921,7 @@ * _.intersection([2, 1], [2, 3]); * // => [2] */ - var intersection = baseRest(function(arrays) { + var intersection = baseRest(function (arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) @@ -5962,8 +5998,7 @@ if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { start = 0; end = length; - } - else { + } else { start = start == null ? 0 : toInteger(start); end = end === undefined ? length : toInteger(end); } @@ -6054,7 +6089,7 @@ * _.union([2], [1, 2]); * // => [2, 1] */ - var union = baseRest(function(arrays) { + var union = baseRest(function (arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); @@ -6131,13 +6166,13 @@ return []; } var length = 0; - array = arrayFilter(array, function(group) { + array = arrayFilter(array, function (group) { if (isArrayLikeObject(group)) { length = nativeMax(group.length, length); return true; } }); - return baseTimes(length, function(index) { + return baseTimes(length, function (index) { return arrayMap(array, baseProperty(index)); }); } @@ -6162,7 +6197,7 @@ * _.without([2, 1, 2, 3], 1, 2); * // => [3] */ - var without = baseRest(function(array, values) { + var without = baseRest(function (array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : []; @@ -6314,11 +6349,13 @@ * _(object).at(['a[0].b.c', 'a[1]']).value(); * // => [3, 4] */ - var wrapperAt = flatRest(function(paths) { + var wrapperAt = flatRest(function (paths) { var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, - interceptor = function(object) { return baseAt(object, paths); }; + interceptor = function (object) { + return baseAt(object, paths); + }; if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { @@ -6330,7 +6367,7 @@ 'args': [interceptor], 'thisArg': undefined }); - return new LodashWrapper(value, this.__chain__).thru(function(array) { + return new LodashWrapper(value, this.__chain__).thru(function (array) { if (length && !array.length) { array.push(undefined); } @@ -6577,7 +6614,7 @@ * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ - var countBy = createAggregator(function(result, value, key) { + var countBy = createAggregator(function (result, value, key) { if (hasOwnProperty.call(result, key)) { ++result[key]; } else { @@ -6772,7 +6809,7 @@ * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ - var groupBy = createAggregator(function(result, value, key) { + var groupBy = createAggregator(function (result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { @@ -7018,7 +7055,7 @@ * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] */ - var sortBy = baseRest(function(collection, iteratees) { + var sortBy = baseRest(function (collection, iteratees) { if (collection == null) { return []; } @@ -7049,7 +7086,7 @@ * }, _.now()); * // => Logs the number of milliseconds it took for the deferred invocation. */ - var now = function() { + var now = function () { return root.Date.now(); }; @@ -7084,7 +7121,7 @@ throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); - return function() { + return function () { if (--n < 1) { return func.apply(this, arguments); } @@ -7114,7 +7151,7 @@ throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); - return function() { + return function () { if (--n > 0) { result = func.apply(this, arguments); } @@ -7160,7 +7197,7 @@ * bound('hi'); * // => 'hi fred!' */ - var bind = baseRest(function(func, thisArg, partials) { + var bind = baseRest(function (func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); @@ -7342,6 +7379,7 @@ } return result; } + debounced.cancel = cancel; debounced.flush = flush; return debounced; @@ -7365,7 +7403,7 @@ * }, 'deferred'); * // => Logs 'deferred' after one millisecond. */ - var defer = baseRest(function(func, args) { + var defer = baseRest(function (func, args) { return baseDelay(func, 1, args); }); @@ -7388,7 +7426,7 @@ * }, 1000, 'later'); * // => Logs 'later' after one second. */ - var delay = baseRest(function(func, wait, args) { + var delay = baseRest(function (func, wait, args) { return baseDelay(func, toNumber(wait) || 0, args); }); @@ -7440,7 +7478,7 @@ if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } - var memoized = function() { + var memoized = function () { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; @@ -7483,13 +7521,17 @@ if (typeof predicate != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } - return function() { + return function () { var args = arguments; switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); + case 0: + return !predicate.call(this); + case 1: + return !predicate.call(this, args[0]); + case 2: + return !predicate.call(this, args[0], args[1]); + case 3: + return !predicate.call(this, args[0], args[1], args[2]); } return !predicate.apply(this, args); }; @@ -7720,7 +7762,9 @@ * _.isArguments([1, 2, 3]); * // => false */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + var isArguments = baseIsArguments(function () { + return arguments; + }()) ? baseIsArguments : function (value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; @@ -8609,7 +8653,7 @@ * _.assignIn({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } */ - var assignIn = createAssigner(function(object, source) { + var assignIn = createAssigner(function (object, source) { copyObject(source, keysIn(source), object); }); @@ -8673,7 +8717,7 @@ * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ - var defaults = baseRest(function(object, sources) { + var defaults = baseRest(function (object, sources) { object = Object(object); var index = -1; @@ -8723,7 +8767,7 @@ * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); * // => { 'a': { 'b': 2, 'c': 3 } } */ - var defaultsDeep = baseRest(function(args) { + var defaultsDeep = baseRest(function (args) { args.push(undefined, customDefaultsMerge); return apply(mergeWith, undefined, args); }); @@ -8915,7 +8959,7 @@ * _.invert(object); * // => { '1': 'c', '2': 'b' } */ - var invert = createInverter(function(result, value, key) { + var invert = createInverter(function (result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); @@ -8950,7 +8994,7 @@ * }); * // => { 'group1': ['a', 'c'], 'group2': ['b'] } */ - var invertBy = createInverter(function(result, value, key) { + var invertBy = createInverter(function (result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); @@ -9053,7 +9097,7 @@ * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ - var merge = createAssigner(function(object, source, srcIndex) { + var merge = createAssigner(function (object, source, srcIndex) { baseMerge(object, source, srcIndex); }); @@ -9088,7 +9132,7 @@ * _.mergeWith(object, other, customizer); * // => { 'a': [1, 3], 'b': [2, 4] } */ - var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { + var mergeWith = createAssigner(function (object, source, srcIndex, customizer) { baseMerge(object, source, srcIndex, customizer); }); @@ -9112,13 +9156,13 @@ * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ - var omit = flatRest(function(object, paths) { + var omit = flatRest(function (object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; - paths = arrayMap(paths, function(path) { + paths = arrayMap(paths, function (path) { path = castPath(path, object); isDeep || (isDeep = path.length > 1); return path; @@ -9175,7 +9219,7 @@ * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ - var pick = flatRest(function(object, paths) { + var pick = flatRest(function (object, paths) { return object == null ? {} : basePick(object, paths); }); @@ -9201,11 +9245,11 @@ if (object == null) { return {}; } - var props = arrayMap(getAllKeysIn(object), function(prop) { + var props = arrayMap(getAllKeysIn(object), function (prop) { return [prop]; }); predicate = baseIteratee(predicate); - return basePickBy(object, props, function(value, path) { + return basePickBy(object, props, function (value, path) { return predicate(value, path[0]); }); } @@ -9399,8 +9443,7 @@ if (typeof upper == 'boolean') { floating = upper; upper = undefined; - } - else if (typeof lower == 'boolean') { + } else if (typeof lower == 'boolean') { floating = lower; lower = undefined; } @@ -9408,8 +9451,7 @@ if (lower === undefined && upper === undefined) { lower = 0; upper = 1; - } - else { + } else { lower = toFinite(lower); if (upper === undefined) { upper = lower; @@ -9553,7 +9595,7 @@ * // => true */ function constant(value) { - return function() { + return function () { return value; }; } @@ -9706,11 +9748,11 @@ var chain = !(isObject(options) && 'chain' in options) || !!options.chain, isFunc = isFunction(object); - arrayEach(methodNames, function(methodName) { + arrayEach(methodNames, function (methodName) { var func = source[methodName]; object[methodName] = func; if (isFunc) { - object.prototype[methodName] = function() { + object.prototype[methodName] = function () { var chainAll = this.__chain__; if (chain || chainAll) { var result = object(this.__wrapped__), @@ -10065,9 +10107,9 @@ lodash.each = forEach; lodash.first = head; - mixin(lodash, (function() { + mixin(lodash, (function () { var source = {}; - baseForOwn(lodash, function(func, methodName) { + baseForOwn(lodash, function (func, methodName) { if (!hasOwnProperty.call(lodash.prototype, methodName)) { source[methodName] = func; } @@ -10087,8 +10129,8 @@ lodash.VERSION = VERSION; // Add `LazyWrapper` methods for `_.drop` and `_.take` variants. - arrayEach(['drop', 'take'], function(methodName, index) { - LazyWrapper.prototype[methodName] = function(n) { + arrayEach(['drop', 'take'], function (methodName, index) { + LazyWrapper.prototype[methodName] = function (n) { n = n === undefined ? 1 : nativeMax(toInteger(n), 0); var result = (this.__filtered__ && !index) @@ -10106,17 +10148,17 @@ return result; }; - LazyWrapper.prototype[methodName + 'Right'] = function(n) { + LazyWrapper.prototype[methodName + 'Right'] = function (n) { return this.reverse()[methodName](n).reverse(); }; }); // Add `LazyWrapper` methods that accept an `iteratee` value. - arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) { + arrayEach(['filter', 'map', 'takeWhile'], function (methodName, index) { var type = index + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; - LazyWrapper.prototype[methodName] = function(iteratee) { + LazyWrapper.prototype[methodName] = function (iteratee) { var result = this.clone(); result.__iteratees__.push({ 'iteratee': getIteratee(iteratee, 3), @@ -10128,49 +10170,49 @@ }); // Add `LazyWrapper` methods for `_.head` and `_.last`. - arrayEach(['head', 'last'], function(methodName, index) { + arrayEach(['head', 'last'], function (methodName, index) { var takeName = 'take' + (index ? 'Right' : ''); - LazyWrapper.prototype[methodName] = function() { + LazyWrapper.prototype[methodName] = function () { return this[takeName](1).value()[0]; }; }); // Add `LazyWrapper` methods for `_.initial` and `_.tail`. - arrayEach(['initial', 'tail'], function(methodName, index) { + arrayEach(['initial', 'tail'], function (methodName, index) { var dropName = 'drop' + (index ? '' : 'Right'); - LazyWrapper.prototype[methodName] = function() { + LazyWrapper.prototype[methodName] = function () { return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); }; }); - LazyWrapper.prototype.compact = function() { + LazyWrapper.prototype.compact = function () { return this.filter(identity); }; - LazyWrapper.prototype.find = function(predicate) { + LazyWrapper.prototype.find = function (predicate) { return this.filter(predicate).head(); }; - LazyWrapper.prototype.findLast = function(predicate) { + LazyWrapper.prototype.findLast = function (predicate) { return this.reverse().find(predicate); }; - LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { + LazyWrapper.prototype.invokeMap = baseRest(function (path, args) { if (typeof path == 'function') { return new LazyWrapper(this); } - return this.map(function(value) { + return this.map(function (value) { return baseInvoke(value, path, args); }); }); - LazyWrapper.prototype.reject = function(predicate) { + LazyWrapper.prototype.reject = function (predicate) { return this.filter(negate(getIteratee(predicate))); }; - LazyWrapper.prototype.slice = function(start, end) { + LazyWrapper.prototype.slice = function (start, end) { start = toInteger(start); var result = this; @@ -10189,16 +10231,16 @@ return result; }; - LazyWrapper.prototype.takeRightWhile = function(predicate) { + LazyWrapper.prototype.takeRightWhile = function (predicate) { return this.reverse().takeWhile(predicate).reverse(); }; - LazyWrapper.prototype.toArray = function() { + LazyWrapper.prototype.toArray = function () { return this.take(MAX_ARRAY_LENGTH); }; // Add `LazyWrapper` methods to `lodash.prototype`. - baseForOwn(LazyWrapper.prototype, function(func, methodName) { + baseForOwn(LazyWrapper.prototype, function (func, methodName) { var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName], @@ -10207,14 +10249,14 @@ if (!lodashFunc) { return; } - lodash.prototype[methodName] = function() { + lodash.prototype[methodName] = function () { var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee = args[0], useLazy = isLazy || isArray(value); - var interceptor = function(value) { + var interceptor = function (value) { var result = lodashFunc.apply(lodash, arrayPush([value], args)); return (isTaker && chainAll) ? result[0] : result; }; @@ -10243,25 +10285,25 @@ }); // Add `Array` methods to `lodash.prototype`. - arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { + arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function (methodName) { var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', retUnwrapped = /^(?:pop|shift)$/.test(methodName); - lodash.prototype[methodName] = function() { + lodash.prototype[methodName] = function () { var args = arguments; if (retUnwrapped && !this.__chain__) { var value = this.value(); return func.apply(isArray(value) ? value : [], args); } - return this[chainName](function(value) { + return this[chainName](function (value) { return func.apply(isArray(value) ? value : [], args); }); }; }); // Map minified method names to their real names. - baseForOwn(LazyWrapper.prototype, function(func, methodName) { + baseForOwn(LazyWrapper.prototype, function (func, methodName) { var lodashFunc = lodash[methodName]; if (lodashFunc) { var key = (lodashFunc.name + ''), @@ -10271,10 +10313,12 @@ } }); - realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{ - 'name': 'wrapper', - 'func': undefined - }]; + realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [ + { + 'name': 'wrapper', + 'func': undefined + } + ]; // Add methods to `LazyWrapper`. LazyWrapper.prototype.clone = lazyClone; @@ -10300,7 +10344,7 @@ // Define as an anonymous module so, through path mapping, it can be // referenced as the "underscore" module. - define(function() { + define(function () { return lodash; }); } @@ -10310,8 +10354,7 @@ (freeModule.exports = lodash)._ = lodash; // Export for CommonJS support. freeExports._ = lodash; - } - else { + } else { // Export to the global object. BI._ = lodash; } From 2287879d95fbd64c30b7428d5bbd6e3d276b1e31 Mon Sep 17 00:00:00 2001 From: zsmj Date: Thu, 12 Jan 2023 16:15:03 +0800 Subject: [PATCH 101/300] update --- src/widget/index.js | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/widget/index.js b/src/widget/index.js index 5d238bd4f..14146c7ae 100644 --- a/src/widget/index.js +++ b/src/widget/index.js @@ -46,11 +46,6 @@ export * from "./datetimepane"; export * from "./dynamicdatetime"; export * from "./time"; export * from "./editor"; -export { SelectTreeCombo } from "./selecttree/selecttree.combo"; -export { SingleTreeCombo } from "./singletree/singletree.combo"; -export { MultiTreeCombo } from "./multitree/multi.tree.combo"; -export { MultiTreeInsertCombo } from "./multitree/multi.tree.insert.combo"; -export { MultiTreeListCombo } from "./multitree/multi.tree.list.combo"; export * from "./multiselect"; export * from "./multiselectlist"; From f87bab8068dd4271cad76b57d4d8f777436cd510 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Thu, 12 Jan 2023 16:26:37 +0800 Subject: [PATCH 102/300] =?UTF-8?q?KERNEL-14083=20refactor:=20widget/downl?= =?UTF-8?q?ist=E3=80=81singleslider=E3=80=81intervalslider=20es6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/case/calendar/calendar.js | 4 +- src/case/layer/panel.js | 4 +- src/case/list/list.select.js | 10 +- src/core/wrapper/layout/flex/flex.vertical.js | 1 - src/widget/downlist/combo.downlist.js | 268 ++++--- src/widget/downlist/group.downlist.js | 113 +-- src/widget/downlist/index.js | 5 + src/widget/downlist/item.downlist.js | 227 +++--- src/widget/downlist/item.downlistgroup.js | 259 ++++--- src/widget/downlist/popup.downlist.js | 587 +++++++------- src/widget/index.js | 9 + src/widget/intervalslider/index.js | 2 + src/widget/intervalslider/intervalslider.js | 726 ++++++++++-------- .../model.accuratecalculation.js | 271 ++++--- .../singleslider/button/editor.sign.text.js | 265 ++++--- .../singleslider/button/iconbutton.slider.js | 28 +- src/widget/singleslider/index.js | 5 + src/widget/singleslider/singleslider.js | 526 +++++++------ src/widget/singleslider/singleslider.label.js | 464 ++++++----- .../singleslider/singleslider.normal.js | 430 ++++++----- 20 files changed, 2350 insertions(+), 1854 deletions(-) create mode 100644 src/widget/downlist/index.js create mode 100644 src/widget/intervalslider/index.js create mode 100644 src/widget/singleslider/index.js diff --git a/src/case/calendar/calendar.js b/src/case/calendar/calendar.js index b656a271e..b049e18b4 100644 --- a/src/case/calendar/calendar.js +++ b/src/case/calendar/calendar.js @@ -139,8 +139,8 @@ export class Calendar extends Widget { rowSize: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + 8, }))], }); - this.days.on(Controller.EVENT_CHANGE, () => { - this.fireEvent(Controller.EVENT_CHANGE, arguments); + this.days.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); createWidget(extend({ element: this, diff --git a/src/case/layer/panel.js b/src/case/layer/panel.js index 51bd4fc50..de18dc35f 100644 --- a/src/case/layer/panel.js +++ b/src/case/layer/panel.js @@ -50,8 +50,8 @@ export class Panel extends Widget { }], }); - this.button_group.on(Controller.EVENT_CHANGE, () => { - this.fireEvent(Controller.EVENT_CHANGE, ...arguments); + this.button_group.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); this.button_group.on(ButtonGroup.EVENT_CHANGE, (value, obj) => { diff --git a/src/case/list/list.select.js b/src/case/list/list.select.js index e9fce794a..88f4856c6 100644 --- a/src/case/list/list.select.js +++ b/src/case/list/list.select.js @@ -55,13 +55,14 @@ export class SelectList extends Widget { // 全选 this.toolbar = createWidget(o.toolbar); this.allSelected = false; - this.toolbar.on(Controller.EVENT_CHANGE, (type, value, obj) => { + this.toolbar.on(Controller.EVENT_CHANGE, (...args) => { + const [type, value, obj] = args; this.allSelected = this.toolbar.isSelected(); if (type === Events.CLICK) { this.setAllSelected(this.allSelected); this.fireEvent(SelectList.EVENT_CHANGE, value, obj); } - this.fireEvent(Controller.EVENT_CHANGE, arguments); + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); this.list = createWidget(o.el, { @@ -84,12 +85,13 @@ export class SelectList extends Widget { hasNext: o.hasNext, }); - this.list.on(Controller.EVENT_CHANGE, (type, value, obj) => { + this.list.on(Controller.EVENT_CHANGE, (...args) => { + const [type, value, obj] = args; if (type === Events.CLICK) { this._checkAllSelected(); this.fireEvent(SelectList.EVENT_CHANGE, value, obj); } - this.fireEvent(Controller.EVENT_CHANGE, arguments); + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); createWidget(extend({ diff --git a/src/core/wrapper/layout/flex/flex.vertical.js b/src/core/wrapper/layout/flex/flex.vertical.js index fefc7abad..5ee654642 100644 --- a/src/core/wrapper/layout/flex/flex.vertical.js +++ b/src/core/wrapper/layout/flex/flex.vertical.js @@ -12,7 +12,6 @@ import { Layout } from "../../layout"; @shortcut() export class FlexVerticalLayout extends Layout { static xtype = "bi.flex_vertical"; - props() { return extend(super.props(...arguments), { baseCls: "bi-f-v", diff --git a/src/widget/downlist/combo.downlist.js b/src/widget/downlist/combo.downlist.js index 10c39bfbf..eb4c9e636 100644 --- a/src/widget/downlist/combo.downlist.js +++ b/src/widget/downlist/combo.downlist.js @@ -1,143 +1,155 @@ -(function() { - function transformItems(items) { - if (!items) return items; - var result = BI.cloneDeep(items); - var isComplexItmes = BI.some(items, function (_, item) { - return BI.isArray(item); +import { shortcut, Widget, extend, createWidget, cloneDeep, some, isArray, each } from "@/core"; +import { DownListPopup } from "./popup.downlist"; +import { Combo } from "@/base"; +import { IconTrigger } from "@/case"; + + +function transformItems(items) { + if (!items) return items; + let result = cloneDeep(items); + const isComplexItmes = some(items, (_, item) => isArray(item)); + // 传一维数组,帮转二维 + if (!isComplexItmes) { + result = [result]; + } + // 帮转 el + each(result, (_, arr) => { + each(arr, (_, item) => { + if (item.children && !item.el) { + item.el = { + text: item.text, + icon: item.icon, + cls: item.cls, + iconCls1: item.iconCls1, + value: item.value, + }; + } }); - // 传一维数组,帮转二维 - if (!isComplexItmes) { - result = [result]; - } - // 帮转 el - BI.each(result, function (_, arr) { - BI.each(arr, function (_, item) { - if (item.children && !item.el) { - item.el = { - text: item.text, - icon: item.icon, - cls: item.cls, - iconCls1: item.iconCls1, - value: item.value - }; - } - }); + }); + + return result; +} + +@shortcut() +export class DownListCombo extends Widget { + static xtype = "bi.down_list_combo"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_SON_VALUE_CHANGE = "EVENT_SON_VALUE_CHANGE"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { + baseCls: "bi-down-list-combo", + height: 24, + items: [], + adjustLength: 0, + direction: "bottom", + trigger: "click", + container: null, + stopPropagation: false, + el: {}, + popup: {}, + minWidth: 140, + maxHeight: 1000, + destroyWhenHide: false, + isDefaultInit: true, }); - return result; } - /** - * Created by roy on 15/8/14. - */ - BI.DownListCombo = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.DownListCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: "bi-down-list-combo", - height: 24, - items: [], - adjustLength: 0, - direction: "bottom", - trigger: "click", - container: null, - stopPropagation: false, - el: {}, - popup: {}, - minWidth: 140, - maxHeight: 1000, - destroyWhenHide: false, - isDefaultInit: true, - }); - }, + _init() { + super._init(...arguments); + const o = this.options; - _init: function () { - BI.DownListCombo.superclass._init.apply(this, arguments); - var self = this, o = this.options; - - this.downlistcombo = BI.createWidget({ - element: this, - type: "bi.combo", - trigger: o.trigger, - isNeedAdjustWidth: false, - isDefaultInit: o.isDefaultInit, - container: o.container, - adjustLength: o.adjustLength, - direction: o.direction, - belowMouse: o.belowMouse, - stopPropagation: o.stopPropagation, - destroyWhenHide: o.destroyWhenHide, + this.downlistcombo = createWidget({ + element: this, + type: Combo.xtype, + trigger: o.trigger, + isNeedAdjustWidth: false, + isDefaultInit: o.isDefaultInit, + container: o.container, + adjustLength: o.adjustLength, + direction: o.direction, + belowMouse: o.belowMouse, + stopPropagation: o.stopPropagation, + destroyWhenHide: o.destroyWhenHide, + el: { + type: IconTrigger.xtype, + extraCls: o.iconCls, + width: o.width, + height: o.height, + ...o.el, + }, + popup: { el: { - type: "bi.icon_trigger", - extraCls: o.iconCls, - width: o.width, - height: o.height, - ...o.el - }, - popup: { - el: { - type: "bi.down_list_popup", - ref: function (ref) { - self.popupView = ref; - }, - items: transformItems(o.items), - chooseType: o.chooseType, - value: o.value, - listeners: [{ - eventName: BI.DownListPopup.EVENT_CHANGE, - action: function (value) { - self.fireEvent(BI.DownListCombo.EVENT_CHANGE, value); - self.downlistcombo.hideView(); - } - }, { - eventName: BI.DownListPopup.EVENT_SON_VALUE_CHANGE, - action: function (value, fatherValue) { - self.fireEvent(BI.DownListCombo.EVENT_SON_VALUE_CHANGE, value, fatherValue); - self.downlistcombo.hideView(); - } - }] + type: DownListPopup.xtype, + ref: _ref => { + this.popupView = _ref; }, - stopPropagation: o.stopPropagation, - maxHeight: o.maxHeight, - minWidth: o.minWidth, - ...o.popup - } - }); - - this.downlistcombo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { - self.fireEvent(BI.DownListCombo.EVENT_BEFORE_POPUPVIEW); - }); - }, + items: transformItems(o.items), + chooseType: o.chooseType, + value: o.value, + listeners: [ + { + eventName: DownListPopup.EVENT_CHANGE, + action: value => { + this.fireEvent( + DownListCombo.EVENT_CHANGE, + value + ); + this.downlistcombo.hideView(); + }, + }, + { + eventName: DownListPopup.EVENT_SON_VALUE_CHANGE, + action: (value, fatherValue) => { + this.fireEvent( + DownListCombo.EVENT_SON_VALUE_CHANGE, + value, + fatherValue + ); + this.downlistcombo.hideView(); + }, + } + ], + }, + stopPropagation: o.stopPropagation, + maxHeight: o.maxHeight, + minWidth: o.minWidth, + ...o.popup, + }, + }); - hideView: function () { - this.downlistcombo.hideView(); - }, + this.downlistcombo.on(Combo.EVENT_BEFORE_POPUPVIEW, () => { + this.fireEvent(DownListCombo.EVENT_BEFORE_POPUPVIEW); + }); + } - showView: function (e) { - this.downlistcombo.showView(e); - }, + hideView() { + this.downlistcombo.hideView(); + } - populate: function (items) { - this.popupView.populate(items); - }, + showView(e) { + this.downlistcombo.showView(e); + } - setValue: function (v) { - this.popupView.setValue(v); - }, + populate(items) { + this.popupView.populate(items); + } - getValue: function () { - return this.popupView.getValue(); - }, + setValue(v) { + this.popupView.setValue(v); + } - adjustWidth: function () { - this.downlistcombo.adjustWidth(); - }, + getValue() { + return this.popupView.getValue(); + } - adjustHeight: function () { - this.downlistcombo.adjustHeight(); - } - }); - BI.DownListCombo.EVENT_CHANGE = "EVENT_CHANGE"; - BI.DownListCombo.EVENT_SON_VALUE_CHANGE = "EVENT_SON_VALUE_CHANGE"; - BI.DownListCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + adjustWidth() { + this.downlistcombo.adjustWidth(); + } - BI.shortcut("bi.down_list_combo", BI.DownListCombo); -}()); + adjustHeight() { + this.downlistcombo.adjustHeight(); + } +} diff --git a/src/widget/downlist/group.downlist.js b/src/widget/downlist/group.downlist.js index c7cc2ce49..2d06f83e0 100644 --- a/src/widget/downlist/group.downlist.js +++ b/src/widget/downlist/group.downlist.js @@ -1,51 +1,62 @@ -/** - * Created by roy on 15/9/6. - */ -BI.DownListGroup = BI.inherit(BI.Widget, { - constants: { - iconCls: "check-mark-ha-font" - }, - _defaultConfig: function () { - return BI.extend(BI.DownListGroup.superclass._defaultConfig.apply(this, arguments), { - baseCls: "bi-down-list-group", - items: [ - { - el: {} - } - ] - }); - }, - _init: function () { - BI.DownListGroup.superclass._init.apply(this, arguments); - var o = this.options, self = this; - - this.downlistgroup = BI.createWidget({ - element: this, - type: "bi.button_tree", - items: o.items, - chooseType: 0, // 0单选,1多选 - layouts: [{ - type: "bi.vertical", - hgap: 0, - vgap: 0 - }], - value: o.value - }); - this.downlistgroup.on(BI.Controller.EVENT_CHANGE, function (type) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if(type === BI.Events.CLICK) { - self.fireEvent(BI.DownListGroup.EVENT_CHANGE, arguments); - } - }); - }, - getValue: function () { - return this.downlistgroup.getValue(); - }, - setValue: function (v) { - this.downlistgroup.setValue(v); - } - - -}); -BI.DownListGroup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.down_list_group", BI.DownListGroup); \ No newline at end of file +import { + shortcut, + Widget, + extend, + createWidget, + Controller, + Events +} from "@/core"; + +@shortcut() +export class DownListGroup extends Widget { + static xtype = "bi.down_list_group"; + + constants = { iconCls: "check-mark-ha-font" }; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { + baseCls: "bi-down-list-group", + items: [ + { + el: {}, + } + ], + }); + } + + _init() { + super._init(...arguments); + const o = this.options; + + this.downlistgroup = createWidget({ + element: this, + type: "bi.button_tree", + items: o.items, + chooseType: 0, // 0单选,1多选 + layouts: [ + { + type: "bi.vertical", + hgap: 0, + vgap: 0, + } + ], + value: o.value, + }); + this.downlistgroup.on(Controller.EVENT_CHANGE, (type, ...args) => { + this.fireEvent(Controller.EVENT_CHANGE, type, ...args); + if (type === Events.CLICK) { + this.fireEvent(DownListGroup.EVENT_CHANGE, type, ...args); + } + }); + } + + getValue() { + return this.downlistgroup.getValue(); + } + + setValue(v) { + this.downlistgroup.setValue(v); + } +} diff --git a/src/widget/downlist/index.js b/src/widget/downlist/index.js new file mode 100644 index 000000000..07a86df06 --- /dev/null +++ b/src/widget/downlist/index.js @@ -0,0 +1,5 @@ +export { DownListGroup } from "./group.downlist"; +export { DownListItem } from "./item.downlist"; +export { DownListGroupItem } from "./item.downlistgroup"; +export { DownListPopup } from "./popup.downlist"; +export { DownListCombo } from "./combo.downlist"; diff --git a/src/widget/downlist/item.downlist.js b/src/widget/downlist/item.downlist.js index 531806ca0..1a1598490 100644 --- a/src/widget/downlist/item.downlist.js +++ b/src/widget/downlist/item.downlist.js @@ -1,102 +1,125 @@ -BI.DownListItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - var conf = BI.DownListItem.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: "bi-down-list-item bi-list-item-active", - cls: "", - height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - logic: { - dynamic: true - }, - selected: false, - iconHeight: null, - iconWidth: null, - textHgap: 0, - textVgap: 0, - textLgap: 0, - textRgap: 0 - }); - }, - _init: function () { - BI.DownListItem.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.text = BI.createWidget({ - type: "bi.label", - cls: "list-item-text", - textAlign: "left", - hgap: o.textHgap, - vgap: o.textVgap, - lgap: o.textLgap, - rgap: o.textRgap, - text: o.text, - value: o.value, - keyword: o.keyword, - height: o.height - }); - - - var icon = BI.isPlainObject(o.icon) ? o.icon : { - type: "bi.icon", - width: o.iconWidth, - height: o.iconHeight, - } - - this.icon = BI.createWidget({ - type: "bi.center_adapt", - width: 36, - height: o.height, - items: [{ - el: icon, - }], - }); - - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left), BI.extend(o.logic, { - items: BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, this.icon, this.text) - })))); - }, - - setValue: function () { - if (!this.isReadOnly()) { - this.text.setValue.apply(this.text, arguments); - } - }, - - getValue: function () { - return this.text.getValue(); - }, - - setText: function () { - this.text.setText.apply(this.text, arguments); - }, - - getText: function () { - return this.text.getText(); - }, - - doClick: function () { - BI.DownListItem.superclass.doClick.apply(this, arguments); - if (this.isValid()) { - this.fireEvent(BI.DownListItem.EVENT_CHANGE, this.getValue(), this); - } - }, - - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, - - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, - - doHighLight: function () { - this.text.doHighLight.apply(this.text, arguments); - }, - - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - } -}); -BI.DownListItem.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.down_list_item", BI.DownListItem); \ No newline at end of file +import { shortcut, extend, createWidget, isPlainObject, LogicFactory, Direction } from "@/core"; +import { BasicButton } from "@/base"; + +@shortcut() +export class DownListItem extends BasicButton { + static xtype = "bi.down_list_item"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: "bi-down-list-item bi-list-item-active", + cls: "", + height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, + logic: { + dynamic: true, + }, + selected: false, + iconHeight: null, + iconWidth: null, + textHgap: 0, + textVgap: 0, + textLgap: 0, + textRgap: 0, + }); + } + + _init() { + super._init(...arguments); + const o = this.options; + this.text = createWidget({ + type: "bi.label", + cls: "list-item-text", + textAlign: "left", + hgap: o.textHgap, + vgap: o.textVgap, + lgap: o.textLgap, + rgap: o.textRgap, + text: o.text, + value: o.value, + keyword: o.keyword, + height: o.height, + }); + + const icon = isPlainObject(o.icon) + ? o.icon + : { + type: "bi.icon", + width: o.iconWidth, + height: o.iconHeight, + }; + + this.icon = createWidget({ + type: "bi.center_adapt", + width: 36, + height: o.height, + items: [ + { + el: icon, + } + ], + }); + + createWidget( + extend( + { + element: this, + }, + LogicFactory.createLogic( + LogicFactory.createLogicTypeByDirection(Direction.Left), + extend(o.logic, { + items: LogicFactory.createLogicItemsByDirection( + Direction.Left, + this.icon, + this.text + ), + }) + ) + ) + ); + } + + setValue() { + if (!this.isReadOnly()) { + this.text.setValue(...arguments); + } + } + + getValue() { + return this.text.getValue(); + } + + setText() { + this.text.setText(...arguments); + } + + getText() { + return this.text.getText(); + } + + doClick() { + super.doClick(...arguments); + if (this.isValid()) { + this.fireEvent(DownListItem.EVENT_CHANGE, this.getValue(), this); + } + } + + doRedMark() { + this.text.doRedMark(...arguments); + } + + unRedMark() { + this.text.unRedMark(...arguments); + } + + doHighLight() { + this.text.doHighLight(...arguments); + } + + unHighLight() { + this.text.unHighLight(...arguments); + } +} diff --git a/src/widget/downlist/item.downlistgroup.js b/src/widget/downlist/item.downlistgroup.js index df4a09ac7..d2c9d14a7 100644 --- a/src/widget/downlist/item.downlistgroup.js +++ b/src/widget/downlist/item.downlistgroup.js @@ -1,118 +1,141 @@ -BI.DownListGroupItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - var conf = BI.DownListGroupItem.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-down-list-group-item", - logic: { - dynamic: false - }, - // invalid: true, - iconCls1: "dot-e-font", - icon: "", - iconCls2: "pull-right-e-font" - }); - }, - render: function () { - var o = this.options; - var self = this; - this.text = BI.createWidget({ - type: "bi.label", - cls: "list-group-item-text", - textAlign: "left", - text: o.text, - value: o.value, - height: o.height, - }); - - if (BI.isPlainObject(o.icon)) { - this.icon1 = BI.createWidget({ - width: 36, - height: o.height, - type: "bi.center_adapt", - items: [o.icon], - }); - } else { - this.icon1 = BI.createWidget({ - type: "bi.icon_button", - cls: o.iconCls1, - width: 36, - height: o.height, - iconHeight: o.iconHeight, - iconWidth: 36, - disableSelected: true, - selected: this._digest(o.value), - }); - } - - this.icon2 = BI.createWidget({ - type: "bi.icon_button", - cls: o.iconCls2, - width: 24, - forceNotSelected: true - }); - - this.element.hover(function () { - if (self.isEnabled()) { - self.hover(); - } - }, function () { - if (self.isEnabled()) { - self.dishover(); - } - }); - - return { - type: "bi.horizontal_fill", - columnSize: [36, "fill", 24], - items: [this.icon1, this.text, this.icon2] - } - }, - - _getLevel: function () { - var child = BI.first(this.options.childValues); - return BI.isNotNull(child) ? (child + "").split(BI.BlankSplitChar).length : 0; - }, - - _digest: function (v) { - var self = this, o = this.options; - v = BI.isArray(v) ? v : [v]; - var level = this._getLevel(); - return BI.any(v, function (idx, value) { - return BI.contains(o.childValues, (value + "").split(BI.BlankSplitChar).slice(0, level).join(BI.BlankSplitChar)); - }); - }, - - hover: function () { - BI.DownListGroupItem.superclass.hover.apply(this, arguments); - this.icon1.element.addClass("hover"); - this.icon2.element.addClass("hover"); - - }, - - dishover: function () { - BI.DownListGroupItem.superclass.dishover.apply(this, arguments); - this.icon1.element.removeClass("hover"); - this.icon2.element.removeClass("hover"); - }, - - doClick: function () { - BI.DownListGroupItem.superclass.doClick.apply(this, arguments); - if (this.isValid()) { - this.fireEvent(BI.DownListGroupItem.EVENT_CHANGE, this.getValue()); - } - }, - - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, - - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, - - setValue: function (v) { - this.icon1.setSelected && this.icon1.setSelected(this._digest(v)); - }, -}); -BI.DownListGroupItem.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.down_list_group_item", BI.DownListGroupItem); +import { + shortcut, + extend, + createWidget, + isNotNull, + isArray, + any, + contains, + isPlainObject, + first, + BlankSplitChar +} from "@/core"; +import { BasicButton } from "@/base"; + +@shortcut() +export class DownListGroupItem extends BasicButton { + static xtype = "bi.down_list_group_item"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-down-list-group-item`, + logic: { + dynamic: false, + }, + // invalid: true, + iconCls1: "dot-e-font", + icon: "", + iconCls2: "pull-right-e-font", + }); + } + + render() { + const o = this.options; + this.text = createWidget({ + type: "bi.label", + cls: "list-group-item-text", + textAlign: "left", + text: o.text, + value: o.value, + height: o.height, + }); + + if (isPlainObject(o.icon)) { + this.icon1 = createWidget({ + width: 36, + height: o.height, + type: "bi.center_adapt", + items: [o.icon], + }); + } else { + this.icon1 = createWidget({ + type: "bi.icon_button", + cls: o.iconCls1, + width: 36, + height: o.height, + iconHeight: o.iconHeight, + iconWidth: 36, + disableSelected: true, + selected: this._digest(o.value), + }); + } + + this.icon2 = createWidget({ + type: "bi.icon_button", + cls: o.iconCls2, + width: 24, + forceNotSelected: true, + }); + + this.element.hover( + () => { + if (this.isEnabled()) { + this.hover(); + } + }, + () => { + if (this.isEnabled()) { + this.dishover(); + } + } + ); + + return { + type: "bi.horizontal_fill", + columnSize: [36, "fill", 24], + items: [this.icon1, this.text, this.icon2], + }; + } + + _getLevel() { + const child = first(this.options.childValues); + + return isNotNull(child) ? (`${child}`).split(BlankSplitChar).length : 0; + } + + _digest(v) { + const o = this.options; + v = isArray(v) ? v : [v]; + const level = this._getLevel(); + + return any(v, (idx, value) => contains( + o.childValues, + (`${value}`).split(BlankSplitChar).slice(0, level).join(BlankSplitChar) + )); + } + + hover() { + super.hover(...arguments); + this.icon1.element.addClass("hover"); + this.icon2.element.addClass("hover"); + } + + dishover() { + super.dishover(...arguments); + this.icon1.element.removeClass("hover"); + this.icon2.element.removeClass("hover"); + } + + doClick() { + super.doClick(...arguments); + if (this.isValid()) { + this.fireEvent(DownListGroupItem.EVENT_CHANGE, this.getValue()); + } + } + + doRedMark() { + this.text.doRedMark(...arguments); + } + + unRedMark() { + this.text.unRedMark(...arguments); + } + + setValue(v) { + this.icon1.setSelected && this.icon1.setSelected(this._digest(v)); + } +} diff --git a/src/widget/downlist/popup.downlist.js b/src/widget/downlist/popup.downlist.js index 0e802a695..9ca7e0edd 100644 --- a/src/widget/downlist/popup.downlist.js +++ b/src/widget/downlist/popup.downlist.js @@ -1,301 +1,332 @@ -/** - * Created by roy on 15/9/8. - * 处理popup中的item分组样式 - * 一个item分组中的成员大于一时,该分组设置为单选,并且默认状态第一个成员设置为已选择项 - */ -BI.DownListPopup = BI.inherit(BI.Pane, { - constants: { - nextIcon: "pull-right-e-font", - height: 24, - iconHeight: 12, - iconWidth: 12, - hgap: 0, - vgap: 0, - border: 1 - }, - _defaultConfig: function () { - var conf = BI.DownListPopup.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: "bi-down-list-popup", - items: [], - chooseType: BI.Selection.Multi - }); - }, - _init: function () { - BI.DownListPopup.superclass._init.apply(this, arguments); - this.singleValues = []; - this.childValueMap = {}; - this.fatherValueMap = {}; - this.items = []; - var self = this, o = this.options, children = this._createPopupItems(o.items); - this.popup = BI.createWidget({ - type: "bi.button_tree", - items: BI.createItems(children, - {}, { - adjustLength: -2 - } - ), - layouts: [{ - type: "bi.vertical", - hgap: this.constants.hgap, - vgap: this.constants.vgap - }], - value: this._digest(o.value), - chooseType: o.chooseType - }); +import { + shortcut, + extend, + createWidget, + createItems, + isNotNull, + contains, + each, + isEmpty, + map, + isNotEmptyString, + isNotEmptyArray, + some, + deepClone +} from "@/core"; +import { Pane, ButtonTree } from "@/base"; - this.popup.on(BI.ButtonTree.EVENT_CHANGE, function (value, object) { - var changedValue = value; - if (BI.isNotNull(self.childValueMap[value])) { - changedValue = self.childValueMap[value]; - self.fireEvent(BI.DownListPopup.EVENT_SON_VALUE_CHANGE, changedValue, self.fatherValueMap[value]); - } else { - self.fireEvent(BI.DownListPopup.EVENT_CHANGE, changedValue, object); - } +@shortcut() +export class DownListPopup extends Pane { + static xtype = "bi.down_list_popup"; + constants = { + nextIcon: "pull-right-e-font", + height: 24, + iconHeight: 12, + iconWidth: 12, + hgap: 0, + vgap: 0, + border: 1, + }; - if (!BI.contains(self.singleValues, changedValue)) { - var item = self.getValue(); - var result = []; - BI.each(item, function (i, valueObject) { - if (valueObject.value != changedValue) { - result.push(valueObject); - } - }); - self.setValue(result); - } + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_SON_VALUE_CHANGE = "EVENT_SON_VALUE_CHANGE"; - }); + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: "bi-down-list-popup", + items: [], + chooseType: Selection.Multi, + }); + } - BI.createWidget({ - type: "bi.vertical", - element: this, - items: [this.popup], - vgap: 5 - }); + _init() { + super._init(...arguments); + this.singleValues = []; + this.childValueMap = {}; + this.fatherValueMap = {}; + this.items = []; + const o = this.options, + children = this._createPopupItems(o.items); + this.popup = createWidget({ + type: "bi.button_tree", + items: createItems( + children, + {}, + { + adjustLength: -2, + } + ), + layouts: [ + { + type: "bi.vertical", + hgap: this.constants.hgap, + vgap: this.constants.vgap, + } + ], + value: this._digest(o.value), + chooseType: o.chooseType, + }); - }, - _createPopupItems: function (items) { - var self = this, result = []; - // 不能修改populate进来的item的引用 - BI.each(items, function (i, it) { - var item_done = { - type: "bi.down_list_group", - items: [] - }; + this.popup.on(ButtonTree.EVENT_CHANGE, (value, object) => { + let changedValue = value; + if (isNotNull(this.childValueMap[value])) { + changedValue = this.childValueMap[value]; + this.fireEvent( + DownListPopup.EVENT_SON_VALUE_CHANGE, + changedValue, + this.fatherValueMap[value] + ); + } else { + this.fireEvent(DownListPopup.EVENT_CHANGE, changedValue, object); + } - var storeItem = []; + if (!contains(this.singleValues, changedValue)) { + const item = this.getValue(); + const result = []; + each(item, (i, valueObject) => { + if (valueObject.value !== changedValue) { + result.push(valueObject); + } + }); + this.setValue(result); + } + }); - BI.each(it, function (i, sourceItem) { - var item = BI.extend({}, sourceItem); - if (BI.isNotEmptyArray(sourceItem.children) && !BI.isEmpty(sourceItem.el)) { - item.type = "bi.combo_group"; - // popup未初始化返回的是options中的value, 在经过buttontree的getValue concat之后,无法区分值来自options - // 还是item自身, 这边控制defaultInit为true来避免这个问题 - item.isDefaultInit = true; - item.cls = "down-list-group"; - item.trigger = "hover"; - item.isNeedAdjustWidth = false; - item.el = sourceItem.el; - item.el.title = sourceItem.el.title || sourceItem.el.text; - item.el.type = "bi.down_list_group_item"; - item.el.logic = { - dynamic: true - }; - item.el.height = sourceItem.el.height || BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT; - item.el.iconCls2 = self.constants.nextIcon; - item.popup = { - lgap: 1, - el: { - type: "bi.button_tree", - chooseType: 0, - layouts: [{ - type: "bi.vertical" - }] + createWidget({ + type: "bi.vertical", + element: this, + items: [this.popup], + vgap: 5, + }); + } - }, - innerVgap: 5, - maxHeight: 378 - }; - self._createChildren(item, sourceItem); - } else { - item.type = sourceItem.type || "bi.down_list_item"; - item.title = sourceItem.title || sourceItem.text; - item.textRgap = 10; - item.isNeedAdjustWidth = false; - item.logic = { - dynamic: true - }; - } - var el_done = {}; - el_done.el = item; - item_done.items.push(el_done); - storeItem.push(item); - }); - if (self._isGroup(item_done.items)) { - BI.each(item_done.items, function (i, item) { - self.singleValues.push(item.el.value); - }); - } + _createPopupItems(items) { + const result = []; + // 不能修改populate进来的item的引用 + each(items, (i, it) => { + const item_done = { + type: "bi.down_list_group", + items: [], + }; - result.push(item_done); - self.items.push(storeItem); - if (self._needSpliter(i, items.length)) { - var spliter_container = BI.createWidget({ - type: "bi.vertical", - items: [{ - el: { - type: "bi.layout", - cls: "bi-down-list-spliter bi-split-top cursor-pointer", - height: 0 - } + const storeItem = []; - }], - cls: "bi-down-list-spliter-container cursor-pointer", - vgap: 5, - hgap: 12 - }); - result.push(spliter_container); - } - }); - return result; - }, + each(it, (i, sourceItem) => { + const item = extend({}, sourceItem); + if (isNotEmptyArray(sourceItem.children) && !isEmpty(sourceItem.el)) { + item.type = "bi.combo_group"; + // popup未初始化返回的是options中的value, 在经过buttontree的getValue concat之后,无法区分值来自options + // 还是item自身, 这边控制defaultInit为true来避免这个问题 + item.isDefaultInit = true; + item.cls = "down-list-group"; + item.trigger = "hover"; + item.isNeedAdjustWidth = false; + item.el = sourceItem.el; + item.el.title = sourceItem.el.title || sourceItem.el.text; + item.el.type = "bi.down_list_group_item"; + item.el.logic = { + dynamic: true, + }; + item.el.height = + sourceItem.el.height || BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT; + item.el.iconCls2 = this.constants.nextIcon; + item.popup = { + lgap: 1, + el: { + type: "bi.button_tree", + chooseType: 0, + layouts: [ + { + type: "bi.vertical", + } + ], + }, + innerVgap: 5, + maxHeight: 378, + }; + this._createChildren(item, sourceItem); + } else { + item.type = sourceItem.type || "bi.down_list_item"; + item.title = sourceItem.title || sourceItem.text; + item.textRgap = 10; + item.isNeedAdjustWidth = false; + item.logic = { + dynamic: true, + }; + } + const el_done = {}; + el_done.el = item; + item_done.items.push(el_done); + storeItem.push(item); + }); + if (this._isGroup(item_done.items)) { + each(item_done.items, (i, item) => { + this.singleValues.push(item.el.value); + }); + } - _createChildren: function (targetItem, sourceItem) { - var self = this; - targetItem.el.childValues = []; - targetItem.items = targetItem.children = []; - BI.each(sourceItem.children, function (i, child) { - var item = BI.extend({}, child); - var fatherValue = BI.deepClone(targetItem.el.value); - var childValue = BI.deepClone(item.value); - self.singleValues.push(item.value); - item.type = item.type || "bi.down_list_item"; - item.extraCls = " child-down-list-item"; - item.title = item.title || item.text; - item.textRgap = 10; - item.isNeedAdjustWidth = false; - item.logic = { - dynamic: true - }; - item.father = fatherValue; - item.childValue = item.value; - self.fatherValueMap[self._createChildValue(fatherValue, childValue)] = fatherValue; - self.childValueMap[self._createChildValue(fatherValue, childValue)] = childValue; - item.value = self._createChildValue(fatherValue, childValue); - targetItem.el.childValues.push(item.value); - targetItem.items.push(item); - }); - }, + result.push(item_done); + this.items.push(storeItem); + if (this._needSpliter(i, items.length)) { + const spliter_container = createWidget({ + type: "bi.vertical", + items: [ + { + el: { + type: "bi.layout", + cls: "bi-down-list-spliter bi-split-top cursor-pointer", + height: 0, + }, + } + ], + cls: "bi-down-list-spliter-container cursor-pointer", + vgap: 5, + hgap: 12, + }); + result.push(spliter_container); + } + }); + + return result; + } - _isGroup: function (i) { - return i.length > 1; - }, + _createChildren(targetItem, sourceItem) { + targetItem.el.childValues = []; + targetItem.items = targetItem.children = []; + each(sourceItem.children, (i, child) => { + const item = extend({}, child); + const fatherValue = deepClone(targetItem.el.value); + const childValue = deepClone(item.value); + this.singleValues.push(item.value); + item.type = item.type || "bi.down_list_item"; + item.extraCls = " child-down-list-item"; + item.title = item.title || item.text; + item.textRgap = 10; + item.isNeedAdjustWidth = false; + item.logic = { + dynamic: true, + }; + item.father = fatherValue; + item.childValue = item.value; + this.fatherValueMap[this._createChildValue(fatherValue, childValue)] = + fatherValue; + this.childValueMap[this._createChildValue(fatherValue, childValue)] = + childValue; + item.value = this._createChildValue(fatherValue, childValue); + targetItem.el.childValues.push(item.value); + targetItem.items.push(item); + }); + } - _needSpliter: function (i, itemLength) { - return i < itemLength - 1; - }, + _isGroup(i) { + return i.length > 1; + } - _createChildValue: function (fatherValue, childValue) { - return fatherValue + BI.BlankSplitChar + childValue; - }, + _needSpliter(i, itemLength) { + return i < itemLength - 1; + } - _digest: function (valueItem) { - var self = this; - var valueArray = []; - BI.each(valueItem, function (i, item) { - var value; - if (BI.isNotNull(item.childValue)) { - value = self._createChildValue(item.value, item.childValue); - } else { - value = item.value; - } - valueArray.push(value); - } - ); - return valueArray; - }, + _createChildValue(fatherValue, childValue) { + return fatherValue + BI.BlankSplitChar + childValue; + } - _checkValues: function (values) { - var value = []; - BI.each(this.items, function (idx, itemGroup) { - BI.each(itemGroup, function (id, item) { - if(BI.isNotNull(item.children)) { - var childValues = BI.map(item.children, "value"); - var v = joinValue(childValues, values[idx]); - if(BI.isNotEmptyString(v)) { - value.push(v); - } - }else{ - if(item.value === values[idx][0]) { - value.push(values[idx][0]); - } - } - }); - }); - return value; + _digest(valueItem) { + const valueArray = []; + each(valueItem, (i, item) => { + let value; + if (isNotNull(item.childValue)) { + value = this._createChildValue(item.value, item.childValue); + } else { + value = item.value; + } + valueArray.push(value); + }); + + return valueArray; + } - function joinValue (sources, targets) { - var value = ""; - BI.some(sources, function (idx, s) { - return BI.some(targets, function (id, t) { - if(s === t) { - value = s; - return true; - } - }); - }); - return value; - } - }, + _checkValues(values) { + const value = []; + each(this.items, (idx, itemGroup) => { + each(itemGroup, (id, item) => { + if (isNotNull(item.children)) { + const childValues = map(item.children, "value"); + const v = joinValue(childValues, values[idx]); + if (isNotEmptyString(v)) { + value.push(v); + } + } else { + if (item.value === values[idx][0]) { + value.push(values[idx][0]); + } + } + }); + }); + + return value; - populate: function (items) { - BI.DownListPopup.superclass.populate.apply(this, arguments); - this.items = []; - this.childValueMap = {}; - this.fatherValueMap = {}; - this.singleValues = []; - var children = this._createPopupItems(items); - var popupItem = BI.createItems(children, - {}, { - adjustLength: -2 - } - ); - this.popup.populate(popupItem); - }, + function joinValue(sources, targets) { + let value = ""; + some(sources, (idx, s) => some(targets, (id, t) => { + if (s === t) { + value = s; + + return true; + } + })); + + return value; + } + } - setValue: function (valueItem) { - this.popup.setValue(this._digest(valueItem)); - }, + populate(items) { + super.populate(...arguments); + this.items = []; + this.childValueMap = {}; + this.fatherValueMap = {}; + this.singleValues = []; + const children = this._createPopupItems(items); + const popupItem = createItems( + children, + {}, + { + adjustLength: -2, + } + ); + this.popup.populate(popupItem); + } - _getValue: function () { - var v = []; - BI.each(this.popup.getAllButtons(), function (i, item) { - i % 2 === 0 && v.push(item.getValue()); - }); - return v; - }, + setValue(valueItem) { + this.popup.setValue(this._digest(valueItem)); + } - getValue: function () { - var self = this, result = []; - var values = this._checkValues(this._getValue()); - BI.each(values, function (i, value) { - var valueItem = {}; - if (BI.isNotNull(self.childValueMap[value])) { - var fartherValue = self.fatherValueMap[value]; - valueItem.childValue = self.childValueMap[value]; - valueItem.value = fartherValue; - } else { - valueItem.value = value; - } - result.push(valueItem); - }); - return result; - } + _getValue() { + const v = []; + each(this.popup.getAllButtons(), (i, item) => { + i % 2 === 0 && v.push(item.getValue()); + }); + + return v; + } - -}); - -BI.DownListPopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.DownListPopup.EVENT_SON_VALUE_CHANGE = "EVENT_SON_VALUE_CHANGE"; -BI.shortcut("bi.down_list_popup", BI.DownListPopup); + getValue() { + const result = []; + const values = this._checkValues(this._getValue()); + each(values, (i, value) => { + const valueItem = {}; + if (isNotNull(this.childValueMap[value])) { + const fartherValue = this.fatherValueMap[value]; + valueItem.childValue = this.childValueMap[value]; + valueItem.value = fartherValue; + } else { + valueItem.value = value; + } + result.push(valueItem); + }); + + return result; + } +} diff --git a/src/widget/index.js b/src/widget/index.js index 14146c7ae..874fd77cd 100644 --- a/src/widget/index.js +++ b/src/widget/index.js @@ -7,6 +7,9 @@ import * as datetimepane from "./datetimepane"; import * as dynamicdatetime from "./dynamicdatetime"; import * as time from "./time"; import * as editor from "./editor"; +import * as downList from "./downlist"; +import * as singleSliderItem from "./singleslider"; +import * as intervalSliderItem from "./intervalslider"; import { SelectTreeCombo } from "./selecttree/selecttree.combo"; import { SingleTreeCombo } from "./singletree/singletree.combo"; import { MultiTreeCombo } from "./multitree/multi.tree.combo"; @@ -27,6 +30,9 @@ Object.assign(BI, { ...dynamicdatetime, ...time, ...editor, + ...downList, + ...singleSliderItem, + ...intervalSliderItem, SelectTreeCombo, SingleTreeCombo, MultiTreeCombo, @@ -48,6 +54,9 @@ export * from "./time"; export * from "./editor"; export * from "./multiselect"; export * from "./multiselectlist"; +export * from "./downlist"; +export * from "./singleslider"; +export * from "./intervalslider"; export { Collapse, diff --git a/src/widget/intervalslider/index.js b/src/widget/intervalslider/index.js new file mode 100644 index 000000000..2a99c23bd --- /dev/null +++ b/src/widget/intervalslider/index.js @@ -0,0 +1,2 @@ +export { AccurateCalculationModel } from "./model.accuratecalculation"; +export { IntervalSlider } from "./intervalslider"; diff --git a/src/widget/intervalslider/intervalslider.js b/src/widget/intervalslider/intervalslider.js index 59b1e1676..bd0121523 100644 --- a/src/widget/intervalslider/intervalslider.js +++ b/src/widget/intervalslider/intervalslider.js @@ -1,30 +1,50 @@ -/** - * Created by zcf on 2016/9/26. - */ -BI.IntervalSlider = BI.inherit(BI.Single, { - _constant: { +import { + shortcut, + createWidget, + toPix, + parseFloat, + Layout, + AbsoluteLayout, + clamp, + VerticalLayout, + isEmptyString, + isNumeric, + isNull, + isInteger, + i18nText, + size, + parseInt, + isNotEmptyString, + MouseMoveTracker +} from "@/core"; +import { Single, Editor } from "@/base"; +import { AccurateCalculationModel } from "./model.accuratecalculation"; +import { SignTextEditor, SliderIconButton } from "../singleslider"; + +@shortcut() +export class IntervalSlider extends Single { + static xtype = "bi.interval_slider"; + _constant = { EDITOR_WIDTH: 58, EDITOR_R_GAP: 60, EDITOR_HEIGHT: 20, SLIDER_WIDTH_HALF: 15, SLIDER_WIDTH: 30, SLIDER_HEIGHT: 30, - TRACK_HEIGHT: 24 - }, - - props: { + TRACK_HEIGHT: 24, + } + props = { baseCls: "bi-interval-slider bi-slider-track", digit: false, unit: "", min: 0, max: 100, - value: { - min: "", - max: "", - } - }, + value: { min: "", max: "" }, + }; - beforeMount: function () { + static EVENT_CHANGE = "EVENT_CHANGE"; + + beforeMount() { const { value, min, max } = this.options; this._setMinAndMax({ min, @@ -32,90 +52,104 @@ BI.IntervalSlider = BI.inherit(BI.Single, { }); this.setValue(value); this.populate(); - }, - - render: function () { + } - var self = this; - var c = this._constant; + render() { + const c = this._constant; this.enable = false; this.valueOne = ""; this.valueTwo = ""; - this.calculation = new BI.AccurateCalculationModel(); - this.grayTrack = BI.createWidget({ - type: "bi.layout", + this.calculation = new AccurateCalculationModel(); + this.grayTrack = createWidget({ + type: Layout.xtype, cls: "gray-track", - height: 6 + height: 6, }); - this.blueTrack = BI.createWidget({ - type: "bi.layout", + this.blueTrack = createWidget({ + type: Layout.xtype, cls: "blue-track bi-high-light-background", - height: 6 + height: 6, }); this.track = this._createTrackWrapper(); - this.labelOne = BI.createWidget({ - type: "bi.sign_text_editor", + this.labelOne = createWidget({ + type: SignTextEditor.xtype, cls: "slider-editor-button", text: this.options.unit, allowBlank: false, - width: BI.toPix(c.EDITOR_WIDTH, 2), - height: BI.toPix(c.EDITOR_HEIGHT, 2), - validationChecker: function (v) { - return self._checkValidation(v); - } - }); - this.labelOne.element.hover(function () { - self.labelOne.element.removeClass("bi-border").addClass("bi-border"); - }, function () { - self.labelOne.element.removeClass("bi-border"); + width: toPix(c.EDITOR_WIDTH, 2), + height: toPix(c.EDITOR_HEIGHT, 2), + validationChecker: v => this._checkValidation(v), }); - this.labelOne.on(BI.Editor.EVENT_CONFIRM, function () { - var oldValueOne = self.valueOne; - var v = BI.parseFloat(this.getValue()); - self.valueOne = v; - var percent = self._getPercentByValue(v); - var significantPercent = BI.parseFloat(percent.toFixed(1));// 分成1000份 - self._setSliderOnePosition(significantPercent); - self._setBlueTrack(); - self._checkLabelPosition(oldValueOne, self.valueTwo, self.valueOne, self.valueTwo); - self.fireEvent(BI.IntervalSlider.EVENT_CHANGE); + this.labelOne.element.hover( + () => { + this.labelOne.element + .removeClass("bi-border") + .addClass("bi-border"); + }, + () => { + this.labelOne.element.removeClass("bi-border"); + } + ); + this.labelOne.on(Editor.EVENT_CONFIRM, () => { + const oldValueOne = this.valueOne; + const v = parseFloat(this.getValue()); + this.valueOne = v; + const percent = this._getPercentByValue(v); + const significantPercent = parseFloat(percent.toFixed(1)); // 分成1000份 + this._setSliderOnePosition(significantPercent); + this._setBlueTrack(); + this._checkLabelPosition( + oldValueOne, + this.valueTwo, + this.valueOne, + this.valueTwo + ); + this.fireEvent(IntervalSlider.EVENT_CHANGE); }); - this.labelTwo = BI.createWidget({ - type: "bi.sign_text_editor", + this.labelTwo = createWidget({ + type: SignTextEditor.xtype, cls: "slider-editor-button", text: this.options.unit, allowBlank: false, - width: BI.toPix(c.EDITOR_WIDTH, 2), - height: BI.toPix(c.EDITOR_HEIGHT, 2), - validationChecker: function (v) { - return self._checkValidation(v); - } - }); - this.labelTwo.element.hover(function () { - self.labelTwo.element.removeClass("bi-border").addClass("bi-border"); - }, function () { - self.labelTwo.element.removeClass("bi-border"); + width: toPix(c.EDITOR_WIDTH, 2), + height: toPix(c.EDITOR_HEIGHT, 2), + validationChecker: v => this._checkValidation(v), }); - this.labelTwo.on(BI.Editor.EVENT_CONFIRM, function () { - var oldValueTwo = self.valueTwo; - var v = BI.parseFloat(this.getValue()); - self.valueTwo = v; - var percent = self._getPercentByValue(v); - var significantPercent = BI.parseFloat(percent.toFixed(1)); - self._setSliderTwoPosition(significantPercent); - self._setBlueTrack(); - self._checkLabelPosition(self.valueOne, oldValueTwo, self.valueOne, self.valueTwo); - self.fireEvent(BI.IntervalSlider.EVENT_CHANGE); + this.labelTwo.element.hover( + () => { + this.labelTwo.element + .removeClass("bi-border") + .addClass("bi-border"); + }, + () => { + this.labelTwo.element.removeClass("bi-border"); + } + ); + this.labelTwo.on(Editor.EVENT_CONFIRM, () => { + const oldValueTwo = this.valueTwo; + const v = parseFloat(this.getValue()); + this.valueTwo = v; + const percent = this._getPercentByValue(v); + const significantPercent = parseFloat(percent.toFixed(1)); + this._setSliderTwoPosition(significantPercent); + this._setBlueTrack(); + this._checkLabelPosition( + this.valueOne, + oldValueTwo, + this.valueOne, + this.valueTwo + ); + this.fireEvent(IntervalSlider.EVENT_CHANGE); }); - this.sliderOne = BI.createWidget({ - type: "bi.single_slider_button" + this.sliderOne = createWidget({ + type: SliderIconButton.xtype, }); - this.sliderTwo = BI.createWidget({ - type: "bi.single_slider_button" + this.sliderTwo = createWidget({ + type: SliderIconButton.xtype, }); this._draggable(this.sliderOne, true); this._draggable(this.sliderTwo, false); @@ -127,7 +161,7 @@ BI.IntervalSlider = BI.inherit(BI.Single, { items: [ this._createLabelWrapper(), { - type: "bi.absolute", + type: AbsoluteLayout.xtype, items: [ { el: { @@ -135,75 +169,95 @@ BI.IntervalSlider = BI.inherit(BI.Single, { horizontalAlign: "stretch", verticalAlign: "middle", columnSize: ["fill"], - items: [{ - el: this.track, - }], + items: [ + { + el: this.track, + } + ], hgap: 10, }, - inset: 0 + inset: 0, }, - this._createSliderWrapper(), - ] + this._createSliderWrapper() + ], } - ] + ], }; - }, + } - _rePosBySizeAfterMove: function (size, isLeft) { - var o = this.options; - var percent = size * 100 / (this._getGrayTrackLength()); - var significantPercent = BI.parseFloat(percent.toFixed(1)); - var v = this._getValueByPercent(significantPercent); + _rePosBySizeAfterMove(size, isLeft) { + const o = this.options; + const percent = (size * 100) / this._getGrayTrackLength(); + const significantPercent = parseFloat(percent.toFixed(1)); + let v = this._getValueByPercent(significantPercent); v = this._assertValue(v); v = o.digit === false ? v : v.toFixed(o.digit); - var oldValueOne = this.valueOne, oldValueTwo = this.valueTwo; - if(isLeft) { + const oldValueOne = this.valueOne, + oldValueTwo = this.valueTwo; + if (isLeft) { this._setSliderOnePosition(significantPercent); this.labelOne.setValue(v); this.valueOne = v; - this._checkLabelPosition(oldValueOne, oldValueTwo, v, this.valueTwo); - }else{ + this._checkLabelPosition( + oldValueOne, + oldValueTwo, + v, + this.valueTwo + ); + } else { this._setSliderTwoPosition(significantPercent); this.labelTwo.setValue(v); this.valueTwo = v; - this._checkLabelPosition(oldValueOne, oldValueTwo, this.valueOne, v); + this._checkLabelPosition( + oldValueOne, + oldValueTwo, + this.valueOne, + v + ); } this._setBlueTrack(); - }, - - _rePosBySizeAfterStop: function (size, isLeft) { - var percent = size * 100 / (this._getGrayTrackLength()); - var significantPercent = BI.parseFloat(percent.toFixed(1)); - isLeft ? this._setSliderOnePosition(significantPercent) : this._setSliderTwoPosition(significantPercent); - }, - - _draggable: function (widget, isLeft) { - var self = this, o = this.options; - var startDrag = false; - var size = 0, offset = 0, defaultSize = 0; - var mouseMoveTracker = new BI.MouseMoveTracker(function (deltaX) { - if (mouseMoveTracker.isDragging()) { - startDrag = true; - offset += deltaX; - size = optimizeSize(defaultSize + offset); - widget.element.addClass("dragging"); - self._rePosBySizeAfterMove(size, isLeft); - } - }, function () { - if (startDrag === true) { - size = optimizeSize(size); - self._rePosBySizeAfterStop(size, isLeft); - size = 0; - offset = 0; - defaultSize = size; - startDrag = false; - } - widget.element.removeClass("dragging"); - mouseMoveTracker.releaseMouseMoves(); - self.fireEvent(BI.IntervalSlider.EVENT_CHANGE); - }, window); + } + + _rePosBySizeAfterStop(size, isLeft) { + const percent = (size * 100) / this._getGrayTrackLength(); + const significantPercent = parseFloat(percent.toFixed(1)); + isLeft + ? this._setSliderOnePosition(significantPercent) + : this._setSliderTwoPosition(significantPercent); + } + + _draggable(widget, isLeft) { + let startDrag = false; + let size = 0, + offset = 0, + defaultSize = 0; + const mouseMoveTracker = new MouseMoveTracker( + (deltaX => { + if (mouseMoveTracker.isDragging()) { + startDrag = true; + offset += deltaX; + size = optimizeSize(defaultSize + offset); + widget.element.addClass("dragging"); + this._rePosBySizeAfterMove(size, isLeft); + } + }), + (() => { + if (startDrag === true) { + size = optimizeSize(size); + this._rePosBySizeAfterStop(size, isLeft); + size = 0; + offset = 0; + defaultSize = size; + startDrag = false; + } + widget.element.removeClass("dragging"); + mouseMoveTracker.releaseMouseMoves(); + this.fireEvent(IntervalSlider.EVENT_CHANGE); + }), + window + ); widget.element.on("mousedown", function (event) { - if(!widget.isEnabled()) { + if (!widget.isEnabled()) { return; } defaultSize = this.offsetLeft; @@ -211,42 +265,47 @@ BI.IntervalSlider = BI.inherit(BI.Single, { mouseMoveTracker.captureMouseMoves(event); }); - function optimizeSize (s) { - return BI.clamp(s, 0, self._getGrayTrackLength()); - } - }, + const optimizeSize = s => clamp(s, 0, this._getGrayTrackLength()); + } - _createLabelWrapper: function () { - var c = this._constant; + _createLabelWrapper() { + const c = this._constant; + return { el: { - type: "bi.vertical", - items: [{ - type: "bi.absolute", - items: [{ - el: this.labelOne, - top: 0, - left: 0, - }] - }, { - type: "bi.absolute", - items: [{ - el: this.labelTwo, - top: 0, - right: 0, - }] - }], + type: VerticalLayout.xtype, + items: [ + { + type: AbsoluteLayout.xtype, + items: [ + { + el: this.labelOne, + top: 0, + left: 0, + } + ], + }, + { + type: AbsoluteLayout.xtype, + items: [ + { + el: this.labelTwo, + top: 0, + right: 0, + } + ], + } + ], rgap: c.EDITOR_R_GAP, - height: c.SLIDER_HEIGHT + height: c.SLIDER_HEIGHT, }, top: 0, left: 0, - width: "100%" + width: "100%", }; - }, + } - _createSliderWrapper: function () { - var c = this._constant; + _createSliderWrapper() { return { el: { type: "bi.horizontal", @@ -254,7 +313,7 @@ BI.IntervalSlider = BI.inherit(BI.Single, { verticalAlign: "middle", items: [ { - type: "bi.absolute", + type: AbsoluteLayout.xtype, height: 12, width: "fill", items: [ @@ -262,24 +321,25 @@ BI.IntervalSlider = BI.inherit(BI.Single, { el: this.sliderOne, top: 0, bottom: 0, - left: 0 - }, { + left: 0, + }, + { el: this.sliderTwo, top: 0, bottom: 0, - left: "100%" + left: "100%", } ], } ], hgap: 10, }, - inset: 0 + inset: 0, }; - }, + } - _createTrackWrapper: function () { - return BI.createWidget({ + _createTrackWrapper() { + return createWidget({ type: "bi.horizontal", cls: "track-wrapper", horizontalAlign: "stretch", @@ -288,100 +348,110 @@ BI.IntervalSlider = BI.inherit(BI.Single, { scrollx: false, items: [ { - type: "bi.absolute", + type: AbsoluteLayout.xtype, height: 6, - items: [{ - el: this.grayTrack, - top: 0, - left: 0, - bottom: 0, - width: "100%" - }, { - el: this.blueTrack, - top: 0, - left: 0, - bottom: 0, - width: "0%" - }] + items: [ + { + el: this.grayTrack, + top: 0, + left: 0, + bottom: 0, + width: "100%", + }, + { + el: this.blueTrack, + top: 0, + left: 0, + bottom: 0, + width: "0%", + } + ], } ], }); - }, + } - _checkValidation: function (v) { - var o = this.options; - var valid = false; + _checkValidation(v) { + const o = this.options; + let valid = false; // 像90.这样的既不属于整数又不属于小数,是不合法的值 - var dotText = (v + "").split(".")[1]; - if (BI.isEmptyString(dotText)) { - }else{ - if (BI.isNumeric(v) && !(BI.isNull(v) || v < this.min || v > this.max)) { + let dotText = (`${v}`).split(".")[1]; + // eslint-disable-next-line no-empty + if (isEmptyString(dotText)) { + } else { + if (isNumeric(v) && !(isNull(v) || v < this.min || v > this.max)) { // 虽然规定了所填写的小数位数,但是我们认为所有的整数都是满足设置的小数位数的 // 100等价于100.0 100.00 100.000 - if(o.digit === false || BI.isInteger(v)) { + if (o.digit === false || isInteger(v)) { valid = true; - }else{ + } else { dotText = dotText || ""; - valid = (dotText.length === o.digit); + valid = dotText.length === o.digit; } } } + return valid; - }, + } - _checkOverlap: function () { - var labelOneLeft = this.labelOne.element[0].offsetLeft; - var labelTwoLeft = this.labelTwo.element[0].offsetLeft; + _checkOverlap() { + const labelOneLeft = this.labelOne.element[0].offsetLeft; + const labelTwoLeft = this.labelTwo.element[0].offsetLeft; if (labelOneLeft <= labelTwoLeft) { - if ((labelTwoLeft - labelOneLeft) < 90) { - this.labelTwo.element.css({top: 40}); + if (labelTwoLeft - labelOneLeft < 90) { + this.labelTwo.element.css({ top: 40 }); } else { - this.labelTwo.element.css({top: 0}); + this.labelTwo.element.css({ top: 0 }); } } else { - if ((labelOneLeft - labelTwoLeft) < 90) { - this.labelTwo.element.css({top: 40}); + if (labelOneLeft - labelTwoLeft < 90) { + this.labelTwo.element.css({ top: 40 }); } else { - this.labelTwo.element.css({top: 0}); + this.labelTwo.element.css({ top: 0 }); } } - }, - - _checkLabelPosition: function (oldValueOne, oldValueTwo, valueOne, valueTwo, isLeft) { - oldValueOne = BI.parseFloat(oldValueOne); - oldValueTwo = BI.parseFloat(oldValueTwo); - valueOne = BI.parseFloat(valueOne); - valueTwo = BI.parseFloat(valueTwo); - if((oldValueOne <= oldValueTwo && valueOne > valueTwo) || (oldValueOne >= oldValueTwo && valueOne < valueTwo)) { - var isSliderOneLeft = BI.parseFloat(this.labelOne.getValue()) < BI.parseFloat(this.labelTwo.getValue()); + } + + _checkLabelPosition(oldValueOne, oldValueTwo, valueOne, valueTwo, isLeft) { + oldValueOne = parseFloat(oldValueOne); + oldValueTwo = parseFloat(oldValueTwo); + valueOne = parseFloat(valueOne); + valueTwo = parseFloat(valueTwo); + if ( + (oldValueOne <= oldValueTwo && valueOne > valueTwo) || + (oldValueOne >= oldValueTwo && valueOne < valueTwo) + ) { + const isSliderOneLeft = + parseFloat(this.labelOne.getValue()) < + parseFloat(this.labelTwo.getValue()); this._resetLabelPosition(!isSliderOneLeft); } - }, + } - _resetLabelPosition: function(needReverse) { - this.labelOne.element.css({left: needReverse ? "100%" : "0%"}); - this.labelTwo.element.css({left: needReverse ? "0%" : "100%"}); - }, + _resetLabelPosition(needReverse) { + this.labelOne.element.css({ left: needReverse ? "100%" : "0%" }); + this.labelTwo.element.css({ left: needReverse ? "0%" : "100%" }); + } - _setSliderOnePosition: function (percent) { - this.sliderOne.element.css({left: percent + "%"}); - }, + _setSliderOnePosition(percent) { + this.sliderOne.element.css({ left: `${percent}%` }); + } - _setSliderTwoPosition: function (percent) { - this.sliderTwo.element.css({left: percent + "%"}); - }, + _setSliderTwoPosition(percent) { + this.sliderTwo.element.css({ left: `${percent}%` }); + } - _setBlueTrackLeft: function (percent) { - this.blueTrack.element.css({left: percent + "%"}); - }, + _setBlueTrackLeft(percent) { + this.blueTrack.element.css({ left: `${percent}%` }); + } - _setBlueTrackWidth: function (percent) { - this.blueTrack.element.css({width: percent + "%"}); - }, + _setBlueTrackWidth(percent) { + this.blueTrack.element.css({ width: `${percent}%` }); + } - _setBlueTrack: function () { - var percentOne = this._getPercentByValue(this.labelOne.getValue()); - var percentTwo = this._getPercentByValue(this.labelTwo.getValue()); + _setBlueTrack() { + const percentOne = this._getPercentByValue(this.labelOne.getValue()); + const percentTwo = this._getPercentByValue(this.labelTwo.getValue()); if (percentOne <= percentTwo) { this._setBlueTrackLeft(percentOne); this._setBlueTrackWidth(percentTwo - percentOne); @@ -389,133 +459,165 @@ BI.IntervalSlider = BI.inherit(BI.Single, { this._setBlueTrackLeft(percentTwo); this._setBlueTrackWidth(percentOne - percentTwo); } - }, + } - _setAllPosition: function (one, two) { + _setAllPosition(one, two) { this._setSliderOnePosition(one); this._setSliderTwoPosition(two); this._setBlueTrack(); - }, + } - _setVisible: function (visible) { + _setVisible(visible) { this.sliderOne.setVisible(visible); this.sliderTwo.setVisible(visible); this.labelOne.setVisible(visible); this.labelTwo.setVisible(visible); - }, + } - _setErrorText: function () { - var errorText = BI.i18nText("BI-Basic_Please_Enter_Number_Between", this.min, this.max); + _setErrorText() { + const errorText = i18nText( + "BI-Basic_Please_Enter_Number_Between", + this.min, + this.max + ); this.labelOne.setErrorText(errorText); this.labelTwo.setErrorText(errorText); - }, + } - _getGrayTrackLength: function () { + _getGrayTrackLength() { return this.grayTrack.element[0].scrollWidth; - }, + } - // 其中取max-min后保留4为有效数字后的值的小数位数为最终value的精度 - // 端点处的值有可能因为min,max相差量级很大(precision很大)而丢失精度,此时直接返回端点值即可 - _getValueByPercent: function (percent) {// return (((max-min)*percent)/100+min) + _getValueByPercent(percent) { + // return (((max-min)*percent)/100+min) if (percent === 0) { return this.min; } if (percent === 100) { return this.max; } - var sub = this.calculation.accurateSubtraction(this.max, this.min); - var mul = this.calculation.accurateMultiplication(sub, percent); - var div = this.calculation.accurateDivisionTenExponent(mul, 2); - if(this.precision < 0) { - var value = BI.parseFloat(this.calculation.accurateAddition(div, this.min)); - var reduceValue = Math.round(this.calculation.accurateDivisionTenExponent(value, -this.precision)); - return this.calculation.accurateMultiplication(reduceValue, Math.pow(10, -this.precision)); + const sub = this.calculation.accurateSubtraction(this.max, this.min); + const mul = this.calculation.accurateMultiplication(sub, percent); + const div = this.calculation.accurateDivisionTenExponent(mul, 2); + if (this.precision < 0) { + const value = parseFloat( + this.calculation.accurateAddition(div, this.min) + ); + const reduceValue = Math.round( + this.calculation.accurateDivisionTenExponent( + value, + -this.precision + ) + ); + + return this.calculation.accurateMultiplication( + reduceValue, + Math.pow(10, -this.precision) + ); } - return BI.parseFloat(this.calculation.accurateAddition(div, this.min).toFixed(this.precision)); - - }, + + return parseFloat( + this.calculation + .accurateAddition(div, this.min) + .toFixed(this.precision) + ); + } - _getPercentByValue: function (v) { - return (v - this.min) * 100 / (this.max - this.min); - }, + _getPercentByValue(v) { + return ((v - this.min) * 100) / (this.max - this.min); + } - _getPrecision: function () { + _getPrecision() { // 计算每一份值的精度(最大值和最小值的差值保留4为有效数字后的精度) // 如果差值的整数位数大于4,toPrecision(4)得到的是科学计数法123456 => 1.235e+5 // 返回非负值: 保留的小数位数 // 返回负值: 保留的10^n精度中的n - var sub = this.calculation.accurateSubtraction(this.max, this.min); - var pre = sub.toPrecision(4); + const sub = this.calculation.accurateSubtraction(this.max, this.min); + const pre = sub.toPrecision(4); // 科学计数法 - var eIndex = pre.indexOf("e"); - var arr = []; - if(eIndex > -1) { + const eIndex = pre.indexOf("e"); + let arr = []; + if (eIndex > -1) { arr = pre.split("e"); - var decimalPartLength = BI.size(arr[0].split(".")[1]); - var sciencePartLength = BI.parseInt(arr[1].substring(1)); + const decimalPartLength = size(arr[0].split(".")[1]); + const sciencePartLength = parseInt(arr[1].substring(1)); + return decimalPartLength - sciencePartLength; } arr = pre.split("."); + return arr.length > 1 ? arr[1].length : 0; + } - }, - - _assertValue: function (value) { - if(value <= this.min) { + _assertValue(value) { + if (value <= this.min) { return this.min; } - if(value >= this.max) { + if (value >= this.max) { return this.max; } + return value; - }, + } - _setEnable: function (b) { - BI.IntervalSlider.superclass._setEnable.apply(this, [b]); - if(b) { - this.blueTrack.element.removeClass("disabled-blue-track").addClass("blue-track"); + _setEnable(b) { + super._setEnable.apply(this, [b]); + if (b) { + this.blueTrack.element + .removeClass("disabled-blue-track") + .addClass("blue-track"); } else { - this.blueTrack.element.removeClass("blue-track").addClass("disabled-blue-track"); + this.blueTrack.element + .removeClass("blue-track") + .addClass("disabled-blue-track"); } - }, + } - getValue: function () { + getValue() { if (this.valueOne <= this.valueTwo) { - return {min: this.valueOne, max: this.valueTwo}; + return { min: this.valueOne, max: this.valueTwo }; } - return {min: this.valueTwo, max: this.valueOne}; - - }, + + return { min: this.valueTwo, max: this.valueOne }; + } - _setMinAndMax: function (v) { - var minNumber = BI.parseFloat(v.min); - var maxNumber = BI.parseFloat(v.max); - if ((!isNaN(minNumber)) && (!isNaN(maxNumber)) && (maxNumber >= minNumber)) { + _setMinAndMax(v) { + const minNumber = parseFloat(v.min); + const maxNumber = parseFloat(v.max); + if (!isNaN(minNumber) && !isNaN(maxNumber) && maxNumber >= minNumber) { this.min = minNumber; this.max = maxNumber; this.valueOne = minNumber; this.valueTwo = maxNumber; this.precision = this._getPrecision(); } - }, + } - setMinAndMax: function (v) { + setMinAndMax(v) { this._setMinAndMax(v); this.setEnable(v.min <= v.max); - }, - - setValue: function (v) { - var o = this.options; - var valueOne = BI.parseFloat(v.min); - var valueTwo = BI.parseFloat(v.max); - valueOne = o.digit === false ? valueOne : BI.parseFloat(valueOne.toFixed(o.digit)); - valueTwo = o.digit === false ? valueTwo : BI.parseFloat(valueTwo.toFixed(o.digit)); + } + + setValue(v) { + const o = this.options; + let valueOne = parseFloat(v.min); + let valueTwo = parseFloat(v.max); + valueOne = + o.digit === false + ? valueOne + : parseFloat(valueOne.toFixed(o.digit)); + valueTwo = + o.digit === false + ? valueTwo + : parseFloat(valueTwo.toFixed(o.digit)); if (!isNaN(valueOne) && !isNaN(valueTwo)) { if (this._checkValidation(valueOne)) { - this.valueOne = (this.valueOne <= this.valueTwo ? valueOne : valueTwo); + this.valueOne = + this.valueOne <= this.valueTwo ? valueOne : valueTwo; } if (this._checkValidation(valueTwo)) { - this.valueTwo = (this.valueOne <= this.valueTwo ? valueTwo : valueOne); + this.valueTwo = + this.valueOne <= this.valueTwo ? valueTwo : valueOne; } if (valueOne < this.min) { this.valueOne = this.min; @@ -524,9 +626,9 @@ BI.IntervalSlider = BI.inherit(BI.Single, { this.valueTwo = this.max; } } - }, + } - reset: function () { + reset() { this._setVisible(false); this.enable = false; this.valueOne = ""; @@ -534,18 +636,32 @@ BI.IntervalSlider = BI.inherit(BI.Single, { this.min = NaN; this.max = NaN; this._setBlueTrackWidth(0); - }, + } - populate: function () { - var o = this.options; + populate() { + const o = this.options; if (!isNaN(this.min) && !isNaN(this.max)) { this.enable = true; this._setVisible(true); this._setErrorText(); - if ((BI.isNumeric(this.valueOne) || BI.isNotEmptyString(this.valueOne)) && (BI.isNumeric(this.valueTwo) || BI.isNotEmptyString(this.valueTwo))) { - this.labelOne.setValue(o.digit === false ? this.valueOne : BI.parseFloat(this.valueOne).toFixed(o.digit)); - this.labelTwo.setValue(o.digit === false ? this.valueTwo : BI.parseFloat(this.valueTwo).toFixed(o.digit)); - this._setAllPosition(this._getPercentByValue(this.valueOne), this._getPercentByValue(this.valueTwo)); + if ( + (isNumeric(this.valueOne) || isNotEmptyString(this.valueOne)) && + (isNumeric(this.valueTwo) || isNotEmptyString(this.valueTwo)) + ) { + this.labelOne.setValue( + o.digit === false + ? this.valueOne + : parseFloat(this.valueOne).toFixed(o.digit) + ); + this.labelTwo.setValue( + o.digit === false + ? this.valueTwo + : parseFloat(this.valueTwo).toFixed(o.digit) + ); + this._setAllPosition( + this._getPercentByValue(this.valueOne), + this._getPercentByValue(this.valueTwo) + ); } else { this.labelOne.setValue(this.min); this.labelTwo.setValue(this.max); @@ -554,6 +670,4 @@ BI.IntervalSlider = BI.inherit(BI.Single, { this._resetLabelPosition(this.valueOne > this.valueTwo); } } -}); -BI.IntervalSlider.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.interval_slider", BI.IntervalSlider); +} diff --git a/src/widget/intervalslider/model.accuratecalculation.js b/src/widget/intervalslider/model.accuratecalculation.js index aa430dad1..fcc944e78 100644 --- a/src/widget/intervalslider/model.accuratecalculation.js +++ b/src/widget/intervalslider/model.accuratecalculation.js @@ -1,172 +1,239 @@ -/** - * Created by zcf on 2017/3/1. - * 万恶的IEEE-754 - * 使用字符串精确计算含小数加法、减法、乘法和10的指数倍除法,支持负数 - */ -BI.AccurateCalculationModel = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.AccurateCalculationModel.superclass._defaultConfig.apply(this, arguments), { - baseCls: "" +import { Widget, extend, parseInt, parseFloat } from "@/core"; + +export class AccurateCalculationModel extends Widget { + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { + baseCls: "", }); - }, + } - _init: function () { - BI.AccurateCalculationModel.superclass._init.apply(this, arguments); - }, + _init() { + super._init(...arguments); + } - _getMagnitude: function (n) { - var magnitude = "1"; - for (var i = 0; i < n; i++) { + _getMagnitude(n) { + let magnitude = "1"; + for (let i = 0; i < n; i++) { magnitude += "0"; } - return BI.parseInt(magnitude); - }, + + return parseInt(magnitude); + } - _formatDecimal: function (stringNumber1, stringNumber2) { + _formatDecimal(stringNumber1, stringNumber2) { if (stringNumber1.numDecimalLength === stringNumber2.numDecimalLength) { return; } - var magnitudeDiff = stringNumber1.numDecimalLength - stringNumber2.numDecimalLength; + let magnitudeDiff = + stringNumber1.numDecimalLength - stringNumber2.numDecimalLength; + let needAddZero; if (magnitudeDiff > 0) { - var needAddZero = stringNumber2; + needAddZero = stringNumber2; } else { - var needAddZero = stringNumber1; - magnitudeDiff = (0 - magnitudeDiff); + needAddZero = stringNumber1; + magnitudeDiff = 0 - magnitudeDiff; } - for (var i = 0; i < magnitudeDiff; i++) { + for (let i = 0; i < magnitudeDiff; i++) { if (needAddZero.numDecimal === "0" && i === 0) { continue; } needAddZero.numDecimal += "0"; } - }, + } - _stringNumberFactory: function (num) { - var strNum = num.toString(); - var numStrArray = strNum.split("."); - var numInteger = numStrArray[0]; + _stringNumberFactory(num) { + const strNum = num.toString(); + const numStrArray = strNum.split("."); + const numInteger = numStrArray[0]; + let numDecimal; + let numDecimalLength; if (numStrArray.length === 1) { - var numDecimal = "0"; - var numDecimalLength = 0; + numDecimal = "0"; + numDecimalLength = 0; } else { - var numDecimal = numStrArray[1]; - var numDecimalLength = numStrArray[1].length; + numDecimal = numStrArray[1]; + numDecimalLength = numStrArray[1].length; } + return { - numInteger: numInteger, - numDecimal: numDecimal, - numDecimalLength: numDecimalLength + numInteger, + numDecimal, + numDecimalLength, }; - }, + } - _accurateSubtraction: function (num1, num2) {// num1-num2 && num1>num2 - var stringNumber1 = this._stringNumberFactory(num1); - var stringNumber2 = this._stringNumberFactory(num2); + _accurateSubtraction(num1, num2) { + // num1-num2 && num1>num2 + const stringNumber1 = this._stringNumberFactory(num1); + const stringNumber2 = this._stringNumberFactory(num2); // 整数部分计算 - var integerResult = BI.parseInt(stringNumber1.numInteger) - BI.parseInt(stringNumber2.numInteger); + let integerResult = + parseInt(stringNumber1.numInteger) - + parseInt(stringNumber2.numInteger); // 小数部分 this._formatDecimal(stringNumber1, stringNumber2); - var decimalMaxLength = getDecimalMaxLength(stringNumber1, stringNumber2); + const decimalMaxLength = getDecimalMaxLength( + stringNumber1, + stringNumber2 + ); - if (BI.parseInt(stringNumber1.numDecimal) >= BI.parseInt(stringNumber2.numDecimal)) { - var decimalResultTemp = (BI.parseInt(stringNumber1.numDecimal) - BI.parseInt(stringNumber2.numDecimal)).toString(); - var decimalResult = addZero(decimalResultTemp, decimalMaxLength); - } else {// 否则借位 + let decimalResultTemp; + let decimalResult; + + if ( + parseInt(stringNumber1.numDecimal) >= + parseInt(stringNumber2.numDecimal) + ) { + decimalResultTemp = ( + parseInt(stringNumber1.numDecimal) - + parseInt(stringNumber2.numDecimal) + ).toString(); + decimalResult = addZero(decimalResultTemp, decimalMaxLength); + } else { + // 否则借位 integerResult--; - var borrow = this._getMagnitude(decimalMaxLength); - var decimalResultTemp = (borrow + BI.parseInt(stringNumber1.numDecimal) - BI.parseInt(stringNumber2.numDecimal)).toString(); - var decimalResult = addZero(decimalResultTemp, decimalMaxLength); + const borrow = this._getMagnitude(decimalMaxLength); + decimalResultTemp = ( + borrow + + parseInt(stringNumber1.numDecimal) - + parseInt(stringNumber2.numDecimal) + ).toString(); + decimalResult = addZero(decimalResultTemp, decimalMaxLength); } - var result = integerResult + "." + decimalResult; - return BI.parseFloat(result); + const result = `${integerResult}.${decimalResult}`; + + return parseFloat(result); - function getDecimalMaxLength (num1, num2) { + function getDecimalMaxLength(num1, num2) { if (num1.numDecimal.length >= num2.numDecimal.length) { return num1.numDecimal.length; } + return num2.numDecimal.length; } - function addZero (resultTemp, length) { - var diff = length - resultTemp.length; - for (var i = 0; i < diff; i++) { - resultTemp = "0" + resultTemp; + function addZero(resultTemp, length) { + const diff = length - resultTemp.length; + for (let i = 0; i < diff; i++) { + resultTemp = `0${resultTemp}`; } + return resultTemp; } - }, + } - _accurateAddition: function (num1, num2) {// 加法结合律 - var stringNumber1 = this._stringNumberFactory(num1); - var stringNumber2 = this._stringNumberFactory(num2); + _accurateAddition(num1, num2) { + // 加法结合律 + const stringNumber1 = this._stringNumberFactory(num1); + const stringNumber2 = this._stringNumberFactory(num2); // 整数部分计算 - var integerResult = BI.parseInt(stringNumber1.numInteger) + BI.parseInt(stringNumber2.numInteger); + let integerResult = + parseInt(stringNumber1.numInteger) + + parseInt(stringNumber2.numInteger); // 小数部分 this._formatDecimal(stringNumber1, stringNumber2); - var decimalResult = (BI.parseInt(stringNumber1.numDecimal) + BI.parseInt(stringNumber2.numDecimal)).toString(); + let decimalResult = ( + parseInt(stringNumber1.numDecimal) + + parseInt(stringNumber2.numDecimal) + ).toString(); if (decimalResult !== "0") { if (decimalResult.length <= stringNumber1.numDecimal.length) { - decimalResult = addZero(decimalResult, stringNumber1.numDecimal.length); + decimalResult = addZero( + decimalResult, + stringNumber1.numDecimal.length + ); } else { - integerResult++;// 进一 + integerResult++; // 进一 decimalResult = decimalResult.slice(1); } } - var result = integerResult + "." + decimalResult; - return BI.parseFloat(result); + const result = `${integerResult}.${decimalResult}`; + + return parseFloat(result); - function addZero (resultTemp, length) { - var diff = length - resultTemp.length; - for (var i = 0; i < diff; i++) { - resultTemp = "0" + resultTemp; + function addZero(resultTemp, length) { + const diff = length - resultTemp.length; + for (let i = 0; i < diff; i++) { + resultTemp = `0${resultTemp}`; } + return resultTemp; } - }, + } - _accurateMultiplication: function (num1, num2) {// 乘法分配律 - var stringNumber1 = this._stringNumberFactory(num1); - var stringNumber2 = this._stringNumberFactory(num2); + _accurateMultiplication(num1, num2) { + // 乘法分配律 + const stringNumber1 = this._stringNumberFactory(num1); + const stringNumber2 = this._stringNumberFactory(num2); // 整数部分计算 - var integerResult = BI.parseInt(stringNumber1.numInteger) * BI.parseInt(stringNumber2.numInteger); + const integerResult = + parseInt(stringNumber1.numInteger) * + parseInt(stringNumber2.numInteger); // num1的小数和num2的整数 - var dec1Int2 = this._accurateDivisionTenExponent(BI.parseInt(stringNumber1.numDecimal) * BI.parseInt(stringNumber2.numInteger), stringNumber1.numDecimalLength); + const dec1Int2 = this._accurateDivisionTenExponent( + parseInt(stringNumber1.numDecimal) * + parseInt(stringNumber2.numInteger), + stringNumber1.numDecimalLength + ); // num1的整数和num2的小数 - var int1dec2 = this._accurateDivisionTenExponent(BI.parseInt(stringNumber1.numInteger) * BI.parseInt(stringNumber2.numDecimal), stringNumber2.numDecimalLength); + const int1dec2 = this._accurateDivisionTenExponent( + parseInt(stringNumber1.numInteger) * + parseInt(stringNumber2.numDecimal), + stringNumber2.numDecimalLength + ); // 小数*小数 - var dec1dec2 = this._accurateDivisionTenExponent(BI.parseInt(stringNumber1.numDecimal) * BI.parseInt(stringNumber2.numDecimal), (stringNumber1.numDecimalLength + stringNumber2.numDecimalLength)); + const dec1dec2 = this._accurateDivisionTenExponent( + parseInt(stringNumber1.numDecimal) * + parseInt(stringNumber2.numDecimal), + stringNumber1.numDecimalLength + stringNumber2.numDecimalLength + ); - return this._accurateAddition(this._accurateAddition(this._accurateAddition(integerResult, dec1Int2), int1dec2), dec1dec2); - }, + return this._accurateAddition( + this._accurateAddition( + this._accurateAddition(integerResult, dec1Int2), + int1dec2 + ), + dec1dec2 + ); + } - _accurateDivisionTenExponent: function (num, n) {// num/10^n && n>0 - var stringNumber = this._stringNumberFactory(num); + _accurateDivisionTenExponent(num, n) { + // num/10^n && n>0 + const stringNumber = this._stringNumberFactory(num); + let integerResult, partDecimalResult; if (stringNumber.numInteger.length > n) { - var integerResult = stringNumber.numInteger.slice(0, (stringNumber.numInteger.length - n)); - var partDecimalResult = stringNumber.numInteger.slice(-n); + integerResult = stringNumber.numInteger.slice( + 0, + stringNumber.numInteger.length - n + ); + partDecimalResult = stringNumber.numInteger.slice(-n); } else { - var integerResult = "0"; - var partDecimalResult = addZero(stringNumber.numInteger, n); + integerResult = "0"; + partDecimalResult = addZero(stringNumber.numInteger, n); } - var result = integerResult + "." + partDecimalResult + stringNumber.numDecimal; - return BI.parseFloat(result); + const result = + `${integerResult}.${partDecimalResult}${stringNumber.numDecimal}`; + + return parseFloat(result); - function addZero (resultTemp, length) { - var diff = length - resultTemp.length; - for (var i = 0; i < diff; i++) { - resultTemp = "0" + resultTemp; + function addZero(resultTemp, length) { + const diff = length - resultTemp.length; + for (let i = 0; i < diff; i++) { + resultTemp = `0${resultTemp}`; } + return resultTemp; } - }, + } - accurateSubtraction: function (num1, num2) { + accurateSubtraction(num1, num2) { if (num1 >= 0 && num2 >= 0) { if (num1 >= num2) { return this._accurateSubtraction(num1, num2); } + return -this._accurateSubtraction(num2, num1); } if (num1 >= 0 && num2 < 0) { @@ -179,11 +246,12 @@ BI.AccurateCalculationModel = BI.inherit(BI.Widget, { if (num1 >= num2) { return this._accurateSubtraction(-num2, -num1); } + return this._accurateSubtraction(-num1, -num2); } - }, + } - accurateAddition: function (num1, num2) { + accurateAddition(num1, num2) { if (num1 >= 0 && num2 >= 0) { return this._accurateAddition(num1, num2); } @@ -196,9 +264,9 @@ BI.AccurateCalculationModel = BI.inherit(BI.Widget, { if (num1 < 0 && num2 < 0) { return -this._accurateAddition(-num1, -num2); } - }, + } - accurateMultiplication: function (num1, num2) { + accurateMultiplication(num1, num2) { if (num1 >= 0 && num2 >= 0) { return this._accurateMultiplication(num1, num2); } @@ -211,12 +279,13 @@ BI.AccurateCalculationModel = BI.inherit(BI.Widget, { if (num1 < 0 && num2 < 0) { return this._accurateMultiplication(-num1, -num2); } - }, + } - accurateDivisionTenExponent: function (num1, n) { + accurateDivisionTenExponent(num1, n) { if (num1 >= 0) { return this._accurateDivisionTenExponent(num1, n); } + return -this._accurateDivisionTenExponent(-num1, n); } -}); \ No newline at end of file +} diff --git a/src/widget/singleslider/button/editor.sign.text.js b/src/widget/singleslider/button/editor.sign.text.js index 281c7b0e1..09eb164db 100644 --- a/src/widget/singleslider/button/editor.sign.text.js +++ b/src/widget/singleslider/button/editor.sign.text.js @@ -1,196 +1,217 @@ -BI.SignTextEditor = BI.inherit(BI.Widget, { - _defaultConfig: function () { - var conf = BI.SignTextEditor.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-sign-initial-editor", - validationChecker: BI.emptyFn, +import { + shortcut, + Widget, + extend, + emptyFn, + createWidget, + nextTick, + Controller, + AbsoluteLayout, + VerticalLayout, + bind, + isEmpty, + isKey +} from "@/core"; +import { TextButton, Editor } from "@/base"; + +@shortcut() +export class SignTextEditor extends Widget { + static xtype = "bi.sign_text_editor"; + + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; + static EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-sign-initial-editor`, + validationChecker: emptyFn, text: "", - height: 24 + height: 24, }); - }, + } - _init: function () { - BI.SignTextEditor.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.editor = BI.createWidget({ - type: "bi.editor", + _init() { + super._init(...arguments); + const o = this.options; + this.editor = createWidget({ + type: Editor.xtype, simple: o.simple, height: o.height, hgap: 4, vgap: 2, value: o.value, validationChecker: o.validationChecker, - allowBlank: false + allowBlank: false, }); - this.text = BI.createWidget({ - type: "bi.text_button", + this.text = createWidget({ + type: TextButton.xtype, cls: "sign-editor-text", - title: function () { - return self.getValue(); - }, + title: () => this.getValue(), textAlign: o.textAlign, height: o.height, hgap: 4, - handler: function () { - self._showInput(); - self.editor.focus(); - self.editor.selectAll(); - } + handler: () => { + this._showInput(); + this.editor.focus(); + this.editor.selectAll(); + }, }); - this.text.on(BI.TextButton.EVENT_CHANGE, function () { - BI.nextTick(function () { - self.fireEvent(BI.SignTextEditor.EVENT_CLICK_LABEL); + this.text.on(TextButton.EVENT_CHANGE, () => { + nextTick(() => { + this.fireEvent(SignTextEditor.EVENT_CLICK_LABEL); }); }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.text, - left: 0, - right: 0, - top: 0, - bottom: 0 - }] + items: [ + { + el: this.text, + left: 0, + right: 0, + top: 0, + bottom: 0, + } + ], }); - this.editor.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.editor.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.editor.on(BI.Editor.EVENT_CONFIRM, function () { - self._showHint(); - self._checkText(); - self.fireEvent(BI.SignTextEditor.EVENT_CONFIRM, arguments); + this.editor.on(Editor.EVENT_CONFIRM, (...args) => { + this._showHint(); + this._checkText(); + this.fireEvent(SignTextEditor.EVENT_CONFIRM, ...args); }); - this.editor.on(BI.Editor.EVENT_CHANGE_CONFIRM, function () { - self._showHint(); - self._checkText(); - self.fireEvent(BI.SignTextEditor.EVENT_CHANGE_CONFIRM, arguments); + this.editor.on(Editor.EVENT_CHANGE_CONFIRM, (...args) => { + this._showHint(); + this._checkText(); + this.fireEvent(SignTextEditor.EVENT_CHANGE_CONFIRM, ...args); }); - this.editor.on(BI.Editor.EVENT_ERROR, function () { - self._checkText(); + this.editor.on(Editor.EVENT_ERROR, () => { + this._checkText(); }); - BI.createWidget({ - type: "bi.vertical", + createWidget({ + type: VerticalLayout.xtype, scrolly: false, element: this, - items: [this.editor] + items: [this.editor], }); this._showHint(); - self._checkText(); - }, - - _checkText: function () { - var o = this.options; - BI.nextTick(BI.bind(function () { - if (this.editor.getValue() === "") { - this.text.setValue(o.watermark || ""); - this.text.element.addClass("bi-water-mark"); - } else { - var v = this.editor.getValue(); - v = (BI.isEmpty(v) || v == o.text) ? o.text : v + o.text; - this.text.setValue(v); - this.text.element.removeClass("bi-water-mark"); - } - }, this)); - }, - - _showInput: function () { + this._checkText(); + } + + _checkText() { + const o = this.options; + nextTick( + bind(() => { + if (this.editor.getValue() === "") { + this.text.setValue(o.watermark || ""); + this.text.element.addClass("bi-water-mark"); + } else { + let v = this.editor.getValue(); + v = isEmpty(v) || v === o.text ? o.text : v + o.text; + this.text.setValue(v); + this.text.element.removeClass("bi-water-mark"); + } + }, this) + ); + } + + _showInput() { this.editor.visible(); this.text.invisible(); - }, + } - _showHint: function () { + _showHint() { this.editor.invisible(); this.text.visible(); - }, + } - setTitle: function (title) { + setTitle(title) { this.text.setTitle(title); - }, + } - setWarningTitle: function (title) { + setWarningTitle(title) { this.text.setWarningTitle(title); - }, + } - focus: function () { + focus() { this._showInput(); this.editor.focus(); - }, + } - blur: function () { + blur() { this.editor.blur(); this._showHint(); this._checkText(); - }, + } - doRedMark: function () { - if (this.editor.getValue() === "" && BI.isKey(this.options.watermark)) { + doRedMark() { + if (this.editor.getValue() === "" && isKey(this.options.watermark)) { return; } - this.text.doRedMark.apply(this.text, arguments); - }, + this.text.doRedMark(...arguments); + } - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, + unRedMark() { + this.text.unRedMark(...arguments); + } - doHighLight: function () { - if (this.editor.getValue() === "" && BI.isKey(this.options.watermark)) { + doHighLight() { + if (this.editor.getValue() === "" && isKey(this.options.watermark)) { return; } - this.text.doHighLight.apply(this.text, arguments); - }, + this.text.doHighLight(...arguments); + } - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - }, + unHighLight() { + this.text.unHighLight(...arguments); + } - isValid: function () { + isValid() { return this.editor.isValid(); - }, + } - setErrorText: function (text) { + setErrorText(text) { this.editor.setErrorText(text); - }, + } - getErrorText: function () { + getErrorText() { return this.editor.getErrorText(); - }, + } - isEditing: function () { + isEditing() { return this.editor.isEditing(); - }, + } - getLastValidValue: function () { + getLastValidValue() { return this.editor.getLastValidValue(); - }, + } - getLastChangedValue: function () { + getLastChangedValue() { return this.editor.getLastChangedValue(); - }, + } - setValue: function (v) { + setValue(v) { this.editor.setValue(v); this._checkText(); - }, + } - getValue: function () { + getValue() { return this.editor.getValue(); - }, + } - getState: function () { + getState() { return this.text.getValue(); - }, + } - setState: function (v) { - var o = this.options; + setState(v) { + const o = this.options; this._showHint(); - v = (BI.isEmpty(v) || v == o.text) ? o.text : v + o.text; + v = isEmpty(v) || v === o.text ? o.text : v + o.text; this.text.setValue(v); } -}); -BI.SignTextEditor.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.SignTextEditor.EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; -BI.SignTextEditor.EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL"; - -BI.shortcut("bi.sign_text_editor", BI.SignTextEditor); \ No newline at end of file +} diff --git a/src/widget/singleslider/button/iconbutton.slider.js b/src/widget/singleslider/button/iconbutton.slider.js index 3b3432253..c1b5ce6f8 100644 --- a/src/widget/singleslider/button/iconbutton.slider.js +++ b/src/widget/singleslider/button/iconbutton.slider.js @@ -1,26 +1,24 @@ -/** - * Created by zcf on 2016/9/22. - */ -BI.SliderIconButton = BI.inherit(BI.Widget, { +import { shortcut, Widget, Layout } from "@/core"; - props: { +@shortcut() +export class SliderIconButton extends Widget { + static xtype = "bi.single_slider_button"; + + props = { baseCls: "bi-single-slider-button slider-button bi-high-light-border", height: 8, width: 8, - }, - - constants: { + } + constants = { LARGE_SIZE: 16, NORMAL_SIZE: 12, LARGE_OFFSET: 4, - NORMAL_OFFSET: 6 - }, + NORMAL_OFFSET: 6, + }; - render: function () { - var self = this; + render() { return { - type: "bi.layout", + type: Layout.xtype, }; } -}); -BI.shortcut("bi.single_slider_button", BI.SliderIconButton); +} diff --git a/src/widget/singleslider/index.js b/src/widget/singleslider/index.js new file mode 100644 index 000000000..dc4943c0c --- /dev/null +++ b/src/widget/singleslider/index.js @@ -0,0 +1,5 @@ +export { SingleSlider } from "./singleslider"; +export { SingleSliderLabel } from "./singleslider.label"; +export { SingleSliderNormal } from "./singleslider.normal"; +export { SignTextEditor } from "./button/editor.sign.text"; +export { SliderIconButton } from "./button/iconbutton.slider"; diff --git a/src/widget/singleslider/singleslider.js b/src/widget/singleslider/singleslider.js index 8cf77b180..0a2b7496e 100644 --- a/src/widget/singleslider/singleslider.js +++ b/src/widget/singleslider/singleslider.js @@ -1,8 +1,29 @@ -/** - * Created by zcf on 2016/9/22. - */ -BI.SingleSlider = BI.inherit(BI.Single, { - _constant: { +import { + shortcut, + createWidget, + parseFloat, + toPix, + Layout, + VerticalAdaptLayout, + AbsoluteLayout, + VerticalLayout, + HorizontalAutoLayout, + clamp, + isNumeric, + isNull, + parseInt, + i18nText, + isNotEmptyString, + MouseMoveTracker +} from "@/core"; +import { Single } from "@/base"; +import { SignEditor } from "@/case"; + +@shortcut() +export class SingleSlider extends Single { + static xtype = "bi.single_slider"; + + _constant = { EDITOR_WIDTH: 90, EDITOR_HEIGHT: 20, SLIDER_WIDTH_HALF: 15, @@ -10,19 +31,21 @@ BI.SingleSlider = BI.inherit(BI.Single, { SLIDER_HEIGHT: 30, TRACK_HEIGHT: 24, TRACK_GAP_HALF: 7, - TRACK_GAP: 14 - }, + TRACK_GAP: 14, + } - props: { + props = { baseCls: "bi-single-slider bi-slider-track", digit: false, unit: "", value: "", min: 0, max: 100, - }, + }; - beforeMount: function () { + static EVENT_CHANGE = "EVENT_CHANGE"; + + beforeMount() { const { value, min, max } = this.options; this.setMinAndMax({ min, @@ -30,175 +53,205 @@ BI.SingleSlider = BI.inherit(BI.Single, { }); this.setValue(value); this.populate(); - }, + } - render: function () { - var self = this, o = this.options; - var c = this._constant; + render() { + const o = this.options; + const c = this._constant; this.enable = false; this.value = ""; - this.grayTrack = BI.createWidget({ - type: "bi.layout", + this.grayTrack = createWidget({ + type: Layout.xtype, cls: "gray-track", - height: 6 + height: 6, }); - this.blueTrack = BI.createWidget({ - type: "bi.layout", + this.blueTrack = createWidget({ + type: Layout.xtype, cls: "blue-track bi-high-light-background", - height: 6 + height: 6, }); this.track = this._createTrackWrapper(); - this.slider = BI.createWidget({ - type: "bi.single_slider_button" + this.slider = createWidget({ + type: "bi.single_slider_button", }); this._draggable(this.slider); - var sliderVertical = BI.createWidget({ - type: "bi.vertical_adapt", + const sliderVertical = createWidget({ + type: VerticalAdaptLayout.xtype, cls: "slider-wrapper", columnSize: ["fill"], - items: [{ - type: "bi.absolute", - items: [ - { - el: this.slider, - top: 8, - } - ], - height: c.SLIDER_HEIGHT - }], + items: [ + { + type: AbsoluteLayout.xtype, + items: [ + { + el: this.slider, + top: 8, + } + ], + height: c.SLIDER_HEIGHT, + } + ], hgap: c.SLIDER_WIDTH_HALF, - height: c.SLIDER_HEIGHT + height: c.SLIDER_HEIGHT, }); // 这边其实是有问题的,拖拽区域是个圆,在圆的边缘拖拽后放开,这边计算出来的蓝条宽度实际上会比放开时长一点或者短一点 - sliderVertical.element.click(function (e) { - if (self.enable && self.isEnabled() && sliderVertical.element[0] === e.originalEvent.target) { - var offset = e.clientX - self.element.offset().left - c.SLIDER_WIDTH_HALF; - var trackLength = self.track.element[0].scrollWidth - c.TRACK_GAP; - var percent = 0; + sliderVertical.element.click(e => { + if ( + this.enable && + this.isEnabled() && + sliderVertical.element[0] === e.originalEvent.target + ) { + const offset = + e.clientX - + this.element.offset().left - + c.SLIDER_WIDTH_HALF; + const trackLength = + this.track.element[0].scrollWidth - c.TRACK_GAP; + let percent = 0; if (offset < 0) { percent = 0; } if (offset > 0 && offset < trackLength) { - percent = offset * 100 / self._getGrayTrackLength(); + percent = (offset * 100) / this._getGrayTrackLength(); } if (offset >= trackLength) { percent = 100; } - var significantPercent = BI.parseFloat(percent.toFixed(1)); - self._setAllPosition(significantPercent); - var v = self._getValueByPercent(significantPercent); + const significantPercent = parseFloat(percent.toFixed(1)); + this._setAllPosition(significantPercent); + let v = this._getValueByPercent(significantPercent); v = o.digit === false ? v : v.toFixed(o.digit); - self.label.setValue(v); - self.value = v; - self.fireEvent(BI.SingleSlider.EVENT_CHANGE); + this.label.setValue(v); + this.value = v; + this.fireEvent(SingleSlider.EVENT_CHANGE); } }); - this.label = BI.createWidget({ + this.label = createWidget({ type: "bi.sign_text_editor", cls: "slider-editor-button", text: o.unit, - width: BI.toPix(c.EDITOR_WIDTH, 2), - height: BI.toPix(c.EDITOR_HEIGHT, 2), + width: toPix(c.EDITOR_WIDTH, 2), + height: toPix(c.EDITOR_HEIGHT, 2), allowBlank: false, textAlign: "center", - validationChecker: function (v) { - return self._checkValidation(v); - } + validationChecker: v => this._checkValidation(v), }); - this.label.element.hover(function () { - self.label.element.removeClass("bi-border").addClass("bi-border"); - }, function () { - self.label.element.removeClass("bi-border"); - }); - this.label.on(BI.SignEditor.EVENT_CONFIRM, function () { - var v = BI.parseFloat(this.getValue()); - var percent = self._getPercentByValue(v); - var significantPercent = BI.parseFloat(percent.toFixed(1)); - self._setAllPosition(significantPercent); + this.label.element.hover( + () => { + this.label.element + .removeClass("bi-border") + .addClass("bi-border"); + }, + () => { + this.label.element.removeClass("bi-border"); + } + ); + this.label.on(SignEditor.EVENT_CONFIRM, () => { + const v = parseFloat(this.getValue()); + const percent = this._getPercentByValue(v); + const significantPercent = parseFloat(percent.toFixed(1)); + this._setAllPosition(significantPercent); this.setValue(v); - self.value = v; - self.fireEvent(BI.SingleSlider.EVENT_CHANGE); + this.value = v; + this.fireEvent(SingleSlider.EVENT_CHANGE); }); this._setVisible(false); + return { - type: "bi.absolute", - items: [{ - el: { - type: "bi.vertical", - items: [{ - type: "bi.absolute", - items: [{ - el: this.track, - width: "100%", - height: c.TRACK_HEIGHT - }] - }], - hgap: c.TRACK_GAP_HALF, - height: c.TRACK_HEIGHT + type: AbsoluteLayout.xtype, + items: [ + { + el: { + type: VerticalLayout.xtype, + items: [ + { + type: AbsoluteLayout.xtype, + items: [ + { + el: this.track, + width: "100%", + height: c.TRACK_HEIGHT, + } + ], + } + ], + hgap: c.TRACK_GAP_HALF, + height: c.TRACK_HEIGHT, + }, + top: 23, + left: 0, + width: "100%", }, - top: 23, - left: 0, - width: "100%" - }, { - el: sliderVertical, - top: 20, - left: 0, - width: "100%" - }, { - el: { - type: "bi.vertical", - items: [{ - type: "bi.horizontal_auto", - items: [this.label] - }], - // height: c.EDITOR_HEIGHT + { + el: sliderVertical, + top: 20, + left: 0, + width: "100%", }, - top: 0, - left: 0, - width: "100%" - }] + { + el: { + type: VerticalLayout.xtype, + items: [ + { + type: HorizontalAutoLayout.xtype, + items: [this.label], + } + ], + // height: c.EDITOR_HEIGHT + }, + top: 0, + left: 0, + width: "100%", + } + ], }; - }, + } - _draggable: function (widget) { - var self = this, o = this.options; - var startDrag = false; - var size = 0, offset = 0, defaultSize = 0; - var mouseMoveTracker = new BI.MouseMoveTracker(function (deltaX) { - if (mouseMoveTracker.isDragging()) { - startDrag = true; - offset += deltaX; - size = optimizeSize(defaultSize + offset); - widget.element.addClass("dragging"); - var percent = size * 100 / (self._getGrayTrackLength()); - var significantPercent = BI.parseFloat(percent.toFixed(1));// 直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 - self._setBlueTrack(significantPercent); - self._setLabelPosition(significantPercent); - self._setSliderPosition(significantPercent); - var v = self._getValueByPercent(significantPercent); - v = o.digit === false ? v : v.toFixed(o.digit); - self.label.setValue(v); - self.value = v; - } - }, function () { - if (startDrag === true) { - size = optimizeSize(size); - var percent = size * 100 / (self._getGrayTrackLength()); - var significantPercent = BI.parseFloat(percent.toFixed(1)); - self._setSliderPosition(significantPercent); - size = 0; - offset = 0; - defaultSize = size; - startDrag = false; - } - widget.element.removeClass("dragging"); - mouseMoveTracker.releaseMouseMoves(); - self.fireEvent(BI.SingleSlider.EVENT_CHANGE); - }, window); + _draggable(widget) { + const o = this.options; + let startDrag = false; + let size = 0, + offset = 0, + defaultSize = 0; + const mouseMoveTracker = new MouseMoveTracker( + (deltaX => { + if (mouseMoveTracker.isDragging()) { + startDrag = true; + offset += deltaX; + size = optimizeSize(defaultSize + offset); + widget.element.addClass("dragging"); + const percent = (size * 100) / this._getGrayTrackLength(); + const significantPercent = parseFloat(percent.toFixed(1)); // 直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 + this._setBlueTrack(significantPercent); + this._setLabelPosition(significantPercent); + this._setSliderPosition(significantPercent); + let v = this._getValueByPercent(significantPercent); + v = o.digit === false ? v : v.toFixed(o.digit); + this.label.setValue(v); + this.value = v; + } + }), + (() => { + if (startDrag === true) { + size = optimizeSize(size); + const percent = (size * 100) / this._getGrayTrackLength(); + const significantPercent = parseFloat(percent.toFixed(1)); + this._setSliderPosition(significantPercent); + size = 0; + offset = 0; + defaultSize = size; + startDrag = false; + } + widget.element.removeClass("dragging"); + mouseMoveTracker.releaseMouseMoves(); + this.fireEvent(SingleSlider.EVENT_CHANGE); + }), + window + ); widget.element.on("mousedown", function (event) { - if(!widget.isEnabled()) { + if (!widget.isEnabled()) { return; } defaultSize = this.offsetLeft; @@ -206,100 +259,107 @@ BI.SingleSlider = BI.inherit(BI.Single, { mouseMoveTracker.captureMouseMoves(event); }); - function optimizeSize (s) { - return BI.clamp(s, 0, self._getGrayTrackLength()); - } - }, + const optimizeSize = s => clamp(s, 0, this._getGrayTrackLength()); + } - _createTrackWrapper: function () { - return BI.createWidget({ - type: "bi.absolute", - items: [{ - el: { - type: "bi.vertical", - items: [{ - type: "bi.absolute", - items: [{ - el: this.grayTrack, - top: 0, - left: 0, - width: "100%" - }, { - el: this.blueTrack, - top: 0, - left: 0, - width: "0%" - }] - }], - hgap: 8, - height: 8 - }, - top: 8, - left: 0, - width: "100%" - }] + _createTrackWrapper() { + return createWidget({ + type: AbsoluteLayout.xtype, + items: [ + { + el: { + type: VerticalLayout.xtype, + items: [ + { + type: AbsoluteLayout.xtype, + items: [ + { + el: this.grayTrack, + top: 0, + left: 0, + width: "100%", + }, + { + el: this.blueTrack, + top: 0, + left: 0, + width: "0%", + } + ], + } + ], + hgap: 8, + height: 8, + }, + top: 8, + left: 0, + width: "100%", + } + ], }); - }, + } - _checkValidation: function (v) { - var o = this.options; - var valid = false; - if (BI.isNumeric(v) && !(BI.isNull(v) || v < this.min || v > this.max)) { - if(o.digit === false) { + _checkValidation(v) { + const o = this.options; + let valid = false; + if (isNumeric(v) && !(isNull(v) || v < this.min || v > this.max)) { + if (o.digit === false) { valid = true; - }else{ - var dotText = (v + "").split(".")[1] || ""; - valid = (dotText.length === o.digit); + } else { + const dotText = (`${v}`).split(".")[1] || ""; + valid = dotText.length === o.digit; } } + return valid; - }, + } - _setBlueTrack: function (percent) { - this.blueTrack.element.css({width: percent + "%"}); - }, + _setBlueTrack(percent) { + this.blueTrack.element.css({ width: `${percent}%` }); + } - _setLabelPosition: function (percent) { + _setLabelPosition(percent) { // this.label.element.css({left: percent + "%"}); - }, + } - _setSliderPosition: function (percent) { - this.slider.element.css({left: percent + "%"}); - }, + _setSliderPosition(percent) { + this.slider.element.css({ left: `${percent}%` }); + } - _setAllPosition: function (percent) { + _setAllPosition(percent) { this._setSliderPosition(percent); this._setLabelPosition(percent); this._setBlueTrack(percent); - }, + } - _setVisible: function (visible) { + _setVisible(visible) { this.slider.setVisible(visible); this.label.setVisible(visible); - }, + } - _getGrayTrackLength: function () { + _getGrayTrackLength() { return this.grayTrack.element[0].scrollWidth; - }, + } - _getValueByPercent: function (percent) { - var thousandth = BI.parseInt(percent * 10); - return (((this.max - this.min) * thousandth) / 1000 + this.min); - }, + _getValueByPercent(percent) { + const thousandth = parseInt(percent * 10); + + return ((this.max - this.min) * thousandth) / 1000 + this.min; + } - _getPercentByValue: function (v) { - return (v - this.min) * 100 / (this.max - this.min); - }, + _getPercentByValue(v) { + return ((v - this.min) * 100) / (this.max - this.min); + } - getValue: function () { + getValue() { return this.value; - }, + } - setValue: function (v) { - var o = this.options; - v = BI.parseFloat(v); + setValue(v) { + const o = this.options; + v = parseFloat(v); v = o.digit === false ? v : v.toFixed(o.digit); - if ((!isNaN(v))) { + if (!isNaN(v)) { if (this._checkValidation(v)) { this.value = v; } @@ -310,47 +370,63 @@ BI.SingleSlider = BI.inherit(BI.Single, { this.value = this.min; } } - }, + } - _setEnable: function (b) { - BI.SingleSlider.superclass._setEnable.apply(this, [b]); - if(b) { - this.blueTrack.element.removeClass("disabled-blue-track").addClass("blue-track"); + _setEnable(b) { + super._setEnable.apply(this, [b]); + if (b) { + this.blueTrack.element + .removeClass("disabled-blue-track") + .addClass("blue-track"); } else { - this.blueTrack.element.removeClass("blue-track").addClass("disabled-blue-track"); + this.blueTrack.element + .removeClass("blue-track") + .addClass("disabled-blue-track"); } - }, + } - setMinAndMax: function (v) { - var minNumber = BI.parseFloat(v.min); - var maxNumber = BI.parseFloat(v.max); - if ((!isNaN(minNumber)) && (!isNaN(maxNumber)) && (maxNumber > minNumber )) { + setMinAndMax(v) { + const minNumber = parseFloat(v.min); + const maxNumber = parseFloat(v.max); + if (!isNaN(minNumber) && !isNaN(maxNumber) && maxNumber > minNumber) { this.min = minNumber; this.max = maxNumber; } - }, + } - reset: function () { + reset() { this._setVisible(false); this.enable = false; this.value = ""; this.min = 0; this.max = 0; this._setBlueTrack(0); - }, + } - populate: function () { - var o = this.options; + populate() { + const o = this.options; if (!isNaN(this.min) && !isNaN(this.max)) { this._setVisible(true); this.enable = true; if (o.digit) { - this.label.setErrorText(BI.i18nText("BI-Basic_Please_Enter_Number_Between", this.min, this.max)); + this.label.setErrorText( + i18nText( + "BI-Basic_Please_Enter_Number_Between", + this.min, + this.max + ) + ); } else { - this.label.setErrorText(BI.i18nText("BI-Basic_Please_Enter_Integer_Number_Between", this.min, this.max)); + this.label.setErrorText( + i18nText( + "BI-Basic_Please_Enter_Integer_Number_Between", + this.min, + this.max + ) + ); } - if (BI.isNumeric(this.value) || BI.isNotEmptyString(this.value)) { + if (isNumeric(this.value) || isNotEmptyString(this.value)) { this.label.setValue(this.value); this._setAllPosition(this._getPercentByValue(this.value)); } else { @@ -359,6 +435,4 @@ BI.SingleSlider = BI.inherit(BI.Single, { } } } -}); -BI.SingleSlider.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.single_slider", BI.SingleSlider); +} diff --git a/src/widget/singleslider/singleslider.label.js b/src/widget/singleslider/singleslider.label.js index c9ec33998..1253c5681 100644 --- a/src/widget/singleslider/singleslider.label.js +++ b/src/widget/singleslider/singleslider.label.js @@ -1,8 +1,26 @@ -/** - * Created by Urthur on 2017/9/12. - */ -BI.SingleSliderLabel = BI.inherit(BI.Single, { - _constant: { +import { + shortcut, + createWidget, + parseFloat, + toPix, + Layout, + VerticalAdaptLayout, + AbsoluteLayout, + VerticalLayout, + HorizontalAutoLayout, + clamp, + isNumeric, + isNull, + parseInt, + isNotEmptyString, + MouseMoveTracker +} from "@/core"; +import { Single, Label } from "@/base"; + +@shortcut() +export class SingleSliderLabel extends Single { + static xtype = "bi.single_slider_label"; + _constant = { EDITOR_WIDTH: 90, EDITOR_HEIGHT: 20, HEIGHT: 20, @@ -11,19 +29,20 @@ BI.SingleSliderLabel = BI.inherit(BI.Single, { SLIDER_HEIGHT: 30, TRACK_HEIGHT: 24, TRACK_GAP_HALF: 7, - TRACK_GAP: 14 - }, - - props: { + TRACK_GAP: 14, + } + props = { baseCls: "bi-single-slider-label bi-slider-track", digit: false, unit: "", value: "", min: 0, max: 100, - }, + }; - beforeMount: function () { + static EVENT_CHANGE = "EVENT_CHANGE"; + + beforeMount() { const { value, min, max } = this.options; this.setMinAndMax({ min, @@ -31,152 +50,179 @@ BI.SingleSliderLabel = BI.inherit(BI.Single, { }); this.setValue(value); this.populate(); - }, + } - render: function () { - var self = this, o = this.options; - var c = this._constant; + render() { + const o = this.options; + const c = this._constant; this.enable = false; this.value = ""; - this.grayTrack = BI.createWidget({ - type: "bi.layout", + this.grayTrack = createWidget({ + type: Layout.xtype, cls: "gray-track", - height: 6 + height: 6, }); - this.blueTrack = BI.createWidget({ - type: "bi.layout", + this.blueTrack = createWidget({ + type: Layout.xtype, cls: "blue-track bi-high-light-background", - height: 6 + height: 6, }); this.track = this._createTrackWrapper(); - this.slider = BI.createWidget({ - type: "bi.single_slider_button" + this.slider = createWidget({ + type: "bi.single_slider_button", }); this._draggable(this.slider); - var sliderVertical = BI.createWidget({ - type: "bi.vertical_adapt", + const sliderVertical = createWidget({ + type: VerticalAdaptLayout.xtype, columnSize: ["fill"], - items: [{ - type: "bi.absolute", - items: [ - { - el: this.slider, - top: 8, - } - ], - height: c.SLIDER_HEIGHT - }], + items: [ + { + type: AbsoluteLayout.xtype, + items: [ + { + el: this.slider, + top: 8, + } + ], + height: c.SLIDER_HEIGHT, + } + ], hgap: c.SLIDER_WIDTH_HALF, - height: c.SLIDER_HEIGHT + height: c.SLIDER_HEIGHT, }); - sliderVertical.element.click(function (e) { - if (self.enable && self.isEnabled() && sliderVertical.element[0] === e.originalEvent.target) { - var offset = e.clientX - self.element.offset().left - c.SLIDER_WIDTH_HALF; - var trackLength = self.track.element[0].scrollWidth - c.TRACK_GAP; - var percent = 0; + sliderVertical.element.click(e => { + if ( + this.enable && + this.isEnabled() && + sliderVertical.element[0] === e.originalEvent.target + ) { + const offset = + e.clientX - + this.element.offset().left - + c.SLIDER_WIDTH_HALF; + const trackLength = + this.track.element[0].scrollWidth - c.TRACK_GAP; + let percent = 0; if (offset < 0) { percent = 0; } if (offset > 0 && offset < trackLength) { - percent = offset * 100 / self._getGrayTrackLength(); + percent = (offset * 100) / this._getGrayTrackLength(); } if (offset >= trackLength) { percent = 100; } - var significantPercent = BI.parseFloat(percent.toFixed(1)); - self._setAllPosition(significantPercent); - var v = self._getValueByPercent(significantPercent); + const significantPercent = parseFloat(percent.toFixed(1)); + this._setAllPosition(significantPercent); + let v = this._getValueByPercent(significantPercent); v = o.digit === false ? v : v.toFixed(o.digit); - self.label.setText(v + o.unit); - self.value = v; - self.fireEvent(BI.SingleSliderLabel.EVENT_CHANGE); + this.label.setText(v + o.unit); + this.value = v; + this.fireEvent(SingleSliderLabel.EVENT_CHANGE); } }); - this.label = BI.createWidget({ - type: "bi.label", + this.label = createWidget({ + type: Label.xtype, height: c.HEIGHT, - width: BI.toPix(c.EDITOR_WIDTH, 2) + width: toPix(c.EDITOR_WIDTH, 2), }); this._setVisible(false); - return ({ - type: "bi.absolute", - items: [{ - el: { - type: "bi.vertical", - items: [{ - type: "bi.absolute", - items: [{ - el: this.track, - width: "100%", - height: c.TRACK_HEIGHT - }] - }], - hgap: c.TRACK_GAP_HALF, - height: c.TRACK_HEIGHT + + return { + type: AbsoluteLayout.xtype, + items: [ + { + el: { + type: VerticalLayout.xtype, + items: [ + { + type: AbsoluteLayout.xtype, + items: [ + { + el: this.track, + width: "100%", + height: c.TRACK_HEIGHT, + } + ], + } + ], + hgap: c.TRACK_GAP_HALF, + height: c.TRACK_HEIGHT, + }, + top: 13, + left: 0, + width: "100%", }, - top: 13, - left: 0, - width: "100%" - }, { - el: sliderVertical, - top: 10, - left: 0, - width: "100%" - }, { - el: { - type: "bi.vertical", - items: [{ - type: "bi.horizontal_auto", - items: [this.label] - }], - height: c.EDITOR_HEIGHT + { + el: sliderVertical, + top: 10, + left: 0, + width: "100%", }, - top: 0, - left: 0, - width: "100%" - }] - }); - }, + { + el: { + type: VerticalLayout.xtype, + items: [ + { + type: HorizontalAutoLayout.xtype, + items: [this.label], + } + ], + height: c.EDITOR_HEIGHT, + }, + top: 0, + left: 0, + width: "100%", + } + ], + }; + } - _draggable: function (widget) { - var self = this, o = this.options; - var startDrag = false; - var size = 0, offset = 0, defaultSize = 0; - var mouseMoveTracker = new BI.MouseMoveTracker(function (deltaX) { - if (mouseMoveTracker.isDragging()) { - startDrag = true; - offset += deltaX; - size = optimizeSize(defaultSize + offset); - widget.element.addClass("dragging"); - var percent = size * 100 / (self._getGrayTrackLength()); - var significantPercent = BI.parseFloat(percent.toFixed(1));// 直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 - self._setBlueTrack(significantPercent); - self._setLabelPosition(significantPercent); - self._setSliderPosition(significantPercent); - var v = self._getValueByPercent(significantPercent); - v = o.digit === false ? v : v.toFixed(o.digit); - self.label.setValue(v + o.unit); - self.value = v; - self.fireEvent(BI.SingleSliderLabel.EVENT_CHANGE); - } - }, function () { - if (startDrag === true) { - size = optimizeSize(size); - var percent = size * 100 / (self._getGrayTrackLength()); - var significantPercent = BI.parseFloat(percent.toFixed(1)); - self._setSliderPosition(significantPercent); - size = 0; - offset = 0; - defaultSize = size; - startDrag = false; - } - widget.element.removeClass("dragging"); - mouseMoveTracker.releaseMouseMoves(); - self.fireEvent(BI.SingleSliderLabel.EVENT_CHANGE); - }, window); + _draggable(widget) { + const o = this.options; + let startDrag = false; + let size = 0, + offset = 0, + defaultSize = 0; + const mouseMoveTracker = new MouseMoveTracker( + (deltaX => { + if (mouseMoveTracker.isDragging()) { + startDrag = true; + offset += deltaX; + size = optimizeSize(defaultSize + offset); + widget.element.addClass("dragging"); + const percent = (size * 100) / this._getGrayTrackLength(); + const significantPercent = parseFloat(percent.toFixed(1)); // 直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 + this._setBlueTrack(significantPercent); + this._setLabelPosition(significantPercent); + this._setSliderPosition(significantPercent); + let v = this._getValueByPercent(significantPercent); + v = o.digit === false ? v : v.toFixed(o.digit); + this.label.setValue(v + o.unit); + this.value = v; + this.fireEvent(SingleSliderLabel.EVENT_CHANGE); + } + }), + (() => { + if (startDrag === true) { + size = optimizeSize(size); + const percent = (size * 100) / this._getGrayTrackLength(); + const significantPercent = parseFloat(percent.toFixed(1)); + this._setSliderPosition(significantPercent); + size = 0; + offset = 0; + defaultSize = size; + startDrag = false; + } + widget.element.removeClass("dragging"); + mouseMoveTracker.releaseMouseMoves(); + this.fireEvent(SingleSliderLabel.EVENT_CHANGE); + }), + window + ); widget.element.on("mousedown", function (event) { if (!widget.isEnabled()) { return; @@ -186,99 +232,109 @@ BI.SingleSliderLabel = BI.inherit(BI.Single, { mouseMoveTracker.captureMouseMoves(event); }); - function optimizeSize(s) { - return BI.clamp(s, 0, self._getGrayTrackLength()); - } - }, + const optimizeSize = s => clamp(s, 0, this._getGrayTrackLength()); + } - _createTrackWrapper: function () { - return BI.createWidget({ - type: "bi.absolute", - items: [{ - el: { - type: "bi.vertical", - items: [{ - type: "bi.absolute", - items: [{ - el: this.grayTrack, - top: 0, - left: 0, - width: "100%" - }, { - el: this.blueTrack, - top: 0, - left: 0, - width: "0%" - }] - }], - hgap: 8, - height: 8 - }, - top: 8, - left: 0, - width: "100%" - }] + _createTrackWrapper() { + return createWidget({ + type: AbsoluteLayout.xtype, + items: [ + { + el: { + type: VerticalLayout.xtype, + items: [ + { + type: AbsoluteLayout.xtype, + items: [ + { + el: this.grayTrack, + top: 0, + left: 0, + width: "100%", + }, + { + el: this.blueTrack, + top: 0, + left: 0, + width: "0%", + } + ], + } + ], + hgap: 8, + height: 8, + }, + top: 8, + left: 0, + width: "100%", + } + ], }); - }, + } - _checkValidation: function (v) { - return BI.isNumeric(v) && !(BI.isNull(v) || v < this.min || v > this.max); - }, + _checkValidation(v) { + return isNumeric(v) && !(isNull(v) || v < this.min || v > this.max); + } - _setBlueTrack: function (percent) { - this.blueTrack.element.css({ width: percent + "%" }); - }, + _setBlueTrack(percent) { + this.blueTrack.element.css({ width: `${percent}%` }); + } - _setLabelPosition: function (percent) { + _setLabelPosition(percent) { // this.label.element.css({left: percent + "%"}); - }, + } - _setSliderPosition: function (percent) { - this.slider.element.css({ left: percent + "%" }); - }, + _setSliderPosition(percent) { + this.slider.element.css({ left: `${percent}%` }); + } - _setAllPosition: function (percent) { + _setAllPosition(percent) { this._setSliderPosition(percent); this._setLabelPosition(percent); this._setBlueTrack(percent); - }, + } - _setVisible: function (visible) { + _setVisible(visible) { this.slider.setVisible(visible); this.label.setVisible(visible); - }, + } - _getGrayTrackLength: function () { + _getGrayTrackLength() { return this.grayTrack.element[0].scrollWidth; - }, + } - _getValueByPercent: function (percent) { - var thousandth = BI.parseInt(percent * 10); - return (((this.max - this.min) * thousandth) / 1000 + this.min); - }, + _getValueByPercent(percent) { + const thousandth = parseInt(percent * 10); + + return ((this.max - this.min) * thousandth) / 1000 + this.min; + } - _getPercentByValue: function (v) { - return (v - this.min) * 100 / (this.max - this.min); - }, + _getPercentByValue(v) { + return ((v - this.min) * 100) / (this.max - this.min); + } - _setEnable: function (b) { - BI.SingleSliderLabel.superclass._setEnable.apply(this, [b]); + _setEnable(b) { + super._setEnable.apply(this, [b]); if (b) { - this.blueTrack.element.removeClass("disabled-blue-track").addClass("blue-track"); + this.blueTrack.element + .removeClass("disabled-blue-track") + .addClass("blue-track"); } else { - this.blueTrack.element.removeClass("blue-track").addClass("disabled-blue-track"); + this.blueTrack.element + .removeClass("blue-track") + .addClass("disabled-blue-track"); } - }, + } - getValue: function () { + getValue() { return this.value; - }, + } - setValue: function (v) { - var o = this.options; - v = BI.parseFloat(v); + setValue(v) { + const o = this.options; + v = parseFloat(v); v = o.digit === false ? v : v.toFixed(o.digit); - if ((!isNaN(v))) { + if (!isNaN(v)) { if (this._checkValidation(v)) { this.value = v; } @@ -289,32 +345,32 @@ BI.SingleSliderLabel = BI.inherit(BI.Single, { this.value = this.min; } } - }, + } - setMinAndMax: function (v) { - var minNumber = BI.parseFloat(v.min); - var maxNumber = BI.parseFloat(v.max); - if ((!isNaN(minNumber)) && (!isNaN(maxNumber)) && (maxNumber > minNumber)) { + setMinAndMax(v) { + const minNumber = parseFloat(v.min); + const maxNumber = parseFloat(v.max); + if (!isNaN(minNumber) && !isNaN(maxNumber) && maxNumber > minNumber) { this.min = minNumber; this.max = maxNumber; } - }, + } - reset: function () { + reset() { this._setVisible(false); this.enable = false; this.value = ""; this.min = 0; this.max = 0; this._setBlueTrack(0); - }, + } - populate: function () { - var o = this.options; + populate() { + const o = this.options; if (!isNaN(this.min) && !isNaN(this.max)) { this._setVisible(true); this.enable = true; - if (BI.isNumeric(this.value) || BI.isNotEmptyString(this.value)) { + if (isNumeric(this.value) || isNotEmptyString(this.value)) { this.label.setValue(this.value + o.unit); this._setAllPosition(this._getPercentByValue(this.value)); } else { @@ -323,6 +379,4 @@ BI.SingleSliderLabel = BI.inherit(BI.Single, { } } } -}); -BI.SingleSliderLabel.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.single_slider_label", BI.SingleSliderLabel); +} diff --git a/src/widget/singleslider/singleslider.normal.js b/src/widget/singleslider/singleslider.normal.js index 1f7338530..993e86043 100644 --- a/src/widget/singleslider/singleslider.normal.js +++ b/src/widget/singleslider/singleslider.normal.js @@ -1,28 +1,43 @@ -/** - * normal single slider - * Created by Young on 2017/6/21. - */ -BI.SingleSliderNormal = BI.inherit(BI.Single, { +import { + shortcut, + createWidget, + parseFloat, + VerticalAdaptLayout, + AbsoluteLayout, + VerticalLayout, + clamp, + Layout, + isNull, + parseInt, + isNumeric, + isNotEmptyString, + MouseMoveTracker +} from "@/core"; +import { Single } from "@/base"; +import { SingleSlider } from "./singleslider"; - _constant: { +@shortcut() +export class SingleSliderNormal extends Single { + static xtype = "bi.single_slider_normal"; + _constant = { HEIGHT: 28, SLIDER_WIDTH_HALF: 15, SLIDER_WIDTH: 30, SLIDER_HEIGHT: 30, TRACK_HEIGHT: 24, TRACK_GAP_HALF: 7, - TRACK_GAP: 14 - }, - - props: { + TRACK_GAP: 14, + } + props = { baseCls: "bi-single-slider-normal bi-slider-track", min: 0, max: 100, value: "", - // color: "#3f8ce8" - }, + }; - beforeMount: function () { + static EVENT_DRAG = "EVENT_DRAG"; + + beforeMount() { const { value, min, max } = this.options; this.setMinAndMax({ min, @@ -30,122 +45,143 @@ BI.SingleSliderNormal = BI.inherit(BI.Single, { }); this.setValue(value); this.populate(); - }, + } - render: function () { - var self = this; - var o = this.options; - var c = this._constant; + render() { + const c = this._constant; - var track = this._createTrack(); - this.slider = BI.createWidget({ - type: "bi.single_slider_button" + const track = this._createTrack(); + this.slider = createWidget({ + type: "bi.single_slider_button", }); this._draggable(this.slider); - var sliderVertical = BI.createWidget({ - type: "bi.vertical_adapt", + const sliderVertical = createWidget({ + type: VerticalAdaptLayout.xtype, columnSize: ["fill"], - items: [{ - type: "bi.absolute", - items: [ - { - el: this.slider, - top: 8, - } - ], - height: c.SLIDER_HEIGHT - }], + items: [ + { + type: AbsoluteLayout.xtype, + items: [ + { + el: this.slider, + top: 8, + } + ], + height: c.SLIDER_HEIGHT, + } + ], hgap: c.SLIDER_WIDTH_HALF, - height: c.SLIDER_HEIGHT + height: c.SLIDER_HEIGHT, }); - sliderVertical.element.click(function (e) { - if (self.enable && self.isEnabled() && sliderVertical.element[0] === e.originalEvent.target) { - var offset = e.clientX - self.element.offset().left - c.SLIDER_WIDTH_HALF; - var trackLength = self.track.element[0].scrollWidth - c.TRACK_GAP; - var percent = 0; + sliderVertical.element.click(e => { + if ( + this.enable && + this.isEnabled() && + sliderVertical.element[0] === e.originalEvent.target + ) { + const offset = + e.clientX - + this.element.offset().left - + c.SLIDER_WIDTH_HALF; + const trackLength = + this.track.element[0].scrollWidth - c.TRACK_GAP; + let percent = 0; if (offset < 0) { percent = 0; } if (offset > 0 && offset < trackLength) { - percent = offset * 100 / self._getGrayTrackLength(); + percent = (offset * 100) / this._getGrayTrackLength(); } if (offset >= trackLength) { percent = 100; } - var significantPercent = BI.parseFloat(percent.toFixed(1)); - self._setAllPosition(significantPercent); - var v = self._getValueByPercent(significantPercent); - self.value = v; - self.fireEvent(BI.SingleSlider.EVENT_CHANGE); + const significantPercent = parseFloat(percent.toFixed(1)); + this._setAllPosition(significantPercent); + const v = this._getValueByPercent(significantPercent); + this.value = v; + this.fireEvent(SingleSlider.EVENT_CHANGE); } }); return { - type: "bi.absolute", + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: { - type: "bi.vertical", - items: [{ - type: "bi.absolute", - items: [{ - el: track, - width: "100%", - height: c.TRACK_HEIGHT - }] - }], - hgap: c.TRACK_GAP_HALF, - height: c.TRACK_HEIGHT + items: [ + { + el: { + type: VerticalLayout.xtype, + items: [ + { + type: AbsoluteLayout.xtype, + items: [ + { + el: track, + width: "100%", + height: c.TRACK_HEIGHT, + } + ], + } + ], + hgap: c.TRACK_GAP_HALF, + height: c.TRACK_HEIGHT, + }, + top: 3, + left: 0, + width: "100%", }, - top: 3, - left: 0, - width: "100%" - }, { - el: sliderVertical, - top: 0, - left: 0, - width: "100%" - }] + { + el: sliderVertical, + top: 0, + left: 0, + width: "100%", + } + ], }; - }, + } - _draggable: function (widget) { - var self = this, o = this.options; - var startDrag = false; - var size = 0, offset = 0, defaultSize = 0; - var mouseMoveTracker = new BI.MouseMoveTracker(function (deltaX) { - if (mouseMoveTracker.isDragging()) { - startDrag = true; - offset += deltaX; - size = optimizeSize(defaultSize + offset); - widget.element.addClass("dragging"); - var percent = size * 100 / (self._getGrayTrackLength()); - var significantPercent = BI.parseFloat(percent.toFixed(1));// 直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 - self._setBlueTrack(significantPercent); - self._setSliderPosition(significantPercent); - var v = self._getValueByPercent(significantPercent); - v = o.digit === false ? v : v.toFixed(o.digit); - self.value = v; - self.fireEvent(BI.SingleSliderNormal.EVENT_DRAG, v); - } - }, function () { - if (startDrag === true) { - size = optimizeSize(size); - var percent = size * 100 / (self._getGrayTrackLength()); - var significantPercent = BI.parseFloat(percent.toFixed(1)); - self._setSliderPosition(significantPercent); - size = 0; - offset = 0; - defaultSize = size; - startDrag = false; - } - widget.element.removeClass("dragging"); - mouseMoveTracker.releaseMouseMoves(); - self.fireEvent(BI.SingleSlider.EVENT_CHANGE); - }, window); + _draggable(widget) { + const o = this.options; + let startDrag = false; + let size = 0, + offset = 0, + defaultSize = 0; + const mouseMoveTracker = new MouseMoveTracker( + (deltaX => { + if (mouseMoveTracker.isDragging()) { + startDrag = true; + offset += deltaX; + size = optimizeSize(defaultSize + offset); + widget.element.addClass("dragging"); + const percent = (size * 100) / this._getGrayTrackLength(); + const significantPercent = parseFloat(percent.toFixed(1)); // 直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 + this._setBlueTrack(significantPercent); + this._setSliderPosition(significantPercent); + let v = this._getValueByPercent(significantPercent); + v = o.digit === false ? v : v.toFixed(o.digit); + this.value = v; + this.fireEvent(SingleSliderNormal.EVENT_DRAG, v); + } + }), + (() => { + if (startDrag === true) { + size = optimizeSize(size); + const percent = (size * 100) / this._getGrayTrackLength(); + const significantPercent = parseFloat(percent.toFixed(1)); + this._setSliderPosition(significantPercent); + size = 0; + offset = 0; + defaultSize = size; + startDrag = false; + } + widget.element.removeClass("dragging"); + mouseMoveTracker.releaseMouseMoves(); + this.fireEvent(SingleSlider.EVENT_CHANGE); + }), + window + ); widget.element.on("mousedown", function (event) { - if(!widget.isEnabled()) { + if (!widget.isEnabled()) { return; } defaultSize = this.offsetLeft; @@ -153,110 +189,120 @@ BI.SingleSliderNormal = BI.inherit(BI.Single, { mouseMoveTracker.captureMouseMoves(event); }); - function optimizeSize (s) { - return BI.clamp(s, 0, self._getGrayTrackLength()); - } - }, + const optimizeSize = s => clamp(s, 0, this._getGrayTrackLength()); + } - _createTrack: function () { - var self = this; - var c = this._constant; - this.grayTrack = BI.createWidget({ - type: "bi.layout", + _createTrack() { + this.grayTrack = createWidget({ + type: Layout.xtype, cls: "gray-track", - height: 6 + height: 6, }); - this.blueTrack = BI.createWidget({ - type: "bi.layout", + this.blueTrack = createWidget({ + type: Layout.xtype, cls: "blue-track bi-high-light-background", - height: 6 + height: 6, }); if (this.options.color) { - this.blueTrack.element.css({"background-color": this.options.color}); + this.blueTrack.element.css({ + "background-color": this.options.color, + }); } return { - type: "bi.absolute", - items: [{ - el: { - type: "bi.vertical", - items: [{ - type: "bi.absolute", - items: [{ - el: this.grayTrack, - top: 0, - left: 0, - width: "100%" - }, { - el: this.blueTrack, - top: 0, - left: 0, - width: "0%" - }] - }], - hgap: 8, - height: 8 - }, - top: 8, - left: 0, - width: "100%" - }], - ref: function (ref) { - self.track = ref; - } + type: AbsoluteLayout.xtype, + items: [ + { + el: { + type: VerticalLayout.xtype, + items: [ + { + type: AbsoluteLayout.xtype, + items: [ + { + el: this.grayTrack, + top: 0, + left: 0, + width: "100%", + }, + { + el: this.blueTrack, + top: 0, + left: 0, + width: "0%", + } + ], + } + ], + hgap: 8, + height: 8, + }, + top: 8, + left: 0, + width: "100%", + } + ], + ref: _ref => { + this.track = _ref; + }, }; - }, + } - _checkValidation: function (v) { - return !(BI.isNull(v) || v < this.min || v > this.max); - }, + _checkValidation(v) { + return !(isNull(v) || v < this.min || v > this.max); + } - _setBlueTrack: function (percent) { - this.blueTrack.element.css({width: percent + "%"}); - }, + _setBlueTrack(percent) { + this.blueTrack.element.css({ width: `${percent}%` }); + } - _setSliderPosition: function (percent) { - this.slider.element.css({left: percent + "%"}); - }, + _setSliderPosition(percent) { + this.slider.element.css({ left: `${percent}%` }); + } - _setAllPosition: function (percent) { + _setAllPosition(percent) { this._setSliderPosition(percent); this._setBlueTrack(percent); - }, + } - _setVisible: function (visible) { + _setVisible(visible) { this.slider.setVisible(visible); - }, + } - _getGrayTrackLength: function () { + _getGrayTrackLength() { return this.grayTrack.element[0].scrollWidth; - }, + } - _getValueByPercent: function (percent) { - var thousandth = BI.parseInt(percent * 10); - return (((this.max - this.min) * thousandth) / 1000 + this.min); - }, + _getValueByPercent(percent) { + const thousandth = parseInt(percent * 10); + + return ((this.max - this.min) * thousandth) / 1000 + this.min; + } - _getPercentByValue: function (v) { - return (v - this.min) * 100 / (this.max - this.min); - }, + _getPercentByValue(v) { + return ((v - this.min) * 100) / (this.max - this.min); + } - _setEnable: function (b) { - BI.SingleSliderNormal.superclass._setEnable.apply(this, [b]); - if(b) { - this.blueTrack.element.removeClass("disabled-blue-track").addClass("blue-track"); + _setEnable(b) { + super._setEnable.apply(this, [b]); + if (b) { + this.blueTrack.element + .removeClass("disabled-blue-track") + .addClass("blue-track"); } else { - this.blueTrack.element.removeClass("blue-track").addClass("disabled-blue-track"); + this.blueTrack.element + .removeClass("blue-track") + .addClass("disabled-blue-track"); } - }, + } - getValue: function () { + getValue() { return this.value; - }, + } - setValue: function (v) { - var value = BI.parseFloat(v); - if ((!isNaN(value))) { + setValue(v) { + const value = parseFloat(v); + if (!isNaN(value)) { if (this._checkValidation(value)) { this.value = value; } @@ -267,37 +313,35 @@ BI.SingleSliderNormal = BI.inherit(BI.Single, { this.value = this.min; } } - }, + } - setMinAndMax: function (v) { - var minNumber = BI.parseFloat(v.min); - var maxNumber = BI.parseFloat(v.max); - if ((!isNaN(minNumber)) && (!isNaN(maxNumber)) && (maxNumber > minNumber )) { + setMinAndMax(v) { + const minNumber = parseFloat(v.min); + const maxNumber = parseFloat(v.max); + if (!isNaN(minNumber) && !isNaN(maxNumber) && maxNumber > minNumber) { this.min = minNumber; this.max = maxNumber; } - }, + } - reset: function () { + reset() { this._setVisible(false); this.enable = false; this.value = ""; this.min = 0; this.max = 0; this._setBlueTrack(0); - }, + } - populate: function () { + populate() { if (!isNaN(this.min) && !isNaN(this.max)) { this._setVisible(true); this.enable = true; - if (BI.isNumeric(this.value) || BI.isNotEmptyString(this.value)) { + if (isNumeric(this.value) || isNotEmptyString(this.value)) { this._setAllPosition(this._getPercentByValue(this.value)); } else { this._setAllPosition(100); } } } -}); -BI.SingleSliderNormal.EVENT_DRAG = "EVENT_DRAG"; -BI.shortcut("bi.single_slider_normal", BI.SingleSliderNormal); +} From 27c6956b1d45c1c98be566871a3518d7f996f9e7 Mon Sep 17 00:00:00 2001 From: Treecat Date: Thu, 12 Jan 2023 17:31:46 +0800 Subject: [PATCH 103/300] =?UTF-8?q?KERNEL-14076=20feat:=E9=80=92=E5=BD=92x?= =?UTF-8?q?type=E5=90=88=E5=B9=B6=20import?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.js | 124 ++++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 106 insertions(+), 18 deletions(-) diff --git a/es6.js b/es6.js index fbfede5a2..3e7fcef7f 100644 --- a/es6.js +++ b/es6.js @@ -3,6 +3,7 @@ const path = require("path"); const prettier = require("prettier"); const { exec } = require("child_process"); const { search, initDepts, depts } = require("./es6.xtype"); +const _ = require("lodash"); // const XTYPE_ONLY = false; // const THIS_REPLACE = false; @@ -20,7 +21,32 @@ function objHaveFunction(obj) { }); } -async function fix(path) { +function parserImport(code) { + const reg = /import {([\s\S]*?)} from "(.*?)";/g; + + const importMap = {}; + let regResult = reg.exec(code); + while (regResult) { + importMap[regResult[2]] = regResult[1] + .split(",") + .map(el => el.trim()).filter(el => el); + regResult = reg.exec(code); + } + + return importMap; +} + +async function saveAndFixCode(path, code) { + let _code = code; + if (!code) { + _code = fs.readFileSync(path).toString(); + } + const prettierCode = prettier.format(_code, { + tabWidth: 4, + parser: 'babel', + }); + fs.writeFileSync(path, prettierCode); + new Promise(res => { exec(`yarn eslint --fix ${path}`, () => { res(); @@ -104,18 +130,16 @@ const loader = { }; async function handleFile(srcName) { + await saveAndFixCode(srcName); // 全局状态回归 - const G = loader.G = { "@/core": { shortcut: true } }; - + let G = loader.G = { }; + const sourceCode = fs.readFileSync(srcName).toString(); const result = /BI\.(.*?)\s=\sBI\.inherit\(/.exec(sourceCode); if (!result) { console.log(`已经es6过,替换 xtype => ${srcName}`); - // 处理 xtype - - // 尝试对 xtype 进行替换 const noXtypeCode = sourceCode.replace(/type:\s?"bi\.(.*?)"/g, v => { const matchedSentence = v.replace(/type:\s?/, ""); const loadSuccess = loader.load(srcName, matchedSentence); @@ -126,18 +150,87 @@ async function handleFile(srcName) { } else { console.log(`xtype 替换失败 ${matchedSentence} `); - return matchedSentence; + return v; } }); + // 识别 import + const importMap = parserImport(noXtypeCode); + + // 合并原来的 import 到 G + _.forEach(importMap, (depts, module) => { + depts.forEach(dept => { + if (!G[module]) { + G[module] = {}; + } - fs.writeFileSync(srcName, noXtypeCode); + G[module][dept] = true; + }); + }); + + // 合并 core + const crossPackages = fs.readdirSync("src"); + _.forEach(G, (depts, module) => { + crossPackages.forEach(crosspackage => { + if (module.indexOf(crosspackage) >= 0) { + if (!G[`@/${crosspackage}`]) { + G[`@/${crosspackage}`] = {}; + } + Object.assign(G[`@/${crosspackage}`], depts); + } + }); + }); + + const tmpG = {}; + _.forEach(G, (depts, module)=> { + const flag = _.some(crossPackages, crosspackage => module.indexOf(crosspackage) >= 0 && !module.startsWith("@")) + if (!flag) { + tmpG[module] = depts; + } + }); + G = tmpG; + + const noImportCode = noXtypeCode.replace(/import {([\s\S]*?)} from "(.*?)";/g, ""); + + let I = ""; + Object.keys(G).forEach(key => { + let moduleKey = key; + if (moduleKey === path.basename(srcName).replace(/.js$/g, "")) { + return; + } + let i = ""; + Object.keys(G[moduleKey]).forEach(key => { + i += `${key}, `; + }); + + // 必须以 . 开头 + const moduleInValid = /^[^@.]/.test(moduleKey); + if (moduleInValid) { + moduleKey = `./${moduleKey}`; + } + + + I += `import {${i}} from '${moduleKey}'\n`; + }); + const code = `${I}\n${noImportCode}`; + + await saveAndFixCode(srcName, code); return; } + + G["@/core"] = { shortcut: true }; + + const clzName = result[1]; - const superName = /inherit\(BI\.(.*?),/.exec(sourceCode)[1]; + if (!clzName) { + console.log(`${srcName} 不需要 es6 化`); + + return; + } + const superName = /inherit\(BI\.(.*?),/.exec(sourceCode)[1]; + // const xtype = /BI.shortcut\(\"(.*?)\"/.exec(sourceCode)[1]; const collection = { @@ -296,13 +389,7 @@ ${E} ${M} } `; - - const prettierCode = prettier.format(outputCode, { - tabWidth: 4, - parser: 'babel', - }); - fs.writeFileSync(srcName, prettierCode); - await fix(srcName); + await saveAndFixCode(srcName, outputCode); return clzName; } @@ -314,8 +401,9 @@ async function traverse(srcName) { try { return await handleFile(srcName); } catch (error) { - console.log(`文件处理失败 ${srcName} \n${error}`); - + console.log(`文件处理失败 ${srcName} \n`); + console.error(error); + return; } } else { From c3dd73622fb460edc5586579d0d2d9e2dd43c1cc Mon Sep 17 00:00:00 2001 From: zsmj Date: Thu, 12 Jan 2023 17:37:00 +0800 Subject: [PATCH 104/300] update --- src/base/combination/searcher.js | 19 ++- src/case/button/index.js | 11 +- .../button/treeitem/item.first.treeleaf.js | 105 -------------- .../button/treeitem/item.last.treeleaf.js | 105 -------------- src/case/button/treeitem/item.mid.treeleaf.js | 105 -------------- .../button/treeitem/item.root.treeleaf.js | 78 ---------- src/case/button/treeitem/item.treetextleaf.js | 76 ---------- src/case/button/treeitem/treeitem.js | 134 ++++++++++++++---- src/case/layer/pane.list.js | 98 ++++++++----- src/case/list/list.select.js | 2 +- src/less/base/dom.less | 2 - 11 files changed, 193 insertions(+), 542 deletions(-) delete mode 100644 src/case/button/treeitem/item.first.treeleaf.js delete mode 100644 src/case/button/treeitem/item.last.treeleaf.js delete mode 100644 src/case/button/treeitem/item.mid.treeleaf.js delete mode 100644 src/case/button/treeitem/item.root.treeleaf.js delete mode 100644 src/case/button/treeitem/item.treetextleaf.js delete mode 100644 src/less/base/dom.less diff --git a/src/base/combination/searcher.js b/src/base/combination/searcher.js index dcf482527..1004fb94e 100644 --- a/src/base/combination/searcher.js +++ b/src/base/combination/searcher.js @@ -5,14 +5,27 @@ * @class BI.Searcher * @extends BI.Widget */ -import { shortcut, Widget, Controller, extend, createWidget, debounce, bind, endWith, deepWithout, nextTick, isEmptyString, isNull } from "../../core"; +import { + shortcut, + Widget, + Controller, + extend, + createWidget, + debounce, + bind, + endWith, + deepWithout, + nextTick, + isEmptyString, + isNull +} from "../../core"; import { ButtonGroup } from "./group.button"; import { Maskers } from "../0.base"; @shortcut() export class Searcher extends Widget { static xtype = "bi.searcher"; - + static EVENT_CHANGE = "EVENT_CHANGE"; static EVENT_START = "EVENT_START"; static EVENT_STOP = "EVENT_STOP"; @@ -217,7 +230,7 @@ export class Searcher extends Widget { _getLastSearchKeyword() { if (this.isValid()) { - const res = this.editor.getValue().split(/\u200b\s\u200b/); + let res = this.editor.getValue().split(/\u200b\s\u200b/); if (isEmptyString(res[res.length - 1])) { res = res.slice(0, res.length - 1); } diff --git a/src/case/button/index.js b/src/case/button/index.js index f19d10b13..8f366680c 100644 --- a/src/case/button/index.js +++ b/src/case/button/index.js @@ -19,11 +19,10 @@ export { PlusGroupNode } from "./node/node.plus"; export { TreeNodeSwitcher } from "./node/siwtcher.tree.node"; export { BasicTreeNode } from "./node/treenode"; -export { FirstTreeLeafItem } from "./treeitem/item.first.treeleaf"; export { IconTreeLeafItem } from "./treeitem/item.icon.treeleaf"; -export { LastTreeLeafItem } from "./treeitem/item.last.treeleaf"; -export { MidTreeLeafItem } from "./treeitem/item.mid.treeleaf"; export { MultiLayerIconTreeLeafItem } from "./treeitem/item.multilayer.icon.treeleaf"; -export { RootTreeLeafItem } from "./treeitem/item.root.treeleaf"; -export { TreeTextLeafItem } from "./treeitem/item.treetextleaf"; -export { BasicTreeItem } from "./treeitem/treeitem"; + + +export { + BasicTreeItem, FirstTreeLeafItem, MidTreeLeafItem, LastTreeLeafItem, RootTreeLeafItem +} from "./treeitem/treeitem"; diff --git a/src/case/button/treeitem/item.first.treeleaf.js b/src/case/button/treeitem/item.first.treeleaf.js deleted file mode 100644 index b69340b14..000000000 --- a/src/case/button/treeitem/item.first.treeleaf.js +++ /dev/null @@ -1,105 +0,0 @@ -import { BasicButton } from "../../../base/single/button/button.basic"; -import { shortcut, extend, createWidget } from "../../../core"; - -@shortcut() -export class FirstTreeLeafItem extends BasicButton { - static xtype = "bi.first_tree_leaf_item"; - - _defaultConfig() { - return extend(super._defaultConfig(...arguments), { - extraCls: "bi-first-tree-leaf-item bi-list-item-active", - logic: { - dynamic: false, - }, - id: "", - pId: "", - layer: 0, - height: 24, - }); - } - - _init() { - super._init(...arguments); - const o = this.options; - this.text = createWidget({ - type: "bi.label", - textAlign: "left", - whiteSpace: "nowrap", - textHeight: o.height, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - py: o.py, - keyword: o.keyword, - }); - const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, ((o.layer === 0) ? "" : { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, - el: { - type: "bi.layout", - cls: (o.pNode && o.pNode.isLastNode) ? "" : this._getBaseLineCls(), - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, - height: o.height, - }, - }), { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: { - type: "bi.layout", - cls: this._getFirstLineCls(), - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - height: o.height, - }, - }, { - el: this.text, - }); - createWidget(extend({ - element: this, - }, BI.LogicFactory.createLogic(type, extend(o.logic, { - items, - })))); - } - - _getBaseLineCls() { - switch (BI.STYLE_CONSTANTS.LINK_LINE_TYPE) { - case "solid": - return "base-solid-line-conn-background"; - default: - return "base-line-conn-background"; - } - } - - _getFirstLineCls() { - switch (BI.STYLE_CONSTANTS.LINK_LINE_TYPE) { - case "solid": - return "first-solid-line-conn-background"; - default: - return "first-line-conn-background"; - } - } - - doRedMark() { - this.text.doRedMark(...arguments); - } - - unRedMark() { - this.text.unRedMark(...arguments); - } - - doHighLight() { - this.text.doHighLight(...arguments); - } - - unHighLight() { - this.text.unHighLight(...arguments); - } - - getId() { - return this.options.id; - } - - getPId() { - return this.options.pId; - } -} - diff --git a/src/case/button/treeitem/item.last.treeleaf.js b/src/case/button/treeitem/item.last.treeleaf.js deleted file mode 100644 index 6b89cfbf6..000000000 --- a/src/case/button/treeitem/item.last.treeleaf.js +++ /dev/null @@ -1,105 +0,0 @@ -import { BasicButton } from "../../../base/single/button/button.basic"; -import { shortcut, extend, createWidget } from "../../../core"; - -@shortcut() -export class LastTreeLeafItem extends BasicButton { - static xtype = "bi.last_tree_leaf_item"; - - _defaultConfig() { - return extend(super._defaultConfig(...arguments), { - extraCls: "bi-last-tree-leaf-item bi-list-item-active", - logic: { - dynamic: false, - }, - id: "", - pId: "", - layer: 0, - height: 24, - }); - } - - _init() { - super._init(...arguments); - const o = this.options; - this.text = createWidget({ - type: "bi.label", - textAlign: "left", - whiteSpace: "nowrap", - textHeight: o.height, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - py: o.py, - keyword: o.keyword, - }); - const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, ((o.layer === 0) ? "" : { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, - el: { - type: "bi.layout", - cls: (o.pNode && o.pNode.isLastNode) ? "" : this._getBaseLineCls(), - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, - height: o.height, - }, - }), { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: { - type: "bi.layout", - cls: this._getLastLineCls(), - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - height: o.height, - }, - }, { - el: this.text, - }); - createWidget(extend({ - element: this, - }, BI.LogicFactory.createLogic(type, extend(o.logic, { - items, - })))); - } - - _getBaseLineCls() { - switch (BI.STYLE_CONSTANTS.LINK_LINE_TYPE) { - case "solid": - return "base-solid-line-conn-background"; - default: - return "base-line-conn-background"; - } - } - - _getLastLineCls() { - switch (BI.STYLE_CONSTANTS.LINK_LINE_TYPE) { - case "solid": - return "last-solid-line-conn-background"; - default: - return "last-line-conn-background"; - } - } - - doRedMark() { - this.text.doRedMark(...arguments); - } - - unRedMark() { - this.text.unRedMark(...arguments); - } - - doHighLight() { - this.text.doHighLight(...arguments); - } - - unHighLight() { - this.text.unHighLight(...arguments); - } - - getId() { - return this.options.id; - } - - getPId() { - return this.options.pId; - } -} - diff --git a/src/case/button/treeitem/item.mid.treeleaf.js b/src/case/button/treeitem/item.mid.treeleaf.js deleted file mode 100644 index 60d76c414..000000000 --- a/src/case/button/treeitem/item.mid.treeleaf.js +++ /dev/null @@ -1,105 +0,0 @@ -import { BasicButton } from "../../../base/single/button/button.basic"; -import { shortcut, extend, createWidget } from "../../../core"; - -@shortcut() -export class MidTreeLeafItem extends BasicButton { - static xtype = "bi.mid_tree_leaf_item"; - - _defaultConfig() { - return extend(super._defaultConfig(...arguments), { - extraCls: "bi-mid-tree-leaf-item bi-list-item-active", - logic: { - dynamic: false, - }, - id: "", - pId: "", - layer: 0, - height: 24, - }); - } - - _init() { - super._init(...arguments); - const o = this.options; - this.text = createWidget({ - type: "bi.label", - textAlign: "left", - whiteSpace: "nowrap", - textHeight: o.height, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - py: o.py, - keyword: o.keyword, - }); - const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, ((o.layer === 0) ? "" : { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, - el: { - type: "bi.layout", - cls: (o.pNode && o.pNode.isLastNode) ? "" : this._getBaseLineCls(), - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, - height: o.height, - }, - }), { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: { - type: "bi.layout", - cls: this._getMidLineCls(), - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - height: o.height, - }, - }, { - el: this.text, - }); - createWidget(extend({ - element: this, - }, BI.LogicFactory.createLogic(type, extend(o.logic, { - items, - })))); - } - - _getBaseLineCls() { - switch (BI.STYLE_CONSTANTS.LINK_LINE_TYPE) { - case "solid": - return "base-solid-line-conn-background"; - default: - return "base-line-conn-background"; - } - } - - _getMidLineCls() { - switch (BI.STYLE_CONSTANTS.LINK_LINE_TYPE) { - case "solid": - return "mid-solid-line-conn-background"; - default: - return "mid-line-conn-background"; - } - } - - doRedMark() { - this.text.doRedMark(...arguments); - } - - unRedMark () { - this.text.unRedMark(...arguments); - } - - doHighLight() { - this.text.doHighLight(...arguments); - } - - unHighLight() { - this.text.unHighLight(...arguments); - } - - getId() { - return this.options.id; - } - - getPId() { - return this.options.pId; - } -} - diff --git a/src/case/button/treeitem/item.root.treeleaf.js b/src/case/button/treeitem/item.root.treeleaf.js deleted file mode 100644 index f6fdd9c81..000000000 --- a/src/case/button/treeitem/item.root.treeleaf.js +++ /dev/null @@ -1,78 +0,0 @@ -import { BasicButton } from "../../../base/single/button/button.basic"; -import { shortcut, extend } from "../../../core"; - -@shortcut() -export class RootTreeLeafItem extends BasicButton { - static xtype = "bi.root_tree_leaf_item"; - - props = { - baseCls: "bi-root-tree-leaf-item bi-list-item-active", - logic: { - dynamic: false, - }, - id: "", - pId: "", - layer: 0, - height: 24, - } - - render() { - const o = this.options; - const text = { - type: "bi.label", - ref: _ref => { - this.text = _ref; - }, - textAlign: "left", - whiteSpace: "nowrap", - textHeight: o.height, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - py: o.py, - keyword: o.keyword, - }; - - const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: { - type: "bi.layout", - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - height: o.height, - }, - }, { - el: text, - }); - - return BI.LogicFactory.createLogic(type, extend(o.logic, { - items, - })); - } - - doRedMark() { - this.text.doRedMark(...arguments); - } - - unRedMark() { - this.text.unRedMark(...arguments); - } - - doHighLight() { - this.text.doHighLight(...arguments); - } - - unHighLight() { - this.text.unHighLight(...arguments); - } - - getId() { - return this.options.id; - } - - getPId() { - return this.options.pId; - } -} - diff --git a/src/case/button/treeitem/item.treetextleaf.js b/src/case/button/treeitem/item.treetextleaf.js deleted file mode 100644 index 7bc273210..000000000 --- a/src/case/button/treeitem/item.treetextleaf.js +++ /dev/null @@ -1,76 +0,0 @@ -import { BasicButton } from "../../../base/single/button/button.basic"; -import { shortcut, extend, createWidget } from "../../../core"; - -/** - * 树叶子节点 - * Created by GUY on 2015/9/6. - * @class BI.TreeTextLeafItem - * @extends BI.BasicButton - */ -@shortcut() -export class TreeTextLeafItem extends BasicButton { - static xtype = "bi.tree_text_leaf_item"; - - _defaultConfig() { - return extend(super._defaultConfig.apply(this, arguments), { - extraCls: "bi-tree-text-leaf-item bi-list-item-active", - id: "", - pId: "", - height: 24, - hgap: 0, - lgap: 0, - rgap: 0, - }); - } - - _init() { - super._init(...arguments); - const o = this.options; - this.text = createWidget({ - type: "bi.label", - textAlign: "left", - whiteSpace: "nowrap", - textHeight: o.height, - height: o.height, - hgap: o.hgap, - lgap: o.lgap, - rgap: o.hgap, - text: o.text, - value: o.value, - py: o.py, - keyword: o.keyword, - }); - createWidget({ - type: "bi.htape", - element: this, - items: [{ - el: this.text, - }], - }); - } - - doRedMark() { - this.text.doRedMark(...arguments); - } - - unRedMark() { - this.text.unRedMark(...arguments); - } - - doHighLight() { - this.text.doHighLight(...arguments); - } - - unHighLight() { - this.text.unHighLight(...arguments); - } - - getId() { - return this.options.id; - } - - getPId() { - return this.options.pId; - } -} - diff --git a/src/case/button/treeitem/treeitem.js b/src/case/button/treeitem/treeitem.js index 64ae3ffdc..189573c33 100644 --- a/src/case/button/treeitem/treeitem.js +++ b/src/case/button/treeitem/treeitem.js @@ -1,5 +1,5 @@ -import { shortcut, extend, VerticalAdaptLayout, Layout } from "@/core"; -import { NodeButton, Label } from "@/base"; +import { shortcut, extend, VerticalAdaptLayout, Layout, compact, isKey } from "@/core"; +import { NodeButton, Label, IconLabel } from "@/base"; @shortcut() export class BasicTreeItem extends NodeButton { @@ -16,25 +16,57 @@ export class BasicTreeItem extends NodeButton { readonly: true, isFirstNode: false, isLastNode: false, + layer: 0, + iconWidth: 16, + iconHeight: 16, + iconCls: "", }); } render() { - const o = this.options; + const { + layer, + height, + hgap, + textHgap, + textVgap, + textLgap, + textRgap, + text, + value, + py, + keyword, + iconWidth, + iconHeight, + iconCls, + } = this.options; + + const icon = isKey(iconCls) ? { + el: { + type: IconLabel.xtype, + iconWidth, + iconHeight, + cls: iconCls, + }, + width: 24, + } : null; + + const indent = layer === 0 ? null : { + el: { + type: Layout.xtype, + height, + width: height, + cls: this.getLineCls(), + }, + lgap: layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, // 偏移公式为每一层的偏移量为节点高度的一半 + width: "", + }; return { type: VerticalAdaptLayout.xtype, - columnSize: ["", "fill"], - items: [ - { - el: { - type: Layout.xtype, - height: o.height, - width: o.height, - cls: this.getLineCls(), - }, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, // 偏移公式为每一层的偏移量为节点高度的一半 - }, + items: compact([ + icon, + indent, { el: { type: Label.xtype, @@ -43,19 +75,20 @@ export class BasicTreeItem extends NodeButton { }, textAlign: "left", whiteSpace: "nowrap", - textHeight: o.height, - height: o.height, - hgap: o.hgap || o.textHgap, - vgap: o.textVgap, - lgap: o.textLgap, - rgap: o.textRgap, - text: o.text, - value: o.value, - keyword: o.keyword, - py: o.py, + textHeight: height, + height, + hgap: hgap || textHgap, + vgap: textVgap, + lgap: textLgap, + rgap: textRgap, + text, + value, + keyword, + py, }, + width: "fill", } - ], + ]), }; } @@ -88,3 +121,54 @@ export class BasicTreeItem extends NodeButton { return this.options.pId; } } + +export class FirstTreeLeafItem extends BasicTreeItem { + static xtype = "bi.first_tree_leaf_item"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { + extraCls: "bi-first-tree-leaf-item", + isFirstNode: true, + isLastNode: false, + }); + } +} + +@shortcut() +export class MidTreeLeafItem extends BasicTreeItem { + static xtype = "bi.mid_tree_leaf_item"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { + extraCls: "bi-mid-tree-leaf-item", + isFirstNode: false, + isLastNode: false, + }); + } +} + +@shortcut() +export class LastTreeLeafItem extends BasicTreeItem { + static xtype = "bi.last_tree_leaf_item"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { + extraCls: "bi-last-tree-leaf-item", + isFirstNode: false, + isLastNode: true, + }); + } +} + +@shortcut() +export class RootTreeLeafItem extends BasicTreeItem { + static xtype = "bi.root_tree_leaf_item"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { + extraCls: "bi-root-tree-leaf-item", + isFirstNode: false, + isLastNode: false, + }); + } +} diff --git a/src/case/layer/pane.list.js b/src/case/layer/pane.list.js index 69d6f4df1..5395c0e20 100644 --- a/src/case/layer/pane.list.js +++ b/src/case/layer/pane.list.js @@ -5,15 +5,36 @@ * @class BI.ListPane * @extends BI.Pane */ -import { shortcut, extend, each, createWidget, emptyFn, nextTick, concat, get, Controller, Events, LogicFactory, Direction, isNull, removeAt, isFunction, isNotEmptyString, isEmptyArray } from "@/core"; +import { + shortcut, + extend, + each, + createWidget, + emptyFn, + nextTick, + concat, + get, + Controller, + Events, + LogicFactory, + Direction, + isNull, + removeAt, + isFunction, + isNotEmptyString, + isEmptyArray, + VerticalLayout +} from "@/core"; import { Pane, ButtonGroup } from "@/base"; + @shortcut() export class ListPane extends Pane { static xtype = "bi.list_pane"; static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig () { + + _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-list-pane`, logic: { @@ -30,15 +51,16 @@ export class ListPane extends Pane { hasNext: emptyFn, onLoaded: emptyFn, el: { - type: "bi.button_group", + type: ButtonGroup.xtype, }, }); } - _init () { + + _init() { super._init(...arguments); const o = this.options; this.button_group = createWidget(o.el, { - type: "bi.button_group", + type: ButtonGroup.xtype, chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, behaviors: {}, items: o.items, @@ -52,9 +74,9 @@ export class ListPane extends Pane { } o.itemsCreator(op, (...args) => { callback(...args); - o.items = concat(o.items, get(...args, [0], [])); + o.items = concat(o.items, get(args, [0], [])); if (op.times === 1) { - o.items = get(...args, [0], []); + o.items = get(args, [0], []); nextTick(() => { this.loaded(); // callback可能在loading之前执行, check保证显示正确 @@ -64,9 +86,11 @@ export class ListPane extends Pane { }); }, hasNext: o.hasNext, - layouts: [{ - type: "bi.vertical", - }], + layouts: [ + { + type: VerticalLayout.xtype, + } + ], }); this.button_group.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { @@ -92,43 +116,45 @@ export class ListPane extends Pane { })))); } - hasPrev () { + hasPrev() { return this.button_group.hasPrev && this.button_group.hasPrev(); } - hasNext () { + hasNext() { return this.button_group.hasNext && this.button_group.hasNext(); } - prependItems (items) { + prependItems(items) { this.options.items = items.concat(this.options.items); this.button_group.prependItems(...arguments); this.check(); } - addItems (items) { + addItems(items) { this.options.items = this.options.items.concat(items); this.button_group.addItems(...arguments); this.check(); } - removeItemAt (indexes) { + removeItemAt(indexes) { indexes = isNull(indexes) ? [] : indexes; removeAt(this.options.items, indexes); this.button_group.removeItemAt(...arguments); this.check(); } - populate (items) { + populate(items) { const o = this.options; if (arguments.length === 0 && (isFunction(this.button_group.attr("itemsCreator")))) {// 接管loader的populate方法 - this.button_group.attr("itemsCreator").apply(this, [{ times: 1 }, (...args) => { - if (args.length === 0) { - throw new Error("参数不能为空"); + this.button_group.attr("itemsCreator").apply(this, [ + { times: 1 }, (...args) => { + if (args.length === 0) { + throw new Error("参数不能为空"); + } + this.populate(...args); } - this.populate(...args); - }]); - + ]); + return; } @@ -144,23 +170,23 @@ export class ListPane extends Pane { } } - empty () { + empty() { this.button_group.empty(); } - setNotSelectedValue () { + setNotSelectedValue() { this.button_group.setNotSelectedValue(...arguments); } - getNotSelectedValue () { + getNotSelectedValue() { return this.button_group.getNotSelectedValue(); } - setValue () { + setValue() { this.button_group.setValue(...arguments); } - setAllSelected (v) { + setAllSelected(v) { if (this.button_group.setAllSelected) { this.button_group.setAllSelected(v); } else { @@ -170,35 +196,35 @@ export class ListPane extends Pane { } } - getValue () { + getValue() { return this.button_group.getValue(...arguments); } - getAllButtons () { + getAllButtons() { return this.button_group.getAllButtons(); } - getAllLeaves () { + getAllLeaves() { return this.button_group.getAllLeaves(); } - getSelectedButtons () { + getSelectedButtons() { return this.button_group.getSelectedButtons(); } - getNotSelectedButtons () { + getNotSelectedButtons() { return this.button_group.getNotSelectedButtons(); } - getIndexByValue (value) { + getIndexByValue(value) { return this.button_group.getIndexByValue(value); } - getNodeById (id) { + getNodeById(id) { return this.button_group.getNodeById(id); } - getNodeByValue (value) { + getNodeByValue(value) { return this.button_group.getNodeByValue(value); } } diff --git a/src/case/list/list.select.js b/src/case/list/list.select.js index e9fce794a..cdd440f7c 100644 --- a/src/case/list/list.select.js +++ b/src/case/list/list.select.js @@ -67,7 +67,7 @@ export class SelectList extends Widget { this.list = createWidget(o.el, { type: ListPane.xtype, items: o.items, - itemsCreator(op, callback) { + itemsCreator: (op, callback) => { op.times === 1 && this.toolbar.setVisible(false); o.itemsCreator(op, (items, keywords, context, ...args) => { callback(items, keywords, context, ...args); diff --git a/src/less/base/dom.less b/src/less/base/dom.less deleted file mode 100644 index ffac75ef8..000000000 --- a/src/less/base/dom.less +++ /dev/null @@ -1,2 +0,0 @@ -@import "../index.less"; -@import "../lib/colors.less"; From a6cc9b9ebf78f7ce9aace281036eeee0b44bd335 Mon Sep 17 00:00:00 2001 From: Treecat Date: Thu, 12 Jan 2023 18:45:14 +0800 Subject: [PATCH 105/300] =?UTF-8?q?=E6=97=A0jira=20fix:=20xtype=20?= =?UTF-8?q?=E6=90=9E=E9=94=99=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/case/combo/bubblecombo/popup.bubble.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/case/combo/bubblecombo/popup.bubble.js b/src/case/combo/bubblecombo/popup.bubble.js index 2b145941a..ef62146c7 100644 --- a/src/case/combo/bubblecombo/popup.bubble.js +++ b/src/case/combo/bubblecombo/popup.bubble.js @@ -3,7 +3,7 @@ import { PopupView, Label } from "@/base"; @shortcut() export class BubblePopupView extends PopupView { - static xtype = "bi.text_bubble_bar_popup_view"; + static xtype = "bi.bubble_popup_view"; static EVENT_CLICK_TOOLBAR_BUTTON = "EVENT_CLICK_TOOLBAR_BUTTON"; static EVENT_CHANGE = "EVENT_CLICK_TOOLBAR_BUTTON"; From 6b1aeb6d9f49def0d7c773be77f926e1efc61d17 Mon Sep 17 00:00:00 2001 From: "crawford.zhou" Date: Thu, 12 Jan 2023 19:16:54 +0800 Subject: [PATCH 106/300] =?UTF-8?q?KERNEL-14067=20feat:year=20&&=20yearInt?= =?UTF-8?q?erval=20=E7=9A=84es6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/widget/index.js | 10 +- src/widget/year/card.dynamic.year.js | 135 ++++---- src/widget/year/card.year.js | 229 ++++++------ src/widget/year/combo.year.js | 262 +++++++------- src/widget/year/index.js | 5 + src/widget/year/popup.year.js | 440 ++++++++++++++---------- src/widget/year/trigger.year.js | 291 ++++++++-------- src/widget/yearinterval/yearinterval.js | 296 +++++++++------- 8 files changed, 914 insertions(+), 754 deletions(-) create mode 100644 src/widget/year/index.js diff --git a/src/widget/index.js b/src/widget/index.js index 874fd77cd..e86e9e362 100644 --- a/src/widget/index.js +++ b/src/widget/index.js @@ -19,7 +19,8 @@ import { NumberEditor } from "./numbereditor/number.editor"; import { NumberInterval } from "./numberinterval/numberinterval"; import * as multiselect from "./multiselect"; import * as multiselectlist from "./multiselectlist"; - +import * as year from "./year"; +import { YearInterval } from "./yearinterval/yearinterval"; Object.assign(BI, { Collapse, ...calendar, @@ -29,6 +30,7 @@ Object.assign(BI, { ...datetimepane, ...dynamicdatetime, ...time, + ...year, ...editor, ...downList, ...singleSliderItem, @@ -40,6 +42,7 @@ Object.assign(BI, { MultiTreeListCombo, NumberEditor, NumberInterval, + YearInterval, ...multiselect, ...multiselectlist, }); @@ -57,7 +60,7 @@ export * from "./multiselectlist"; export * from "./downlist"; export * from "./singleslider"; export * from "./intervalslider"; - +export * from "./year"; export { Collapse, NumberEditor, @@ -66,5 +69,6 @@ export { SingleTreeCombo, MultiTreeCombo, MultiTreeInsertCombo, - MultiTreeListCombo + MultiTreeListCombo, + YearInterval }; diff --git a/src/widget/year/card.dynamic.year.js b/src/widget/year/card.dynamic.year.js index b38d55119..8edcb0047 100644 --- a/src/widget/year/card.dynamic.year.js +++ b/src/widget/year/card.dynamic.year.js @@ -5,115 +5,118 @@ * @class BI.YearCard * @extends BI.Trigger */ -BI.DynamicYearCard = BI.inherit(BI.Widget, { +import { checkDateVoid, i18nText, isNotEmptyString, parseDateTime, shortcut, VerticalLayout, Widget } from "@/core"; +import { Bubbles, Label } from "@/base"; +import { DynamicDateCard, DynamicDateHelper, DynamicDateParamItem } from "@/widget"; - props: { - baseCls: "bi-year-card" - }, - - render: function () { - var self = this, o = this.options; +@shortcut() +export class DynamicYearCard extends Widget { + static xtype = "bi.dynamic_year_card"; + static EVENT_CHANGE = "EVENT_CHANGE"; + props = { + baseCls: "bi-year-card", + } + render() { return { - type: "bi.vertical", - ref: function (_ref) { - self.wrapper = _ref; + type: VerticalLayout.xtype, + ref: _ref => { + this.wrapper = _ref; }, items: [{ - type: "bi.label", - text: BI.i18nText("BI-Multi_Date_Relative_Current_Time"), + type: Label.xtype, + text: i18nText("BI-Multi_Date_Relative_Current_Time"), textAlign: "left", height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, }, { - type: "bi.dynamic_date_param_item", - ref: function () { - self.item = this; + type: DynamicDateParamItem.xtype, + ref: _ref => { + this.item = _ref; }, listeners: [{ eventName: "EVENT_CHANGE", - action: function () { - self.fireEvent("EVENT_CHANGE"); - } + action: () => { + this.fireEvent("EVENT_CHANGE"); + }, }, { eventName: "EVENT_INPUT_CHANGE", - action: function () { - BI.Bubbles.hide("dynamic-year-error"); - } - }] + action: () => { + Bubbles.hide("dynamic-year-error"); + }, + }], }], vgap: 10, - hgap: 10 + hgap: 10, }; - }, - - _checkDate: function (obj) { - var o = this.options; - var date = BI.DynamicDateHelper.getCalculation(this._getValue()); + } + _checkDate() { + const o = this.options; + const date = DynamicDateHelper.getCalculation(this._getValue()); - return !BI.checkDateVoid(date.getFullYear(), date.getMonth() + 1, date.getDate(), o.min, o.max)[0]; - }, + return !checkDateVoid(date.getFullYear(), date.getMonth() + 1, date.getDate(), o.min, o.max)[0]; + } - _createValue: function (type, v) { + _createValue(type, v) { return { dateType: type, value: Math.abs(v), - offset: v > 0 ? 1 : 0 + offset: v > 0 ? 1 : 0, }; - }, + } - _getErrorText: function () { - var o = this.options; - var start = BI.parseDateTime(o.min, "%Y-%X-%d"); - var end = BI.parseDateTime(o.max, "%Y-%X-%d"); - return BI.i18nText("BI-Basic_Year_Range_Error", + _getErrorText() { + const o = this.options; + const start = parseDateTime(o.min, "%Y-%X-%d"); + const end = parseDateTime(o.max, "%Y-%X-%d"); + + return i18nText("BI-Basic_Year_Range_Error", start.getFullYear(), end.getFullYear()); - }, + } - setMinDate: function(minDate) { - if (BI.isNotEmptyString(this.options.min)) { + setMinDate(minDate) { + if (isNotEmptyString(this.options.min)) { this.options.min = minDate; } - }, + } - setMaxDate: function (maxDate) { - if (BI.isNotEmptyString(this.options.max)) { + setMaxDate(maxDate) { + if (isNotEmptyString(this.options.max)) { this.options.max = maxDate; } - }, + } - setValue: function (v) { - v = v || {year: 0}; - this.item.setValue(this._createValue(BI.DynamicDateCard.TYPE.YEAR, v.year)); - }, + setValue(v) { + v = v || { year: 0 }; + this.item.setValue(this._createValue(DynamicDateCard.TYPE.YEAR, v.year)); + } - _getValue: function () { - var value = this.item.getValue(); + _getValue() { + const value = this.item.getValue(); + return { - year: (value.offset === 0 ? -value.value : +value.value) + year: (value.offset === 0 ? -value.value : +value.value), }; - }, + } - getInputValue: function () { + getInputValue() { return this._getValue(); - }, + } - getValue: function () { + getValue() { return this.checkValidation() ? this._getValue() : {}; - }, + } - checkValidation: function (show) { - var errorText; - var invalid = !this.item.checkValidation(); + checkValidation(show) { + let errorText; + let invalid = !this.item.checkValidation(); if (invalid) { - errorText = BI.i18nText("BI-Please_Input_Natural_Number"); + errorText = i18nText("BI-Please_Input_Natural_Number"); } else { invalid = !this._checkDate(this._getValue()); errorText = this._getErrorText(); } - invalid && show && BI.Bubbles.show("dynamic-year-error", errorText, this.item); + invalid && show && Bubbles.show("dynamic-year-error", errorText, this.item, {}); return !invalid; - }, -}); -BI.DynamicYearCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.dynamic_year_card", BI.DynamicYearCard); \ No newline at end of file + } +} diff --git a/src/widget/year/card.year.js b/src/widget/year/card.year.js index b747d104b..2eb1149de 100644 --- a/src/widget/year/card.year.js +++ b/src/widget/year/card.year.js @@ -1,194 +1,205 @@ -/** - * 年份展示面板 - * - * Created by GUY on 2015/9/2. - * @class BI.StaticYearCard - * @extends BI.Trigger - */ -BI.StaticYearCard = BI.inherit(BI.Widget, { - - _defaultConfig: function () { - return BI.extend(BI.StaticYearCard.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, Widget, extend, createWidget, getDate, bind, Controller, isKey, HTapeLayout, CenterAdaptLayout, Layout, each, isNotEmptyString, checkDateVoid, parseInt } from "@/core"; +import { YearCalendar } from "@/case"; +import { IconButton, Navigation } from "@/base"; + +@shortcut() +export class StaticYearCard extends Widget { + static xtype = "bi.static_year_card"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-year-card", behaviors: {}, min: "1900-01-01", // 最小日期 - max: "2099-12-31" // 最大日期 + max: "2099-12-31", // 最大日期 }); - }, - - _createYearCalendar: function (v) { - var o = this.options, y = this._year; + } - var calendar = BI.createWidget({ - type: "bi.year_calendar", + _createYearCalendar(v) { + const o = this.options, + y = this._year; + const calendar = createWidget({ + type: YearCalendar.xtype, behaviors: o.behaviors, min: o.min, max: o.max, logic: { - dynamic: true + dynamic: true, }, - year: y + v * 12 + year: y + v * 12, }); calendar.setValue(this._year); + return calendar; - }, - - _init: function () { - BI.StaticYearCard.superclass._init.apply(this, arguments); - var self = this, o = this.options; + } - this.selectedYear = this._year = BI.getDate().getFullYear(); + _init() { + super._init(...arguments); + const o = this.options; - this.backBtn = BI.createWidget({ - type: "bi.icon_button", + this.selectedYear = this._year = getDate().getFullYear(); + this.backBtn = createWidget({ + type: IconButton.xtype, cls: "pre-page-h-font", width: 25, height: 25, value: -1, - listeners: [{ - eventName: BI.IconButton.EVENT_CHANGE, - action: function () { - self.navigation.setSelect(self.navigation.getSelect() - 1); - self._checkLeftValid(); - self._checkRightValid(); + listeners: [ + { + eventName: IconButton.EVENT_CHANGE, + action :() => { + this.navigation.setSelect( + this.navigation.getSelect() - 1 + ); + this._checkLeftValid(); + this._checkRightValid(); + }, } - }] + ], }); - this.preBtn = BI.createWidget({ - type: "bi.icon_button", + this.preBtn = createWidget({ + type: IconButton.xtype, cls: "next-page-h-font", width: 25, height: 25, value: 1, - listeners: [{ - eventName: BI.IconButton.EVENT_CHANGE, - action: function () { - self.navigation.setSelect(self.navigation.getSelect() + 1); - self._checkLeftValid(); - self._checkRightValid(); + listeners: [ + { + eventName: IconButton.EVENT_CHANGE, + action :() => { + this.navigation.setSelect( + this.navigation.getSelect() + 1 + ); + this._checkLeftValid(); + this._checkRightValid(); + }, } - }] + ], }); - this.navigation = BI.createWidget({ - type: "bi.navigation", + this.navigation = createWidget({ + type: Navigation.xtype, direction: "top", element: this, single: true, logic: { - dynamic: true + dynamic: true, }, tab: { - type: "bi.htape", + type: HTapeLayout.xtype, cls: "bi-split-top bi-split-bottom", height: 30, - items: [{ - el: { - type: "bi.center_adapt", - items: [self.backBtn] + items: [ + { + el: { + type: CenterAdaptLayout.xtype, + items: [this.backBtn], + }, + width: 25, }, - width: 25 - }, { - type: "bi.layout" - }, { - el: { - type: "bi.center_adapt", - items: [self.preBtn] + { + type: Layout.xtype, }, - width: 25 - }] + { + el: { + type: CenterAdaptLayout.xtype, + items: [this.preBtn], + }, + width: 25, + } + ], }, - cardCreator: BI.bind(this._createYearCalendar, this), + cardCreator: bind(this._createYearCalendar, this), - afterCardShow: function () { - this.setValue(self.selectedYear); + afterCardShow: () => { + this.navigation.setValue(this.selectedYear); // var calendar = this.getSelectedCard(); - // self.backBtn.setEnable(!calendar.isFrontYear()); - // self.preBtn.setEnable(!calendar.isFinalYear()); - } + // this.backBtn.setEnable(!calendar.isFrontYear()); + // this.preBtn.setEnable(!calendar.isFinalYear()); + }, }); - this.navigation.on(BI.Navigation.EVENT_CHANGE, function () { - self.selectedYear = this.getValue(); - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - self.fireEvent(BI.StaticYearCard.EVENT_CHANGE, self.selectedYear); + this.navigation.on(Navigation.EVENT_CHANGE, () => { + this.selectedYear = this.navigation.getValue(); + this.fireEvent(Controller.EVENT_CHANGE, ...arguments); + this.fireEvent(StaticYearCard.EVENT_CHANGE, this.selectedYear); }); - if(BI.isKey(o.value)){ + if (isKey(o.value)) { this.setValue(o.value); } - }, + } - _checkLeftValid: function () { - var o = this.options; - var valid = true; + _checkLeftValid() { + const valid = true; this.backBtn.setEnable(valid); + return valid; - }, + } - _checkRightValid: function () { - var o = this.options; - var valid = true; + _checkRightValid() { + const valid = true; this.preBtn.setEnable(valid); + return valid; - }, + } - _checkMin: function () { - var o = this.options; - BI.each(this.navigation.getAllCard(), function (idx, calendar) { + _checkMin() { + const o = this.options; + each(this.navigation.getAllCard(), (idx, calendar) => { calendar.setMinDate(o.min); }); - }, + } - _checkMax: function () { - var o = this.options; - BI.each(this.navigation.getAllCard(), function (idx, calendar) { + _checkMax() { + const o = this.options; + each(this.navigation.getAllCard(), (idx, calendar) => { calendar.setMaxDate(o.max); }); - }, + } - setMinDate: function (minDate) { - if (BI.isNotEmptyString(this.options.min)) { + setMinDate(minDate) { + if (isNotEmptyString(this.options.min)) { this.options.min = minDate; this._checkLeftValid(); this._checkRightValid(); this._checkMin(); } - }, + } - setMaxDate: function (maxDate) { - if (BI.isNotEmptyString(this.options.max)) { + setMaxDate(maxDate) { + if (isNotEmptyString(this.options.max)) { this.options.max = maxDate; this._checkLeftValid(); this._checkRightValid(); this._checkMax(); } - }, + } - getValue: function () { + getValue() { return { - year: this.selectedYear + year: this.selectedYear, }; - }, + } - setValue: function (obj) { - var o = this.options; + setValue(obj) { + const o = this.options; obj = obj || {}; - var v = obj.year; - if (BI.checkDateVoid(v, 1, 1, o.min, o.max)[0]) { - v = BI.getDate().getFullYear(); + let v = obj.year; + if (checkDateVoid(v, 1, 1, o.min, o.max)[0]) { + v = getDate().getFullYear(); this.selectedYear = ""; - this.navigation.setSelect(BI.YearCalendar.getPageByYear(v)); + this.navigation.setSelect(YearCalendar.getPageByYear(v)); this.navigation.setValue(""); } else { - this.selectedYear = BI.parseInt(v); - this.navigation.setSelect(BI.YearCalendar.getPageByYear(v)); + this.selectedYear = parseInt(v); + this.navigation.setSelect(YearCalendar.getPageByYear(v)); this.navigation.setValue(this.selectedYear); } this._checkLeftValid(); this._checkRightValid(); } -}); -BI.StaticYearCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.static_year_card", BI.StaticYearCard); \ No newline at end of file +} diff --git a/src/widget/year/combo.year.js b/src/widget/year/combo.year.js index d2d68d19b..a2ef773b9 100644 --- a/src/widget/year/combo.year.js +++ b/src/widget/year/combo.year.js @@ -1,73 +1,84 @@ -BI.DynamicYearCombo = BI.inherit(BI.Widget, { +import { shortcut, Widget, toPix, getDate, isNotNull, AbsoluteLayout, HorizontalFillLayout, extend } from "@/core"; +import { DynamicYearTrigger } from "@/widget/year/trigger.year"; +import { DynamicDateCombo } from "@/widget"; +import { Combo } from "@/base"; +import { DynamicYearPopup } from "@/widget/year/popup.year"; - _const: { - iconWidth: 24 - }, +@shortcut() +export class DynamicYearCombo extends Widget { + static xtype = "bi.dynamic_year_combo"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_VALID = "EVENT_VALID"; + static EVENT_FOCUS = "EVENT_FOCUS"; + _const ={ + iconWidth: 24, + } - props: { + props={ baseCls: "bi-year-combo", behaviors: {}, minDate: "1900-01-01", // 最小日期 maxDate: "2099-12-31", // 最大日期 height: 24, - supportDynamic: true - }, + supportDynamic: true, + } - _init: function () { - var self = this, o = this.options; - BI.DynamicYearCombo.superclass._init.apply(this, arguments); + _init() { + const o = this.options; + super._init(...arguments); this.storeValue = o.value; - var border = o.simple ? 1 : 2; + const border = o.simple ? 1 : 2; this.trigger = BI.createWidget({ - type: "bi.dynamic_year_trigger", + type: DynamicYearTrigger.xtype, simple: o.simple, min: o.minDate, max: o.maxDate, - height: BI.toPix(o.height, border), + height: toPix(o.height, border), value: o.value || "", - watermark: o.watermark + watermark: o.watermark, }); - this.trigger.on(BI.DynamicYearTrigger.EVENT_KEY_DOWN, function () { - if (self.combo.isViewVisible()) { - self.combo.hideView(); + this.trigger.on(DynamicYearTrigger.EVENT_KEY_DOWN, () => { + if (this.combo.isViewVisible()) { + this.combo.hideView(); } }); - this.trigger.on(BI.DynamicYearTrigger.EVENT_FOCUS, function () { - self.storeTriggerValue = this.getKey(); - self.fireEvent(BI.DynamicYearCombo.EVENT_FOCUS); + this.trigger.on(DynamicYearTrigger.EVENT_FOCUS, () => { + this.storeTriggerValue = this.getKey(); + this.fireEvent(DynamicYearCombo.EVENT_FOCUS); }); - this.trigger.on(BI.DynamicYearTrigger.EVENT_START, function () { - self.combo.isViewVisible() && self.combo.hideView(); + this.trigger.on(DynamicYearTrigger.EVENT_START, () => { + this.combo.isViewVisible() && this.combo.hideView(); }); - this.trigger.on(BI.DynamicYearTrigger.EVENT_STOP, function () { - self.combo.showView(); + this.trigger.on(DynamicYearTrigger.EVENT_STOP, () => { + this.combo.showView(); }); - this.trigger.on(BI.DynamicYearTrigger.EVENT_ERROR, function () { - self.combo.isViewVisible() && self.combo.hideView(); - self.comboWrapper.element.addClass("error"); - self.fireEvent(BI.DynamicYearCombo.EVENT_ERROR); + this.trigger.on(DynamicYearTrigger.EVENT_ERROR, () => { + this.combo.isViewVisible() && this.combo.hideView(); + this.comboWrapper.element.addClass("error"); + this.fireEvent(DynamicYearCombo.EVENT_ERROR); }); - this.trigger.on(BI.DynamicYearTrigger.EVENT_VALID, function () { - self.comboWrapper.element.removeClass("error"); - self.fireEvent(BI.DynamicYearCombo.EVENT_VALID); + this.trigger.on(DynamicYearTrigger.EVENT_VALID, () => { + this.comboWrapper.element.removeClass("error"); + this.fireEvent(DynamicYearCombo.EVENT_VALID); }); - this.trigger.on(BI.DynamicYearTrigger.EVENT_CONFIRM, function () { - if (self.combo.isViewVisible()) { + this.trigger.on(DynamicYearTrigger.EVENT_CONFIRM, () => { + if (this.combo.isViewVisible()) { return; } - if (this.getKey() && this.getKey() !== self.storeTriggerValue) { - self.storeValue = self.trigger.getValue(); - self.setValue(self.storeValue); + if (this.getKey() && this.getKey() !== this.storeTriggerValue) { + this.storeValue = this.trigger.getValue(); + this.setValue(this.storeValue); } else if (!this.getKey()) { - self.storeValue = null; - self.setValue(); + this.storeValue = null; + this.setValue(); } - self._checkDynamicValue(self.storeValue); - self.fireEvent(BI.DynamicYearCombo.EVENT_CONFIRM); + this._checkDynamicValue(this.storeValue); + this.fireEvent(DynamicYearCombo.EVENT_CONFIRM); }); - this.combo = BI.createWidget({ - type: "bi.combo", + type: Combo.xtype, container: o.container, isNeedAdjustHeight: false, isNeedAdjustWidth: false, @@ -78,150 +89,143 @@ BI.DynamicYearCombo = BI.inherit(BI.Widget, { minWidth: 85, stopPropagation: false, el: { - type: "bi.dynamic_year_popup", + type: DynamicYearPopup.xtype, supportDynamic: o.supportDynamic, - ref: function () { - self.popup = this; + ref: _ref => { + this.popup = _ref; }, listeners: [{ - eventName: BI.DynamicYearPopup.EVENT_CHANGE, - action: function () { - self.setValue(self.popup.getValue()); - self.combo.hideView(); - self.fireEvent(BI.DynamicYearCombo.EVENT_CONFIRM); - } + eventName: DynamicYearPopup.EVENT_CHANGE, + action:() => { + this.setValue(this.popup.getValue()); + this.combo.hideView(); + this.fireEvent(DynamicYearCombo.EVENT_CONFIRM); + }, }, { - eventName: BI.DynamicYearPopup.BUTTON_CLEAR_EVENT_CHANGE, - action: function () { - self.setValue(); - self.combo.hideView(); - self.fireEvent(BI.DynamicYearCombo.EVENT_CONFIRM); - } + eventName: DynamicYearPopup.BUTTON_CLEAR_EVENT_CHANGE, + action: () => { + this.setValue(); + this.combo.hideView(); + this.fireEvent(DynamicYearCombo.EVENT_CONFIRM); + }, }, { - eventName: BI.DynamicYearPopup.BUTTON_lABEL_EVENT_CHANGE, - action: function () { - var date = BI.getDate(); - self.setValue({ type: BI.DynamicYearCombo.Static, value: { year: date.getFullYear() } }); - self.combo.hideView(); - self.fireEvent(BI.DynamicDateCombo.EVENT_CONFIRM); - } + eventName: DynamicYearPopup.BUTTON_lABEL_EVENT_CHANGE, + action: () => { + const date = getDate(); + this.setValue({ type: DynamicYearCombo.Static, value: { year: date.getFullYear() } }); + this.combo.hideView(); + this.fireEvent(DynamicDateCombo.EVENT_CONFIRM); + }, }, { - eventName: BI.DynamicYearPopup.BUTTON_OK_EVENT_CHANGE, - action: function () { - self.setValue(self.popup.getValue()); - self.combo.hideView(); - self.fireEvent(BI.DynamicDateCombo.EVENT_CONFIRM); - } + eventName: DynamicYearPopup.BUTTON_OK_EVENT_CHANGE, + action: () => { + this.setValue(this.popup.getValue()); + this.combo.hideView(); + this.fireEvent(DynamicDateCombo.EVENT_CONFIRM); + }, }], behaviors: o.behaviors, min: o.minDate, - max: o.maxDate + max: o.maxDate, }, - value: o.value || "" - } + value: o.value || "", + }, }); - this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { - self.popup.setMinDate(o.minDate); - self.popup.setMaxDate(o.maxDate); - self.popup.setValue(self.storeValue); - self.fireEvent(BI.DynamicYearCombo.EVENT_BEFORE_POPUPVIEW); + this.combo.on(Combo.EVENT_BEFORE_POPUPVIEW, () => { + this.popup.setMinDate(o.minDate); + this.popup.setMaxDate(o.maxDate); + this.popup.setValue(this.storeValue); + this.fireEvent(DynamicYearCombo.EVENT_BEFORE_POPUPVIEW); }); BI.createWidget({ - type: "bi.absolute", + type: AbsoluteLayout.xtype, element: this, items: [{ el: { - type: "bi.horizontal_fill", + type: HorizontalFillLayout.xtype, columnSize: ["", "fill"], - cls: (o.simple ? "bi-border-bottom" : "bi-border bi-border-radius") + " bi-focus-shadow", - ref: function () { - self.comboWrapper = this; + cls: `${o.simple ? "bi-border-bottom" : "bi-border bi-border-radius"} bi-focus-shadow`, + ref: _ref => { + this.comboWrapper = _ref; }, items: [{ el: { type: "bi.icon_button", cls: "bi-trigger-icon-button date-change-h-font", width: this._const.iconWidth, - height: BI.toPix(o.height, border), - ref: function () { - self.changeIcon = this; - } + height: toPix(o.height, border), + ref: _ref => { + this.changeIcon = _ref; + }, }, - }, this.combo] + }, this.combo], }, top: 0, left: 0, right: 0, - bottom: 0 - }] + bottom: 0, + }], }); this._checkDynamicValue(o.value); - }, + } - _checkDynamicValue: function (v) { - var type = null; - if (BI.isNotNull(v)) { + _checkDynamicValue(v) { + let type = null; + if (isNotNull(v)) { type = v.type; } switch (type) { - case BI.DynamicYearCombo.Dynamic: - this.changeIcon.setVisible(true); - break; - default: - this.changeIcon.setVisible(false); - break; + case DynamicYearCombo.Dynamic: + this.changeIcon.setVisible(true); + break; + default: + this.changeIcon.setVisible(false); + break; } - }, + } - setMinDate: function (minDate) { - var o = this.options; + setMinDate(minDate) { + const o = this.options; o.minDate = minDate; this.trigger.setMinDate(minDate); this.popup && this.popup.setMinDate(minDate); - }, + } - setMaxDate: function (maxDate) { - var o = this.options; + setMaxDate(maxDate) { + const o = this.options; o.maxDate = maxDate; this.trigger.setMaxDate(maxDate); this.popup && this.popup.setMaxDate(maxDate); - }, + } - hideView: function () { + hideView() { this.combo.hideView(); - }, + } - getKey: function () { - return this.trigger.getKey() + ""; - }, + getKey() { + return `${this.trigger.getKey()}`; + } - setValue: function (v) { + setValue(v) { this.storeValue = v; this.trigger.setValue(v); this._checkDynamicValue(v); - }, + } - getValue: function () { + getValue() { return this.storeValue; - }, + } - isStateValid: function () { + isStateValid() { return this.trigger.isValid(); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.trigger.setWaterMark(v); } -}); -BI.DynamicYearCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.DynamicYearCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.DynamicYearCombo.EVENT_ERROR = "EVENT_ERROR"; -BI.DynamicYearCombo.EVENT_VALID = "EVENT_VALID"; -BI.DynamicYearCombo.EVENT_FOCUS = "EVENT_FOCUS"; -BI.shortcut("bi.dynamic_year_combo", BI.DynamicYearCombo); - -BI.extend(BI.DynamicYearCombo, { +} +extend(DynamicYearCombo, { Static: 1, - Dynamic: 2 + Dynamic: 2, }); diff --git a/src/widget/year/index.js b/src/widget/year/index.js new file mode 100644 index 000000000..bc5810fe7 --- /dev/null +++ b/src/widget/year/index.js @@ -0,0 +1,5 @@ +export { DynamicYearCard } from "./card.dynamic.year"; +export { StaticYearCard } from "./card.year"; +export { DynamicYearCombo } from "./combo.year"; +export { DynamicYearPopup } from "./popup.year"; +export { DynamicYearTrigger } from "./trigger.year"; diff --git a/src/widget/year/popup.year.js b/src/widget/year/popup.year.js index 2e6d4b952..9ce8e1d9a 100644 --- a/src/widget/year/popup.year.js +++ b/src/widget/year/popup.year.js @@ -1,246 +1,318 @@ -/** - * 年份展示面板 - * - * Created by GUY on 2015/9/2. - * @class BI.DynamicYearPopup - * @extends BI.Trigger - */ -BI.DynamicYearPopup = BI.inherit(BI.Widget, { - constants: { - tabHeight: 40, - }, +import { shortcut, Widget, toPix, i18nText, VerticalLayout, GridLayout, print, getDate, checkDateVoid, createItems } from "@/core"; +import { TextButton, Tab } from "@/base"; +import { DynamicDateCombo, DynamicDateHelper, DynamicYearCard, DynamicYearCombo, StaticYearCard } from "@/widget"; +import { LinearSegment } from "@/case"; - props: { +@shortcut() +export class DynamicYearPopup extends Widget { + static xtype = "bi.dynamic_year_popup"; + props = { baseCls: "bi-dynamic-year-popup", behaviors: {}, - min: "1900-01-01", // 最小日期 - max: "2099-12-31", // 最大日期, + min: "1900-01-01", + max: "2099-12-31", width: 180, supportDynamic: true, - }, + }; + constants = { + tabHeight: 40, + }; + static BUTTON_CLEAR_EVENT_CHANGE = "BUTTON_CLEAR_EVENT_CHANGE"; + static BUTTON_lABEL_EVENT_CHANGE = "BUTTON_lABEL_EVENT_CHANGE"; + static BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE"; + static EVENT_CHANGE = "EVENT_CHANGE"; - render: function () { - var self = this, opts = this.options, c = this.constants; - this.storeValue = {type: BI.DynamicYearCombo.Static}; + render() { + this.storeValue = { type: DynamicYearCombo.Static }; + return { - type: "bi.vertical", - items: [{ - el: this._getTabJson() - }, { - el: { - type: "bi.grid", - items: [[{ - type: "bi.text_button", - cls: "bi-split-top bi-high-light", - textHeight: BI.toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), - shadow: true, - text: BI.i18nText("BI-Basic_Clear"), - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.DynamicYearPopup.BUTTON_CLEAR_EVENT_CHANGE); - } - }] - }, { - type: "bi.text_button", - textHeight: BI.toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), - cls: "bi-split-left bi-split-right bi-high-light bi-split-top", - shadow: true, - text: BI.i18nText("BI-Basic_Current_Year"), - disabled: this._checkTodayValid(), - ref: function () { - self.yearButton = this; - }, - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.DynamicYearPopup.BUTTON_lABEL_EVENT_CHANGE); - } - }] - }, { - type: "bi.text_button", - cls: "bi-split-top bi-high-light", - textHeight: BI.toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), - shadow: true, - text: BI.i18nText("BI-Basic_OK"), - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - var type = self.dateTab.getSelect(); - if (type === BI.DynamicDateCombo.Dynamic) { - self.dynamicPane.checkValidation(true) && self.fireEvent(BI.DynamicYearMonthPopup.BUTTON_OK_EVENT_CHANGE); - } else { - self.fireEvent(BI.DynamicYearPopup.BUTTON_OK_EVENT_CHANGE); - } - } - }] - }]], - height: BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, + type: VerticalLayout.xtype, + items: [ + { + el: this._getTabJson(), }, - }] + { + el: { + type: GridLayout.xtype, + items: [ + [ + { + type: TextButton.xtype, + cls: "bi-split-top bi-high-light", + textHeight: toPix( + BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, + 1 + ), + shadow: true, + text: i18nText("BI-Basic_Clear"), + listeners: [ + { + eventName: TextButton.EVENT_CHANGE, + action :() => { + this.fireEvent( + DynamicYearPopup.BUTTON_CLEAR_EVENT_CHANGE + ); + }, + } + ], + }, + { + type: TextButton.xtype, + textHeight: toPix( + BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, + 1 + ), + cls: "bi-split-left bi-split-right bi-high-light bi-split-top", + shadow: true, + text: i18nText("BI-Basic_Current_Year"), + disabled: this._checkTodayValid(), + ref: _ref => { + this.yearButton = _ref; + }, + listeners: [ + { + eventName: TextButton.EVENT_CHANGE, + action :() => { + this.fireEvent( + DynamicYearPopup.BUTTON_lABEL_EVENT_CHANGE + ); + }, + } + ], + }, + { + type: TextButton.xtype, + cls: "bi-split-top bi-high-light", + textHeight: toPix( + BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, + 1 + ), + shadow: true, + text: i18nText("BI-Basic_OK"), + listeners: [ + { + eventName: TextButton.EVENT_CHANGE, + action :() => { + const type = + this.dateTab.getSelect(); + if ( + type === + DynamicDateCombo.Dynamic + ) { + this.dynamicPane.checkValidation( + true + ) && + this.fireEvent( + BI.DynamicYearMonthPopup.BUTTON_OK_EVENT_CHANGE + ); + } else { + this.fireEvent( + DynamicYearPopup.BUTTON_OK_EVENT_CHANGE + ); + } + }, + } + ], + } + ] + ], + height: BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, + }, + } + ], }; - }, + } - _setInnerValue: function () { - if (this.dateTab.getSelect() === BI.DynamicDateCombo.Static) { - this.yearButton.setValue(BI.i18nText("BI-Basic_Current_Year")); + _setInnerValue() { + if (this.dateTab.getSelect() === DynamicDateCombo.Static) { + this.yearButton.setValue(i18nText("BI-Basic_Current_Year")); this.yearButton.setEnable(!this._checkYearValid()); } else { - var date = BI.DynamicDateHelper.getCalculation(this.dynamicPane.getInputValue()); - date = BI.print(date, "%Y"); + let date = DynamicDateHelper.getCalculation( + this.dynamicPane.getInputValue() + ); + date = print(date, "%Y"); this.yearButton.setValue(date); this.yearButton.setEnable(false); } - }, + } - _checkYearValid: function () { - var o = this.options; - var today = BI.getDate(); - return !!BI.checkDateVoid(today.getFullYear(), today.getMonth() + 1, today.getDate(), o.min, o.max)[0]; - }, + _checkYearValid() { + const o = this.options; + const today = getDate(); + + return !!checkDateVoid( + today.getFullYear(), + today.getMonth() + 1, + today.getDate(), + o.min, + o.max + )[0]; + } - _getTabJson: function () { - var self = this, o = this.options; + _getTabJson() { + const o = this.options; + return { - type: "bi.tab", + type: Tab.xtype, logic: { - dynamic: true + dynamic: true, }, - ref: function () { - self.dateTab = this; + ref: _ref => { + this.dateTab = _ref; }, tab: { - type: "bi.linear_segment", + type: LinearSegment.xtype, invisible: !o.supportDynamic, height: this.constants.tabHeight, - items: BI.createItems([{ - text: BI.i18nText("BI-Basic_Year_Fen"), - value: BI.DynamicYearCombo.Static - }, { - text: BI.i18nText("BI-Basic_Dynamic_Title"), - value: BI.DynamicYearCombo.Dynamic - }], { - textAlign: "center" - }) + items: createItems( + [ + { + text: i18nText("BI-Basic_Year_Fen"), + value: DynamicYearCombo.Static, + }, + { + text: i18nText("BI-Basic_Dynamic_Title"), + value: DynamicYearCombo.Dynamic, + } + ], + { + textAlign: "center", + } + ), }, - cardCreator: function (v) { + cardCreator: v => { switch (v) { - case BI.DynamicYearCombo.Dynamic: - return { - type: "bi.dynamic_year_card", - cls: "dynamic-year-pane", - min: self.options.min, - max: self.options.max, - listeners: [{ + case DynamicYearCombo.Dynamic: + return { + type: DynamicYearCard.xtype, + cls: "dynamic-year-pane", + min: o.min, + max: o.max, + listeners: [ + { eventName: "EVENT_CHANGE", - action: function () { - self._setInnerValue(self.year, v); - } - }], - ref: function () { - self.dynamicPane = this; + action : () => { + this._setInnerValue(this.year, v); + }, } - }; - case BI.DynamicYearCombo.Static: - default: - return { - type: "bi.static_year_card", - behaviors: o.behaviors, - min: self.options.min, - max: self.options.max, - listeners: [{ - eventName: BI.StaticYearCard.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.DynamicYearPopup.EVENT_CHANGE); - } - }], - ref: function () { - self.year = this; + ], + ref: _ref => { + this.dynamicPane = _ref; + }, + }; + case DynamicYearCombo.Static: + default: + return { + type: StaticYearCard.xtype, + behaviors: o.behaviors, + min: o.min, + max: o.max, + listeners: [ + { + eventName: StaticYearCard.EVENT_CHANGE, + action: () => { + this.fireEvent( + DynamicYearPopup.EVENT_CHANGE + ); + }, } - }; + ], + ref: _ref => { + this.year = _ref; + }, + }; } }, - listeners: [{ - eventName: BI.Tab.EVENT_CHANGE, - action: function () { - var v = self.dateTab.getSelect(); - switch (v) { - case BI.DynamicYearCombo.Static: - var date = BI.DynamicDateHelper.getCalculation(self.dynamicPane.getValue()); - self.year.setValue({year: date.getFullYear()}); - self._setInnerValue(); + listeners: [ + { + eventName: Tab.EVENT_CHANGE, + action :() => { + const v = this.dateTab.getSelect(); + switch (v) { + case DynamicYearCombo.Static: { + const date = DynamicDateHelper.getCalculation(this.dynamicPane.getValue()); + this.year.setValue({ year: date.getFullYear() }); + this._setInnerValue(); break; - case BI.DynamicYearCombo.Dynamic: + } + case DynamicYearCombo.Dynamic: default: - if(self.storeValue && self.storeValue.type === BI.DynamicYearCombo.Dynamic) { - self.dynamicPane.setValue(self.storeValue.value); - }else{ - self.dynamicPane.setValue({ - year: 0 + if ( + this.storeValue && + this.storeValue.type === + DynamicYearCombo.Dynamic + ) { + this.dynamicPane.setValue( + this.storeValue.value + ); + } else { + this.dynamicPane.setValue({ + year: 0, }); } - self._setInnerValue(); + this._setInnerValue(); break; - } + } + }, } - }] + ], }; - }, + } - _checkTodayValid: function () { - var o = this.options; - var today = BI.getDate(); - return !!BI.checkDateVoid(today.getFullYear(), today.getMonth() + 1, today.getDate(), o.min, o.max)[0]; - }, + _checkTodayValid() { + const o = this.options; + const today = getDate(); + + return !!checkDateVoid( + today.getFullYear(), + today.getMonth() + 1, + today.getDate(), + o.min, + o.max + )[0]; + } - setMinDate: function (minDate) { + setMinDate(minDate) { if (this.options.min !== minDate) { this.options.min = minDate; this.year && this.year.setMinDate(minDate); this.dynamicPane && this.dynamicPane.setMinDate(minDate); } - }, + } - setMaxDate: function (maxDate) { + setMaxDate(maxDate) { if (this.options.max !== maxDate) { this.options.max = maxDate; this.year && this.year.setMaxDate(maxDate); this.dynamicPane && this.dynamicPane.setMaxDate(maxDate); } - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v; - var self = this; - var type, value; v = v || {}; - type = v.type || BI.DynamicDateCombo.Static; - value = v.value || v; + const type = v.type || DynamicDateCombo.Static; + const value = v.value || v; this.dateTab.setSelect(type); switch (type) { - case BI.DynamicDateCombo.Dynamic: - this.dynamicPane.setValue(value); - self._setInnerValue(); - break; - case BI.DynamicDateCombo.Static: - default: - this.year.setValue(value); - this.yearButton.setValue(BI.i18nText("BI-Basic_Current_Year")); - this.yearButton.setEnable(!this._checkTodayValid()); - break; + case DynamicDateCombo.Dynamic: + this.dynamicPane.setValue(value); + this._setInnerValue(); + break; + case DynamicDateCombo.Static: + default: + this.year.setValue(value); + this.yearButton.setValue(i18nText("BI-Basic_Current_Year")); + this.yearButton.setEnable(!this._checkTodayValid()); + break; } - }, + } - getValue: function () { + getValue() { return { type: this.dateTab.getSelect(), - value: this.dateTab.getValue() + value: this.dateTab.getValue(), }; } - -}); -BI.DynamicYearPopup.BUTTON_CLEAR_EVENT_CHANGE = "BUTTON_CLEAR_EVENT_CHANGE"; -BI.DynamicYearPopup.BUTTON_lABEL_EVENT_CHANGE = "BUTTON_lABEL_EVENT_CHANGE"; -BI.DynamicYearPopup.BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE"; -BI.DynamicYearPopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.dynamic_year_popup", BI.DynamicYearPopup); +} diff --git a/src/widget/year/trigger.year.js b/src/widget/year/trigger.year.js index 2a9cb1fde..17db67598 100644 --- a/src/widget/year/trigger.year.js +++ b/src/widget/year/trigger.year.js @@ -1,204 +1,227 @@ -BI.DynamicYearTrigger = BI.inherit(BI.Trigger, { - _const: { - hgap: 4, - vgap: 2, - iconWidth: 24 - }, - - _defaultConfig: function () { - return BI.extend(BI.DynamicYearTrigger.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, extend, i18nText, bind, createWidget, isPositiveInteger, checkDateVoid, parseDateTime, isNotNull, isNotEmptyString, parseInt, print, getDate, HorizontalFillLayout } from "@/core"; +import { Trigger, TextButton } from "@/base"; +import { SignEditor, TriggerIconButton } from "@/case"; +import { DynamicDateCombo, DynamicDateHelper } from "@/widget"; + +@shortcut() +export class DynamicYearTrigger extends Trigger { + static xtype = "bi.dynamic_year_trigger"; + + _const = { hgap: 4, vgap: 2, iconWidth: 24 }; + + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_START = "EVENT_START"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_VALID = "EVENT_VALID"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-year-trigger", min: "1900-01-01", // 最小日期 max: "2099-12-31", // 最大日期 height: 24, - watermark: BI.i18nText("BI-Basic_Unrestricted") + watermark: i18nText("BI-Basic_Unrestricted"), }); - }, + } - beforeInit: function (callback) { - var o = this.options; - o.title = BI.bind(this._titleCreator, this); + beforeInit(callback) { + const o = this.options; + o.title = bind(this._titleCreator, this); callback(); - }, + } - _init: function () { - BI.DynamicYearTrigger.superclass._init.apply(this, arguments); - var self = this, o = this.options, c = this._const; - this.editor = BI.createWidget({ - type: "bi.sign_editor", + _init() { + super._init(...arguments); + const o = this.options, + c = this._const; + this.editor = createWidget({ + type: SignEditor.xtype, simple: o.simple, height: o.height, - validationChecker: function (v) { - return v === "" || (BI.isPositiveInteger(v) && !BI.checkDateVoid(v, 1, 1, o.min, o.max)[0]); - }, - quitChecker: function (v) { - return false; - }, + validationChecker: v => ( + v === "" || + (isPositiveInteger(v) && + !checkDateVoid(v, 1, 1, o.min, o.max)[0]) + ), + quitChecker: () => false, hgap: c.hgap, vgap: c.vgap, watermark: o.watermark, allowBlank: true, - errorText: function (v) { - if (BI.isPositiveInteger(v)) { - var start = BI.parseDateTime(o.min, "%Y-%X-%d"); - var end = BI.parseDateTime(o.max, "%Y-%X-%d"); + errorText:v => { + if (isPositiveInteger(v)) { + const start = parseDateTime(o.min, "%Y-%X-%d"); + const end = parseDateTime(o.max, "%Y-%X-%d"); - return BI.i18nText("BI-Basic_Year_Range_Error", + return i18nText( + "BI-Basic_Year_Range_Error", start.getFullYear(), - end.getFullYear()); + end.getFullYear() + ); } - return BI.i18nText("BI-Year_Trigger_Invalid_Text"); + return i18nText("BI-Year_Trigger_Invalid_Text"); }, }); - this.editor.on(BI.SignEditor.EVENT_KEY_DOWN, function () { - self.fireEvent(BI.DynamicYearTrigger.EVENT_KEY_DOWN, arguments); + this.editor.on(SignEditor.EVENT_KEY_DOWN, () => { + this.fireEvent(DynamicYearTrigger.EVENT_KEY_DOWN, ...arguments); }); - this.editor.on(BI.SignEditor.EVENT_FOCUS, function () { - self.fireEvent(BI.DynamicYearTrigger.EVENT_FOCUS); + this.editor.on(SignEditor.EVENT_FOCUS, () => { + this.fireEvent(DynamicYearTrigger.EVENT_FOCUS); }); - this.editor.on(BI.SignEditor.EVENT_STOP, function () { - self.fireEvent(BI.DynamicYearTrigger.EVENT_STOP); + this.editor.on(SignEditor.EVENT_STOP, () => { + this.fireEvent(DynamicYearTrigger.EVENT_STOP); }); - this.editor.on(BI.SignEditor.EVENT_CONFIRM, function () { - var value = self.editor.getValue(); - if (BI.isNotNull(value)) { - self.editor.setValue(value); + this.editor.on(SignEditor.EVENT_CONFIRM, () => { + const value = this.editor.getValue(); + if (isNotNull(value)) { + this.editor.setValue(value); } - if (BI.isNotEmptyString(value)) { - self.storeValue = { - type: BI.DynamicDateCombo.Static, + if (isNotEmptyString(value)) { + this.storeValue = { + type: DynamicDateCombo.Static, value: { - year: value - } + year: value, + }, }; } - self.fireEvent(BI.DynamicYearTrigger.EVENT_CONFIRM); + this.fireEvent(DynamicYearTrigger.EVENT_CONFIRM); }); - this.editor.on(BI.SignEditor.EVENT_SPACE, function () { - if (self.editor.isValid()) { - self.editor.blur(); + this.editor.on(SignEditor.EVENT_SPACE, () => { + if (this.editor.isValid()) { + this.editor.blur(); } }); - this.editor.on(BI.SignEditor.EVENT_START, function () { - self.fireEvent(BI.DynamicYearTrigger.EVENT_START); + this.editor.on(SignEditor.EVENT_START, () => { + this.fireEvent(DynamicYearTrigger.EVENT_START); }); - this.editor.on(BI.SignEditor.EVENT_ERROR, function () { - self.fireEvent(BI.DynamicYearTrigger.EVENT_ERROR); + this.editor.on(SignEditor.EVENT_ERROR, () => { + this.fireEvent(DynamicYearTrigger.EVENT_ERROR); }); - this.editor.on(BI.SignEditor.EVENT_VALID, function () { - self.fireEvent(BI.DynamicYearTrigger.EVENT_VALID); + this.editor.on(SignEditor.EVENT_VALID, () => { + this.fireEvent(DynamicYearTrigger.EVENT_VALID); }); - BI.createWidget({ + createWidget({ element: this, - type: "bi.horizontal_fill", + type: HorizontalFillLayout.xtype, columnSize: ["fill", "", ""], - items: [{ - el: this.editor - }, { - el: { - type: "bi.text_button", - baseCls: "bi-trigger-year-text", - text: BI.i18nText("BI-Multi_Date_Year"), + items: [ + { + el: this.editor, + }, + { + el: { + type: TextButton.xtype, + baseCls: "bi-trigger-year-text", + text: i18nText("BI-Multi_Date_Year"), + }, }, - }, { - el: { - type: "bi.trigger_icon_button", - width: this._const.iconWidth + { + el: { + type: TriggerIconButton.xtype, + width: this._const.iconWidth, + }, } - }] + ], }); this.setValue(o.value); - }, + } - _getText: function (obj) { - var value = ""; - if(BI.isNotNull(obj.year) && BI.parseInt(obj.year) !== 0) { - value += Math.abs(obj.year) + BI.i18nText("BI-Basic_Year") + (obj.year < 0 ? BI.i18nText("BI-Basic_Front") : BI.i18nText("BI-Basic_Behind")); + _getText(obj) { + let value = ""; + if (isNotNull(obj.year) && parseInt(obj.year) !== 0) { + value += + Math.abs(obj.year) + + i18nText("BI-Basic_Year") + + (obj.year < 0 + ? i18nText("BI-Basic_Front") + : i18nText("BI-Basic_Behind")); } + return value; - }, + } - _setInnerValue: function (date, text) { - var dateStr = BI.print(date, "%Y"); + _setInnerValue(date) { + const dateStr = print(date, "%Y"); this.editor.setState(dateStr); this.editor.setValue(dateStr); - }, + } - _titleCreator: function () { - var storeValue = this.storeValue || {}; - var type = storeValue.type || BI.DynamicDateCombo.Static; - var value = storeValue.value; - if(!this.editor.isValid()) { + _titleCreator() { + const storeValue = this.storeValue || {}; + const type = storeValue.type || DynamicDateCombo.Static; + let value = storeValue.value; + if (!this.editor.isValid()) { return ""; } + switch (type) { - case BI.DynamicDateCombo.Dynamic: - var text = this._getText(value); - var date = BI.getDate(); - date = BI.DynamicDateHelper.getCalculation(value); - var dateStr = BI.print(date, "%Y"); - return BI.isEmptyString(text) ? dateStr : (text + ":" + dateStr); - case BI.DynamicDateCombo.Static: - default: - value = value || {}; - return value.year; + case DynamicDateCombo.Dynamic: { + const text = this._getText(value); + let date = getDate(); + date = DynamicDateHelper.getCalculation(value); + const dateStr = BI.print(date, "%Y"); + + return BI.isEmptyString(text) ? dateStr : (`${text}:${dateStr}`); + } + + case DynamicDateCombo.Static: + default: + value = value || {}; + + return value.year; } - }, + } - setValue: function (v) { - var type, value; - var date = BI.getDate(); + setValue(v) { + let type, value; + let date = getDate(); this.storeValue = v; - if (BI.isNotNull(v)) { - type = v.type || BI.DynamicDateCombo.Static; + if (isNotNull(v)) { + type = v.type || DynamicDateCombo.Static; value = v.value || v; } switch (type) { - case BI.DynamicDateCombo.Dynamic: - var text = this._getText(value); - date = BI.DynamicDateHelper.getCalculation(value); - this._setInnerValue(date, text); - break; - case BI.DynamicDateCombo.Static: - default: - value = value || {}; - this.editor.setState(value.year); - this.editor.setValue(value.year); - break; + case DynamicDateCombo.Dynamic: { + const text = this._getText(value); + date = DynamicDateHelper.getCalculation(value); + this._setInnerValue(date, text); + break; + } + case DynamicDateCombo.Static: + default: + value = value || {}; + this.editor.setState(value.year); + this.editor.setValue(value.year); + break; } - }, + } - setMinDate: function (minDate) { - if (BI.isNotEmptyString(this.options.min)) { + setMinDate(minDate) { + if (isNotEmptyString(this.options.min)) { this.options.min = minDate; } - }, + } - setMaxDate: function (maxDate) { - if (BI.isNotEmptyString(this.options.max)) { + setMaxDate(maxDate) { + if (isNotEmptyString(this.options.max)) { this.options.max = maxDate; } - }, + } - getValue: function () { + getValue() { return this.storeValue; - }, + } - getKey: function () { + getKey() { return this.editor.getValue() | 0; - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.editor.setWaterMark(v); } -}); -BI.DynamicYearTrigger.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.DynamicYearTrigger.EVENT_FOCUS = "EVENT_FOCUS"; -BI.DynamicYearTrigger.EVENT_ERROR = "EVENT_ERROR"; -BI.DynamicYearTrigger.EVENT_START = "EVENT_START"; -BI.DynamicYearTrigger.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.DynamicYearTrigger.EVENT_STOP = "EVENT_STOP"; -BI.DynamicYearTrigger.EVENT_VALID = "EVENT_VALID"; -BI.shortcut("bi.dynamic_year_trigger", BI.DynamicYearTrigger); \ No newline at end of file +} diff --git a/src/widget/yearinterval/yearinterval.js b/src/widget/yearinterval/yearinterval.js index 56756e60c..952c655d4 100644 --- a/src/widget/yearinterval/yearinterval.js +++ b/src/widget/yearinterval/yearinterval.js @@ -1,194 +1,232 @@ -/** - * @author windy - * @version 2.0 - * Created by windy on 2021/1/25 - */ -BI.YearInterval = BI.inherit(BI.Single, { - constants: { +import { shortcut, HorizontalFillLayout, createWidget, i18nText, print, parseDateTime, checkDateVoid, isNotNull, checkDateLegal } from "@/core"; +import { Single, Label, Bubbles } from "@/base"; +import { DynamicYearCombo } from "../year"; + +@shortcut() +export class YearInterval extends Single { + static xtype = "bi.year_interval"; + + constants = { height: 24, width: 25, lgap: 15, offset: -15, - timeErrorCls: "time-error" - }, - - props: { + timeErrorCls: "time-error", + }; + props = { extraCls: "bi-year-interval", minDate: "1900-01-01", maxDate: "2099-12-31", supportDynamic: true, - }, + }; + + static EVENT_VALID = "EVENT_VALID"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; o.value = o.value || {}; this.left = this._createCombo(o.value.start, o.watermark?.start); this.right = this._createCombo(o.value.end, o.watermark?.end); return { - type: "bi.horizontal_fill", + type: HorizontalFillLayout.xtype, columnSize: ["fill", "", "fill"], - items: [{ - el: self.left - }, { - el: { - type: "bi.label", - height: o.height, - hgap: 5, - text: "-", - ref: function (_ref) { - self.label = _ref; - } + items: [ + { + el: this.left, + }, + { + el: { + type: Label.xtype, + height: o.height, + hgap: 5, + text: "-", + ref: _ref => { + this.label = _ref; + }, + }, + }, + { + el: this.right, } - }, { - el: self.right - }] + ], }; - }, + } - _createCombo: function (v, watermark) { - var self = this, o = this.options; - var combo = BI.createWidget({ - type: "bi.dynamic_year_combo", + _createCombo(v, watermark) { + const o = this.options; + const combo = createWidget({ + type: DynamicYearCombo.xtype, supportDynamic: o.supportDynamic, minDate: o.minDate, maxDate: o.maxDate, height: o.height, behaviors: o.behaviors, value: v, - watermark: watermark, - listeners: [{ - eventName: BI.DynamicYearCombo.EVENT_BEFORE_POPUPVIEW, - action: function () { - self.fireEvent(BI.YearInterval.EVENT_BEFORE_POPUPVIEW); + watermark, + listeners: [ + { + eventName: DynamicYearCombo.EVENT_BEFORE_POPUPVIEW, + action: () => { + this.fireEvent(YearInterval.EVENT_BEFORE_POPUPVIEW); + }, } - }] + ], }); - combo.on(BI.DynamicYearCombo.EVENT_ERROR, function () { - self._clearTitle(); - BI.Bubbles.hide("error"); - self.element.removeClass(self.constants.timeErrorCls); - self.fireEvent(BI.YearInterval.EVENT_ERROR); + combo.on(DynamicYearCombo.EVENT_ERROR, () => { + this._clearTitle(); + Bubbles.hide("error"); + this.element.removeClass(this.constants.timeErrorCls); + this.fireEvent(YearInterval.EVENT_ERROR); }); - combo.on(BI.DynamicYearCombo.EVENT_VALID, function () { - self._checkValid(); + combo.on(DynamicYearCombo.EVENT_VALID, () => { + this._checkValid(); }); - combo.on(BI.DynamicYearCombo.EVENT_FOCUS, function () { - self._checkValid(); + combo.on(DynamicYearCombo.EVENT_FOCUS, () => { + this._checkValid(); }); - combo.on(BI.DynamicYearCombo.EVENT_CONFIRM, function () { - BI.Bubbles.hide("error"); - var smallDate = self.left.getKey(), bigDate = self.right.getKey(); - if (self.left.isStateValid() && self.right.isStateValid() && self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { - self._setTitle(BI.i18nText("BI-Time_Interval_Error_Text")); - self.element.addClass(self.constants.timeErrorCls); - self.fireEvent(BI.YearInterval.EVENT_ERROR); - }else{ - self._clearTitle(); - self.element.removeClass(self.constants.timeErrorCls); - self.fireEvent(BI.YearInterval.EVENT_CHANGE); + combo.on(DynamicYearCombo.EVENT_CONFIRM, () => { + Bubbles.hide("error"); + const smallDate = this.left.getKey(), + bigDate = this.right.getKey(); + if ( + this.left.isStateValid() && + this.right.isStateValid() && + this._check(smallDate, bigDate) && + this._compare(smallDate, bigDate) + ) { + this._setTitle(i18nText("BI-Time_Interval_Error_Text")); + this.element.addClass(this.constants.timeErrorCls); + this.fireEvent(YearInterval.EVENT_ERROR); + } else { + this._clearTitle(); + this.element.removeClass(this.constants.timeErrorCls); + this.fireEvent(YearInterval.EVENT_CHANGE); } }); + return combo; - }, - - - _dateCheck: function (date) { - return BI.print(BI.parseDateTime(date, "%Y"), "%Y") === date || BI.print(BI.parseDateTime(date, "%Y"), "%Y") === date; - }, + } + _dateCheck(date) { + return ( + print(parseDateTime(date, "%Y"), "%Y") === date || + print(parseDateTime(date, "%Y"), "%Y") === date + ); + } - // 判是否在最大最小之间 - _checkVoid: function (obj) { - var o = this.options; - return !BI.checkDateVoid(obj.year, 1, 1, o.minDate, o.maxDate)[0]; - }, + _checkVoid(obj) { + const o = this.options; + + return !checkDateVoid(obj.year, 1, 1, o.minDate, o.maxDate)[0]; + } - // 判格式合法 - _check: function (smallDate, bigDate) { - var smallObj = smallDate.match(/\d+/g), bigObj = bigDate.match(/\d+/g); + _check(smallDate, bigDate) { + const smallObj = smallDate.match(/\d+/g), + bigObj = bigDate.match(/\d+/g); - var smallDate4Check = ""; - if (BI.isNotNull(smallObj)) { + let smallDate4Check = ""; + if (isNotNull(smallObj)) { smallDate4Check = smallObj[0] || ""; } - var bigDate4Check = ""; - if (BI.isNotNull(bigObj)) { + let bigDate4Check = ""; + if (isNotNull(bigObj)) { bigDate4Check = bigObj[0] || ""; } - return this._dateCheck(smallDate4Check) && BI.checkDateLegal(smallDate4Check) && this._checkVoid({ - year: smallObj[0], - month: 1, - day: 1 - }) && this._dateCheck(bigDate4Check) && BI.checkDateLegal(bigDate4Check) && this._checkVoid({ - year: bigObj[0], - month: 12, - day: 1 - }); - }, - - _compare: function (smallDate, bigDate) { - smallDate = BI.print(BI.parseDateTime(smallDate, "%Y"), "%Y"); - bigDate = BI.print(BI.parseDateTime(bigDate, "%Y"), "%Y"); - return BI.isNotNull(smallDate) && BI.isNotNull(bigDate) && smallDate > bigDate; - }, - _setTitle: function (v) { + return ( + this._dateCheck(smallDate4Check) && + checkDateLegal(smallDate4Check) && + this._checkVoid({ + year: smallObj[0], + month: 1, + day: 1, + }) && + this._dateCheck(bigDate4Check) && + checkDateLegal(bigDate4Check) && + this._checkVoid({ + year: bigObj[0], + month: 12, + day: 1, + }) + ); + } + + _compare(smallDate, bigDate) { + smallDate = print(parseDateTime(smallDate, "%Y"), "%Y"); + bigDate = print(parseDateTime(bigDate, "%Y"), "%Y"); + + return ( + isNotNull(smallDate) && isNotNull(bigDate) && smallDate > bigDate + ); + } + + _setTitle(v) { this.setTitle(v); - }, - _clearTitle: function () { + } + + _clearTitle() { this.setTitle(""); - }, - _checkValid: function () { - var self = this; - - BI.Bubbles.hide("error"); - var smallDate = self.left.getKey(), bigDate = self.right.getKey(); - if (self.left.isValid() && self.right.isValid() && self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { - self._setTitle(BI.i18nText("BI-Time_Interval_Error_Text")); - self.element.addClass(self.constants.timeErrorCls); - BI.Bubbles.show("error", BI.i18nText("BI-Time_Interval_Error_Text"), self, { - offsetStyle: "center" - }); - self.fireEvent(BI.YearInterval.EVENT_ERROR); + } + + _checkValid() { + Bubbles.hide("error"); + const smallDate = this.left.getKey(), + bigDate = this.right.getKey(); + if ( + this.left.isValid() && + this.right.isValid() && + this._check(smallDate, bigDate) && + this._compare(smallDate, bigDate) + ) { + this._setTitle(i18nText("BI-Time_Interval_Error_Text")); + this.element.addClass(this.constants.timeErrorCls); + Bubbles.show( + "error", + i18nText("BI-Time_Interval_Error_Text"), + this, + { + offsetStyle: "center", + } + ); + this.fireEvent(YearInterval.EVENT_ERROR); } else { - self._clearTitle(); - self.element.removeClass(self.constants.timeErrorCls); + this._clearTitle(); + this.element.removeClass(this.constants.timeErrorCls); } - }, + } - setMinDate: function (minDate) { - var o = this.options; + setMinDate(minDate) { + const o = this.options; o.minDate = minDate; this.left.setMinDate(minDate); this.right.setMinDate(minDate); - }, + } - setMaxDate: function (maxDate) { - var o = this.options; + setMaxDate(maxDate) { + const o = this.options; o.maxDate = maxDate; this.left.setMaxDate(maxDate); this.right.setMaxDate(maxDate); - }, + } - setValue: function (date) { + setValue(date) { date = date || {}; this.left.setValue(date.start); this.right.setValue(date.end); this._checkValid(); - }, - getValue: function () { - return {start: this.left.getValue(), end: this.right.getValue()}; } -}); -BI.YearInterval.EVENT_VALID = "EVENT_VALID"; -BI.YearInterval.EVENT_ERROR = "EVENT_ERROR"; -BI.YearInterval.EVENT_CHANGE = "EVENT_CHANGE"; -BI.YearInterval.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut("bi.year_interval", BI.YearInterval); + + getValue() { + return { start: this.left.getValue(), end: this.right.getValue() }; + } +} From f32af40f0f1b1020127eaee7eb4013f1237cfd7e Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Thu, 12 Jan 2023 20:06:01 +0800 Subject: [PATCH 107/300] KERNEL-14101 refactor: widget/singleselect --- src/widget/index.js | 3 + src/widget/multiselect/index.js | 1 + src/widget/singleselect/index.js | 9 + src/widget/singleselect/search/index.js | 3 + .../search/singleselect.search.loader.js | 181 +++++----- .../search/singleselect.search.pane.insert.js | 124 +++---- .../search/singleselect.search.pane.js | 130 +++---- src/widget/singleselect/singleselect.combo.js | 321 +++++++++--------- .../singleselect/singleselect.insert.combo.js | 260 +++++++------- src/widget/singleselect/singleselect.list.js | 226 ++++++------ .../singleselect/singleselect.loader.js | 239 ++++++------- .../singleselect/singleselect.popup.view.js | 88 +++-- .../singleselect/singleselect.trigger.js | 174 +++++----- .../singleselect/singleselectlist.insert.js | 266 ++++++++------- .../trigger/editor.singleselect.js | 102 +++--- src/widget/singleselect/trigger/index.js | 2 + .../trigger/searcher.singleselect.js | 189 +++++------ 17 files changed, 1204 insertions(+), 1114 deletions(-) create mode 100644 src/widget/singleselect/index.js create mode 100644 src/widget/singleselect/search/index.js create mode 100644 src/widget/singleselect/trigger/index.js diff --git a/src/widget/index.js b/src/widget/index.js index 874fd77cd..84e8b6e4f 100644 --- a/src/widget/index.js +++ b/src/widget/index.js @@ -19,6 +19,7 @@ import { NumberEditor } from "./numbereditor/number.editor"; import { NumberInterval } from "./numberinterval/numberinterval"; import * as multiselect from "./multiselect"; import * as multiselectlist from "./multiselectlist"; +import * as singleselect from "./singleselect"; Object.assign(BI, { Collapse, @@ -42,6 +43,7 @@ Object.assign(BI, { NumberInterval, ...multiselect, ...multiselectlist, + ...singleselect, }); export * from "./date/calendar"; @@ -57,6 +59,7 @@ export * from "./multiselectlist"; export * from "./downlist"; export * from "./singleslider"; export * from "./intervalslider"; +export * from "./singleselect"; export { Collapse, diff --git a/src/widget/multiselect/index.js b/src/widget/multiselect/index.js index 9d15e06a0..9e0934c14 100644 --- a/src/widget/multiselect/index.js +++ b/src/widget/multiselect/index.js @@ -2,3 +2,4 @@ export { MultiSelectCombo } from "./multiselect.combo"; export { MultiSelectNoBarCombo } from "./multiselect.combo.nobar"; export { MultiSelectInsertCombo } from "./multiselect.insert.combo"; export { MultiSelectInsertNoBarCombo } from "./multiselect.insert.combo.nobar"; +export { SelectPatchEditor } from "./trigger/editor/editor.patch"; diff --git a/src/widget/singleselect/index.js b/src/widget/singleselect/index.js new file mode 100644 index 000000000..7e3f4cd04 --- /dev/null +++ b/src/widget/singleselect/index.js @@ -0,0 +1,9 @@ +export { SingleSelectCombo } from "./singleselect.combo"; +export { SingleSelectInsertCombo } from "./singleselect.insert.combo"; +export { SingleSelectList } from "./singleselect.list"; +export { SingleSelectLoader } from "./singleselect.loader"; +export { SingleSelectPopupView } from "./singleselect.popup.view"; +export { SingleSelectTrigger } from "./singleselect.trigger"; +export { SingleSelectInsertList } from "./singleselectlist.insert"; +export * from "./trigger"; +export * from "./search"; diff --git a/src/widget/singleselect/search/index.js b/src/widget/singleselect/search/index.js new file mode 100644 index 000000000..70c02c573 --- /dev/null +++ b/src/widget/singleselect/search/index.js @@ -0,0 +1,3 @@ +export { SingleSelectSearchLoader } from "./singleselect.search.loader"; +export { SingleSelectSearchPane } from "./singleselect.search.pane"; +export { SingleSelectSearchInsertPane } from "./singleselect.search.pane.insert"; diff --git a/src/widget/singleselect/search/singleselect.search.loader.js b/src/widget/singleselect/search/singleselect.search.loader.js index 5625593dd..56ab10f3c 100644 --- a/src/widget/singleselect/search/singleselect.search.loader.js +++ b/src/widget/singleselect/search/singleselect.search.loader.js @@ -1,73 +1,80 @@ -/** - * 单选加载数据搜索loader面板 - * Created by guy on 15/11/4. - * @class BI.SingleSelectSearchLoader - * @extends Widget - */ -BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { +import { shortcut, Widget, extend, emptyFn, createWidget, i18nText, isUndefined, Controller, VerticalLayout, map, isArray, isKey, Func } from "@/core"; +import { ButtonGroup, Loader } from "@/base"; +import { SingleSelectList } from "../singleselect.list"; +import { SingleSelectItem, SingleSelectRadioItem } from "@/case"; - _defaultConfig: function () { - return BI.extend(BI.SingleSelectSearchLoader.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class SingleSelectSearchLoader extends Widget { + static xtype = "bi.single_select_search_loader"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-single-select-search-loader", allowNoSelect: false, logic: { - dynamic: false + dynamic: false, }, - itemsCreator: BI.emptyFn, - keywordGetter: BI.emptyFn, - valueFormatter: BI.emptyFn + itemsCreator: emptyFn, + keywordGetter: emptyFn, + valueFormatter: emptyFn, }); - }, + } - _init: function () { - BI.SingleSelectSearchLoader.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, opts = this.options; - var hasNext = false; + const self = this, + opts = this.options; + let hasNext = false; - this.button_group = BI.createWidget({ - type: "bi.single_select_list", + this.button_group = createWidget({ + type: SingleSelectList.xtype, allowNoSelect: opts.allowNoSelect, element: this, logic: { - dynamic: false + dynamic: false, }, value: opts.value, el: { - tipText: BI.i18nText("BI-No_Select"), + tipText: i18nText("BI-No_Select"), el: { - type: "bi.loader", + type: Loader.xtype, isDefaultInit: false, logic: { dynamic: true, - scrolly: true + scrolly: true, }, el: { - chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, + chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, behaviors: { - redmark: function () { + redmark () { return true; - } + }, }, - layouts: [{ - type: "bi.vertical" - }] - } - } + layouts: [ + { + type: VerticalLayout.xtype, + } + ], + }, + }, }, - itemsCreator: function (op, callback) { - self.storeValue && (op = BI.extend(op || {}, { - selectedValues: [self.storeValue] - })); - opts.itemsCreator(op, function (ob) { - var keyword = ob.keyword = opts.keywordGetter(); + itemsCreator (op, callback) { + self.storeValue && + (op = extend(op || {}, { + selectedValues: [self.storeValue], + })); + opts.itemsCreator(op, ob => { + const keyword = (ob.keyword = opts.keywordGetter()); hasNext = ob.hasNext; - var firstItems = []; - if (op.times === 1 && !BI.isUndefined(self.storeValue)) { - var json = self._filterValues(self.storeValue); + let firstItems = []; + if (op.times === 1 && !isUndefined(self.storeValue)) { + const json = self._filterValues(self.storeValue); firstItems = self._createItems(json); } - var context = { + const context = { tipText: ob.tipText, }; callback(firstItems.concat(self._createItems(ob.items)), keyword || "", context); @@ -76,88 +83,88 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { } }); }, - hasNext: function () { + hasNext () { return hasNext; - } + }, }); - this.button_group.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.button_group.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.button_group.on(BI.SingleSelectList.EVENT_CHANGE, function () { - self.fireEvent(BI.SingleSelectSearchLoader.EVENT_CHANGE, arguments); + this.button_group.on(SingleSelectList.EVENT_CHANGE, function () { + self.fireEvent(SingleSelectSearchLoader.EVENT_CHANGE, arguments); }); - }, + } - _createItems: function (items) { - var o = this.options; - return BI.map(items, function (i, item) { - return BI.extend({ - type: o.allowNoSelect ? "bi.single_select_item" : "bi.single_select_radio_item", + _createItems(items) { + const o = this.options; + + return map(items, (i, item) => extend( + { + type: o.allowNoSelect ? SingleSelectItem.xtype : SingleSelectRadioItem.xtype, logic: o.logic, cls: "bi-list-item-active", height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, selected: false, iconWrapperWidth: 26, hgap: o.allowNoSelect ? 10 : 0, - title: item.title || item.text - }, item); - }); - }, + title: item.title || item.text, + }, + item + )); + } - _filterValues: function (src) { - var o = this.options; - var keyword = o.keywordGetter(); - var values = src || []; - var newValues = BI.map(BI.isArray(values) ? values : [values], function (i, v) { + _filterValues(src) { + const o = this.options; + const keyword = o.keywordGetter(); + let values = src || []; + const newValues = map(isArray(values) ? values : [values], (i, v) => { return { text: o.valueFormatter(v) || v, - value: v + value: v, }; }); - if (BI.isKey(keyword)) { - var search = BI.Func.getSearchResult(newValues, keyword); + if (isKey(keyword)) { + const search = Func.getSearchResult(newValues, keyword); values = search.match.concat(search.find); } - return BI.map(values, function (i, v) { + + return map(values, (i, v) => { return { text: v.text, title: v.text, value: v.value, - selected: false + selected: false, }; }); - }, + } - setValue: function (v) { + setValue(v) { // 暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 this.storeValue = v; this.button_group.setValue(v); - }, + } - getValue: function () { + getValue() { return this.button_group.getValue(); - }, + } - getAllButtons: function () { + getAllButtons() { return this.button_group.getAllButtons(); - }, + } - empty: function () { + empty() { this.button_group.empty(); - }, + } - populate: function (items) { - this.button_group.populate.apply(this.button_group, arguments); - }, + populate(items) { + this.button_group.populate(...arguments); + } - resetHeight: function (h) { + resetHeight(h) { this.button_group.resetHeight(h); - }, + } - resetWidth: function (w) { + resetWidth(w) { this.button_group.resetWidth(w); } -}); - -BI.SingleSelectSearchLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.single_select_search_loader", BI.SingleSelectSearchLoader); +} diff --git a/src/widget/singleselect/search/singleselect.search.pane.insert.js b/src/widget/singleselect/search/singleselect.search.pane.insert.js index 6c1e49af2..5c7ca6e5d 100644 --- a/src/widget/singleselect/search/singleselect.search.pane.insert.js +++ b/src/widget/singleselect/search/singleselect.search.pane.insert.js @@ -1,96 +1,96 @@ -/** - * - * 在搜索框中输入文本弹出的面板 - * @class BI.SingleSelectSearchInsertPane - * @extends Widget - */ +import { shortcut, Widget, extend, emptyFn, createWidget, i18nText, Controller, VerticalFillLayout, VerticalLayout } from "@/core"; +import { Label } from "@/base"; +import { SingleSelectSearchLoader } from "./singleselect.search.loader"; -BI.SingleSelectSearchInsertPane = BI.inherit(BI.Widget, { +@shortcut() +export class SingleSelectSearchInsertPane extends Widget { + static xtype = "bi.single_select_search_insert_pane"; - constants: { - height: 25, - lgap: 10, - tgap: 5 - }, + constants = { height: 25, lgap: 10, tgap: 5 }; - _defaultConfig: function () { - return BI.extend(BI.SingleSelectSearchInsertPane.superclass._defaultConfig.apply(this, arguments), { + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-single-select-search-pane-insert bi-card", allowNoSelect: false, - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, - keywordGetter: BI.emptyFn + itemsCreator: emptyFn, + valueFormatter: emptyFn, + keywordGetter: emptyFn, }); - }, + } - _init: function () { - BI.SingleSelectSearchInsertPane.superclass._init.apply(this, arguments); - var self = this, o = this.options; + _init() { + super._init(...arguments); + const self = this, + o = this.options; - this.addNotMatchTip = BI.createWidget({ - type: "bi.label", - text: BI.i18nText("BI-Basic_Press_Enter_To_Add_Text", ""), + this.addNotMatchTip = createWidget({ + type: Label.xtype, + text: i18nText("BI-Basic_Press_Enter_To_Add_Text", ""), height: this.constants.height, cls: "bi-keyword-red-mark", hgap: 5, }); - this.loader = BI.createWidget({ - type: "bi.single_select_search_loader", + this.loader = createWidget({ + type: SingleSelectSearchLoader.xtype, allowNoSelect: o.allowNoSelect, keywordGetter: o.keywordGetter, valueFormatter: o.valueFormatter, - itemsCreator: function (op, callback) { - o.itemsCreator.apply(self, [op, function (res) { - callback(res); - self.setKeyword(o.keywordGetter()); - }]); + itemsCreator (op, callback) { + o.itemsCreator.apply(self, [ + op, + function (res) { + callback(res); + self.setKeyword(o.keywordGetter()); + } + ]); }, - value: o.value + value: o.value, }); - this.loader.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.loader.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.resizer = BI.createWidget({ - type: "bi.vertical_fill", + this.resizer = createWidget({ + type: VerticalFillLayout.xtype, rowSize: ["", "fill"], element: this, - items: [{ - type: "bi.vertical", - items: [this.addNotMatchTip], - height: this.constants.height - }, { - el: this.loader - }] + items: [ + { + type: VerticalLayout.xtype, + items: [this.addNotMatchTip], + height: this.constants.height, + }, + { + el: this.loader, + } + ], }); - }, + } - setKeyword: function (keyword) { - this.addNotMatchTip.setText(BI.i18nText("BI-Basic_Press_Enter_To_Add_Text", keyword)); - }, + setKeyword(keyword) { + this.addNotMatchTip.setText(i18nText("BI-Basic_Press_Enter_To_Add_Text", keyword)); + } - hasMatched: function () { + hasMatched() { return false; - }, + } - setValue: function (v) { + setValue(v) { this.loader.setValue(v); - }, + } - getValue: function () { + getValue() { return this.loader.getValue(); - }, + } - empty: function () { + empty() { this.loader.empty(); - }, - - populate: function (items) { - this.loader.populate.apply(this.loader, arguments); } -}); -BI.SingleSelectSearchInsertPane.EVENT_CHANGE = "EVENT_CHANGE"; - -BI.shortcut("bi.single_select_search_insert_pane", BI.SingleSelectSearchInsertPane); + populate(items) { + this.loader.populate(...arguments); + } +} diff --git a/src/widget/singleselect/search/singleselect.search.pane.js b/src/widget/singleselect/search/singleselect.search.pane.js index ea923c5f6..d11421f34 100644 --- a/src/widget/singleselect/search/singleselect.search.pane.js +++ b/src/widget/singleselect/search/singleselect.search.pane.js @@ -1,101 +1,105 @@ -/** - * - * 在搜索框中输入文本弹出的面板 - * @class BI.SingleSelectSearchPane - * @extends Widget - */ +import { shortcut, Widget, extend, emptyFn, createWidget, i18nText, Controller, VerticalFillLayout } from "@/core"; +import { Label } from "@/base"; +import { SingleSelectSearchLoader } from "./singleselect.search.loader"; -BI.SingleSelectSearchPane = BI.inherit(BI.Widget, { +@shortcut() +export class SingleSelectSearchPane extends Widget { + static xtype = "bi.single_select_search_pane"; - constants: { - height: 25, - lgap: 10, - tgap: 5 - }, + constants = { height: 25, lgap: 10, tgap: 5 }; - _defaultConfig: function () { - return BI.extend(BI.SingleSelectSearchPane.superclass._defaultConfig.apply(this, arguments), { + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-single-select-search-pane bi-card", allowNoSelect: false, - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, - keywordGetter: BI.emptyFn + itemsCreator: emptyFn, + valueFormatter: emptyFn, + keywordGetter: emptyFn, }); - }, + } - _init: function () { - BI.SingleSelectSearchPane.superclass._init.apply(this, arguments); - var self = this, o = this.options; + _init() { + super._init(...arguments); + const self = this, + o = this.options; - this.tooltipClick = BI.createWidget({ - type: "bi.label", + this.tooltipClick = createWidget({ + type: Label.xtype, invisible: true, - text: BI.i18nText("BI-Click_Blank_To_Select"), + text: i18nText("BI-Click_Blank_To_Select"), cls: "single-select-toolbar", - height: this.constants.height + height: this.constants.height, }); - this.loader = BI.createWidget({ - type: "bi.single_select_search_loader", + this.loader = createWidget({ + type: SingleSelectSearchLoader.xtype, allowNoSelect: o.allowNoSelect, keywordGetter: o.keywordGetter, valueFormatter: o.valueFormatter, - itemsCreator: function (op, callback) { - o.itemsCreator.apply(self, [op, function (res) { - callback(res); - self.setKeyword(o.keywordGetter()); - }]); + itemsCreator (op, callback) { + o.itemsCreator.apply(self, [ + op, + function (res) { + callback(res); + self.setKeyword(o.keywordGetter()); + } + ]); }, - value: o.value + value: o.value, }); - this.loader.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.loader.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.resizer = BI.createWidget({ - type: "bi.vertical_fill", + this.resizer = createWidget({ + type: VerticalFillLayout.xtype, rowSize: ["", "fill"], element: this, - items: [{ - el: this.tooltipClick, - }, { - el: this.loader - }] + items: [ + { + el: this.tooltipClick, + }, + { + el: this.loader, + } + ], }); this.tooltipClick.setVisible(false); - }, + } - setKeyword: function (keyword) { - var btn, o = this.options; - var isVisible = this.loader.getAllButtons().length > 0 && (btn = this.loader.getAllButtons()[0]) && (keyword === (o.valueFormatter(btn.getValue()) || btn.getValue())); + setKeyword(keyword) { + let btn; + const o = this.options; + const isVisible = + this.loader.getAllButtons().length > 0 && + (btn = this.loader.getAllButtons()[0]) && + keyword === (o.valueFormatter(btn.getValue()) || btn.getValue()); if (isVisible !== this.tooltipClick.isVisible()) { this.tooltipClick.setVisible(isVisible); - this.resizer.attr("items")[0].height = (isVisible ? this.constants.height : 0); + this.resizer.attr("items")[0].height = isVisible ? this.constants.height : 0; this.resizer.resize(); } - }, + } - hasMatched: function () { + hasMatched() { return this.tooltipClick.isVisible(); - }, + } - setValue: function (v) { + setValue(v) { this.loader.setValue(v); - }, + } - getValue: function () { + getValue() { return this.loader.getValue(); - }, + } - empty: function () { + empty() { this.loader.empty(); - }, - - populate: function (items) { - this.loader.populate.apply(this.loader, arguments); } -}); -BI.SingleSelectSearchPane.EVENT_CHANGE = "EVENT_CHANGE"; - -BI.shortcut("bi.single_select_search_pane", BI.SingleSelectSearchPane); + populate(items) { + this.loader.populate(...arguments); + } +} diff --git a/src/widget/singleselect/singleselect.combo.js b/src/widget/singleselect/singleselect.combo.js index cc4d7c261..2d1d2b013 100644 --- a/src/widget/singleselect/singleselect.combo.js +++ b/src/widget/singleselect/singleselect.combo.js @@ -1,89 +1,104 @@ -/** - * - * @class BI.SingleSelectCombo - * @extends BI.Single - */ -BI.SingleSelectCombo = BI.inherit(BI.Single, { +import { shortcut, extend, emptyFn, isKey, createWidget, toPix, isNotNull, nextTick, AbsoluteLayout, makeObject, map, each, remove } from "@/core"; +import { Single, Combo } from "@/base"; +import { SingleSelectTrigger } from "./singleselect.trigger"; +import { SingleSelectPopupView } from "./singleselect.popup.view"; +import { TriggerIconButton } from "@/case"; - _defaultConfig: function () { - return BI.extend(BI.SingleSelectCombo.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class SingleSelectCombo extends Single { + static xtype = "bi.single_select_combo"; + + static REQ_GET_DATA_LENGTH = 0; + static REQ_GET_ALL_DATA = -1; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_CLICK_ITEM = "EVENT_CLICK_ITEM"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-single-select-combo", allowNoSelect: false, - itemsCreator: BI.emptyFn, - itemWrapper: BI.emptyFn, - valueFormatter: BI.emptyFn, + itemsCreator: emptyFn, + itemWrapper: emptyFn, + valueFormatter: emptyFn, height: 24, - allowEdit: true + allowEdit: true, }); - }, + } - _init: function () { - var self = this, o = this.options; - BI.SingleSelectCombo.superclass._init.apply(this, arguments); + _init() { + const o = this.options; + super._init(...arguments); - var assertShowValue = function () { - BI.isKey(self._startValue) && (self.storeValue = self._startValue); - self.trigger.getSearcher().setState(self.storeValue); + const assertShowValue = () => { + isKey(this._startValue) && (this.storeValue = this._startValue); + this.trigger.getSearcher().setState(this.storeValue); }; this.storeValue = o.value; // 标记正在请求数据 this.requesting = false; - this.trigger = BI.createWidget({ + this.trigger = createWidget({ type: "bi.single_select_trigger", - height: BI.toPix(o.height, o.simple ? 1 : 2), + height: toPix(o.height, o.simple ? 1 : 2), // adapter: this.popup, allowNoSelect: o.allowNoSelect, allowEdit: o.allowEdit, valueFormatter: o.valueFormatter, - itemsCreator: function (op, callback) { - o.itemsCreator(op, function (res) { - if (op.times === 1 && BI.isNotNull(op.keywords)) { + itemsCreator: (op, callback) => { + o.itemsCreator(op, (...args) => { + if (op.times === 1 && isNotNull(op.keywords)) { // 预防trigger内部把当前的storeValue改掉 - self.trigger.setValue(self.getValue()); + this.trigger.setValue(this.getValue()); } - callback.apply(self, arguments); + callback.apply(this, ...args); }); }, text: o.text, - value: this.storeValue + value: this.storeValue, }); - this.trigger.on(BI.SingleSelectTrigger.EVENT_FOCUS, function () { - self.fireEvent(BI.SingleSelectCombo.EVENT_FOCUS); + this.trigger.on(SingleSelectTrigger.EVENT_FOCUS, () => { + this.fireEvent(SingleSelectCombo.EVENT_FOCUS); }); - this.trigger.on(BI.SingleSelectTrigger.EVENT_BLUR, function () { - self.fireEvent(BI.SingleSelectCombo.EVENT_BLUR); + this.trigger.on(SingleSelectTrigger.EVENT_BLUR, () => { + this.fireEvent(SingleSelectCombo.EVENT_BLUR); }); - this.trigger.on(BI.SingleSelectTrigger.EVENT_START, function () { - self._setStartValue(); - this.getSearcher().setValue(self.storeValue); + this.trigger.on(SingleSelectTrigger.EVENT_START, () => { + this._setStartValue(); + this.getSearcher().setValue(this.storeValue); }); - this.trigger.on(BI.SingleSelectTrigger.EVENT_STOP, function () { - self._setStartValue(); - self.fireEvent(BI.SingleSelectCombo.EVENT_STOP); + this.trigger.on(SingleSelectTrigger.EVENT_STOP, () => { + this._setStartValue(); + this.fireEvent(SingleSelectCombo.EVENT_STOP); }); - this.trigger.on(BI.SingleSelectTrigger.EVENT_SEARCHING, function () { - self._dataChange = true; - self.fireEvent(BI.SingleSelectCombo.EVENT_SEARCHING); + this.trigger.on(SingleSelectTrigger.EVENT_SEARCHING, () => { + this._dataChange = true; + this.fireEvent(SingleSelectCombo.EVENT_SEARCHING); }); - this.trigger.on(BI.SingleSelectTrigger.EVENT_CHANGE, function (value, obj) { - self.storeValue = this.getValue(); - assertShowValue(); - self._defaultState(); - self._dataChange = true; - }); - this.trigger.on(BI.SingleSelectTrigger.EVENT_COUNTER_CLICK, function () { - if (!self.combo.isViewVisible()) { - self.combo.showView(); + this.trigger.on( + SingleSelectTrigger.EVENT_CHANGE, + (value, obj) => { + this.storeValue = this.trigger.getValue(); + assertShowValue(); + this._defaultState(); + this._dataChange = true; + } + ); + this.trigger.on(SingleSelectTrigger.EVENT_COUNTER_CLICK, () => { + if (!this.combo.isViewVisible()) { + this.combo.showView(); } }); - this.combo = BI.createWidget({ - type: "bi.combo", - cls: (o.simple ? "bi-border-bottom" : "bi-border bi-border-radius"), + this.combo = createWidget({ + type: Combo.xtype, + cls: o.simple ? "bi-border-bottom" : "bi-border bi-border-radius", container: o.container, toggle: false, el: this.trigger, @@ -91,182 +106,174 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { popup: { type: "bi.single_select_popup_view", allowNoSelect: o.allowNoSelect, - ref: function () { - self.popup = this; - self.trigger.setAdapter(this); + ref: _ref => { + this.popup = _ref; + this.trigger.setAdapter(_ref); }, listeners: [{ - eventName: BI.SingleSelectPopupView.EVENT_CHANGE, - action: function () { - self._dataChange = true; - self.storeValue = this.getValue(); - self._adjust(function () { + eventName: SingleSelectPopupView.EVENT_CHANGE, + action: () => { + this._dataChange = true; + this.storeValue = this.popup.getValue(); + this._adjust(() => { assertShowValue(); - self._defaultState(); + this._defaultState(); }); - self.fireEvent(BI.SingleSelectCombo.EVENT_CLICK_ITEM); - } + this.fireEvent(SingleSelectCombo.EVENT_CLICK_ITEM); + }, }], itemsCreator: o.itemsCreator, itemWrapper: o.itemWrapper, valueFormatter: o.valueFormatter, - onLoaded: function () { - BI.nextTick(function () { - self.combo.adjustWidth(); - self.combo.adjustHeight(); - self.trigger.getSearcher().adjustView(); + onLoaded: () => { + nextTick(() => { + this.combo.adjustWidth(); + this.combo.adjustHeight(); + this.trigger.getSearcher().adjustView(); }); - } + }, }, - hideChecker: function (e) { + hideChecker(e) { return triggerBtn.element.find(e.target).length === 0; }, - value: o.value + value: o.value, }); - this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { - if (!this.isViewVisible()) { - self._dataChange = false;// 标记数据是否发生变化 + this.combo.on(Combo.EVENT_BEFORE_POPUPVIEW, () => { + if (!this.combo.isViewVisible()) { + this._dataChange = false; // 标记数据是否发生变化 } - this.setValue(self.storeValue); - BI.nextTick(function () { - self.populate(); + this.setValue(this.storeValue); + nextTick(() => { + this.populate(); }); }); // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; - this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { + this.combo.on(Combo.EVENT_AFTER_HIDEVIEW, () => { // important:关闭弹出时又可能没有退出编辑状态 - self.trigger.stopEditing(); - if (self.requesting === true) { - self.wants2Quit = true; + this.trigger.stopEditing(); + if (this.requesting === true) { + this.wants2Quit = true; } else { - self._dataChange && self.fireEvent(BI.SingleSelectCombo.EVENT_CONFIRM); + this._dataChange && + this.fireEvent(SingleSelectCombo.EVENT_CONFIRM); } }); - var triggerBtn = BI.createWidget({ - type: "bi.trigger_icon_button", + const triggerBtn = createWidget({ + type: TriggerIconButton.xtype, width: o.height, height: o.height, - cls: "single-select-trigger-icon-button" + cls: "single-select-trigger-icon-button", }); - triggerBtn.on(BI.TriggerIconButton.EVENT_CHANGE, function () { - if (self.combo.isViewVisible()) { - self.combo.hideView(); + triggerBtn.on(TriggerIconButton.EVENT_CHANGE, () => { + if (this.combo.isViewVisible()) { + this.combo.hideView(); } else { - self.combo.showView(); + this.combo.showView(); } }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, items: [{ el: this.combo, left: 0, right: 0, top: 0, - bottom: 0 - }, { + bottom: 0, + }, + { el: triggerBtn, right: 0, top: 0, - bottom: 0 - }] + bottom: 0, + } + ], }); - }, + } - _defaultState: function () { + _defaultState() { this.trigger.stopEditing(); this.combo.hideView(); - }, + } - _assertValue: function (val) { - }, + _assertValue(val) {} - _makeMap: function (values) { - return BI.makeObject(values || []); - }, + _makeMap(values) { + return makeObject(values || []); + } - _joinKeywords: function (keywords, callback) { - var self = this, o = this.options; + _joinKeywords(keywords, callback) { + const o = this.options; this._assertValue(this.storeValue); this.requesting = true; o.itemsCreator({ - type: BI.SingleSelectCombo.REQ_GET_ALL_DATA, - keywords: keywords - }, function (ob) { - var values = BI.map(ob.items, "value"); + type: SingleSelectCombo.REQ_GET_ALL_DATA, + keywords, + }, + ob => { + const values = map(ob.items, "value"); digest(values); - }); + } + ); - function digest (items) { - var selectedMap = self._makeMap(items); - BI.each(keywords, function (i, val) { - if (BI.isNotNull(selectedMap[val])) { - BI.remove(self.storeValue.value, val); + const digest = items => { + const selectedMap = this._makeMap(items); + each(keywords, (i, val) => { + if (isNotNull(selectedMap[val])) { + remove(this.storeValue.value, val); } }); - self._adjust(callback); - } - }, + this._adjust(callback); + }; + } - _adjust: function (callback) { - var self = this, o = this.options; + _adjust(callback) { + const adjust = () => { + if (this.wants2Quit === true) { + this._dataChange && + this.fireEvent(SingleSelectCombo.EVENT_CONFIRM); + this.wants2Quit = false; + } + this.requesting = false; + }; + + const o = this.options; if (!this._count) { o.itemsCreator({ - type: BI.SingleSelectCombo.REQ_GET_DATA_LENGTH - }, function (res) { - self._count = res.count; + type: SingleSelectCombo.REQ_GET_DATA_LENGTH, + }, + res => { + this._count = res.count; adjust(); callback(); - }); + } + ); } else { adjust(); callback(); - } + } - function adjust () { - if (self.wants2Quit === true) { - self._dataChange && self.fireEvent(BI.SingleSelectCombo.EVENT_CONFIRM); - self.wants2Quit = false; - } - self.requesting = false; - } - }, - - _setStartValue: function (value) { + _setStartValue(value) { this._startValue = value; this.popup.setStartValue(value); - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v; this._assertValue(this.storeValue); this.combo.setValue(this.storeValue); - }, + } - getValue: function () { + getValue() { return this.storeValue; - }, + } - populate: function () { + populate() { this._count = null; - this.combo.populate.apply(this.combo, arguments); + this.combo.populate(...arguments); } -}); - -BI.extend(BI.SingleSelectCombo, { - REQ_GET_DATA_LENGTH: 0, - REQ_GET_ALL_DATA: -1 -}); - -BI.SingleSelectCombo.EVENT_BLUR = "EVENT_BLUR"; -BI.SingleSelectCombo.EVENT_FOCUS = "EVENT_FOCUS"; -BI.SingleSelectCombo.EVENT_STOP = "EVENT_STOP"; -BI.SingleSelectCombo.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.SingleSelectCombo.EVENT_CLICK_ITEM = "EVENT_CLICK_ITEM"; -BI.SingleSelectCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; - -BI.shortcut("bi.single_select_combo", BI.SingleSelectCombo); +} diff --git a/src/widget/singleselect/singleselect.insert.combo.js b/src/widget/singleselect/singleselect.insert.combo.js index a36bf0bd6..991735404 100644 --- a/src/widget/singleselect/singleselect.insert.combo.js +++ b/src/widget/singleselect/singleselect.insert.combo.js @@ -1,45 +1,58 @@ -/** - * - * @class BI.SingleSelectInsertCombo - * @extends BI.Single - */ -BI.SingleSelectInsertCombo = BI.inherit(BI.Single, { - - _defaultConfig: function () { - return BI.extend(BI.SingleSelectInsertCombo.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, extend, emptyFn, i18nText, isKey, createWidget, toPix, isNotNull, nextTick, AbsoluteLayout, makeObject } from "@/core"; +import { Single, Combo } from "@/base"; +import { SingleSelectTrigger } from "./singleselect.trigger"; +import { SingleSelectPopupView } from "./singleselect.popup.view"; +import { TriggerIconButton } from "@/case"; + +@shortcut() +export class SingleSelectInsertCombo extends Single { + static xtype = "bi.single_select_insert_combo"; + + static REQ_GET_DATA_LENGTH = 0; + static REQ_GET_ALL_DATA = -1; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_CLICK_ITEM = "EVENT_CLICK_ITEM"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-single-select-combo", allowNoSelect: false, - itemsCreator: BI.emptyFn, - itemWrapper: BI.emptyFn, - valueFormatter: BI.emptyFn, + itemsCreator: emptyFn, + itemWrapper: emptyFn, + valueFormatter: emptyFn, height: 24, allowEdit: true, - watermark: BI.i18nText("BI-Basic_Search_And_Patch_Paste"), + watermark: i18nText("BI-Basic_Search_And_Patch_Paste"), }); - }, - - _init: function () { - var self = this, o = this.options; - BI.SingleSelectInsertCombo.superclass._init.apply(this, arguments); - var assertShowValue = function () { - BI.isKey(self._startValue) && (self.storeValue = self._startValue); - self.trigger.getSearcher().setState(self.storeValue); + } + + _init() { + const self = this, + o = this.options; + super._init(...arguments); + const assertShowValue = () => { + isKey(this._startValue) && (this.storeValue = this._startValue); + this.trigger.getSearcher().setState(this.storeValue); }; this.storeValue = o.value; // 标记正在请求数据 this.requesting = false; - this.trigger = BI.createWidget({ - type: "bi.single_select_trigger", + this.trigger = createWidget({ + type: SingleSelectTrigger.xtype, watermark: o.watermark, - height: BI.toPix(o.height, o.simple ? 1 : 2), + height: toPix(o.height, o.simple ? 1 : 2), allowNoSelect: o.allowNoSelect, allowEdit: o.allowEdit, // adapter: this.popup, valueFormatter: o.valueFormatter, - itemsCreator: function (op, callback) { + itemsCreator (op, callback) { o.itemsCreator(op, function (res) { - if (op.times === 1 && BI.isNotNull(op.keywords)) { + if (op.times === 1 && isNotNull(op.keywords)) { // 预防trigger内部把当前的storeValue改掉 self.trigger.setValue(self.getValue()); } @@ -51,198 +64,195 @@ BI.SingleSelectInsertCombo = BI.inherit(BI.Single, { searcher: { popup: { type: "bi.single_select_search_insert_pane", - } - } + }, + }, }); - this.trigger.on(BI.SingleSelectTrigger.EVENT_FOCUS, function () { - self.fireEvent(BI.SingleSelectInsertCombo.EVENT_FOCUS); + this.trigger.on(SingleSelectTrigger.EVENT_FOCUS, () => { + self.fireEvent(SingleSelectInsertCombo.EVENT_FOCUS); }); - this.trigger.on(BI.SingleSelectTrigger.EVENT_BLUR, function () { - self.fireEvent(BI.SingleSelectInsertCombo.EVENT_BLUR); + this.trigger.on(SingleSelectTrigger.EVENT_BLUR, () => { + self.fireEvent(SingleSelectInsertCombo.EVENT_BLUR); }); - this.trigger.on(BI.SingleSelectTrigger.EVENT_START, function () { + this.trigger.on(SingleSelectTrigger.EVENT_START, function () { self._setStartValue(); this.getSearcher().setValue(self.storeValue); }); - this.trigger.on(BI.SingleSelectTrigger.EVENT_STOP, function () { + this.trigger.on(SingleSelectTrigger.EVENT_STOP, () => { self._setStartValue(); - self.fireEvent(BI.SingleSelectInsertCombo.EVENT_STOP); + self.fireEvent(SingleSelectInsertCombo.EVENT_STOP); }); - this.trigger.on(BI.SingleSelectTrigger.EVENT_PAUSE, function () { + this.trigger.on(SingleSelectTrigger.EVENT_PAUSE, () => { self.storeValue = self.trigger.getSearcher().getKeyword(); assertShowValue(); self._defaultState(); }); - this.trigger.on(BI.SingleSelectTrigger.EVENT_SEARCHING, function () { + this.trigger.on(SingleSelectTrigger.EVENT_SEARCHING, () => { self._dataChange = true; - self.fireEvent(BI.SingleSelectInsertCombo.EVENT_SEARCHING); + self.fireEvent(SingleSelectInsertCombo.EVENT_SEARCHING); }); - this.trigger.on(BI.SingleSelectTrigger.EVENT_CHANGE, function (value, obj) { - self.storeValue = this.getValue(); - assertShowValue(); - self._defaultState(); - self._dataChange = true; - }); - this.trigger.on(BI.SingleSelectTrigger.EVENT_COUNTER_CLICK, function () { + this.trigger.on( + SingleSelectTrigger.EVENT_CHANGE, + function (value, obj) { + self.storeValue = this.getValue(); + assertShowValue(); + self._defaultState(); + self._dataChange = true; + } + ); + this.trigger.on(SingleSelectTrigger.EVENT_COUNTER_CLICK, () => { if (!self.combo.isViewVisible()) { self.combo.showView(); } }); - this.combo = BI.createWidget({ - type: "bi.combo", - cls: (o.simple ? "bi-border-bottom" : "bi-border bi-border-radius"), + this.combo = createWidget({ + type: Combo.xtype, + cls: o.simple ? "bi-border-bottom" : "bi-border bi-border-radius", container: o.container, toggle: false, el: this.trigger, adjustLength: 1, popup: { - type: "bi.single_select_popup_view", + type: SingleSelectPopupView.xtype, allowNoSelect: o.allowNoSelect, - ref: function () { + ref () { self.popup = this; self.trigger.setAdapter(this); }, - listeners: [{ - eventName: BI.SingleSelectPopupView.EVENT_CHANGE, - action: function () { - self._dataChange = true; - self.storeValue = this.getValue(); - self._adjust(function () { - assertShowValue(); - self._defaultState(); - }); - self.fireEvent(BI.SingleSelectInsertCombo.EVENT_CLICK_ITEM); + listeners: [ + { + eventName: SingleSelectPopupView.EVENT_CHANGE, + action () { + self._dataChange = true; + self.storeValue = this.getValue(); + self._adjust(() => { + assertShowValue(); + self._defaultState(); + }); + self.fireEvent( + SingleSelectInsertCombo.EVENT_CLICK_ITEM + ); + }, } - }], + ], itemsCreator: o.itemsCreator, itemWrapper: o.itemWrapper, valueFormatter: o.valueFormatter, - onLoaded: function () { - BI.nextTick(function () { + onLoaded () { + nextTick(() => { self.combo.adjustWidth(); self.combo.adjustHeight(); self.trigger.getSearcher().adjustView(); }); - } + }, }, - hideChecker: function (e) { + hideChecker (e) { return triggerBtn.element.find(e.target).length === 0; }, - value: o.value + value: o.value, }); - this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { + this.combo.on(Combo.EVENT_BEFORE_POPUPVIEW, function () { if (!this.isViewVisible()) { - self._dataChange = false;// 标记数据是否发生变化 + self._dataChange = false; // 标记数据是否发生变化 } this.setValue(self.storeValue); - BI.nextTick(function () { + nextTick(() => { self.populate(); }); }); // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; - this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { + this.combo.on(Combo.EVENT_AFTER_HIDEVIEW, () => { // important:关闭弹出时又可能没有退出编辑状态 self.trigger.stopEditing(); if (self.requesting === true) { self.wants2Quit = true; } else { - self._dataChange && self.fireEvent(BI.SingleSelectInsertCombo.EVENT_CONFIRM); + self._dataChange && + self.fireEvent(SingleSelectInsertCombo.EVENT_CONFIRM); } }); - var triggerBtn = BI.createWidget({ - type: "bi.trigger_icon_button", + const triggerBtn = createWidget({ + type: TriggerIconButton.xtype, width: o.height, height: o.height, - cls: "single-select-trigger-icon-button" + cls: "single-select-trigger-icon-button", }); - triggerBtn.on(BI.TriggerIconButton.EVENT_CHANGE, function () { + triggerBtn.on(TriggerIconButton.EVENT_CHANGE, () => { if (self.combo.isViewVisible()) { self.combo.hideView(); } else { self.combo.showView(); } }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.combo, - left: 0, - right: 0, - top: 0, - bottom: 0 - }, { - el: triggerBtn, - right: 0, - top: 0, - bottom: 0 - }] + items: [ + { + el: this.combo, + left: 0, + right: 0, + top: 0, + bottom: 0, + }, + { + el: triggerBtn, + right: 0, + top: 0, + bottom: 0, + } + ], }); - }, + } - _defaultState: function () { + _defaultState() { this.trigger.stopEditing(); this.combo.hideView(); - }, + } - _assertValue: function (val) { - }, + _assertValue(val) {} - _makeMap: function (values) { - return BI.makeObject(values || []); - }, + _makeMap(values) { + return makeObject(values || []); + } - _adjust: function (callback) { - var self = this, o = this.options; + _adjust(callback) { + const self = this; adjust(); callback(); - function adjust () { + function adjust() { if (self.wants2Quit === true) { - self._dataChange && self.fireEvent(BI.SingleSelectInsertCombo.EVENT_CONFIRM); + self._dataChange && + self.fireEvent(SingleSelectInsertCombo.EVENT_CONFIRM); self.wants2Quit = false; } self.requesting = false; } - }, + } - _setStartValue: function (value) { + _setStartValue(value) { this._startValue = value; this.popup.setStartValue(value); - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v; this._assertValue(this.storeValue); this.combo.setValue(this.storeValue); - }, + } - getValue: function () { + getValue() { return this.storeValue; - }, - - populate: function () { - this.combo.populate.apply(this.combo, arguments); } -}); -BI.extend(BI.SingleSelectInsertCombo, { - REQ_GET_DATA_LENGTH: 0, - REQ_GET_ALL_DATA: -1 -}); - -BI.SingleSelectInsertCombo.EVENT_FOCUS = "EVENT_FOCUS"; -BI.SingleSelectInsertCombo.EVENT_BLUR = "EVENT_BLUR"; -BI.SingleSelectInsertCombo.EVENT_STOP = "EVENT_STOP"; -BI.SingleSelectInsertCombo.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.SingleSelectInsertCombo.EVENT_CLICK_ITEM = "EVENT_CLICK_ITEM"; -BI.SingleSelectInsertCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; - -BI.shortcut("bi.single_select_insert_combo", BI.SingleSelectInsertCombo); + populate() { + this.combo.populate(...arguments); + } +} diff --git a/src/widget/singleselect/singleselect.list.js b/src/widget/singleselect/singleselect.list.js index 9842eb3ea..13c51656b 100644 --- a/src/widget/singleselect/singleselect.list.js +++ b/src/widget/singleselect/singleselect.list.js @@ -1,41 +1,41 @@ -/** - * 选择列表 - * - * Created by GUY on 2015/11/1. - * @class BI.SingleSelectList - * @extends BI.Widget - */ -BI.SingleSelectList = BI.inherit(BI.Widget, { - - _constants: { - itemHeight: 24 - }, - - _defaultConfig: function () { - return BI.extend(BI.SingleSelectList.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, Widget, extend, emptyFn, createWidget, Controller, Events, i18nText } from "@/core"; +import { ListPane, SingleSelectItem } from "@/case"; + +@shortcut() +export class SingleSelectList extends Widget { + static xtype = "bi.single_select_list"; + + _constants = { itemHeight: 24 }; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-select-list", direction: BI.Direction.Top, // toolbar的位置 logic: { - dynamic: true + dynamic: true, }, items: [], - itemsCreator: BI.emptyFn, - hasNext: BI.emptyFn, - onLoaded: BI.emptyFn, + itemsCreator: emptyFn, + hasNext: emptyFn, + onLoaded: emptyFn, el: { - type: "bi.list_pane" + type: ListPane.xtype, }, - allowNoSelect: false + allowNoSelect: false, }); - }, - _init: function () { - BI.SingleSelectList.superclass._init.apply(this, arguments); - var self = this, o = this.options; + } + + _init() { + super._init(...arguments); + const self = this, + o = this.options; - this.list = BI.createWidget(o.el, { - type: "bi.list_pane", + this.list = createWidget(o.el, { + type: ListPane.xtype, items: o.items, - itemsCreator: function (op, callback) { + itemsCreator (op, callback) { op.times === 1 && self.toolbar && self.toolbar.setVisible(false); o.itemsCreator(op, function (items) { callback.apply(self, arguments); @@ -47,117 +47,137 @@ BI.SingleSelectList = BI.inherit(BI.Widget, { }, onLoaded: o.onLoaded, hasNext: o.hasNext, - value: o.value + value: o.value, }); - this.list.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - if (type === BI.Events.CLICK) { - self.fireEvent(BI.SingleSelectList.EVENT_CHANGE, value, obj); + this.list.on(Controller.EVENT_CHANGE, function (type, value, obj) { + if (type === Events.CLICK) { + self.fireEvent(SingleSelectList.EVENT_CHANGE, value, obj); } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend({ - scrolly: true - }, o.logic, { - items: o.allowNoSelect ? BI.LogicFactory.createLogicItemsByDirection(o.direction, { - type: "bi.single_select_item", - cls: "bi-list-item-active", - height: this._constants.itemHeight, - forceNotSelected: true, - text: BI.i18nText("BI-Basic_No_Select"), - ref: function (_ref) { - self.toolbar = _ref; + createWidget( + extend( + { + element: this, }, - listeners: [{ - eventName: BI.Controller.EVENT_CHANGE, - action: function (type) { - if (type === BI.Events.CLICK) { - self.list.setValue(); - self.fireEvent(BI.SingleSelectList.EVENT_CHANGE); + BI.LogicFactory.createLogic( + BI.LogicFactory.createLogicTypeByDirection(o.direction), + extend( + { + scrolly: true, + }, + o.logic, + { + items: o.allowNoSelect + ? BI.LogicFactory.createLogicItemsByDirection( + o.direction, + { + type: SingleSelectItem.xtype, + cls: "bi-list-item-active", + height: this._constants.itemHeight, + forceNotSelected: true, + text: i18nText("BI-Basic_No_Select"), + ref (_ref) { + self.toolbar = _ref; + }, + listeners: [ + { + eventName: Controller.EVENT_CHANGE, + action (type) { + if (type === Events.CLICK) { + self.list.setValue(); + self.fireEvent(SingleSelectList.EVENT_CHANGE); + } + self.fireEvent(Controller.EVENT_CHANGE, arguments); + }, + } + ], + }, + this.list + ) + : BI.LogicFactory.createLogicItemsByDirection(o.direction, this.list), } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - } - }] - }, this.list) : BI.LogicFactory.createLogicItemsByDirection(o.direction, this.list) - })))); - - }, + ) + ) + ) + ); + } - hasPrev: function () { + hasPrev() { return this.list.hasPrev(); - }, + } - hasNext: function () { + hasNext() { return this.list.hasNext(); - }, + } - prependItems: function (items) { - this.list.prependItems.apply(this.list, arguments); - }, + prependItems(items) { + this.list.prependItems(...arguments); + } - addItems: function (items) { - this.list.addItems.apply(this.list, arguments); - }, + addItems(items) { + this.list.addItems(...arguments); + } - setValue: function (v) { + setValue(v) { this.list.setValue([v]); - }, + } - getValue: function () { + getValue() { return this.list.getValue()[0]; - }, + } - empty: function () { + empty() { this.list.empty(); - }, + } - populate: function (items) { - this.list.populate.apply(this.list, arguments); - }, + populate(items) { + this.list.populate(...arguments); + } - resetHeight: function (h) { - this.list.resetHeight ? this.list.resetHeight(h) : - this.list.element.css({"max-height": BI.pixFormat(h - (this.options.allowNoSelect ? this._constants.itemHeight : 0))}); - }, + resetHeight(h) { + this.list.resetHeight + ? this.list.resetHeight(h) + : this.list.element.css({ + "max-height": BI.pixFormat(h - (this.options.allowNoSelect ? this._constants.itemHeight : 0)), + }); + } - setNotSelectedValue: function () { - this.list.setNotSelectedValue.apply(this.list, arguments); - }, + setNotSelectedValue() { + this.list.setNotSelectedValue(...arguments); + } - getNotSelectedValue: function () { + getNotSelectedValue() { return this.list.getNotSelectedValue(); - }, + } - getAllButtons: function () { + getAllButtons() { return this.list.getAllButtons(); - }, + } - getAllLeaves: function () { + getAllLeaves() { return this.list.getAllLeaves(); - }, + } - getSelectedButtons: function () { + getSelectedButtons() { return this.list.getSelectedButtons(); - }, + } - getNotSelectedButtons: function () { + getNotSelectedButtons() { return this.list.getNotSelectedButtons(); - }, + } - getIndexByValue: function (value) { + getIndexByValue(value) { return this.list.getIndexByValue(value); - }, + } - getNodeById: function (id) { + getNodeById(id) { return this.list.getNodeById(id); - }, + } - getNodeByValue: function (value) { + getNodeByValue(value) { return this.list.getNodeByValue(value); } -}); -BI.SingleSelectList.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.single_select_list", BI.SingleSelectList); +} diff --git a/src/widget/singleselect/singleselect.loader.js b/src/widget/singleselect/singleselect.loader.js index 645bdad66..678f4a681 100644 --- a/src/widget/singleselect/singleselect.loader.js +++ b/src/widget/singleselect/singleselect.loader.js @@ -1,178 +1,187 @@ -/** - * 单选加载数据面板 - * Created by guy on 15/11/2. - * @class BI.SingleSelectLoader - * @extends Widget - */ -BI.SingleSelectLoader = BI.inherit(BI.Widget, { - - _constants: { - itemVgap: 5 - }, - - _defaultConfig: function () { - return BI.extend(BI.SingleSelectLoader.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, Widget, extend, emptyFn, createWidget, isUndefined, map, isKey, Controller, VerticalLayout, delay } from "@/core"; +import { ButtonGroup, Loader } from "@/base"; +import { SingleSelectList } from "./singleselect.list"; +import { SingleSelectItem, SingleSelectRadioItem } from "@/case"; + +@shortcut() +export class SingleSelectLoader extends Widget { + static xtype = "bi.single_select_loader"; + + _constants = { itemVgap: 5 }; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-single-select-loader", logic: { - dynamic: true + dynamic: true, }, el: { - height: 400 + height: 400, }, allowNoSelect: false, - valueFormatter: BI.emptyFn, - itemsCreator: BI.emptyFn, - itemWrapper: BI.emptyFn, - onLoaded: BI.emptyFn + valueFormatter: emptyFn, + itemsCreator: emptyFn, + itemWrapper: emptyFn, + onLoaded: emptyFn, }); - }, + } - _init: function () { - BI.SingleSelectLoader.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, opts = this.options; - var hasNext = false; + const self = this, + opts = this.options; + let hasNext = false; this.storeValue = opts.value; - this.button_group = BI.createWidget({ - type: "bi.single_select_list", + this.button_group = createWidget({ + type: SingleSelectList.xtype, allowNoSelect: opts.allowNoSelect, logic: opts.logic, - el: BI.extend({ - onLoaded: opts.onLoaded, - el: { - type: "bi.loader", - isDefaultInit: false, - logic: { - dynamic: true, - scrolly: true - }, + el: extend( + { + onLoaded: opts.onLoaded, el: { - chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, - behaviors: { - redmark: function () { - return true; - } + type: Loader.xtype, + isDefaultInit: false, + logic: { + dynamic: true, + scrolly: true, }, - layouts: [{ - type: "bi.vertical" - }] - } - } - }, opts.el), - itemsCreator: function (op, callback) { - var startValue = self._startValue; - !BI.isUndefined(self.storeValue) && (op = BI.extend(op || {}, { - selectedValues: [self.storeValue] - })); - opts.itemsCreator(op, function (ob) { + el: { + chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, + behaviors: { + redmark () { + return true; + }, + }, + layouts: [ + { + type: VerticalLayout.xtype, + } + ], + }, + }, + }, + opts.el + ), + itemsCreator (op, callback) { + const startValue = self._startValue; + !isUndefined(self.storeValue) && + (op = extend(op || {}, { + selectedValues: [self.storeValue], + })); + opts.itemsCreator(op, ob => { hasNext = ob.hasNext; - var firstItems = []; - if (op.times === 1 && !BI.isUndefined(self.storeValue)) { - var json = BI.map([self.storeValue], function (i, v) { - var txt = opts.valueFormatter(v) || v; - return opts.itemWrapper({ - text: txt, - value: v, - title: txt, - selected: true - }) || { - text: txt, - value: v, - title: txt, - selected: true - }; + let firstItems = []; + if (op.times === 1 && !isUndefined(self.storeValue)) { + const json = map([self.storeValue], (i, v) => { + const txt = opts.valueFormatter(v) || v; + + return ( + opts.itemWrapper({ + text: txt, + value: v, + title: txt, + selected: true, + }) || { + text: txt, + value: v, + title: txt, + selected: true, + } + ); }); firstItems = self._createItems(json); } callback(firstItems.concat(self._createItems(ob.items)), ob.keyword || ""); if (op.times === 1 && self.storeValue) { - BI.isKey(startValue) && (self.storeValue = startValue); + isKey(startValue) && (self.storeValue = startValue); self.setValue(self.storeValue); } - (op.times === 1) && self._scrollToTop(); + op.times === 1 && self._scrollToTop(); }); }, - hasNext: function () { + hasNext () { return hasNext; }, - value: this.storeValue + value: this.storeValue, }); - BI.createWidget({ - type: "bi.vertical", + createWidget({ + type: VerticalLayout.xtype, element: this, items: [this.button_group], - vgap: this._constants.itemVgap + vgap: this._constants.itemVgap, }); - this.button_group.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.button_group.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.button_group.on(BI.SingleSelectList.EVENT_CHANGE, function () { - self.fireEvent(BI.SingleSelectLoader.EVENT_CHANGE, arguments); + this.button_group.on(SingleSelectList.EVENT_CHANGE, function () { + self.fireEvent(SingleSelectLoader.EVENT_CHANGE, arguments); }); - }, + } - _createItems: function (items) { - var o = this.options; - return BI.map(items, function (i, item) { - return BI.extend({ - type: o.allowNoSelect ? "bi.single_select_item" : "bi.single_select_radio_item", + _createItems(items) { + const o = this.options; + + return map(items, (i, item) => extend( + { + type: o.allowNoSelect ? SingleSelectItem.xtype : SingleSelectRadioItem.xtype, logic: o.logic, cls: "bi-list-item-active", height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, selected: false, iconWrapperWidth: 26, textHgap: o.allowNoSelect ? 10 : 0, - title: item.title || item.text - }, item); - }); - }, + title: item.title || item.text, + }, + item + )); + } - _scrollToTop: function () { - var self = this; - BI.delay(function () { + _scrollToTop() { + const self = this; + delay(() => { self.button_group.element.scrollTop(0); }, 30); - }, + } - _assertValue: function (val) { - }, + _assertValue(val) {} - setStartValue: function (v) { + setStartValue(v) { this._startValue = v; - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v; this._assertValue(this.storeValue); this.button_group.setValue(this.storeValue); - }, + } - getValue: function () { + getValue() { return this.button_group.getValue(); - }, + } - getAllButtons: function () { + getAllButtons() { return this.button_group.getAllButtons(); - }, + } - empty: function () { + empty() { this.button_group.empty(); - }, + } - populate: function (items) { - this.button_group.populate.apply(this.button_group, arguments); - }, + populate(items) { + this.button_group.populate(...arguments); + } - resetHeight: function (h) { + resetHeight(h) { this.button_group.resetHeight(h - this._constants.itemVgap * 2); - }, + } - resetWidth: function (w) { + resetWidth(w) { this.button_group.resetWidth(w); } -}); - -BI.SingleSelectLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.single_select_loader", BI.SingleSelectLoader); +} diff --git a/src/widget/singleselect/singleselect.popup.view.js b/src/widget/singleselect/singleselect.popup.view.js index ffa8766bd..c03d71522 100644 --- a/src/widget/singleselect/singleselect.popup.view.js +++ b/src/widget/singleselect/singleselect.popup.view.js @@ -1,84 +1,82 @@ -/** - * 带加载的单选下拉面板 - * @class BI.SingleSelectPopupView - * @extends Widget - */ -BI.SingleSelectPopupView = BI.inherit(BI.Widget, { +import { shortcut, Widget, extend, emptyFn, createWidget } from "@/core"; +import { MultiPopupView } from "@/case"; +import { PopupView } from "@/base"; - _defaultConfig: function () { - return BI.extend(BI.SingleSelectPopupView.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class SingleSelectPopupView extends Widget { + static xtype = "bi.single_select_popup_view"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-single-select-popup-view", allowNoSelect: false, maxWidth: "auto", minWidth: 135, maxHeight: 400, - valueFormatter: BI.emptyFn, - itemsCreator: BI.emptyFn, - itemWrapper: BI.emptyFn, - onLoaded: BI.emptyFn + valueFormatter: emptyFn, + itemsCreator: emptyFn, + itemWrapper: emptyFn, + onLoaded: emptyFn, }); - }, + } - _init: function () { - BI.SingleSelectPopupView.superclass._init.apply(this, arguments); - var self = this, opts = this.options; + _init() { + super._init(...arguments); + const opts = this.options; - this.loader = BI.createWidget({ + this.loader = createWidget({ type: "bi.single_select_loader", allowNoSelect: opts.allowNoSelect, itemsCreator: opts.itemsCreator, itemWrapper: opts.itemWrapper, valueFormatter: opts.valueFormatter, onLoaded: opts.onLoaded, - value: opts.value + value: opts.value, }); - this.popupView = BI.createWidget({ - type: "bi.popup_view", + this.popupView = createWidget({ + type: PopupView.xtype, stopPropagation: false, maxWidth: opts.maxWidth, minWidth: opts.minWidth, maxHeight: opts.maxHeight, element: this, el: this.loader, - value: opts.value + value: opts.value, }); - this.popupView.on(BI.MultiPopupView.EVENT_CHANGE, function () { - self.fireEvent(BI.SingleSelectPopupView.EVENT_CHANGE); + this.popupView.on(MultiPopupView.EVENT_CHANGE, () => { + this.fireEvent(SingleSelectPopupView.EVENT_CHANGE); }); - }, + } - setStartValue: function (v) { + setStartValue(v) { this.loader.setStartValue(v); - }, + } - setValue: function (v) { + setValue(v) { this.popupView.setValue(v); - }, + } - getValue: function () { + getValue() { return this.popupView.getValue(); - }, + } - populate: function (items) { - this.popupView.populate.apply(this.popupView, arguments); - }, + populate(items) { + this.popupView.populate(...arguments); + } - resetHeight: function (h) { + resetHeight(h) { this.popupView.resetHeight(h); - }, + } - resetWidth: function (w) { + resetWidth(w) { this.popupView.resetWidth(w); - }, + } - setDirection: function (direction, position) { + setDirection(direction, position) { this.popupView.setDirection(direction, position); - }, -}); - -BI.SingleSelectPopupView.EVENT_CHANGE = "EVENT_CHANGE"; - - -BI.shortcut("bi.single_select_popup_view", BI.SingleSelectPopupView); + } +} diff --git a/src/widget/singleselect/singleselect.trigger.js b/src/widget/singleselect/singleselect.trigger.js index 35c6c0349..02021774c 100644 --- a/src/widget/singleselect/singleselect.trigger.js +++ b/src/widget/singleselect/singleselect.trigger.js @@ -1,40 +1,46 @@ -/** - * - * 单选下拉框 - * @class BI.SingleSelectTrigger - * @extends BI.Trigger - */ - -BI.SingleSelectTrigger = BI.inherit(BI.Trigger, { - - constants: { - height: 14, - rgap: 4, - lgap: 4 - }, - - _defaultConfig: function () { - return BI.extend(BI.SingleSelectTrigger.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, extend, emptyFn, createWidget, HTapeLayout, AbsoluteLayout } from "@/core"; +import { Trigger, Text } from "@/base"; +import { SingleSelectSearcher } from "./trigger"; + +@shortcut() +export class SingleSelectTrigger extends Trigger { + static xtype = "bi.single_select_trigger"; + + constants = { height: 14, rgap: 4, lgap: 4 }; + + static EVENT_TRIGGER_CLICK = "EVENT_TRIGGER_CLICK"; + static EVENT_COUNTER_CLICK = "EVENT_COUNTER_CLICK"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_START = "EVENT_START"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_BEFORE_COUNTER_POPUPVIEW = "EVENT_BEFORE_COUNTER_POPUPVIEW"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-single-select-trigger", allowNoSelect: false, - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, + itemsCreator: emptyFn, + valueFormatter: emptyFn, searcher: {}, switcher: {}, adapter: null, masker: {}, - allowEdit: true + allowEdit: true, }); - }, + } - _init: function () { - BI.SingleSelectTrigger.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, o = this.options; + const o = this.options; - this.searcher = BI.createWidget(o.searcher, { - type: "bi.single_select_searcher", + this.searcher = createWidget(o.searcher, { + type: SingleSelectSearcher.xtype, watermark: o.watermark, allowNoSelect: o.allowNoSelect, text: o.text, @@ -44,95 +50,85 @@ BI.SingleSelectTrigger = BI.inherit(BI.Trigger, { popup: {}, adapter: o.adapter, masker: o.masker, - value: o.value + value: o.value, }); - this.searcher.on(BI.SingleSelectSearcher.EVENT_START, function () { - self.fireEvent(BI.SingleSelectTrigger.EVENT_START); + this.searcher.on(SingleSelectSearcher.EVENT_START, () => { + this.fireEvent(SingleSelectTrigger.EVENT_START); }); - this.searcher.on(BI.SingleSelectSearcher.EVENT_PAUSE, function () { - self.fireEvent(BI.SingleSelectTrigger.EVENT_PAUSE); + this.searcher.on(SingleSelectSearcher.EVENT_PAUSE, () => { + this.fireEvent(SingleSelectTrigger.EVENT_PAUSE); }); - this.searcher.on(BI.SingleSelectSearcher.EVENT_SEARCHING, function () { - self.fireEvent(BI.SingleSelectTrigger.EVENT_SEARCHING, arguments); + this.searcher.on(SingleSelectSearcher.EVENT_SEARCHING, (...args) => { + this.fireEvent(SingleSelectTrigger.EVENT_SEARCHING, ...args); }); - this.searcher.on(BI.SingleSelectSearcher.EVENT_STOP, function () { - self.fireEvent(BI.SingleSelectTrigger.EVENT_STOP); + this.searcher.on(SingleSelectSearcher.EVENT_STOP, () => { + this.fireEvent(SingleSelectTrigger.EVENT_STOP); }); - this.searcher.on(BI.SingleSelectSearcher.EVENT_CHANGE, function () { - self.fireEvent(BI.SingleSelectTrigger.EVENT_CHANGE, arguments); + this.searcher.on(SingleSelectSearcher.EVENT_CHANGE, (...args) => { + this.fireEvent(SingleSelectTrigger.EVENT_CHANGE, ...args); }); - this.searcher.on(BI.SingleSelectSearcher.EVENT_FOCUS, function () { - self.fireEvent(BI.SingleSelectTrigger.EVENT_FOCUS); + this.searcher.on(SingleSelectSearcher.EVENT_FOCUS, () => { + this.fireEvent(SingleSelectTrigger.EVENT_FOCUS); }); - this.searcher.on(BI.SingleSelectSearcher.EVENT_BLUR, function () { - self.fireEvent(BI.SingleSelectTrigger.EVENT_BLUR, arguments); + this.searcher.on(SingleSelectSearcher.EVENT_BLUR, (...args) => { + this.fireEvent(SingleSelectTrigger.EVENT_BLUR, ...args); }); - var wrapper = BI.createWidget({ - type: "bi.htape", + createWidget({ + type: HTapeLayout.xtype, element: this, items: [ { el: this.searcher, - width: "fill" - }, { - el: BI.createWidget(), - width: 24 - }] + width: "fill", + }, + { + el: createWidget(), + width: 24, + } + ], }); - !o.allowEdit && BI.createWidget({ - type: "bi.absolute", - element: this, - items: [{ - el: { - type: "bi.text", - title: function () { - return self.searcher.getState(); + !o.allowEdit && + createWidget({ + type: AbsoluteLayout.xtype, + element: this, + items: [ + { + el: { + type: Text.xtype, + title: () => this.searcher.getState(), + }, + left: 0, + right: 24, + top: 0, + bottom: 0, } - }, - left: 0, - right: 24, - top: 0, - bottom: 0 - }] - }); - }, + ], + }); + } - getSearcher: function () { + getSearcher() { return this.searcher; - }, + } - stopEditing: function () { + stopEditing() { this.searcher.stopSearch(); - }, + } - setAdapter: function (adapter) { + setAdapter(adapter) { this.searcher.setAdapter(adapter); - }, + } - setValue: function (v) { + setValue(v) { this.searcher.setValue(v); - }, + } - getKey: function () { + getKey() { return this.searcher.getKey(); - }, + } - getValue: function () { + getValue() { return this.searcher.getValue(); } -}); - -BI.SingleSelectTrigger.EVENT_TRIGGER_CLICK = "EVENT_TRIGGER_CLICK"; -BI.SingleSelectTrigger.EVENT_COUNTER_CLICK = "EVENT_COUNTER_CLICK"; -BI.SingleSelectTrigger.EVENT_CHANGE = "EVENT_CHANGE"; -BI.SingleSelectTrigger.EVENT_START = "EVENT_START"; -BI.SingleSelectTrigger.EVENT_STOP = "EVENT_STOP"; -BI.SingleSelectTrigger.EVENT_PAUSE = "EVENT_PAUSE"; -BI.SingleSelectTrigger.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.SingleSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW = "EVENT_BEFORE_COUNTER_POPUPVIEW"; -BI.SingleSelectTrigger.EVENT_FOCUS = "EVENT_FOCUS"; -BI.SingleSelectTrigger.EVENT_BLUR = "EVENT_BLUR"; - -BI.shortcut("bi.single_select_trigger", BI.SingleSelectTrigger); \ No newline at end of file +} diff --git a/src/widget/singleselect/singleselectlist.insert.js b/src/widget/singleselect/singleselectlist.insert.js index cd32a22e8..e2dc37b9b 100644 --- a/src/widget/singleselect/singleselectlist.insert.js +++ b/src/widget/singleselect/singleselectlist.insert.js @@ -1,61 +1,83 @@ -/** - * @author: Teller - * @createdAt: 2018/3/28 - * @Description -*/ -BI.SingleSelectInsertList = BI.inherit(BI.Single, { - _defaultConfig: function () { - return BI.extend(BI.SingleSelectInsertList.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + emptyFn, + isKey, + createWidget, + isNotEmptyString, + i18nText, + deepClone, + VerticalFillLayout, + AbsoluteLayout, + makeObject +} from "@/core"; +import { Single, Searcher } from "@/base"; +import { SingleSelectLoader } from "./singleselect.loader"; +import { SelectPatchEditor } from "../multiselect"; +import { SearchEditor } from "../editor"; + +@shortcut() +export class SingleSelectInsertList extends Single { + static xtype = "bi.single_select_insert_list"; + + static REQ_GET_DATA_LENGTH = 0; + static REQ_GET_ALL_DATA = -1; + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-single-select-insert-list", allowNoSelect: false, - itemsCreator: BI.emptyFn, - itemWrapper: BI.emptyFn, - valueFormatter: BI.emptyFn, + itemsCreator: emptyFn, + itemWrapper: emptyFn, + valueFormatter: emptyFn, searcherHeight: 24, }); - }, - _init: function () { - BI.SingleSelectInsertList.superclass._init.apply(this, arguments); + } + + _init() { + super._init(...arguments); - var self = this, o = this.options; + const self = this, + o = this.options; this.storeValue = o.value; - var assertShowValue = function () { - BI.isKey(self._startValue) && (self.storeValue = self._startValue); - // self.trigger.setValue(self.storeValue); + const assertShowValue = () => { + isKey(this._startValue) && (this.storeValue = this._startValue); + // this.trigger.setValue(this.storeValue); }; - this.adapter = BI.createWidget({ - type: "bi.single_select_loader", + this.adapter = createWidget({ + type: SingleSelectLoader.xtype, allowNoSelect: o.allowNoSelect, cls: "popup-single-select-list bi-border-left bi-border-right bi-border-bottom", itemsCreator: o.itemsCreator, valueFormatter: o.valueFormatter, itemWrapper: o.itemWrapper, logic: { - dynamic: true + dynamic: true, }, // onLoaded: o.onLoaded, el: {}, - value: o.value + value: o.value, }); - this.adapter.on(BI.SingleSelectLoader.EVENT_CHANGE, function () { + this.adapter.on(SingleSelectLoader.EVENT_CHANGE, function () { self.storeValue = this.getValue(); assertShowValue(); - self.fireEvent(BI.SingleSelectInsertList.EVENT_CHANGE); + self.fireEvent(SingleSelectInsertList.EVENT_CHANGE); }); - this.searcherPane = BI.createWidget({ + this.searcherPane = createWidget({ type: "bi.single_select_search_insert_pane", allowNoSelect: o.allowNoSelect, cls: "bi-border-left bi-border-right bi-border-bottom", valueFormatter: o.valueFormatter, - keywordGetter: function () { + keywordGetter () { return self.trigger.getKeyword(); }, - itemsCreator: function (op, callback) { + itemsCreator (op, callback) { op.keywords = [self.trigger.getKeyword()]; - if (BI.isNotEmptyString(op.keywords[0])) { + if (isNotEmptyString(op.keywords[0])) { this.setKeyword(op.keywords[0]); o.itemsCreator(op, callback); } @@ -63,145 +85,147 @@ BI.SingleSelectInsertList = BI.inherit(BI.Single, { }); this.searcherPane.setVisible(false); - this.trigger = BI.createWidget({ - type: "bi.searcher", + this.trigger = createWidget({ + type: Searcher.xtype, el: { - type: "bi.select_patch_editor", + type: SelectPatchEditor.xtype, el: { - type: "bi.search_editor", - watermark: BI.i18nText("BI-Basic_Search_And_Patch_Paste"), + type: SearchEditor.xtype, + watermark: i18nText("BI-Basic_Search_And_Patch_Paste"), }, - ref: function (ref) { + ref (ref) { self.editor = ref; }, height: o.searcherHeight, }, isAutoSearch: false, isAutoSync: false, - onSearch: function (op, callback) { + onSearch (op, callback) { callback(); }, adapter: this.adapter, popup: this.searcherPane, masker: false, value: o.value, - listeners: [{ - eventName: BI.Searcher.EVENT_START, - action: function () { - self._showSearcherPane(); - self._setStartValue(); - this.setValue(BI.deepClone(self.storeValue)); - } - }, { - eventName: BI.Searcher.EVENT_STOP, - action: function () { - self._showAdapter(); - self._setStartValue(); - self.adapter.setValue(self.storeValue); - // 需要刷新回到初始界面,否则搜索的结果不能放在最前面 - self.adapter.populate(); - } - }, { - eventName: BI.Searcher.EVENT_PAUSE, - action: function () { - var keyword = this.getKeyword(); - self.storeValue = keyword; - self._showAdapter(); - self.adapter.setValue(self.storeValue); - self._setStartValue(keyword); - assertShowValue(); - self.adapter.populate(); - self._setStartValue(); - self.fireEvent(BI.SingleSelectInsertList.EVENT_CHANGE); - - } - }, { - eventName: BI.Searcher.EVENT_CHANGE, - action: function () { - self.storeValue = this.getValue(); - self.fireEvent(BI.SingleSelectInsertList.EVENT_CHANGE); + listeners: [ + { + eventName: Searcher.EVENT_START, + action () { + self._showSearcherPane(); + self._setStartValue(); + this.setValue(deepClone(self.storeValue)); + }, + }, + { + eventName: Searcher.EVENT_STOP, + action () { + self._showAdapter(); + self._setStartValue(); + self.adapter.setValue(self.storeValue); + // 需要刷新回到初始界面,否则搜索的结果不能放在最前面 + self.adapter.populate(); + }, + }, + { + eventName: Searcher.EVENT_PAUSE, + action () { + const keyword = this.getKeyword(); + self.storeValue = keyword; + self._showAdapter(); + self.adapter.setValue(self.storeValue); + self._setStartValue(keyword); + assertShowValue(); + self.adapter.populate(); + self._setStartValue(); + self.fireEvent(SingleSelectInsertList.EVENT_CHANGE); + }, + }, + { + eventName: Searcher.EVENT_CHANGE, + action () { + self.storeValue = this.getValue(); + self.fireEvent(SingleSelectInsertList.EVENT_CHANGE); + }, } - }] + ], }); - BI.createWidget({ - type: "bi.vertical_fill", + createWidget({ + type: VerticalFillLayout.xtype, rowSize: ["", "fill"], element: this, - items: [{ - el: this.trigger, - }, { - el: this.adapter, - }] + items: [ + { + el: this.trigger, + }, + { + el: this.adapter, + } + ], }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.searcherPane, - top: 24, - bottom: 0, - left: 0, - right: 0 - }] + items: [ + { + el: this.searcherPane, + top: 24, + bottom: 0, + left: 0, + right: 0, + } + ], }); - }, + } - _showAdapter: function () { + _showAdapter() { this.adapter.setVisible(true); this.searcherPane.setVisible(false); - }, + } - _showSearcherPane: function () { + _showSearcherPane() { this.searcherPane.setVisible(true); this.adapter.setVisible(false); - }, + } - _defaultState: function () { + _defaultState() { this.trigger.stopEditing(); - }, + } - _assertValue: function () {}, + _assertValue() {} - _makeMap: function (values) { - return BI.makeObject(values || []); - }, + _makeMap(values) { + return makeObject(values || []); + } - _setStartValue: function (value) { + _setStartValue(value) { this._startValue = value; this.adapter.setStartValue(value); - }, + } - isAllSelected: function () { + isAllSelected() { return this.adapter.isAllSelected(); - }, + } - resize: function () { + resize() { // this.trigger.getCounter().adjustView(); // this.trigger.adjustView(); - }, - setValue: function (v) { + } + + setValue(v) { this.storeValue = v; this.adapter.setValue(this.storeValue); this.trigger.setValue(this.storeValue); - }, + } - getValue: function () { - return BI.deepClone(this.storeValue); - }, + getValue() { + return deepClone(this.storeValue); + } - populate: function () { + populate() { this._count = null; this._allData = null; - this.adapter.populate.apply(this.adapter, arguments); - this.trigger.populate.apply(this.trigger, arguments); + this.adapter.populate(...arguments); + this.trigger.populate(...arguments); } -}); - -BI.extend(BI.SingleSelectInsertList, { - REQ_GET_DATA_LENGTH: 0, - REQ_GET_ALL_DATA: -1 -}); - -BI.SingleSelectInsertList.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.single_select_insert_list", BI.SingleSelectInsertList); +} diff --git a/src/widget/singleselect/trigger/editor.singleselect.js b/src/widget/singleselect/trigger/editor.singleselect.js index 881f60b45..635b7481e 100644 --- a/src/widget/singleselect/trigger/editor.singleselect.js +++ b/src/widget/singleselect/trigger/editor.singleselect.js @@ -1,25 +1,28 @@ -/** - * 单选输入框 - * Created by guy on 15/11/3. - * @class BI.SingleSelectEditor - * @extends Widget - */ -BI.SingleSelectEditor = BI.inherit(BI.Widget, { +import { shortcut, Widget, extend, i18nText, createWidget, Controller, isEmptyString, isEmptyArray, BlankSplitChar } from "@/core"; +import { StateEditor } from "@/case"; +import { SelectPatchEditor } from "../../multiselect"; - _defaultConfig: function () { - return BI.extend(BI.SingleSelectEditor.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class SingleSelectEditor extends Widget { + static xtype = "bi.single_select_editor"; + + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-single-select-editor", el: {}, - text: BI.i18nText("BI-Basic_Please_Select"), - watermark: BI.i18nText("BI-Basic_Search"), + text: i18nText("BI-Basic_Please_Select"), + watermark: i18nText("BI-Basic_Search"), }); - }, + } - _init: function () { - BI.SingleSelectEditor.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.editor = BI.createWidget(o.el, { - type: "bi.select_patch_editor", + _init() { + super._init(...arguments); + const o = this.options; + this.editor = createWidget(o.el, { + type: SelectPatchEditor.xtype, element: this, height: o.height, watermark: o.watermark, @@ -29,64 +32,59 @@ BI.SingleSelectEditor = BI.inherit(BI.Widget, { text: o.text, }); - this.editor.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.editor.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.editor.on(BI.StateEditor.EVENT_FOCUS, function () { - self.fireEvent(BI.SingleSelectEditor.EVENT_FOCUS); + this.editor.on(StateEditor.EVENT_FOCUS, () => { + this.fireEvent(SingleSelectEditor.EVENT_FOCUS); }); - this.editor.on(BI.StateEditor.EVENT_BLUR, function () { - self.fireEvent(BI.SingleSelectEditor.EVENT_BLUR); + this.editor.on(StateEditor.EVENT_BLUR, () => { + this.fireEvent(SingleSelectEditor.EVENT_BLUR); }); - }, + } - focus: function () { + focus() { this.editor.focus(); - }, + } - blur: function () { + blur() { this.editor.blur(); - }, + } - setState: function (state) { + setState(state) { this.editor.setState(state); - }, + } - setValue: function (v) { + setValue(v) { this.editor.setValue(v); - }, + } - getValue: function () { + getValue() { return this.editor.getValue(); - }, + } - getKeywords: function () { - var val = this.editor.getValue(); - var keywords = val.split(/\u200b\s\u200b/); - if (BI.isEmptyString(keywords[keywords.length - 1])) { + getKeywords() { + const val = this.editor.getValue(); + let keywords = val.split(/\u200b\s\u200b/); + if (isEmptyString(keywords[keywords.length - 1])) { keywords = keywords.slice(0, keywords.length - 1); } if (/\u200b\s\u200b$/.test(val)) { - return keywords.concat([BI.BlankSplitChar]); + return keywords.concat([BlankSplitChar]); } return keywords; - }, + } - getKeyword: function () { - var val = this.editor.getValue(); - var keywords = val.split(/\u200b\s\u200b/); - if (BI.isEmptyString(keywords[keywords.length - 1])) { + getKeyword() { + const val = this.editor.getValue(); + let keywords = val.split(/\u200b\s\u200b/); + if (isEmptyString(keywords[keywords.length - 1])) { keywords = keywords.slice(0, keywords.length - 1); } - return BI.isEmptyArray(keywords) ? "" : keywords[keywords.length - 1]; - }, - - populate: function (items) { + return isEmptyArray(keywords) ? "" : keywords[keywords.length - 1]; } -}); -BI.SingleSelectEditor.EVENT_FOCUS = "EVENT_FOCUS"; -BI.SingleSelectEditor.EVENT_BLUR = "EVENT_BLUR"; -BI.shortcut("bi.single_select_editor", BI.SingleSelectEditor); \ No newline at end of file + populate(items) {} +} diff --git a/src/widget/singleselect/trigger/index.js b/src/widget/singleselect/trigger/index.js new file mode 100644 index 000000000..e5abc14b0 --- /dev/null +++ b/src/widget/singleselect/trigger/index.js @@ -0,0 +1,2 @@ +export { SingleSelectEditor } from "./editor.singleselect"; +export { SingleSelectSearcher } from "./searcher.singleselect"; diff --git a/src/widget/singleselect/trigger/searcher.singleselect.js b/src/widget/singleselect/trigger/searcher.singleselect.js index 800fd7560..82b581942 100644 --- a/src/widget/singleselect/trigger/searcher.singleselect.js +++ b/src/widget/singleselect/trigger/searcher.singleselect.js @@ -1,162 +1,161 @@ -/** - * searcher - * Created by guy on 15/11/3. - * @class BI.SingleSelectSearcher - * @extends Widget - */ -BI.SingleSelectSearcher = BI.inherit(BI.Widget, { - - _defaultConfig: function () { - return BI.extend(BI.SingleSelectSearcher.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, Widget, extend, emptyFn, createWidget, isNotNull, isUndefined, Selection } from "@/core"; +import { SingleSelectEditor } from "./editor.singleselect"; +import { Searcher } from "@/base"; + +@shortcut() +export class SingleSelectSearcher extends Widget { + static xtype = "bi.single_select_searcher"; + + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_START = "EVENT_START"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-single-select-searcher", - itemsCreator: BI.emptyFn, + itemsCreator: emptyFn, el: {}, popup: {}, - valueFormatter: BI.emptyFn, + valueFormatter: emptyFn, adapter: null, masker: {}, - allowNoSelect: false + allowNoSelect: false, }); - }, + } - _init: function () { - BI.SingleSelectSearcher.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.editor = BI.createWidget(o.el, { + _init() { + super._init(...arguments); + const self = this, + o = this.options; + this.editor = createWidget(o.el, { type: "bi.single_select_editor", height: o.height, watermark: o.watermark, text: o.text, listeners: [{ - eventName: BI.SingleSelectEditor.EVENT_FOCUS, - action: function () { - self.fireEvent(BI.SingleSelectSearcher.EVENT_FOCUS); - } - }, { - eventName: BI.SingleSelectEditor.EVENT_BLUR, - action: function () { - self.fireEvent(BI.SingleSelectSearcher.EVENT_BLUR); - } - }] + eventName: SingleSelectEditor.EVENT_FOCUS, + action: () => { + this.fireEvent(SingleSelectSearcher.EVENT_FOCUS); + }, + }, + { + eventName: SingleSelectEditor.EVENT_BLUR, + action: () => { + this.fireEvent(SingleSelectSearcher.EVENT_BLUR); + }, + } + ], }); - this.searcher = BI.createWidget({ - type: "bi.searcher", + this.searcher = createWidget({ + type: Searcher.xtype, element: this, height: o.height, isAutoSearch: false, isAutoSync: false, - onSearch: function (op, callback) { + onSearch(op, callback) { callback(); }, el: this.editor, - popup: BI.extend({ + popup: extend({ type: "bi.single_select_search_pane", allowNoSelect: o.allowNoSelect, valueFormatter: o.valueFormatter, - keywordGetter: function () { - return self.editor.getValue(); - }, - itemsCreator: function (op, callback) { - var keyword = self.editor.getValue(); + keywordGetter: () => this.editor.getValue(), + itemsCreator(op, callback) { + const keyword = self.editor.getValue(); op.keywords = [keyword]; this.setKeyword(keyword); o.itemsCreator(op, callback); }, - value: o.value - }, o.popup), + value: o.value, + }, + o.popup + ), adapter: o.adapter, - masker: o.masker + masker: o.masker, }); - this.searcher.on(BI.Searcher.EVENT_START, function () { - self.fireEvent(BI.SingleSelectSearcher.EVENT_START); + this.searcher.on(Searcher.EVENT_START, () => { + this.fireEvent(SingleSelectSearcher.EVENT_START); }); - this.searcher.on(BI.Searcher.EVENT_PAUSE, function () { - if (this.hasMatched()) { - - } - self.fireEvent(BI.SingleSelectSearcher.EVENT_PAUSE); + this.searcher.on(Searcher.EVENT_PAUSE, () => { + this.fireEvent(SingleSelectSearcher.EVENT_PAUSE); }); - this.searcher.on(BI.Searcher.EVENT_STOP, function () { - self.fireEvent(BI.SingleSelectSearcher.EVENT_STOP); + this.searcher.on(Searcher.EVENT_STOP, () => { + this.fireEvent(SingleSelectSearcher.EVENT_STOP); }); - this.searcher.on(BI.Searcher.EVENT_CHANGE, function () { - self.fireEvent(BI.SingleSelectSearcher.EVENT_CHANGE, arguments); + this.searcher.on(Searcher.EVENT_CHANGE, (...args) => { + this.fireEvent(SingleSelectSearcher.EVENT_CHANGE, ...args); }); - this.searcher.on(BI.Searcher.EVENT_SEARCHING, function () { - var keywords = this.getKeywords(); - self.fireEvent(BI.SingleSelectSearcher.EVENT_SEARCHING, keywords); + this.searcher.on(Searcher.EVENT_SEARCHING, () => { + const keywords = this.searcher.getKeywords(); + this.fireEvent(SingleSelectSearcher.EVENT_SEARCHING, keywords); }); - if(BI.isNotNull(o.value)){ + if (isNotNull(o.value)) { this.setState(o.value); } - }, + } - adjustView: function () { + adjustView() { this.searcher.adjustView(); - }, + } - isSearching: function () { + isSearching() { return this.searcher.isSearching(); - }, + } - stopSearch: function () { + stopSearch() { this.searcher.stopSearch(); - }, + } - getKeyword: function () { + getKeyword() { return this.editor.getKeyword(); - }, + } - hasMatched: function () { + hasMatched() { return this.searcher.hasMatched(); - }, + } - hasChecked: function () { + hasChecked() { return this.searcher.getView() && this.searcher.getView().hasChecked(); - }, + } - setAdapter: function (adapter) { + setAdapter(adapter) { this.searcher.setAdapter(adapter); - }, + } - setState: function (v) { - var o = this.options; - if (BI.isUndefined(v)) { - this.editor.setState(BI.Selection.None); + setState(v) { + const o = this.options; + if (isUndefined(v)) { + this.editor.setState(Selection.None); } else { v = v ?? ""; - this.editor.setState(o.valueFormatter(v + "") || (v + "")); + this.editor.setState(o.valueFormatter(`${v}`) || `${v}`); } - }, + } - setValue: function (ob) { + setValue(ob) { this.setState(ob); this.searcher.setValue(ob); - }, + } - getKey: function () { + getKey() { return this.editor.getValue(); - }, + } - getValue: function () { + getValue() { return this.searcher.getValue(); - }, + } - populate: function (items) { - this.searcher.populate.apply(this.searcher, arguments); + populate(items) { + this.searcher.populate(...arguments); } -}); - -BI.SingleSelectSearcher.EVENT_FOCUS = "EVENT_FOCUS"; -BI.SingleSelectSearcher.EVENT_BLUR = "EVENT_BLUR"; -BI.SingleSelectSearcher.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.SingleSelectSearcher.EVENT_CHANGE = "EVENT_CHANGE"; -BI.SingleSelectSearcher.EVENT_START = "EVENT_START"; -BI.SingleSelectSearcher.EVENT_STOP = "EVENT_STOP"; -BI.SingleSelectSearcher.EVENT_PAUSE = "EVENT_PAUSE"; -BI.SingleSelectSearcher.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.shortcut("bi.single_select_searcher", BI.SingleSelectSearcher); +} From 99931d45d85f7e8630d99335a17e410b4aece147 Mon Sep 17 00:00:00 2001 From: zsmj Date: Fri, 13 Jan 2023 10:40:34 +0800 Subject: [PATCH 108/300] update --- src/base/single/bar/bar.loading.js | 2 +- src/case/button/treeitem/treeitem.js | 2 +- src/widget/singletree/singletree.popup.js | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/base/single/bar/bar.loading.js b/src/base/single/bar/bar.loading.js index a4ab85a46..4331844e0 100644 --- a/src/base/single/bar/bar.loading.js +++ b/src/base/single/bar/bar.loading.js @@ -2,7 +2,7 @@ import { shortcut, emptyFn } from "@/core"; import { Single } from "../0.single"; @shortcut() -class LoadingBar extends Single { +export class LoadingBar extends Single { static xtype = "bi.loading_bar"; _defaultConfig() { diff --git a/src/case/button/treeitem/treeitem.js b/src/case/button/treeitem/treeitem.js index 189573c33..8a9bcae3b 100644 --- a/src/case/button/treeitem/treeitem.js +++ b/src/case/button/treeitem/treeitem.js @@ -51,7 +51,7 @@ export class BasicTreeItem extends NodeButton { width: 24, } : null; - const indent = layer === 0 ? null : { + const indent = { el: { type: Layout.xtype, height, diff --git a/src/widget/singletree/singletree.popup.js b/src/widget/singletree/singletree.popup.js index 7e4b6899d..87438cb2f 100644 --- a/src/widget/singletree/singletree.popup.js +++ b/src/widget/singletree/singletree.popup.js @@ -31,7 +31,7 @@ export class SingleTreePopup extends Pane { o = this.options; this.tree = createWidget({ - type: "bi.level_tree", + type: LevelTree.xtype, expander: { isDefaultInit: true, }, From 7c29cb461cbc41f471a2c67fc055cdac566632a1 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Fri, 13 Jan 2023 11:01:17 +0800 Subject: [PATCH 109/300] =?UTF-8?q?KERNEL-14101=20refactor:=20multilayerdo?= =?UTF-8?q?wnlist=E3=80=81multilayersingletree?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .eslintrc | 3 +- src/widget/index.js | 6 + .../multilayerdownlist/combo.downlist.js | 94 ++--- src/widget/multilayerdownlist/index.js | 2 + .../multilayerdownlist/popup.downlist.js | 380 ++++++++++-------- src/widget/multilayersingletree/index.js | 7 + .../multilayersingletree.combo.js | 356 ++++++++-------- ...multilayersingletree.insert.search.pane.js | 140 ++++--- .../multilayersingletree.leveltree.js | 228 ++++++----- .../multilayersingletree.popup.js | 79 ++-- .../multilayersingletree.trigger.js | 311 ++++++++------ src/widget/multilayersingletree/node/index.js | 4 + .../node/node.first.plus.js | 117 +++--- .../node/node.last.plus.js | 117 +++--- .../node/node.mid.plus.js | 117 +++--- .../multilayersingletree/node/node.plus.js | 130 +++--- .../multilayersingletree/treeitem/index.js | 3 + .../treeitem/item.first.treeleaf.js | 93 ++--- .../treeitem/item.last.treeleaf.js | 93 ++--- .../treeitem/item.mid.treeleaf.js | 93 ++--- 20 files changed, 1315 insertions(+), 1058 deletions(-) create mode 100644 src/widget/multilayerdownlist/index.js create mode 100644 src/widget/multilayersingletree/index.js create mode 100644 src/widget/multilayersingletree/node/index.js create mode 100644 src/widget/multilayersingletree/treeitem/index.js diff --git a/.eslintrc b/.eslintrc index a2c317000..427a7b32b 100644 --- a/.eslintrc +++ b/.eslintrc @@ -36,7 +36,8 @@ "no-var": 2, "prefer-const": 2, "indent": ["error", 4], - "no-use-before-define": 0 + "no-use-before-define": 0, + "eqeqeq": 0 } }, { "files": ["webpack/*.js", "./*.js", "lib/**/*.js", "lib/*.js", "./bin/*.js", "./bin/**/*.js"], diff --git a/src/widget/index.js b/src/widget/index.js index 84e8b6e4f..e7d24f493 100644 --- a/src/widget/index.js +++ b/src/widget/index.js @@ -20,6 +20,8 @@ import { NumberInterval } from "./numberinterval/numberinterval"; import * as multiselect from "./multiselect"; import * as multiselectlist from "./multiselectlist"; import * as singleselect from "./singleselect"; +import * as multilayerdownlist from "./multilayerdownlist"; +import * as multilayersingletree from "./multilayersingletree"; Object.assign(BI, { Collapse, @@ -44,6 +46,8 @@ Object.assign(BI, { ...multiselect, ...multiselectlist, ...singleselect, + ...multilayerdownlist, + ...multilayersingletree, }); export * from "./date/calendar"; @@ -60,6 +64,8 @@ export * from "./downlist"; export * from "./singleslider"; export * from "./intervalslider"; export * from "./singleselect"; +export * from "./multilayerdownlist"; +export * from "./multilayersingletree"; export { Collapse, diff --git a/src/widget/multilayerdownlist/combo.downlist.js b/src/widget/multilayerdownlist/combo.downlist.js index e2e333827..281e2fc0f 100644 --- a/src/widget/multilayerdownlist/combo.downlist.js +++ b/src/widget/multilayerdownlist/combo.downlist.js @@ -1,9 +1,18 @@ -/** - * Created by roy on 15/8/14. - */ -BI.MultiLayerDownListCombo = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.MultiLayerDownListCombo.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, Widget, extend, createWidget } from "@/core"; +import { MultiLayerDownListPopup } from "./popup.downlist"; +import { Combo } from "@/base"; +import { IconTrigger } from "@/case"; + +@shortcut() +export class MultiLayerDownListCombo extends Widget { + static xtype = "bi.multi_layer_down_list_combo"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_SON_VALUE_CHANGE = "EVENT_SON_VALUE_CHANGE"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multilayer-down-list-combo", height: 24, items: [], @@ -12,79 +21,74 @@ BI.MultiLayerDownListCombo = BI.inherit(BI.Widget, { trigger: "click", container: null, stopPropagation: false, - el: {} + el: {}, }); - }, + } - _init: function () { - BI.MultiLayerDownListCombo.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.popupview = BI.createWidget({ + _init() { + super._init(...arguments); + const o = this.options; + this.popupview = createWidget({ type: "bi.multi_layer_down_list_popup", items: o.items, chooseType: o.chooseType, - value: o.value + value: o.value, }); - this.popupview.on(BI.MultiLayerDownListPopup.EVENT_CHANGE, function (value) { - self.fireEvent(BI.MultiLayerDownListCombo.EVENT_CHANGE, value); - self.downlistcombo.hideView(); + this.popupview.on(MultiLayerDownListPopup.EVENT_CHANGE, value => { + this.fireEvent(MultiLayerDownListCombo.EVENT_CHANGE, value); + this.downlistcombo.hideView(); }); - this.popupview.on(BI.MultiLayerDownListPopup.EVENT_SON_VALUE_CHANGE, function (value, fatherValue) { - self.fireEvent(BI.MultiLayerDownListCombo.EVENT_SON_VALUE_CHANGE, value, fatherValue); - self.downlistcombo.hideView(); + this.popupview.on(MultiLayerDownListPopup.EVENT_SON_VALUE_CHANGE, (value, fatherValue) => { + this.fireEvent(MultiLayerDownListCombo.EVENT_SON_VALUE_CHANGE, value, fatherValue); + this.downlistcombo.hideView(); }); - - this.downlistcombo = BI.createWidget({ + this.downlistcombo = createWidget({ element: this, - type: "bi.combo", + type: Combo.xtype, trigger: o.trigger, isNeedAdjustWidth: false, container: o.container, adjustLength: o.adjustLength, direction: o.direction, stopPropagation: o.stopPropagation, - el: BI.createWidget(o.el, { - type: "bi.icon_trigger", + el: createWidget(o.el, { + type: IconTrigger.xtype, extraCls: o.iconCls ? o.iconCls : "pull-down-font", width: o.width, - height: o.height + height: o.height, }), popup: { el: this.popupview, stopPropagation: o.stopPropagation, - maxHeight: 1000 - } + maxHeight: 1000, + }, }); - this.downlistcombo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { - self.fireEvent(BI.MultiLayerDownListCombo.EVENT_BEFORE_POPUPVIEW); + this.downlistcombo.on(Combo.EVENT_BEFORE_POPUPVIEW, () => { + this.fireEvent(MultiLayerDownListCombo.EVENT_BEFORE_POPUPVIEW); }); - }, + } - hideView: function () { + hideView() { this.downlistcombo.hideView(); - }, + } - showView: function (e) { + showView(e) { this.downlistcombo.showView(e); - }, + } - populate: function (items) { + populate(items) { this.popupview.populate(items); - }, + } - setValue: function (v) { + setValue(v) { this.popupview.setValue(v); - }, - getValue: function () { - return this.popupview.getValue(); } -}); -BI.MultiLayerDownListCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiLayerDownListCombo.EVENT_SON_VALUE_CHANGE = "EVENT_SON_VALUE_CHANGE"; -BI.MultiLayerDownListCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut("bi.multi_layer_down_list_combo", BI.MultiLayerDownListCombo); \ No newline at end of file + getValue() { + return this.popupview.getValue(); + } +} diff --git a/src/widget/multilayerdownlist/index.js b/src/widget/multilayerdownlist/index.js new file mode 100644 index 000000000..e73818700 --- /dev/null +++ b/src/widget/multilayerdownlist/index.js @@ -0,0 +1,2 @@ +export { MultiLayerDownListCombo } from "./combo.downlist"; +export { MultiLayerDownListPopup } from "./popup.downlist"; diff --git a/src/widget/multilayerdownlist/popup.downlist.js b/src/widget/multilayerdownlist/popup.downlist.js index 8fbacd285..b8abc5cf9 100644 --- a/src/widget/multilayerdownlist/popup.downlist.js +++ b/src/widget/multilayerdownlist/popup.downlist.js @@ -1,136 +1,173 @@ -/** - * Created by roy on 15/9/8. - * 处理popup中的item分组样式 - * 一个item分组中的成员大于一时,该分组设置为单选,并且默认状态第一个成员设置为已选择项 - */ -BI.MultiLayerDownListPopup = BI.inherit(BI.Pane, { - constants: { +import { + shortcut, + extend, + Selection, + createWidget, + createItems, + isNotNull, + contains, + each, + VerticalLayout, + isNotEmptyArray, + isEmpty, + Layout, + deepClone, + isArray, + isNotEmptyString, + some, + concat, + BlankSplitChar +} from "@/core"; +import { Pane, ButtonTree, ComboGroup } from "@/base"; +import { DownListGroup, DownListGroupItem, DownListItem } from "../downlist"; + +@shortcut() +export class MultiLayerDownListPopup extends Pane { + static xtype = "bi.multi_layer_down_list_popup"; + + constants = { nextIcon: "pull-right-e-font", height: 25, iconHeight: 12, iconWidth: 12, hgap: 0, vgap: 0, - border: 1 - }, - _defaultConfig: function () { - var conf = BI.MultiLayerDownListPopup.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { + border: 1, + }; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_SON_VALUE_CHANGE = "EVENT_SON_VALUE_CHANGE"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { baseCls: "bi-down-list-popup", items: [], - chooseType: BI.Selection.Multi + chooseType: Selection.Multi, }); - }, - _init: function () { - BI.MultiLayerDownListPopup.superclass._init.apply(this, arguments); + } + + _init() { + super._init(...arguments); this.singleValues = []; this.childValueMap = {}; this.fatherValueMap = {}; this.items = []; - var self = this, o = this.options, children = this._createPopupItems(o.items); - this.popup = BI.createWidget({ - type: "bi.button_tree", - items: BI.createItems(children, - {}, { - adjustLength: -2 + const self = this, + o = this.options, + children = this._createPopupItems(o.items); + this.popup = createWidget({ + type: ButtonTree.xtype, + items: createItems( + children, + {}, + { + adjustLength: -2, } ), - layouts: [{ - type: "bi.vertical", - hgap: this.constants.hgap, - vgap: this.constants.vgap - }], + layouts: [ + { + type: VerticalLayout.xtype, + hgap: this.constants.hgap, + vgap: this.constants.vgap, + } + ], value: this._digest(o.value), - chooseType: o.chooseType + chooseType: o.chooseType, }); - this.popup.on(BI.ButtonTree.EVENT_CHANGE, function (value, object) { - var changedValue = value; - if (BI.isNotNull(self.childValueMap[value])) { + this.popup.on(ButtonTree.EVENT_CHANGE, (value, object) => { + let changedValue = value; + if (isNotNull(self.childValueMap[value])) { changedValue = self.childValueMap[value]; - var fatherValue = self.fatherValueMap[value]; - var fatherArrayValue = (fatherValue + "").split(BI.BlankSplitChar); - self.fireEvent(BI.MultiLayerDownListPopup.EVENT_SON_VALUE_CHANGE, changedValue, fatherArrayValue.length > 1 ? fatherArrayValue : fatherValue); + const fatherValue = self.fatherValueMap[value]; + const fatherArrayValue = (`${fatherValue}`).split(BlankSplitChar); + self.fireEvent( + MultiLayerDownListPopup.EVENT_SON_VALUE_CHANGE, + changedValue, + fatherArrayValue.length > 1 ? fatherArrayValue : fatherValue + ); } else { - self.fireEvent(BI.MultiLayerDownListPopup.EVENT_CHANGE, changedValue, object); + self.fireEvent(MultiLayerDownListPopup.EVENT_CHANGE, changedValue, object); } - - if (!BI.contains(self.singleValues, changedValue)) { - var item = self.getValue(); - var result = []; - BI.each(item, function (i, valueObject) { + if (!contains(self.singleValues, changedValue)) { + const item = self.getValue(); + const result = []; + each(item, (i, valueObject) => { if (valueObject.value != changedValue) { result.push(valueObject); } }); self.setValue(result); } - }); - BI.createWidget({ - type: "bi.vertical", + createWidget({ + type: VerticalLayout.xtype, element: this, items: [this.popup], - vgap: 5 + vgap: 5, }); + } - }, - _createPopupItems: function (items) { - var self = this, result = []; - BI.each(items, function (i, it) { - var item_done = { - type: "bi.down_list_group", - items: [] + _createPopupItems(items) { + const self = this, + result = []; + each(items, (i, it) => { + const item_done = { + type: DownListGroup.xtype, + items: [], }; - var storeItem = []; + const storeItem = []; - BI.each(it, function (i, sourceItem) { - var item = BI.extend({}, sourceItem); - if (BI.isNotEmptyArray(sourceItem.children) && !BI.isEmpty(sourceItem.el)) { - item.type = "bi.combo_group"; + each(it, (i, sourceItem) => { + const item = extend({}, sourceItem); + if (isNotEmptyArray(sourceItem.children) && !isEmpty(sourceItem.el)) { + item.type = ComboGroup.xtype; item.cls = "down-list-group"; item.trigger = "hover"; item.isNeedAdjustWidth = false; item.el = sourceItem.el; item.el.title = sourceItem.el.title || sourceItem.el.text; - item.el.type = "bi.down_list_group_item"; + item.el.type = DownListGroupItem.xtype; item.el.logic = { - dynamic: true + dynamic: true, }; item.el.height = sourceItem.el.height || BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT; item.el.iconCls2 = self.constants.nextIcon; item.popup = { lgap: 1, el: { - type: "bi.button_tree", + type: ButtonTree.xtype, chooseType: 0, - layouts: [{ - type: "bi.vertical" - }] - + layouts: [ + { + type: VerticalLayout.xtype, + } + ], }, innerVgap: 5, maxHeight: 378, }; self._createChildren(item, sourceItem); } else { - item.type = sourceItem.type || "bi.down_list_item"; + item.type = sourceItem.type || DownListItem.xtype; item.title = sourceItem.title || sourceItem.text; item.textRgap = 10; item.isNeedAdjustWidth = false; item.logic = { - dynamic: true + dynamic: true, }; } - var el_done = {}; + const el_done = {}; el_done.el = item; item_done.items.push(el_done); storeItem.push(item); }); if (self._isGroup(item_done.items)) { - BI.each(item_done.items, function (i, item) { + each(item_done.items, (i, item) => { self.singleValues.push(item.el.value); }); } @@ -138,16 +175,17 @@ BI.MultiLayerDownListPopup = BI.inherit(BI.Pane, { result.push(item_done); self.items.push(storeItem); if (self._needSpliter(i, items.length)) { - var spliter_container = BI.createWidget({ - type: "bi.vertical", - items: [{ - el: { - type: "bi.layout", - cls: "bi-down-list-spliter bi-border-top cursor-pointer", - height: 0 + const spliter_container = createWidget({ + type: VerticalLayout.xtype, + items: [ + { + el: { + type: Layout.xtype, + cls: "bi-down-list-spliter bi-border-top cursor-pointer", + height: 0, + }, } - - }], + ], cls: "bi-down-list-spliter-container cursor-pointer", vgap: 5, hgap: 12, @@ -155,178 +193,180 @@ BI.MultiLayerDownListPopup = BI.inherit(BI.Pane, { result.push(spliter_container); } }); + return result; - }, + } - _createChildren: function (targetItem, sourceItem) { - var self = this; + _createChildren(targetItem, sourceItem) { + const self = this; this._formatEL(targetItem).el.childValues = []; targetItem.items = targetItem.children = []; - BI.each(sourceItem.children, function (i, child) { - var item = child.el ? BI.extend({}, child.el, {children: child.children}) : BI.extend({}, child); - var fatherValue = BI.deepClone(self._formatEL(targetItem).el.value); - var childValue = BI.deepClone(item.value); + each(sourceItem.children, (i, child) => { + const item = child.el ? extend({}, child.el, { children: child.children }) : extend({}, child); + const fatherValue = deepClone(self._formatEL(targetItem).el.value); + const childValue = deepClone(item.value); self.singleValues.push(item.value); - item.type = item.type || "bi.down_list_item"; + item.type = item.type || DownListItem.xtype; item.extraCls = " child-down-list-item"; item.title = item.title || item.text; item.textRgap = 10; item.isNeedAdjustWidth = false; item.logic = { - dynamic: true + dynamic: true, }; item.father = fatherValue; self.fatherValueMap[self._createChildValue(fatherValue, childValue)] = fatherValue; self.childValueMap[self._createChildValue(fatherValue, childValue)] = childValue; item.value = self._createChildValue(fatherValue, childValue); self._formatEL(targetItem).el.childValues.push(item.value); - if (BI.isNotEmptyArray(child.children)) { - item.type = "bi.down_list_group_item"; + if (isNotEmptyArray(child.children)) { + item.type = DownListGroupItem.xtype; item.iconCls2 = self.constants.nextIcon; item.height = child.height || BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT; self._createChildren(item, child); } targetItem.items.push(item); }); - }, + } - _formatEL: function(obj) { + _formatEL(obj) { if (obj && obj.el) { return obj; } return { - el: obj + el: obj, }; - }, + } - _isGroup: function (i) { + _isGroup(i) { return i.length > 1; - }, + } - _needSpliter: function (i, itemLength) { + _needSpliter(i, itemLength) { return i < itemLength - 1; - }, + } - _createChildValue: function (fatherValue, childValue) { - var fValue = fatherValue; - if(BI.isArray(fatherValue)) { - fValue = fatherValue.join(BI.BlankSplitChar); + _createChildValue(fatherValue, childValue) { + let fValue = fatherValue; + if (isArray(fatherValue)) { + fValue = fatherValue.join(BlankSplitChar); } - return fValue + BI.BlankSplitChar + childValue; - }, + + return fValue + BlankSplitChar + childValue; + } - _digest: function (valueItem) { - var self = this; - var valueArray = []; - BI.each(valueItem, function (i, item) { - var value; - if (BI.isNotNull(item.childValue)) { - value = self._createChildValue(item.value, item.childValue); - } else { - value = item.value; - } - valueArray.push(value); + _digest(valueItem) { + const self = this; + const valueArray = []; + each(valueItem, (i, item) => { + let value; + if (isNotNull(item.childValue)) { + value = self._createChildValue(item.value, item.childValue); + } else { + value = item.value; } - ); + valueArray.push(value); + }); + return valueArray; - }, + } - _checkValues: function (values) { - var self = this, o = this.options; - var value = []; - BI.each(this.items, function (idx, itemGroup) { - BI.each(itemGroup, function (id, item) { - if(BI.isNotNull(item.children)) { - var childValues = getChildrenValue(item); - var v = joinValue(childValues, values[idx]); - if(BI.isNotEmptyString(v)) { + _checkValues(values) { + const value = []; + each(this.items, (idx, itemGroup) => { + each(itemGroup, (id, item) => { + if (isNotNull(item.children)) { + const childValues = getChildrenValue(item); + const v = joinValue(childValues, values[idx]); + if (isNotEmptyString(v)) { value.push(v); } - }else{ - if(item.value === values[idx][0]) { + } else { + if (item.value === values[idx][0]) { value.push(values[idx][0]); } } }); }); + return value; - function joinValue (sources, targets) { - var value = ""; - BI.some(sources, function (idx, s) { - return BI.some(targets, function (id, t) { - if(s === t) { - value = s; - return true; - } - }); - }); + function joinValue(sources, targets) { + let value = ""; + some(sources, (idx, s) => some(targets, (id, t) => { + if (s === t) { + value = s; + + return true; + } + })); + return value; } - function getChildrenValue (item) { - var children = []; - if(BI.isNotNull(item.children)) { - BI.each(item.children, function (idx, child) { - children = BI.concat(children, getChildrenValue(child)); + function getChildrenValue(item) { + let children = []; + if (isNotNull(item.children)) { + each(item.children, (idx, child) => { + children = concat(children, getChildrenValue(child)); }); } else { children.push(item.value); } + return children; } - }, + } - populate: function (items) { - BI.MultiLayerDownListPopup.superclass.populate.apply(this, arguments); - var self = this; + populate(items) { + super.populate(...arguments); + const self = this; self.childValueMap = {}; self.fatherValueMap = {}; self.singleValues = []; this.items = []; - var children = self._createPopupItems(items); - var popupItem = BI.createItems(children, - {}, { - adjustLength: -2 + const children = self._createPopupItems(items); + const popupItem = createItems( + children, + {}, + { + adjustLength: -2, } ); self.popup.populate(popupItem); - }, + } - setValue: function (valueItem) { + setValue(valueItem) { this.popup.setValue(this._digest(valueItem)); - }, + } - _getValue: function () { - var v = []; - BI.each(this.popup.getAllButtons(), function (i, item) { + _getValue() { + const v = []; + each(this.popup.getAllButtons(), (i, item) => { i % 2 === 0 && v.push(item.getValue()); }); + return v; - }, + } - getValue: function () { - var self = this, result = []; - var values = this._checkValues(this._getValue()); - BI.each(values, function (i, value) { - var valueItem = {}; - if (BI.isNotNull(self.childValueMap[value])) { - var fartherValue = self.fatherValueMap[value]; + getValue() { + const self = this, + result = []; + const values = this._checkValues(this._getValue()); + each(values, (i, value) => { + const valueItem = {}; + if (isNotNull(self.childValueMap[value])) { + const fartherValue = self.fatherValueMap[value]; valueItem.childValue = self.childValueMap[value]; - var fatherArrayValue = (fartherValue + "").split(BI.BlankSplitChar); + const fatherArrayValue = (`${fartherValue}`).split(BlankSplitChar); valueItem.value = fatherArrayValue.length > 1 ? fatherArrayValue : fartherValue; } else { valueItem.value = value; } result.push(valueItem); }); + return result; } - - -}); - -BI.MultiLayerDownListPopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiLayerDownListPopup.EVENT_SON_VALUE_CHANGE = "EVENT_SON_VALUE_CHANGE"; -BI.shortcut("bi.multi_layer_down_list_popup", BI.MultiLayerDownListPopup); +} diff --git a/src/widget/multilayersingletree/index.js b/src/widget/multilayersingletree/index.js new file mode 100644 index 000000000..4098e74cc --- /dev/null +++ b/src/widget/multilayersingletree/index.js @@ -0,0 +1,7 @@ +export { MultiLayerSingleTreeCombo } from "./multilayersingletree.combo"; +export { MultiLayerSingleTreeInsertSearchPane } from "./multilayersingletree.insert.search.pane"; +export { MultiLayerSingleLevelTree } from "./multilayersingletree.leveltree"; +export { MultiLayerSingleTreePopup } from "./multilayersingletree.popup"; +export { MultiLayerSingleTreeTrigger } from "./multilayersingletree.trigger"; +export * from "./node"; +export * from "./treeitem"; diff --git a/src/widget/multilayersingletree/multilayersingletree.combo.js b/src/widget/multilayersingletree/multilayersingletree.combo.js index 4e26c1a0c..793d2364d 100644 --- a/src/widget/multilayersingletree/multilayersingletree.combo.js +++ b/src/widget/multilayersingletree/multilayersingletree.combo.js @@ -1,81 +1,105 @@ -/** - * 多层级下拉单选树 - * Created by GUY on 2016/1/26. - * - * @class BI.MultiLayerSingleTreeCombo - * @extends BI.Widget - */ -BI.MultiLayerSingleTreeCombo = BI.inherit(BI.Widget, { +import { shortcut, Widget, extend, emptyFn, isKey, toPix, AbsoluteLayout, nextTick, isArray } from "@/core"; +import { SingleTreeTrigger } from "../singletree/singletree.trigger"; +import { MultiLayerSingleTreePopup } from "./multilayersingletree.popup"; +import { Combo } from "@/base"; +import { MultiLayerSingleTreeTrigger } from "./multilayersingletree.trigger"; +import { TriggerIconButton } from "@/case"; - _defaultConfig: function () { - return BI.extend(BI.MultiLayerSingleTreeCombo.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class MultiLayerSingleTreeCombo extends Widget { + static xtype = "bi.multilayer_single_tree_combo"; + + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multilayer-single-tree-combo", isDefaultInit: false, height: 24, text: "", defaultText: "", - itemsCreator: BI.emptyFn, + itemsCreator: emptyFn, items: [], allowEdit: false, allowSearchValue: false, allowInsertValue: false, isNeedAdjustWidth: true, }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const self = this, + o = this.options; - var cls = (o.simple ? "bi-border-bottom bi-focus-shadow " : "bi-border bi-border-radius bi-focus-shadow ") + (BI.isKey(o.status) ? ("status-" + o.status) : ""); + const cls = + (o.simple ? "bi-border-bottom bi-focus-shadow " : "bi-border bi-border-radius bi-focus-shadow ") + + (isKey(o.status) ? `status-${o.status}` : ""); - var baseConfig = this._getBaseConfig(); + const baseConfig = this._getBaseConfig(); if (o.allowEdit) { return { - type: "bi.absolute", - width: BI.toPix(o.width, 2), - height: BI.toPix(o.height, 2), + type: AbsoluteLayout.xtype, + width: toPix(o.width, 2), + height: toPix(o.height, 2), cls, items: [ { - el: BI.extend(baseConfig, this._getSearchConfig()), - top: 0, bottom: 0, right: 0, left: 0 - }, { - el: self._getTriggerIconButton(), - top: 0, bottom: 0, right: 0, + el: extend(baseConfig, this._getSearchConfig()), + top: 0, + bottom: 0, + right: 0, + left: 0, }, - ] + { + el: self._getTriggerIconButton(), + top: 0, + bottom: 0, + right: 0, + } + ], }; } - return BI.extend(baseConfig, { - width: BI.toPix(o.width, 2), - height: BI.toPix(o.height, 2), - el: { - type: "bi.single_tree_trigger", - ref: function (_ref) { - self.textTrigger = _ref; + return extend( + baseConfig, + { + width: toPix(o.width, 2), + height: toPix(o.height, 2), + el: { + type: SingleTreeTrigger.xtype, + ref (_ref) { + self.textTrigger = _ref; + }, + text: o.text, + defaultText: o.defaultText, + height: toPix(o.height, 2), + items: o.items, + value: o.value, + tipType: o.tipType, + warningTitle: o.warningTitle, + valueFormatter: o.valueFormatter, }, - text: o.text, - defaultText: o.defaultText, - height: BI.toPix(o.height, 2), - items: o.items, - value: o.value, - tipType: o.tipType, - warningTitle: o.warningTitle, - valueFormatter: o.valueFormatter, }, - }, { cls }); - }, + { cls } + ); + } - _getBaseConfig: function () { - var self = this, o = this.options; + _getBaseConfig() { + const self = this, + o = this.options; + return { - type: "bi.combo", + type: Combo.xtype, container: o.container, destroyWhenHide: o.destroyWhenHide, adjustLength: 2, - ref: function (_ref) { + ref (_ref) { self.combo = _ref; }, popup: { @@ -84,41 +108,47 @@ BI.MultiLayerSingleTreeCombo = BI.inherit(BI.Widget, { isDefaultInit: o.isDefaultInit, itemsCreator: o.itemsCreator, items: o.items, - ref: function (_ref) { + ref (_ref) { self.trigger && self.trigger.getSearcher().setAdapter(_ref); }, - listeners: [{ - eventName: BI.MultiLayerSingleTreePopup.EVENT_CHANGE, - action: function () { - self.setValue(this.getValue()); - self.combo.hideView(); - self.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_CHANGE); + listeners: [ + { + eventName: MultiLayerSingleTreePopup.EVENT_CHANGE, + action () { + self.setValue(this.getValue()); + self.combo.hideView(); + self.fireEvent(MultiLayerSingleTreeCombo.EVENT_CHANGE); + }, } - }], - onLoaded: function () { - BI.nextTick(function () { + ], + onLoaded () { + nextTick(() => { self.combo.adjustWidth(); self.combo.adjustHeight(); }); - } + }, }, value: o.value, maxHeight: 400, maxWidth: o.isNeedAdjustWidth ? "auto" : 500, - minHeight: 240 + minHeight: 240, }, isNeedAdjustWidth: o.isNeedAdjustWidth, - listeners: [{ - eventName: BI.Combo.EVENT_BEFORE_POPUPVIEW, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_BEFORE_POPUPVIEW); + listeners: [ + { + eventName: Combo.EVENT_BEFORE_POPUPVIEW, + action () { + self.fireEvent(MultiLayerSingleTreeCombo.EVENT_BEFORE_POPUPVIEW); + }, } - }] + ], }; - }, + } - _getSearchConfig: function () { - var self = this, o = this.options; + _getSearchConfig() { + const self = this, + o = this.options; + return { el: { type: "bi.multilayer_single_tree_trigger", @@ -126,154 +156,162 @@ BI.MultiLayerSingleTreeCombo = BI.inherit(BI.Widget, { allowInsertValue: o.allowInsertValue, allowSearchValue: o.allowSearchValue, cls: "multilayer-single-tree-trigger", - ref: function (_ref) { + ref (_ref) { self.trigger = _ref; }, watermark: o.watermark, items: o.items, itemsCreator: o.itemsCreator, valueFormatter: o.valueFormatter, - height: BI.toPix(o.height, 2), + height: toPix(o.height, 2), text: o.text, defaultText: o.defaultText, value: o.value, tipType: o.tipType, warningTitle: o.warningTitle, title: o.title, - listeners: [{ - eventName: BI.MultiLayerSingleTreeTrigger.EVENT_CHANGE, - action: function () { - self.setValue(this.getValue()); - self.combo.hideView(); - self.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_CHANGE); - } - }, { - eventName: BI.MultiLayerSingleTreeTrigger.EVENT_FOCUS, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_FOCUS); - } - }, { - eventName: BI.MultiLayerSingleTreeTrigger.EVENT_BLUR, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_BLUR); - } - }, { - eventName: BI.MultiLayerSingleTreeTrigger.EVENT_SEARCHING, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_SEARCHING); - } - }, { - eventName: BI.MultiLayerSingleTreeTrigger.EVENT_STOP, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_STOP); - } - }, { - eventName: BI.MultiLayerSingleTreeTrigger.EVENT_ADD_ITEM, - action: function () { - var value = self.trigger.getSearcher().getKeyword(); - self.combo.setValue([value]); - self.combo.hideView(); - self.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_CHANGE); + listeners: [ + { + eventName: MultiLayerSingleTreeTrigger.EVENT_CHANGE, + action () { + self.setValue(this.getValue()); + self.combo.hideView(); + self.fireEvent(MultiLayerSingleTreeCombo.EVENT_CHANGE); + }, + }, + { + eventName: MultiLayerSingleTreeTrigger.EVENT_FOCUS, + action () { + self.fireEvent(MultiLayerSingleTreeCombo.EVENT_FOCUS); + }, + }, + { + eventName: MultiLayerSingleTreeTrigger.EVENT_BLUR, + action () { + self.fireEvent(MultiLayerSingleTreeCombo.EVENT_BLUR); + }, + }, + { + eventName: MultiLayerSingleTreeTrigger.EVENT_SEARCHING, + action () { + self.fireEvent(MultiLayerSingleTreeCombo.EVENT_SEARCHING); + }, + }, + { + eventName: MultiLayerSingleTreeTrigger.EVENT_STOP, + action () { + self.fireEvent(MultiLayerSingleTreeCombo.EVENT_STOP); + }, + }, + { + eventName: MultiLayerSingleTreeTrigger.EVENT_ADD_ITEM, + action () { + const value = self.trigger.getSearcher().getKeyword(); + self.combo.setValue([value]); + self.combo.hideView(); + self.fireEvent(MultiLayerSingleTreeCombo.EVENT_CHANGE); + }, } - }] + ], }, toggle: !o.allowEdit, - hideChecker: function (e) { + hideChecker (e) { // 新增传配置container后对应hideChecker的修改 // IE11下,popover(position: fixed)下放置下拉控件(position: fixed), 滚动的时候会异常卡顿 // 通过container参数将popup放置于popover之外解决此问题, 其他下拉控件由于元素少或者有分页,所以 // 卡顿不明显, 先在此做尝试, 并在FineUI特殊处理待解决文档中标记跟踪 - return (o.container && self.trigger.getSearcher().isSearching() && self.trigger.getSearcher().getView().element.find(e.target).length > 0) ? false : self.triggerBtn?.element.find(e.target).length === 0; + return o.container && + self.trigger.getSearcher().isSearching() && + self.trigger.getSearcher().getView().element.find(e.target).length > 0 + ? false + : self.triggerBtn?.element.find(e.target).length === 0; }, - listeners: [{ - eventName: BI.Combo.EVENT_AFTER_HIDEVIEW, - action: function () { - self.trigger.stopEditing(); - } - }, { - eventName: BI.Combo.EVENT_BEFORE_POPUPVIEW, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_BEFORE_POPUPVIEW); + listeners: [ + { + eventName: Combo.EVENT_AFTER_HIDEVIEW, + action () { + self.trigger.stopEditing(); + }, + }, + { + eventName: Combo.EVENT_BEFORE_POPUPVIEW, + action () { + self.fireEvent(MultiLayerSingleTreeCombo.EVENT_BEFORE_POPUPVIEW); + }, } - }] + ], }; - }, + } - _getTriggerIconButton: function () { - var self = this, o = this.options; + _getTriggerIconButton() { + const self = this, + o = this.options; + return { - type: "bi.trigger_icon_button", + type: TriggerIconButton.xtype, cls: "bi-trigger trigger-icon-button", - ref: function (_ref) { + ref (_ref) { self.triggerBtn = _ref; }, - width: BI.toPix(o.height, 2), - height: BI.toPix(o.height, 2), + width: toPix(o.height, 2), + height: toPix(o.height, 2), listeners: [ { - eventName: BI.TriggerIconButton.EVENT_CHANGE, - action: function () { + eventName: TriggerIconButton.EVENT_CHANGE, + action () { if (self.combo.isViewVisible()) { self.combo.hideView(); } else { self.combo.showView(); } - } + }, } - ] + ], }; - }, + } - getSearcher: function () { + getSearcher() { return this.trigger ? this.trigger.getSearcher() : this.textTrigger.getTextor(); - }, + } - setValue: function (v) { - v = BI.isArray(v) ? v : [v]; + setValue(v) { + v = isArray(v) ? v : [v]; this.combo.setValue(v); - }, + } - getValue: function () { + getValue() { return this.combo.getValue(); - }, + } - setStatus: function (status) { - if (BI.isKey(this.options.status)) { - this.element.removeClass("status-" + this.options.status); + setStatus(status) { + if (isKey(this.options.status)) { + this.element.removeClass(`status-${this.options.status}`); } - this.element.addClass("status-" + status); + this.element.addClass(`status-${status}`); this.options.status = status; - }, + } - setTipType: function (v) { + setTipType(v) { this.trigger ? this.trigger.setTipType(v) : this.textTrigger.setTipType(v); - }, + } - populate: function (items) { + populate(items) { this.combo.populate(items); - }, + } - focus: function () { + focus() { this.trigger.focus(); - }, + } - blur: function () { + blur() { this.trigger.blur(); - }, + } - showView: function () { + showView() { this.combo.showView(); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.trigger.setWaterMark(v); } -}); - -BI.MultiLayerSingleTreeCombo.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.MultiLayerSingleTreeCombo.EVENT_BLUR = "EVENT_BLUR"; -BI.MultiLayerSingleTreeCombo.EVENT_FOCUS = "EVENT_FOCUS"; -BI.MultiLayerSingleTreeCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiLayerSingleTreeCombo.EVENT_STOP = "EVENT_STOP"; -BI.MultiLayerSingleTreeCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut("bi.multilayer_single_tree_combo", BI.MultiLayerSingleTreeCombo); +} diff --git a/src/widget/multilayersingletree/multilayersingletree.insert.search.pane.js b/src/widget/multilayersingletree/multilayersingletree.insert.search.pane.js index 8e7fa06de..78b07ea5b 100644 --- a/src/widget/multilayersingletree/multilayersingletree.insert.search.pane.js +++ b/src/widget/multilayersingletree/multilayersingletree.insert.search.pane.js @@ -1,92 +1,110 @@ -/** - * Created by GUY on 2016/1/26. - * - * @class BI.MultiLayerSingleTreeInsertSearchPane - * @extends BI.Pane - */ +import { + shortcut, + Widget, + i18nText, + emptyFn, + createWidget, + Controller, + VerticalLayout, + isEmptyArray, + isArray +} from "@/core"; +import { MultiLayerSelectLevelTree } from "../multilayerselecttree/multilayerselecttree.leveltree"; +import { TextButton } from "@/base"; -BI.MultiLayerSingleTreeInsertSearchPane = BI.inherit(BI.Widget, { +@shortcut() +export class MultiLayerSingleTreeInsertSearchPane extends Widget { + static xtype = "bi.multilayer_single_tree_insert_search_pane"; - props: function() { + static EVENT_ADD_ITEM = "EVENT_ADD_ITEM"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + props() { return { baseCls: "bi-multilayer-single-tree-popup", - tipText: BI.i18nText("BI-No_Selected_Item"), + tipText: i18nText("BI-No_Selected_Item"), isDefaultInit: false, - itemsCreator: BI.emptyFn, + itemsCreator: emptyFn, items: [], - value: "" + value: "", }; - }, + } - render: function() { - var self = this, o = this.options; - this.tree = BI.createWidget({ + render() { + const o = this.options; + this.tree = createWidget({ type: "bi.multilayer_single_level_tree", isDefaultInit: o.isDefaultInit, items: o.items, - itemsCreator: o.itemsCreator === BI.emptyFn ? BI.emptyFn : function (op, callback) { - o.itemsCreator(op, function (res) { - callback(res); - self.setKeyword(o.keywordGetter()); - }); - }, + itemsCreator: + o.itemsCreator === emptyFn + ? emptyFn + : (op, callback) => { + o.itemsCreator(op, res => { + callback(res); + this.setKeyword(o.keywordGetter()); + }); + }, keywordGetter: o.keywordGetter, value: o.value, scrollable: null, - listeners: [{ - eventName: BI.Controller.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - } - }, { - eventName: BI.MultiLayerSelectLevelTree.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeInsertSearchPane.EVENT_CHANGE); + listeners: [ + { + eventName: Controller.EVENT_CHANGE, + action: (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); + }, + }, + { + eventName: MultiLayerSelectLevelTree.EVENT_CHANGE, + action: () => { + this.fireEvent(MultiLayerSingleTreeInsertSearchPane.EVENT_CHANGE); + }, } - }] + ], }); + return { - type: "bi.vertical", + type: VerticalLayout.xtype, scrolly: false, scrollable: true, vgap: 5, - items: [{ - type: "bi.text_button", - invisible: true, - text: BI.i18nText("BI-Basic_Click_To_Add_Text", ""), - height: 24, - cls: "bi-high-light", - hgap: 5, - ref: function (_ref) { - self.addNotMatchTip = _ref; + items: [ + { + type: TextButton.xtype, + invisible: true, + text: i18nText("BI-Basic_Click_To_Add_Text", ""), + height: 24, + cls: "bi-high-light", + hgap: 5, + ref: _ref => { + this.addNotMatchTip = _ref; + }, + handler: () => { + this.fireEvent(MultiLayerSingleTreeInsertSearchPane.EVENT_ADD_ITEM, o.keywordGetter()); + }, }, - handler: function () { - self.fireEvent(BI.MultiLayerSingleTreeInsertSearchPane.EVENT_ADD_ITEM, o.keywordGetter()); - } - }, this.tree] + this.tree + ], }; - }, + } - setKeyword: function (keyword) { - var showTip = BI.isEmptyArray(this.tree.getAllLeaves()); + setKeyword(keyword) { + const showTip = isEmptyArray(this.tree.getAllLeaves()); this.addNotMatchTip.setVisible(showTip); - showTip && this.addNotMatchTip.setText(BI.i18nText("BI-Basic_Click_To_Add_Text", keyword)); - }, + showTip && this.addNotMatchTip.setText(i18nText("BI-Basic_Click_To_Add_Text", keyword)); + } - getValue: function () { + getValue() { return this.tree.getValue(); - }, + } - setValue: function (v) { - v = BI.isArray(v) ? v : [v]; + setValue(v) { + v = isArray(v) ? v : [v]; this.tree.setValue(v); - }, + } - populate: function (items) { + populate(items) { this.tree.populate(items); } -}); - -BI.MultiLayerSingleTreeInsertSearchPane.EVENT_ADD_ITEM = "EVENT_ADD_ITEM"; -BI.MultiLayerSingleTreeInsertSearchPane.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multilayer_single_tree_insert_search_pane", BI.MultiLayerSingleTreeInsertSearchPane); \ No newline at end of file +} diff --git a/src/widget/multilayersingletree/multilayersingletree.leveltree.js b/src/widget/multilayersingletree/multilayersingletree.leveltree.js index 8e14aa749..3e6a05433 100644 --- a/src/widget/multilayersingletree/multilayersingletree.leveltree.js +++ b/src/widget/multilayersingletree/multilayersingletree.leveltree.js @@ -1,170 +1,202 @@ -/** - * guy - * 二级树 - * @class BI.MultiLayerSingleLevelTree - * @extends BI.Single - */ -BI.MultiLayerSingleLevelTree = BI.inherit(BI.Pane, { - _defaultConfig: function () { - return BI.extend(BI.MultiLayerSingleLevelTree.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + emptyFn, + Selection, + each, + isKey, + UUID, + isNotEmptyArray, + defaults, + createWidget, + Tree, + nextTick, + Controller, + Events, + VerticalLayout, + AdaptiveLayout, + isNull, + isArray +} from "@/core"; +import { Pane, CustomTree, Loader, ButtonTree } from "@/base"; +import { BasicTreeNode, BasicTreeItem, TreeExpander } from "@/case"; + +@shortcut() +export class MultiLayerSingleLevelTree extends Pane { + static xtype = "bi.multilayer_single_level_tree"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multilayer-single-level-tree", isDefaultInit: false, items: [], - itemsCreator: BI.emptyFn, - keywordGetter: BI.emptyFn, - chooseType: BI.Selection.Single, - scrollable: true + itemsCreator: emptyFn, + keywordGetter: emptyFn, + chooseType: Selection.Single, + scrollable: true, }); - }, + } - _init: function () { - var o = this.options; - BI.MultiLayerSingleLevelTree.superclass._init.apply(this, arguments); + _init() { + const o = this.options; + super._init(...arguments); this.storeValue = o.value; this.initTree(this.options.items); this.check(); - }, + } - _formatItems: function (nodes, layer, pNode) { - var self = this, o = this.options; - var keyword = o.keywordGetter(); - BI.each(nodes, function (i, node) { - var extend = { + _formatItems(nodes, layer, pNode) { + const self = this, + o = this.options; + const keyword = o.keywordGetter(); + each(nodes, (i, node) => { + const extend = { isFirstNode: i === 0, isLastNode: i === nodes.length - 1, - height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, }; node.layer = layer; - if (!BI.isKey(node.id)) { - node.id = BI.UUID(); + if (!isKey(node.id)) { + node.id = UUID(); } node.keyword = node.keyword || keyword; extend.pNode = pNode; - if (node.isParent === true || node.parent === true || BI.isNotEmptyArray(node.children)) { - extend.type = "bi.tree_node"; + if (node.isParent === true || node.parent === true || isNotEmptyArray(node.children)) { + extend.type = BasicTreeNode.xtype; extend.selectable = false; - BI.defaults(node, extend); + defaults(node, extend); self._formatItems(node.children, layer + 1, node); } else { - extend.type = "bi.tree_item"; - BI.defaults(node, extend); + extend.type = BasicTreeItem.xtype; + defaults(node, extend); } }); + return nodes; - }, + } - _assertId: function (sNodes) { - BI.each(sNodes, function (i, node) { - node.id = node.id || BI.UUID(); + _assertId(sNodes) { + each(sNodes, (i, node) => { + node.id = node.id || UUID(); }); - }, + } - // 构造树结构, - initTree: function (nodes) { - var self = this, o = this.options; - var hasNext = false; + initTree(nodes) { + const self = this, + o = this.options; + let hasNext = false; this.empty(); this._assertId(nodes); - this.tree = BI.createWidget({ - type: "bi.custom_tree", + this.tree = createWidget({ + type: CustomTree.xtype, cls: "tree-view display-table", expander: { - type: "bi.tree_expander", + type: TreeExpander.xtype, isDefaultInit: o.isDefaultInit, el: {}, popup: { - type: "bi.custom_tree" - } + type: CustomTree.xtype, + }, }, - items: this._formatItems(BI.Tree.transformToTreeFormat(nodes), 0), + items: this._formatItems(Tree.transformToTreeFormat(nodes), 0), value: o.value, - itemsCreator: function (op, callback) { - (op.times === 1 && !op.node) && BI.nextTick(function () { - self.loading(); - }); - o.itemsCreator(op, function (ob) { + itemsCreator (op, callback) { + op.times === 1 && + !op.node && + nextTick(() => { + self.loading(); + }); + o.itemsCreator(op, ob => { hasNext = ob.hasNext; - (op.times === 1 && !op.node) && self._populate(ob.items); - callback(self._formatItems(BI.Tree.transformToTreeFormat(ob.items), op.node ? op.node.layer + 1 : 0, op.node)); + op.times === 1 && !op.node && self._populate(ob.items); + callback( + self._formatItems( + Tree.transformToTreeFormat(ob.items), + op.node ? op.node.layer + 1 : 0, + op.node + ) + ); self.setValue(self.storeValue); - (op.times === 1 && !op.node) && BI.nextTick(function () { - self.loaded(); - }); + op.times === 1 && + !op.node && + nextTick(() => { + self.loaded(); + }); }); }, el: { - type: "bi.loader", - isDefaultInit: o.itemsCreator !== BI.emptyFn, + type: Loader.xtype, + isDefaultInit: o.itemsCreator !== emptyFn, el: { - type: "bi.button_tree", - chooseType: o.chooseType === BI.Selection.None ? BI.Selection.None : BI.Selection.Default, // 不使用buttontree内部getValue逻辑 + type: ButtonTree.xtype, + chooseType: o.chooseType === Selection.None ? Selection.None : Selection.Default, // 不使用buttontree内部getValue逻辑 behaviors: o.behaviors, - layouts: [{ - type: "bi.vertical" - }] + layouts: [ + { + type: VerticalLayout.xtype, + } + ], }, - hasNext: function () { + hasNext () { return hasNext; - } - } + }, + }, }); - this.tree.on(BI.Controller.EVENT_CHANGE, function (type, v) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if (type === BI.Events.CLICK) { + this.tree.on(Controller.EVENT_CHANGE, function (type, v) { + self.fireEvent(Controller.EVENT_CHANGE, arguments); + if (type === Events.CLICK) { self.setValue(v); - self.fireEvent(BI.MultiLayerSingleLevelTree.EVENT_CHANGE, v); + self.fireEvent(MultiLayerSingleLevelTree.EVENT_CHANGE, v); } }); - BI.createWidget({ - type: "bi.adaptive", + createWidget({ + type: AdaptiveLayout.xtype, element: this, scrollable: o.scrollable, - items: [this.tree] + items: [this.tree], }); - }, + } - _populate: function () { - BI.MultiLayerSelectLevelTree.superclass.populate.apply(this, arguments); - }, + _populate() { + super.populate(...arguments); + } - populate: function (nodes) { + populate(nodes) { this._populate(nodes); - BI.isNull(nodes) ? this.tree.populate() : this.tree.populate(this._formatItems(BI.Tree.transformToTreeFormat(nodes), 0)); - }, + isNull(nodes) + ? this.tree.populate() + : this.tree.populate(this._formatItems(Tree.transformToTreeFormat(nodes), 0)); + } - setValue: function (v) { + setValue(v) { // getValue依赖于storeValue, 那么不选的时候就不要更新storeValue了 - if (this.options.chooseType === BI.Selection.None) { - } else { + if (this.options.chooseType !== Selection.None) { this.storeValue = v; this.tree.setValue(v); } - }, + } - getValue: function () { - return BI.isArray(this.storeValue) ? - this.storeValue : BI.isNull(this.storeValue) ? - [] : [this.storeValue]; - }, + getValue() { + return isArray(this.storeValue) ? this.storeValue : isNull(this.storeValue) ? [] : [this.storeValue]; + } - getAllLeaves: function () { + getAllLeaves() { return this.tree.getAllLeaves(); - }, + } - getNodeById: function (id) { + getNodeById(id) { return this.tree.getNodeById(id); - }, + } - getNodeByValue: function (id) { + getNodeByValue(id) { return this.tree.getNodeByValue(id); } -}); -BI.MultiLayerSingleLevelTree.EVENT_CHANGE = "EVENT_CHANGE"; - -BI.shortcut("bi.multilayer_single_level_tree", BI.MultiLayerSingleLevelTree); +} diff --git a/src/widget/multilayersingletree/multilayersingletree.popup.js b/src/widget/multilayersingletree/multilayersingletree.popup.js index 630c38237..244786fba 100644 --- a/src/widget/multilayersingletree/multilayersingletree.popup.js +++ b/src/widget/multilayersingletree/multilayersingletree.popup.js @@ -1,76 +1,73 @@ -/** - * Created by GUY on 2016/1/26. - * - * @class BI.MultiLayerSingleTreePopup - * @extends BI.Pane - */ +import { shortcut, Widget, extend, i18nText, emptyFn, createWidget, Controller, VerticalLayout, isArray, pixFormat } from "@/core"; +import { MultiLayerSingleLevelTree } from "./multilayersingletree.leveltree"; -BI.MultiLayerSingleTreePopup = BI.inherit(BI.Widget, { +@shortcut() +export class MultiLayerSingleTreePopup extends Widget { + static xtype = "bi.multilayer_single_tree_popup"; - _defaultConfig: function () { - return BI.extend(BI.MultiLayerSingleTreePopup.superclass._defaultConfig.apply(this, arguments), { + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multilayer-singletree-popup", - tipText: BI.i18nText("BI-No_Selected_Item"), + tipText: i18nText("BI-No_Selected_Item"), isDefaultInit: false, - itemsCreator: BI.emptyFn, + itemsCreator: emptyFn, items: [], - onLoaded: BI.emptyFn, - minHeight: 240 + onLoaded: emptyFn, + minHeight: 240, }); - }, + } - _init: function () { - BI.MultiLayerSingleTreePopup.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, o = this.options; + const o = this.options; - this.tree = BI.createWidget({ - type: "bi.multilayer_single_level_tree", + this.tree = createWidget({ + type: MultiLayerSingleLevelTree.xtype, isDefaultInit: o.isDefaultInit, items: o.items, itemsCreator: o.itemsCreator, keywordGetter: o.keywordGetter, value: o.value, scrollable: null, - onLoaded: function () { - self.tree.check(); + onLoaded: () => { + this.tree.check(); o.onLoaded(); - } + }, }); - BI.createWidget({ - type: "bi.vertical", + createWidget({ + type: VerticalLayout.xtype, scrolly: false, scrollable: true, element: this, vgap: 5, - items: [this.tree] + items: [this.tree], }); - this.tree.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.tree.on(Controller.EVENT_CHANGE, (...args) => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - this.tree.on(BI.MultiLayerSingleLevelTree.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiLayerSingleTreePopup.EVENT_CHANGE); + this.tree.on(MultiLayerSingleLevelTree.EVENT_CHANGE, () => { + this.fireEvent(MultiLayerSingleTreePopup.EVENT_CHANGE); }); - this.tree.css("min-height", BI.pixFormat(o.minHeight - 10)); - }, + this.tree.css("min-height", pixFormat(o.minHeight - 10)); + } - getValue: function () { + getValue() { return this.tree.getValue(); - }, + } - setValue: function (v) { - v = BI.isArray(v) ? v : [v]; + setValue(v) { + v = isArray(v) ? v : [v]; this.tree.setValue(v); - }, + } - populate: function (items) { + populate(items) { this.tree.populate(items); } -}); - -BI.MultiLayerSingleTreePopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multilayer_single_tree_popup", BI.MultiLayerSingleTreePopup); \ No newline at end of file +} diff --git a/src/widget/multilayersingletree/multilayersingletree.trigger.js b/src/widget/multilayersingletree/multilayersingletree.trigger.js index 617c70d7b..d6c5ebda2 100644 --- a/src/widget/multilayersingletree/multilayersingletree.trigger.js +++ b/src/widget/multilayersingletree/multilayersingletree.trigger.js @@ -1,237 +1,282 @@ -/** - * Created by Windy on 2018/2/2. - */ -BI.MultiLayerSingleTreeTrigger = BI.inherit(BI.Trigger, { +import { + shortcut, + emptyFn, + i18nText, + bind, + isNotNull, + isKey, + HorizontalFillLayout, + Tree, + deepClone, + Func, + concat, + isNotEmptyArray, + each, + uniqBy, + map, + isFunction, + find +} from "@/core"; +import { Trigger, Searcher } from "@/base"; +import { StateEditor, DefaultTextEditor } from "@/case"; +import { MultiLayerSingleTreeInsertSearchPane } from "./multilayersingletree.insert.search.pane"; +import { MultiLayerSingleTreePopup } from "./multilayersingletree.popup"; - props: function () { +@shortcut() +export class MultiLayerSingleTreeTrigger extends Trigger { + static xtype = "bi.multilayer_single_tree_trigger"; + + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_START = "EVENT_START"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_ADD_ITEM = "EVENT_ADD_ITEM"; + + props() { return { extraCls: "bi-multi-layer-single-tree-trigger", height: 24, - itemsCreator: BI.emptyFn, - watermark: BI.i18nText("BI-Basic_Search"), + itemsCreator: emptyFn, + watermark: i18nText("BI-Basic_Search"), allowSearchValue: false, - title: BI.bind(this._getShowText, this) + title: bind(this._getShowText, this), }; - }, + } - render: function () { - var self = this, o = this.options; - if (o.itemsCreator === BI.emptyFn) { + render() { + const self = this, + o = this.options; + if (o.itemsCreator === emptyFn) { this._initData(); } return { - type: "bi.horizontal_fill", + type: HorizontalFillLayout.xtype, items: [ { el: { - type: "bi.searcher", - ref: function () { + type: Searcher.xtype, + ref () { self.searcher = this; }, - masker: BI.isNotNull(o.container) ? { - offset: {}, - container: o.container - } : { - offset: {} - }, + masker: isNotNull(o.container) + ? { + offset: {}, + container: o.container, + } + : { + offset: {}, + }, isAutoSearch: false, el: { - type: "bi.default_text_editor", - ref: function () { + type: DefaultTextEditor.xtype, + ref () { self.editor = this; }, defaultText: o.defaultText, - text: BI.isKey(o.value) ? this._digest(o.value) : o.text, + text: isKey(o.value) ? this._digest(o.value) : o.text, value: o.value, height: o.height, tipText: "", watermark: o.watermark, - listeners: [{ - eventName: BI.StateEditor.EVENT_FOCUS, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeTrigger.EVENT_FOCUS); - } - }, { - eventName: BI.StateEditor.EVENT_BLUR, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeTrigger.EVENT_BLUR); + listeners: [ + { + eventName: StateEditor.EVENT_FOCUS, + action () { + self.fireEvent(MultiLayerSingleTreeTrigger.EVENT_FOCUS); + }, + }, + { + eventName: StateEditor.EVENT_BLUR, + action () { + self.fireEvent(MultiLayerSingleTreeTrigger.EVENT_BLUR); + }, + }, + { + eventName: StateEditor.EVENT_CHANGE, + action () { + self.fireEvent(MultiLayerSingleTreeTrigger.EVENT_SEARCHING); + }, } - }, { - eventName: BI.StateEditor.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeTrigger.EVENT_SEARCHING); - } - }] + ], }, popup: { - type: o.allowInsertValue ? "bi.multilayer_single_tree_insert_search_pane" : "bi.multilayer_single_tree_popup", - itemsCreator: o.itemsCreator === BI.emptyFn ? BI.emptyFn : function (op, callback) { - op.keyword = self.editor.getValue(); - o.itemsCreator(op, callback); - }, - keywordGetter: function () { + type: o.allowInsertValue + ? MultiLayerSingleTreeInsertSearchPane.xtype + : MultiLayerSingleTreePopup.xtype, + itemsCreator: + o.itemsCreator === emptyFn + ? emptyFn + : function (op, callback) { + op.keyword = self.editor.getValue(); + o.itemsCreator(op, callback); + }, + keywordGetter () { return self.editor.getValue(); }, cls: "bi-card", - listeners: [{ - eventName: BI.MultiLayerSingleTreeInsertSearchPane.EVENT_ADD_ITEM, - action: function () { - self.options.text = self.getSearcher().getKeyword(); - self.fireEvent(BI.MultiLayerSingleTreeTrigger.EVENT_ADD_ITEM); + listeners: [ + { + eventName: MultiLayerSingleTreeInsertSearchPane.EVENT_ADD_ITEM, + action () { + self.options.text = self.getSearcher().getKeyword(); + self.fireEvent(MultiLayerSingleTreeTrigger.EVENT_ADD_ITEM); + }, } - }], - ref: function (_ref) { + ], + ref (_ref) { self.popup = _ref; - } + }, }, - onSearch: function (obj, callback) { - var keyword = obj.keyword; - if (o.itemsCreator === BI.emptyFn) { + onSearch (obj, callback) { + const keyword = obj.keyword; + if (o.itemsCreator === emptyFn) { callback(self._getSearchItems(keyword)); o.allowInsertValue && self.popup.setKeyword(keyword); } else { callback(); } }, - listeners: [{ - eventName: BI.Searcher.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeTrigger.EVENT_CHANGE); + listeners: [ + { + eventName: Searcher.EVENT_CHANGE, + action () { + self.fireEvent(MultiLayerSingleTreeTrigger.EVENT_CHANGE); + }, } - }] + ], }, width: "fill", rgap: 24, - }, - ] + } + ], }; - }, + } - _initData: function () { - var o = this.options; - this.tree = new BI.Tree(); - this.nodes = BI.Tree.treeFormat(BI.deepClone(o.items)); + _initData() { + const o = this.options; + this.tree = new Tree(); + this.nodes = Tree.treeFormat(deepClone(o.items)); this.tree.initTree(this.nodes); - }, + } - _getSearchItems: function (keyword) { - var self = this, o = this.options; + _getSearchItems(keyword) { + const self = this, + o = this.options; // 把数组搜索换成用BI.tree搜索节点, 搜到了就不再往下搜索 - var items = []; - this.tree.traverse(function (node) { - var find = BI.Func.getSearchResult(self.tree.isRoot(node) ? [] : BI.concat([node.text], (o.allowSearchValue ? [node.value] : [])), keyword); + const items = []; + this.tree.traverse(node => { + const find = Func.getSearchResult( + self.tree.isRoot(node) ? [] : concat([node.text], o.allowSearchValue ? [node.value] : []), + keyword + ); if (find.find.length > 0 || find.match.length > 0) { items.push(node); + return true; } }); + return this._fillTreeStructure4Search(items, "id"); - }, + } - _createJson: function (node, open) { + _createJson(node, open) { return { id: node.id, pId: node.pId, text: node.text, value: node.value, - isParent: BI.isNotEmptyArray(node.children), - open: open + isParent: isNotEmptyArray(node.children), + open, }; - }, + } - _getChildren: function (node) { - var self = this; + _getChildren(node) { + const self = this; node.children = node.children || []; - var nodes = []; - BI.each(node.children, function (idx, child) { - var children = self._getChildren(child); + let nodes = []; + each(node.children, (idx, child) => { + const children = self._getChildren(child); nodes = nodes.concat(children); }); + return node.children.concat(nodes); - }, - - // 将搜索到的节点进行补充,构造成一棵完整的树 - _fillTreeStructure4Search: function (leaves) { - var self = this; - var result = []; - var queue = []; - BI.each(leaves, function (idx, node) { + } + + _fillTreeStructure4Search(leaves) { + const self = this; + let result = []; + const queue = []; + each(leaves, (idx, node) => { queue.push({ pId: node.pId }); result.push(node); result = result.concat(self._getChildren(node)); }); queue.reverse(); - while (BI.isNotEmptyArray(queue)) { - var node = queue.pop(); - var pNode = this.tree.search(this.tree.getRoot(), node.pId, "id"); + while (isNotEmptyArray(queue)) { + const node = queue.pop(); + const pNode = this.tree.search(this.tree.getRoot(), node.pId, "id"); if (pNode != null) { pNode.open = true; queue.push({ pId: pNode.pId }); result.push(pNode); } } - return BI.uniqBy(BI.map(result, function (idx, node) { - return self._createJson(node, node.open); - }), "id"); - }, + + return uniqBy( + map(result, (idx, node) => self._createJson(node, node.open)), + "id" + ); + } - _digest: function (v) { - var o = this.options; + _digest(v) { + const o = this.options; - if (BI.isFunction(o.valueFormatter)) { + if (isFunction(o.valueFormatter)) { return o.valueFormatter(v); } - var result = BI.find(o.items, function (i, item) { - return item.value === v; - }); + const result = find(o.items, (i, item) => item.value === v); - return BI.isNotNull(result) ? result.text : (o.text ?? v); - }, + return isNotNull(result) ? result.text : o.text ?? v; + } - _getShowText: function () { + _getShowText() { return this.editor.getText(); - }, + } - stopEditing: function () { + stopEditing() { this.searcher.stopSearch(); - }, + } - getSearcher: function () { + getSearcher() { return this.searcher; - }, + } - populate: function (items) { + populate(items) { this.options.items = items; this._initData(); - }, + } - setValue: function (v) { + setValue(v) { this.editor.setState(this._digest(v[0])); - }, + } - getValue: function () { + getValue() { return this.searcher.getValue(); - }, + } - focus: function () { + focus() { this.searcher.focus(); - }, + } - blur: function () { + blur() { this.searcher.blur(); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.searcher.setWaterMark(v); } -}); -BI.MultiLayerSingleTreeTrigger.EVENT_FOCUS = "EVENT_FOCUS"; -BI.MultiLayerSingleTreeTrigger.EVENT_BLUR = "EVENT_BLUR"; -BI.MultiLayerSingleTreeTrigger.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.MultiLayerSingleTreeTrigger.EVENT_STOP = "EVENT_STOP"; -BI.MultiLayerSingleTreeTrigger.EVENT_START = "EVENT_START"; -BI.MultiLayerSingleTreeTrigger.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiLayerSingleTreeTrigger.EVENT_ADD_ITEM = "EVENT_ADD_ITEM"; -BI.shortcut("bi.multilayer_single_tree_trigger", BI.MultiLayerSingleTreeTrigger); +} diff --git a/src/widget/multilayersingletree/node/index.js b/src/widget/multilayersingletree/node/index.js new file mode 100644 index 000000000..25a92c14a --- /dev/null +++ b/src/widget/multilayersingletree/node/index.js @@ -0,0 +1,4 @@ +export { MultiLayerSingleTreeFirstPlusGroupNode } from "./node.first.plus"; +export { MultiLayerSingleTreeLastPlusGroupNode } from "./node.last.plus"; +export { MultiLayerSingleTreeMidPlusGroupNode } from "./node.mid.plus"; +export { MultiLayerSingleTreePlusGroupNode } from "./node.plus"; diff --git a/src/widget/multilayersingletree/node/node.first.plus.js b/src/widget/multilayersingletree/node/node.first.plus.js index 51177bcce..07e767331 100644 --- a/src/widget/multilayersingletree/node/node.first.plus.js +++ b/src/widget/multilayersingletree/node/node.first.plus.js @@ -1,69 +1,80 @@ -/** - * 加号表示的组节点 - * - * Created by GUY on 2016/1/27. - * @class BI.MultiLayerSingleTreeFirstPlusGroupNode - * @extends BI.NodeButton - */ -BI.MultiLayerSingleTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.MultiLayerSingleTreeFirstPlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { +import { + shortcut, + extend, + createWidget, + makeArray, + HorizontalAdaptLayout, + isNotNull, + Controller, + Events +} from "@/core"; +import { NodeButton } from "@/base"; +import { FirstPlusGroupNode } from "@/case"; + +@shortcut() +export class MultiLayerSingleTreeFirstPlusGroupNode extends NodeButton { + static xtype = "bi.multilayer_single_tree_first_plus_group_node"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { extraCls: "bi-multilayer-single-tree-first-plus-group-node bi-list-item", layer: 0, // 第几层级 id: "", pId: "", open: false, - height: 24 + height: 24, }); - }, - _init: function () { - BI.MultiLayerSingleTreeFirstPlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; + } + + _init() { + super._init(...arguments); + const o = this.options; this.node = this._createNode(); - var items = []; + const items = []; items.push({ el: this.node, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2 + lgap: (o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT) / 2, }); - BI.createWidget({ - type: "bi.horizontal_adapt", + createWidget({ + type: HorizontalAdaptLayout.xtype, element: this, - columnSize: BI.makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), - items: items + columnSize: makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), + items, }); - }, + } - doRedMark: function () { - this.node.doRedMark.apply(this.node, arguments); - }, + doRedMark() { + this.node.doRedMark(...arguments); + } - unRedMark: function () { - this.node.unRedMark.apply(this.node, arguments); - }, + unRedMark() { + this.node.unRedMark(...arguments); + } - doClick: function () { - BI.MultiLayerSingleTreeFirstPlusGroupNode.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick(...arguments); this.node.setSelected(this.isSelected()); - }, + } - setOpened: function (v) { - BI.MultiLayerSingleTreeFirstPlusGroupNode.superclass.setOpened.apply(this, arguments); - if (BI.isNotNull(this.node)) { + setOpened(v) { + super.setOpened(...arguments); + if (isNotNull(this.node)) { this.node.setOpened(v); } - }, + } - _createNode: function () { - var self = this, o = this.options; + _createNode() { + const o = this.options; - return BI.createWidget({ - type: "bi.first_plus_group_node", + return createWidget({ + type: FirstPlusGroupNode.xtype, cls: "bi-list-item-none", logic: { - dynamic: true + dynamic: true, }, id: o.id, pId: o.pId, @@ -75,17 +86,19 @@ BI.MultiLayerSingleTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { value: o.value, py: o.py, keyword: o.keyword, - listeners: [{ - eventName: BI.Controller.EVENT_CHANGE, - action: function (type) { - if (type === BI.Events.CLICK) {// 本身实现click功能 - return; - } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + listeners: [ + { + eventName: Controller.EVENT_CHANGE, + action: (...args) => { + const [type] = args; + if (type === Events.CLICK) { + // 本身实现click功能 + return; + } + this.fireEvent(Controller.EVENT_CHANGE, ...args); + }, } - }] + ], }); } -}); - -BI.shortcut("bi.multilayer_single_tree_first_plus_group_node", BI.MultiLayerSingleTreeFirstPlusGroupNode); +} diff --git a/src/widget/multilayersingletree/node/node.last.plus.js b/src/widget/multilayersingletree/node/node.last.plus.js index 007837f5c..907dd71f8 100644 --- a/src/widget/multilayersingletree/node/node.last.plus.js +++ b/src/widget/multilayersingletree/node/node.last.plus.js @@ -1,69 +1,80 @@ -/** - * 加号表示的组节点 - * - * Created by GUY on 2016/1/27. - * @class BI.MultiLayerSingleTreeLastPlusGroupNode - * @extends BI.NodeButton - */ -BI.MultiLayerSingleTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.MultiLayerSingleTreeLastPlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { +import { + shortcut, + extend, + createWidget, + makeArray, + HorizontalAdaptLayout, + isNotNull, + Controller, + Events +} from "@/core"; +import { NodeButton } from "@/base"; +import { LastPlusGroupNode } from "@/case"; + +@shortcut() +export class MultiLayerSingleTreeLastPlusGroupNode extends NodeButton { + static xtype = "bi.multilayer_single_tree_last_plus_group_node"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { extraCls: "bi-multilayer-single-tree-last-plus-group-node bi-list-item", layer: 0, // 第几层级 id: "", pId: "", open: false, - height: 24 + height: 24, }); - }, - _init: function () { - BI.MultiLayerSingleTreeLastPlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; + } + + _init() { + super._init(...arguments); + const o = this.options; this.node = this._createNode(); - var items = []; + const items = []; items.push({ el: this.node, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2 + lgap: (o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT) / 2, }); - BI.createWidget({ - type: "bi.horizontal_adapt", + createWidget({ + type: HorizontalAdaptLayout.xtype, element: this, - columnSize: BI.makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), - items: items + columnSize: makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), + items, }); - }, + } - doRedMark: function () { - this.node.doRedMark.apply(this.node, arguments); - }, + doRedMark() { + this.node.doRedMark(...arguments); + } - unRedMark: function () { - this.node.unRedMark.apply(this.node, arguments); - }, + unRedMark() { + this.node.unRedMark(...arguments); + } - doClick: function () { - BI.MultiLayerSingleTreeLastPlusGroupNode.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick(...arguments); this.node.setSelected(this.isSelected()); - }, + } - setOpened: function (v) { - BI.MultiLayerSingleTreeLastPlusGroupNode.superclass.setOpened.apply(this, arguments); - if (BI.isNotNull(this.node)) { + setOpened(v) { + super.setOpened(...arguments); + if (isNotNull(this.node)) { this.node.setOpened(v); } - }, + } - _createNode: function () { - var self = this, o = this.options; + _createNode() { + const o = this.options; - return BI.createWidget({ - type: "bi.last_plus_group_node", + return createWidget({ + type: LastPlusGroupNode.xtype, cls: "bi-list-item-none", logic: { - dynamic: true + dynamic: true, }, id: o.id, pId: o.pId, @@ -74,17 +85,19 @@ BI.MultiLayerSingleTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { value: o.value, py: o.py, keyword: o.keyword, - listeners: [{ - eventName: BI.Controller.EVENT_CHANGE, - action: function (type) { - if (type === BI.Events.CLICK) {// 本身实现click功能 - return; - } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + listeners: [ + { + eventName: Controller.EVENT_CHANGE, + action: (...args) => { + const [type] = args; + if (type === Events.CLICK) { + // 本身实现click功能 + return; + } + this.fireEvent(Controller.EVENT_CHANGE, ...args); + }, } - }] + ], }); } -}); - -BI.shortcut("bi.multilayer_single_tree_last_plus_group_node", BI.MultiLayerSingleTreeLastPlusGroupNode); +} diff --git a/src/widget/multilayersingletree/node/node.mid.plus.js b/src/widget/multilayersingletree/node/node.mid.plus.js index e8709cf78..f051ec2fe 100644 --- a/src/widget/multilayersingletree/node/node.mid.plus.js +++ b/src/widget/multilayersingletree/node/node.mid.plus.js @@ -1,69 +1,80 @@ -/** - * 加号表示的组节点 - * - * Created by GUY on 2016/1/27. - * @class BI.MultiLayerSingleTreeMidPlusGroupNode - * @extends BI.NodeButton - */ -BI.MultiLayerSingleTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.MultiLayerSingleTreeMidPlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { +import { + shortcut, + extend, + createWidget, + makeArray, + HorizontalAdaptLayout, + isNotNull, + Controller, + Events +} from "@/core"; +import { NodeButton } from "@/base"; +import { MidPlusGroupNode } from "@/case"; + +@shortcut() +export class MultiLayerSingleTreeMidPlusGroupNode extends NodeButton { + static xtype = "bi.multilayer_single_tree_mid_plus_group_node"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { extraCls: "bi-multilayer-single-tree-mid-plus-group-node bi-list-item", layer: 0, // 第几层级 id: "", pId: "", open: false, - height: 24 + height: 24, }); - }, - _init: function () { - BI.MultiLayerSingleTreeMidPlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; + } + + _init() { + super._init(...arguments); + const o = this.options; this.node = this._createNode(); - var items = []; + const items = []; items.push({ el: this.node, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2 + lgap: (o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT) / 2, }); - BI.createWidget({ - type: "bi.horizontal_adapt", + createWidget({ + type: HorizontalAdaptLayout.xtype, element: this, - columnSize: BI.makeArray(o.layer, 12), - items: items + columnSize: makeArray(o.layer, 12), + items, }); - }, + } - doRedMark: function () { - this.node.doRedMark.apply(this.node, arguments); - }, + doRedMark() { + this.node.doRedMark(...arguments); + } - unRedMark: function () { - this.node.unRedMark.apply(this.node, arguments); - }, + unRedMark() { + this.node.unRedMark(...arguments); + } - doClick: function () { - BI.MultiLayerSingleTreeMidPlusGroupNode.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick(...arguments); this.node.setSelected(this.isSelected()); - }, + } - setOpened: function (v) { - BI.MultiLayerSingleTreeMidPlusGroupNode.superclass.setOpened.apply(this, arguments); - if (BI.isNotNull(this.node)) { + setOpened(v) { + super.setOpened(...arguments); + if (isNotNull(this.node)) { this.node.setOpened(v); } - }, + } - _createNode: function () { - var self = this, o = this.options; + _createNode() { + const o = this.options; - return BI.createWidget({ - type: "bi.mid_plus_group_node", + return createWidget({ + type: MidPlusGroupNode.xtype, cls: "bi-list-item-none", logic: { - dynamic: true + dynamic: true, }, id: o.id, pId: o.pId, @@ -74,17 +85,19 @@ BI.MultiLayerSingleTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { value: o.value, py: o.py, keyword: o.keyword, - listeners: [{ - eventName: BI.Controller.EVENT_CHANGE, - action: function (type) { - if (type === BI.Events.CLICK) {// 本身实现click功能 - return; - } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + listeners: [ + { + eventName: Controller.EVENT_CHANGE, + action: (...args) => { + const [type] = args; + if (type === Events.CLICK) { + // 本身实现click功能 + return; + } + this.fireEvent(Controller.EVENT_CHANGE, ...args); + }, } - }] + ], }); } -}); - -BI.shortcut("bi.multilayer_single_tree_mid_plus_group_node", BI.MultiLayerSingleTreeMidPlusGroupNode); +} diff --git a/src/widget/multilayersingletree/node/node.plus.js b/src/widget/multilayersingletree/node/node.plus.js index bcff49737..24eebd83e 100644 --- a/src/widget/multilayersingletree/node/node.plus.js +++ b/src/widget/multilayersingletree/node/node.plus.js @@ -1,80 +1,96 @@ -/** - *@desc 根节点,既是第一个又是最后一个 - *@author dailer - *@date 2018/09/16 - */ -BI.MultiLayerSingleTreePlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.MultiLayerSingleTreePlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { +import { + shortcut, + extend, + count, + contains, + createWidget, + makeArray, + Layout, + HorizontalAdaptLayout, + isNotNull, + Controller, + Events +} from "@/core"; +import { NodeButton } from "@/base"; +import { PlusGroupNode } from "@/case"; + +@shortcut() +export class MultiLayerSingleTreePlusGroupNode extends NodeButton { + static xtype = "bi.multilayer_single_tree_plus_group_node"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { extraCls: "bi-multilayer-single-tree-plus-group-node bi-list-item", layer: 0, // 第几层级 id: "", pId: "", open: false, - height: 24 + height: 24, }); - }, - _init: function () { - BI.MultiLayerSingleTreePlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; + } + + _init() { + super._init(...arguments); + const o = this.options; this.node = this._createNode(); - var needBlankLayers = []; - var pNode = o.pNode; + const needBlankLayers = []; + let pNode = o.pNode; while (pNode) { if (pNode.isLastNode) { - needBlankLayers.push(pNode.layer) + needBlankLayers.push(pNode.layer); } pNode = pNode.pNode; } - var items = []; - BI.count(0, o.layer, function (index) { + const items = []; + count(0, o.layer, index => { items.push({ - type: "bi.layout", - cls: BI.contains(needBlankLayers, index) ? "" : "base-line-conn-background", + type: Layout.xtype, + cls: contains(needBlankLayers, index) ? "" : "base-line-conn-background", width: 12, - height: o.height + height: o.height, }); }); items.push(this.node); - BI.createWidget({ - type: "bi.horizontal_adapt", + createWidget({ + type: HorizontalAdaptLayout.xtype, element: this, - columnSize: BI.makeArray(o.layer, 12), - items: items + columnSize: makeArray(o.layer, 12), + items, }); - }, + } - doRedMark: function () { - this.node.doRedMark.apply(this.node, arguments); - }, + doRedMark() { + this.node.doRedMark(...arguments); + } - unRedMark: function () { - this.node.unRedMark.apply(this.node, arguments); - }, + unRedMark() { + this.node.unRedMark(...arguments); + } - doClick: function () { - BI.MultiLayerSingleTreePlusGroupNode.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick(...arguments); this.node.setSelected(this.isSelected()); - }, + } - setOpened: function (v) { - BI.MultiLayerSingleTreePlusGroupNode.superclass.setOpened.apply(this, arguments); - if (BI.isNotNull(this.node)) { + setOpened(v) { + super.setOpened(...arguments); + if (isNotNull(this.node)) { this.node.setOpened(v); } - }, + } - _createNode: function () { - var self = this, o = this.options; + _createNode() { + const o = this.options; - return BI.createWidget({ - type: "bi.plus_group_node", + return createWidget({ + type: PlusGroupNode.xtype, cls: "bi-list-item-none", logic: { - dynamic: true + dynamic: true, }, id: o.id, pId: o.pId, @@ -86,17 +102,19 @@ BI.MultiLayerSingleTreePlusGroupNode = BI.inherit(BI.NodeButton, { value: o.value, py: o.py, keyword: o.keyword, - listeners: [{ - eventName: BI.Controller.EVENT_CHANGE, - action: function (type) { - if (type === BI.Events.CLICK) {// 本身实现click功能 - return; - } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + listeners: [ + { + eventName: Controller.EVENT_CHANGE, + action: (...args) => { + const [type] = args; + if (type === Events.CLICK) { + // 本身实现click功能 + return; + } + this.fireEvent(Controller.EVENT_CHANGE, ...args); + }, } - }] + ], }); } -}); - -BI.shortcut("bi.multilayer_single_tree_plus_group_node", BI.MultiLayerSingleTreePlusGroupNode); \ No newline at end of file +} diff --git a/src/widget/multilayersingletree/treeitem/index.js b/src/widget/multilayersingletree/treeitem/index.js new file mode 100644 index 000000000..ce4dc8b6c --- /dev/null +++ b/src/widget/multilayersingletree/treeitem/index.js @@ -0,0 +1,3 @@ +export { MultiLayerSingleTreeFirstTreeLeafItem } from "./item.first.treeleaf"; +export { MultiLayerSingleTreeLastTreeLeafItem } from "./item.last.treeleaf"; +export { MultiLayerSingleTreeMidTreeLeafItem } from "./item.mid.treeleaf"; diff --git a/src/widget/multilayersingletree/treeitem/item.first.treeleaf.js b/src/widget/multilayersingletree/treeitem/item.first.treeleaf.js index 4cc5203e4..469d215d0 100644 --- a/src/widget/multilayersingletree/treeitem/item.first.treeleaf.js +++ b/src/widget/multilayersingletree/treeitem/item.first.treeleaf.js @@ -1,30 +1,32 @@ -/** - * - * Created by GUY on 2016/1/27. - * @class BI.MultiLayerSingleTreeFirstTreeLeafItem - * @extends BI.BasicButton - */ -BI.MultiLayerSingleTreeFirstTreeLeafItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - return BI.extend(BI.MultiLayerSingleTreeFirstTreeLeafItem.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, extend, createWidget, Controller, Events, makeArray, HorizontalAdaptLayout } from "@/core"; +import { BasicButton } from "@/base"; + +@shortcut() +export class MultiLayerSingleTreeFirstTreeLeafItem extends BasicButton { + static xtype = "bi.multilayer_single_tree_first_tree_leaf_item"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-multilayer-single-tree-first-tree-leaf-item bi-list-item-active", logic: { - dynamic: false + dynamic: false, }, layer: 0, id: "", pId: "", - height: 24 + height: 24, }); - }, - _init: function () { - BI.MultiLayerSingleTreeFirstTreeLeafItem.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.item = BI.createWidget({ + } + + _init() { + super._init(...arguments); + const self = this, + o = this.options; + this.item = createWidget({ type: "bi.first_tree_leaf_item", cls: "bi-list-item-none", logic: { - dynamic: true + dynamic: true, }, id: o.id, pId: o.pId, @@ -33,54 +35,53 @@ BI.MultiLayerSingleTreeFirstTreeLeafItem = BI.inherit(BI.BasicButton, { text: o.text, value: o.value, py: o.py, - keyword: o.keyword + keyword: o.keyword, }); - this.item.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {// 本身实现click功能 + this.item.on(Controller.EVENT_CHANGE, function (type) { + if (type === Events.CLICK) { + // 本身实现click功能 return; } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - var items = []; + const items = []; items.push({ el: this.item, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2 + lgap: (o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT) / 2, }); - BI.createWidget({ - type: "bi.horizontal_adapt", + createWidget({ + type: HorizontalAdaptLayout.xtype, element: this, - columnSize: BI.makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), - items: items + columnSize: makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), + items, }); - }, + } - doHighLight: function () { - this.item.doHighLight.apply(this.item, arguments); - }, + doHighLight() { + this.item.doHighLight(...arguments); + } - unHighLight: function () { - this.item.unHighLight.apply(this.item, arguments); - }, + unHighLight() { + this.item.unHighLight(...arguments); + } - getId: function () { + getId() { return this.options.id; - }, + } - getPId: function () { + getPId() { return this.options.pId; - }, + } - doClick: function () { - BI.MultiLayerSingleTreeFirstTreeLeafItem.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick(...arguments); this.item.setSelected(this.isSelected()); - }, + } - setSelected: function (v) { - BI.MultiLayerSingleTreeFirstTreeLeafItem.superclass.setSelected.apply(this, arguments); + setSelected(v) { + super.setSelected(...arguments); this.item.setSelected(v); } -}); - -BI.shortcut("bi.multilayer_single_tree_first_tree_leaf_item", BI.MultiLayerSingleTreeFirstTreeLeafItem); +} diff --git a/src/widget/multilayersingletree/treeitem/item.last.treeleaf.js b/src/widget/multilayersingletree/treeitem/item.last.treeleaf.js index 9aa604737..f4ca73929 100644 --- a/src/widget/multilayersingletree/treeitem/item.last.treeleaf.js +++ b/src/widget/multilayersingletree/treeitem/item.last.treeleaf.js @@ -1,30 +1,32 @@ -/** - * - * Created by GUY on 2016/1/27. - * @class BI.MultiLayerSingleTreeLastTreeLeafItem - * @extends BI.BasicButton - */ -BI.MultiLayerSingleTreeLastTreeLeafItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - return BI.extend(BI.MultiLayerSingleTreeLastTreeLeafItem.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, extend, createWidget, Controller, Events, makeArray, HorizontalAdaptLayout } from "@/core"; +import { BasicButton } from "@/base"; + +@shortcut() +export class MultiLayerSingleTreeLastTreeLeafItem extends BasicButton { + static xtype = "bi.multilayer_single_tree_last_tree_leaf_item"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-multilayer-single-tree-last-tree-leaf-item bi-list-item-active", logic: { - dynamic: false + dynamic: false, }, layer: 0, id: "", pId: "", - height: 24 + height: 24, }); - }, - _init: function () { - BI.MultiLayerSingleTreeLastTreeLeafItem.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.item = BI.createWidget({ + } + + _init() { + super._init(...arguments); + const self = this, + o = this.options; + this.item = createWidget({ type: "bi.last_tree_leaf_item", cls: "bi-list-item-none", logic: { - dynamic: true + dynamic: true, }, id: o.id, pId: o.pId, @@ -33,54 +35,53 @@ BI.MultiLayerSingleTreeLastTreeLeafItem = BI.inherit(BI.BasicButton, { text: o.text, value: o.value, py: o.py, - keyword: o.keyword + keyword: o.keyword, }); - this.item.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {// 本身实现click功能 + this.item.on(Controller.EVENT_CHANGE, function (type) { + if (type === Events.CLICK) { + // 本身实现click功能 return; } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - var items = []; + const items = []; items.push({ el: this.item, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2 + lgap: (o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT) / 2, }); - BI.createWidget({ - type: "bi.horizontal_adapt", + createWidget({ + type: HorizontalAdaptLayout.xtype, element: this, - columnSize: BI.makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), - items: items + columnSize: makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), + items, }); - }, + } - doHighLight: function () { - this.item.doHighLight.apply(this.item, arguments); - }, + doHighLight() { + this.item.doHighLight(...arguments); + } - unHighLight: function () { - this.item.unHighLight.apply(this.item, arguments); - }, + unHighLight() { + this.item.unHighLight(...arguments); + } - getId: function () { + getId() { return this.options.id; - }, + } - getPId: function () { + getPId() { return this.options.pId; - }, + } - doClick: function () { - BI.MultiLayerSingleTreeLastTreeLeafItem.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick(...arguments); this.item.setSelected(this.isSelected()); - }, + } - setSelected: function (v) { - BI.MultiLayerSingleTreeLastTreeLeafItem.superclass.setSelected.apply(this, arguments); + setSelected(v) { + super.setSelected(...arguments); this.item.setSelected(v); } -}); - -BI.shortcut("bi.multilayer_single_tree_last_tree_leaf_item", BI.MultiLayerSingleTreeLastTreeLeafItem); +} diff --git a/src/widget/multilayersingletree/treeitem/item.mid.treeleaf.js b/src/widget/multilayersingletree/treeitem/item.mid.treeleaf.js index eed7d553c..527dac46a 100644 --- a/src/widget/multilayersingletree/treeitem/item.mid.treeleaf.js +++ b/src/widget/multilayersingletree/treeitem/item.mid.treeleaf.js @@ -1,30 +1,32 @@ -/** - * - * Created by GUY on 2016/1/27. - * @class BI.MultiLayerSingleTreeMidTreeLeafItem - * @extends BI.BasicButton - */ -BI.MultiLayerSingleTreeMidTreeLeafItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - return BI.extend(BI.MultiLayerSingleTreeMidTreeLeafItem.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, extend, createWidget, Controller, Events, makeArray, HorizontalAdaptLayout } from "@/core"; +import { BasicButton } from "@/base"; + +@shortcut() +export class MultiLayerSingleTreeMidTreeLeafItem extends BasicButton { + static xtype = "bi.multilayer_single_tree_mid_tree_leaf_item"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { extraCls: "bi-multilayer-single-tree-mid-tree-leaf-item bi-list-item-active", logic: { - dynamic: false + dynamic: false, }, layer: 0, id: "", pId: "", - height: 24 + height: 24, }); - }, - _init: function () { - BI.MultiLayerSingleTreeMidTreeLeafItem.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.item = BI.createWidget({ + } + + _init() { + super._init(...arguments); + const self = this, + o = this.options; + this.item = createWidget({ type: "bi.mid_tree_leaf_item", cls: "bi-list-item-none", logic: { - dynamic: true + dynamic: true, }, id: o.id, pId: o.pId, @@ -33,54 +35,53 @@ BI.MultiLayerSingleTreeMidTreeLeafItem = BI.inherit(BI.BasicButton, { text: o.text, value: o.value, py: o.py, - keyword: o.keyword + keyword: o.keyword, }); - this.item.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {// 本身实现click功能 + this.item.on(Controller.EVENT_CHANGE, function (type) { + if (type === Events.CLICK) { + // 本身实现click功能 return; } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - var items = []; + const items = []; items.push({ el: this.item, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2 + lgap: (o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT) / 2, }); - BI.createWidget({ - type: "bi.horizontal_adapt", + createWidget({ + type: HorizontalAdaptLayout.xtype, element: this, - columnSize: BI.makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), - items: items + columnSize: makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), + items, }); - }, + } - doHighLight: function () { - this.item.doHighLight.apply(this.item, arguments); - }, + doHighLight() { + this.item.doHighLight(...arguments); + } - unHighLight: function () { - this.item.unHighLight.apply(this.item, arguments); - }, + unHighLight() { + this.item.unHighLight(...arguments); + } - getId: function () { + getId() { return this.options.id; - }, + } - getPId: function () { + getPId() { return this.options.pId; - }, + } - doClick: function () { - BI.MultiLayerSingleTreeMidTreeLeafItem.superclass.doClick.apply(this, arguments); + doClick() { + super.doClick(...arguments); this.item.setSelected(this.isSelected()); - }, + } - setSelected: function (v) { - BI.MultiLayerSingleTreeMidTreeLeafItem.superclass.setSelected.apply(this, arguments); + setSelected(v) { + super.setSelected(...arguments); this.item.setSelected(v); } -}); - -BI.shortcut("bi.multilayer_single_tree_mid_tree_leaf_item", BI.MultiLayerSingleTreeMidTreeLeafItem); +} From 630be6aea073d0968b187c1dd1c08949d7d2f408 Mon Sep 17 00:00:00 2001 From: Treecat Date: Fri, 13 Jan 2023 11:47:15 +0800 Subject: [PATCH 110/300] =?UTF-8?q?KERNEL-14076=20refact:=20es6=20?= =?UTF-8?q?=E8=84=9A=E6=9C=AC=E8=AF=86=E5=88=AB=E5=BE=AA=E7=8E=AF=E4=BE=9D?= =?UTF-8?q?=E8=B5=96=E3=80=82=E5=AE=8C=E6=88=90=20base=20=E5=A4=84?= =?UTF-8?q?=E7=90=86=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.js | 61 +- src/base/0.base.js | 12 +- src/base/1.pane.js | 91 +- src/base/collection/collection.js | 119 ++- src/base/combination/bubble.js | 249 +++-- src/base/combination/combo.js | 475 +++++++--- src/base/combination/expander.js | 166 ++-- src/base/combination/group.button.js | 85 +- src/base/combination/group.combo.js | 55 +- src/base/combination/group.virtual.js | 67 +- src/base/combination/index.js | 2 +- src/base/combination/loader.js | 184 ++-- src/base/combination/navigation.js | 48 +- src/base/combination/searcher.js | 159 ++-- src/base/combination/switcher.js | 163 ++-- src/base/combination/tab.js | 55 +- src/base/combination/tree.button.js | 9 +- src/base/context.js | 57 +- src/base/el.js | 48 +- src/base/foundation/message.js | 175 ++-- src/base/grid/grid.js | 164 +++- src/base/index.js | 9 +- src/base/layer/layer.drawer.js | 457 ++++----- src/base/layer/layer.popover.js | 552 ++++++----- src/base/layer/layer.popup.js | 875 ++++++++++-------- src/base/layer/layer.searcher.js | 259 +++--- src/base/list/listview.js | 221 ++--- src/base/list/virtualgrouplist.js | 331 ++++--- src/base/list/virtuallist.js | 71 +- src/base/pager/pager.js | 149 +-- src/base/single/0.single.js | 39 +- src/base/single/1.text.js | 64 +- src/base/single/a/a.js | 52 +- src/base/single/bar/bar.loading.js | 19 +- src/base/single/button/button.basic.js | 333 ++++--- src/base/single/button/button.node.js | 2 +- src/base/single/button/buttons/button.icon.js | 9 +- .../single/button/buttons/button.image.js | 10 +- src/base/single/button/buttons/button.js | 41 +- src/base/single/button/buttons/button.text.js | 5 +- src/base/single/button/index.js | 34 +- .../button/listitem/blankiconicontextitem.js | 74 +- .../button/listitem/blankicontexticonitem.js | 75 +- .../button/listitem/blankicontextitem.js | 61 +- .../button/listitem/icontexticonitem.js | 67 +- .../single/button/listitem/icontextitem.js | 54 +- .../single/button/listitem/texticonitem.js | 56 +- src/base/single/button/listitem/textitem.js | 5 +- .../single/button/node/icontexticonnode.js | 67 +- src/base/single/button/node/icontextnode.js | 55 +- src/base/single/button/node/texticonnode.js | 55 +- src/base/single/button/node/textnode.js | 10 +- src/base/single/editor/editor.js | 67 +- src/base/single/editor/editor.multifile.js | 35 +- src/base/single/editor/editor.textarea.js | 109 ++- src/base/single/editor/index.js | 6 +- src/base/single/html/html.js | 29 +- src/base/single/icon/icon.js | 7 +- src/base/single/iframe/iframe.js | 23 +- src/base/single/img/img.js | 20 +- .../single/input/checkbox/checkbox.image.js | 9 +- src/base/single/input/checkbox/checkbox.js | 29 +- src/base/single/input/file.js | 369 ++++---- src/base/single/input/index.js | 12 +- src/base/single/input/input.js | 71 +- src/base/single/input/radio/radio.image.js | 9 +- src/base/single/input/radio/radio.js | 31 +- src/base/single/instruction/instruction.js | 16 +- src/base/single/label/abstract.label.js | 179 ++-- src/base/single/label/html.label.js | 10 +- src/base/single/label/icon.label.js | 14 +- src/base/single/label/index.js | 8 +- src/base/single/label/label.js | 7 +- src/base/single/link/link.js | 10 +- src/base/single/text.pure.js | 19 +- src/base/single/tip/0.tip.js | 8 +- src/base/single/tip/tip.toast.js | 221 ++--- src/base/single/tip/tip.tooltip.js | 146 +-- src/base/single/trigger/trigger.js | 13 +- src/base/tree/customtree.js | 72 +- src/case/combo/bubblecombo/popup.bubble.js | 3 +- 81 files changed, 4716 insertions(+), 3391 deletions(-) diff --git a/es6.js b/es6.js index 3e7fcef7f..afc7ff8e1 100644 --- a/es6.js +++ b/es6.js @@ -8,6 +8,9 @@ const _ = require("lodash"); // const XTYPE_ONLY = false; // const THIS_REPLACE = false; +const ConflictImport = []; +const CircularDependency = []; + function objHaveFunction(obj) { return Object.keys(obj).some(key => { const value = obj[key]; @@ -44,6 +47,7 @@ async function saveAndFixCode(path, code) { const prettierCode = prettier.format(_code, { tabWidth: 4, parser: 'babel', + printWidth: 120, }); fs.writeFileSync(path, prettierCode); @@ -138,7 +142,13 @@ async function handleFile(srcName) { const result = /BI\.(.*?)\s=\sBI\.inherit\(/.exec(sourceCode); if (!result) { - console.log(`已经es6过,替换 xtype => ${srcName}`); + // console.log(`已经es6过,替换 xtype => ${srcName}`); + if (!/export class/.test(sourceCode)) { + console.log("忽略文件", srcName); + + return; + } + // 处理 xtype const noXtypeCode = sourceCode.replace(/type:\s?"bi\.(.*?)"/g, v => { const matchedSentence = v.replace(/type:\s?/, ""); @@ -181,12 +191,37 @@ async function handleFile(srcName) { }); const tmpG = {}; - _.forEach(G, (depts, module)=> { - const flag = _.some(crossPackages, crosspackage => module.indexOf(crosspackage) >= 0 && !module.startsWith("@")) + _.forEach(G, (depts, module) => { + const flag = _.some(crossPackages, crosspackage => module.indexOf(crosspackage) >= 0 && !module.startsWith("@")); if (!flag) { tmpG[module] = depts; } }); + + + // 较验手工 import 错误 + const map = {}; + let conflict = false; + let circle = false; + _.forEach(tmpG, (imports, fromStr) => { + if (srcName.indexOf("base") >= 0) { + if (fromStr === "@/case" || fromStr === "@/base") { + circle = true; + } + } + + _.forEach(imports, (bools, _import) => { + if (map[_import] && map[_import] !== fromStr) { + conflict = true; + } + + map[_import] = fromStr; + }); + }); + + conflict && ConflictImport.push(srcName); + circle && CircularDependency.push(srcName); + G = tmpG; const noImportCode = noXtypeCode.replace(/import {([\s\S]*?)} from "(.*?)";/g, ""); @@ -314,7 +349,7 @@ async function handleFile(srcName) { // 换 super._defaultConfig f = f.replace( /super\._defaultConfig\.apply\(this,\sarguments\)/g, - "super._defaultConfig(...arguments)" + "super._defaultConfig(...arguments)", ); // 换 super.xxx.apply f = f.replace(/super\.(.*?)\.apply\(this,\sarguments\)/g, a => { @@ -427,19 +462,27 @@ async function traverse(srcName) { const srcName = process.argv[2]; -initDepts().then(() => { +initDepts().then(async () => { const content = fs.readFileSync("src/core/2.base.js").toString(); let result = content.match(/export function (.*?)\(/g); target.push( ...result.map(el => - el.replace("export function ", "").replace("(", "") - ) + el.replace("export function ", "").replace("(", ""), + ), ); result = content.match(/export const (.*?) =/g); target.push( - ...result.map(el => el.replace("export const ", "").replace(" =", "")) + ...result.map(el => el.replace("export const ", "").replace(" =", "")), ); - traverse(srcName); + await traverse(srcName); + + // 对数据处理 + ConflictImport.forEach(el => { + console.log(`导入冲突 ${el}`); + }); + CircularDependency.forEach(el => { + console.log(`出现循环依赖 ${el}`); + }); }); diff --git a/src/base/0.base.js b/src/base/0.base.js index a2cffed9b..d79ca192d 100644 --- a/src/base/0.base.js +++ b/src/base/0.base.js @@ -20,14 +20,4 @@ const Drawers = new DrawerController(); const Broadcasts = new BroadcastController(); const StyleLoaders = new StyleLoaderManager(); -export { - Resizers, - Layers, - Maskers, - Bubbles, - Tooltips, - Popovers, - Drawers, - Broadcasts, - StyleLoaders -}; +export { Resizers, Layers, Maskers, Bubbles, Tooltips, Popovers, Drawers, Broadcasts, StyleLoaders }; diff --git a/src/base/1.pane.js b/src/base/1.pane.js index 1e6bf38b5..3f07c307f 100644 --- a/src/base/1.pane.js +++ b/src/base/1.pane.js @@ -1,3 +1,19 @@ +import { Label, Text } from "./single"; +import { + CenterAdaptLayout, + HorizontalAdaptLayout, + VerticalLayout, + Widget, + shortcut, + isNotEmptyString, + extend, + isNull, + isEmpty, + createWidget, + Providers +} from "@/core"; +import { Layers } from "@/base"; + /** * 当没有元素时有提示信息的view * @@ -6,8 +22,6 @@ * @extends BI.Widget * @abstract */ -import { Widget, shortcut, isNotEmptyString, extend, isNull, isEmpty, createWidget, Providers } from "../core"; -import { Layers } from "./0.base"; @shortcut() export class Pane extends Widget { @@ -31,32 +45,36 @@ export class Pane extends Widget { createWidget({ type: "bi.absolute_center_adapt", element: this, - items: [{ - type: "bi.label", - ref: _ref => { - this._tipText = _ref; - }, - cls: "bi-tips", - text: this.options.tipText, - height: 25, - }], + items: [ + { + type: Label.xtype, + ref: _ref => { + this._tipText = _ref; + }, + cls: "bi-tips", + text: this.options.tipText, + height: 25, + } + ], }); } } - + loading() { const o = this.options; - const loadingAnimation = createWidget(Providers.getProvider("bi.provider.system").getLoading({ - loadingSize: o.loadingSize, - context: this, - })); + const loadingAnimation = createWidget( + Providers.getProvider("bi.provider.system").getLoading({ + loadingSize: o.loadingSize, + context: this, + }) + ); // pane在同步方式下由items决定tipText的显示与否 // loading的异步情况下由loaded后对面板的populate的时机决定 this.setTipVisible(false); if (o.overlap === true) { if (!Layers.has(`${this.getName()}-loading`)) { createWidget({ - type: "bi.center_adapt", + type: CenterAdaptLayout.xtype, cls: "loading-container", items: this._getLoadingTipItems(loadingAnimation), element: Layers.make(`${this.getName()}-loading`, this), @@ -66,7 +84,7 @@ export class Pane extends Widget { } else if (isNull(this._loading)) { loadingAnimation.element.css("zIndex", 1); createWidget({ - type: "bi.center_adapt", + type: CenterAdaptLayout.xtype, element: this, cls: "loading-container", items: this._getLoadingTipItems(loadingAnimation), @@ -82,23 +100,28 @@ export class Pane extends Widget { _getLoadingTipItems(loadingTip) { const o = this.options; - const loadingTipItems = [{ - type: "bi.horizontal_adapt", - items: [loadingTip], - }]; - isNotEmptyString(o.loadingText) && loadingTipItems.push({ - type: "bi.text", - text: o.loadingText, - tgap: this._getSize(10), - }); + const loadingTipItems = [ + { + type: HorizontalAdaptLayout.xtype, + items: [loadingTip], + } + ]; + isNotEmptyString(o.loadingText) && + loadingTipItems.push({ + type: Text.xtype, + text: o.loadingText, + tgap: this._getSize(10), + }); - return [{ - type: "bi.vertical", - ref: _ref => { - this._loading = _ref; - }, - items: loadingTipItems, - }]; + return [ + { + type: VerticalLayout.xtype, + ref: _ref => { + this._loading = _ref; + }, + items: loadingTipItems, + } + ]; } loaded() { diff --git a/src/base/collection/collection.js b/src/base/collection/collection.js index 0cd227204..8bf7f2274 100644 --- a/src/base/collection/collection.js +++ b/src/base/collection/collection.js @@ -1,3 +1,25 @@ +import { + VerticalLayout, + AbsoluteLayout, + Widget, + shortcut, + extend, + emptyFn, + debounce, + _lazyCreateWidget, + isFunction, + SectionManager, + isNull, + each, + clamp, + toArray, + invert, + min, + max, + nextTick +} from "@/core"; +import { Label } from "../single"; + /** * CollectionView * @@ -5,7 +27,7 @@ * @class BI.CollectionView * @extends BI.Widget */ -import { Widget, shortcut, extend, emptyFn, debounce, _lazyCreateWidget, isFunction, SectionManager, isNull, each, clamp, toArray, invert, min, max, nextTick } from "../../core"; + @shortcut() export class CollectionView extends Widget { _defaultConfig() { @@ -19,7 +41,7 @@ export class CollectionView extends Widget { overflowX: true, overflowY: true, el: { - type: "bi.vertical", + type: VerticalLayout.xtype, }, cellSizeAndPositionGetter: emptyFn, horizontalOverscanSize: 0, @@ -45,7 +67,7 @@ export class CollectionView extends Widget { this._scrollLock = false; }, 1000 / 60); this.container = _lazyCreateWidget({ - type: "bi.absolute", + type: AbsoluteLayout.xtype, }); this.element.scroll(() => { if (this._scrollLock === true) { @@ -61,7 +83,8 @@ export class CollectionView extends Widget { }); // 兼容一下 let scrollable = o.scrollable; - const scrollx = o.scrollx, scrolly = o.scrolly; + const scrollx = o.scrollx, + scrolly = o.scrolly; if (overflowX === false) { if (overflowY === false) { scrollable = false; @@ -74,16 +97,18 @@ export class CollectionView extends Widget { } } _lazyCreateWidget(el, { - type: "bi.vertical", + type: VerticalLayout.xtype, element: this, scrollable, scrolly, scrollx, items: [this.container], }); - o.items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { - this.populate(newValue); - }) : o.items; + o.items = isFunction(o.items) + ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); + }) + : o.items; if (o.items.length > 0) { this._calculateSizeAndPositionData(); this._populate(); @@ -109,10 +134,16 @@ export class CollectionView extends Widget { for (let index = 0, len = items.length; index < len; index++) { const cellMetadatum = cellSizeAndPositionGetter(index); - if (isNull(cellMetadatum.height) || isNaN(cellMetadatum.height) || - isNull(cellMetadatum.width) || isNaN(cellMetadatum.width) || - isNull(cellMetadatum.x) || isNaN(cellMetadatum.x) || - isNull(cellMetadatum.y) || isNaN(cellMetadatum.y)) { + if ( + isNull(cellMetadatum.height) || + isNaN(cellMetadatum.height) || + isNull(cellMetadatum.width) || + isNaN(cellMetadatum.width) || + isNull(cellMetadatum.x) || + isNaN(cellMetadatum.x) || + isNull(cellMetadatum.y) || + isNaN(cellMetadatum.y) + ) { throw Error(); } @@ -157,13 +188,21 @@ export class CollectionView extends Widget { const bottom = Math.min(this._height, scrollTop + height + verticalOverscanSize); if (right > 0 && bottom > 0) { // 如果滚动的区间并没有超出渲染的范围 - if (top >= this.renderRange.minY && bottom <= this.renderRange.maxY && left >= this.renderRange.minX && right <= this.renderRange.maxX) { + if ( + top >= this.renderRange.minY && + bottom <= this.renderRange.maxY && + left >= this.renderRange.minX && + right <= this.renderRange.maxX + ) { return; } const childrenToDisplay = this._cellRenderers(bottom - top, right - left, left, top); - const renderedCells = [], renderedKeys = {}, renderedWidgets = {}; + const renderedCells = [], + renderedKeys = {}, + renderedWidgets = {}; // 存储所有的left和top - let lefts = {}, tops = {}; + let lefts = {}, + tops = {}; for (let i = 0, len = childrenToDisplay.length; i < len; i++) { const datum = childrenToDisplay[i]; lefts[datum.x] = datum.x; @@ -176,7 +215,10 @@ export class CollectionView extends Widget { const leftMap = invert(lefts); const topMap = invert(tops); // 存储上下左右四个边界 - const leftBorder = {}, rightBorder = {}, topBorder = {}, bottomBorder = {}; + const leftBorder = {}, + rightBorder = {}, + topBorder = {}, + bottomBorder = {}; function assertMinBorder(border, offset) { if (isNull(border[offset])) { border[offset] = Number.MAX_VALUE; @@ -197,18 +239,26 @@ export class CollectionView extends Widget { // 这里只使用px this.renderedCells[index].el.element.css("left", `${datum.x}px`); this.renderedCells[index].el.element.css("top", `${datum.y}px`); - renderedCells.push(child = this.renderedCells[index]); + renderedCells.push((child = this.renderedCells[index])); } else { const item = itemFormatter(items[datum.index], datum.index); - child = _lazyCreateWidget(extend({ - type: "bi.label", - width: datum.width, - height: datum.height, - }, item, { - cls: `${item.cls || ""} collection-cell${datum.y === 0 ? " first-row" : ""}${datum.x === 0 ? " first-col" : ""}`, - _left: datum.x, - _top: datum.y, - })); + child = _lazyCreateWidget( + extend( + { + type: Label.xtype, + width: datum.width, + height: datum.height, + }, + item, + { + cls: `${item.cls || ""} collection-cell${datum.y === 0 ? " first-row" : ""}${ + datum.x === 0 ? " first-col" : "" + }`, + _left: datum.x, + _top: datum.y, + } + ) + ); renderedCells.push({ el: child, left: `${datum.x}px`, @@ -242,7 +292,9 @@ export class CollectionView extends Widget { renderedWidgets[i] = child; } // 已存在的, 需要添加的和需要删除的 - const existSet = {}, addSet = {}, deleteArray = []; + const existSet = {}, + addSet = {}, + deleteArray = []; each(renderedKeys, (i, key) => { if (this.renderedKeys[i]) { existSet[i] = key; @@ -289,7 +341,8 @@ export class CollectionView extends Widget { const o = this.options; const { overflowX } = this.options; // 兼容一下 - const scrollable = o.scrollable, scrollx = o.scrollx; + const scrollable = o.scrollable, + scrollx = o.scrollx; if (overflowX === false) { return false; } @@ -299,7 +352,7 @@ export class CollectionView extends Widget { if (scrollable === true || scrollable === "xy" || scrollable === "x") { return true; } - + return false; } @@ -307,7 +360,8 @@ export class CollectionView extends Widget { const o = this.options; const { overflowX } = this.options; // 兼容一下 - const scrollable = o.scrollable, scrolly = o.scrolly; + const scrollable = o.scrollable, + scrolly = o.scrolly; if (overflowX === false) { return false; } @@ -317,7 +371,7 @@ export class CollectionView extends Widget { if (scrollable === true || scrollable === "xy" || scrollable === "y") { return true; } - + return false; } @@ -344,8 +398,7 @@ export class CollectionView extends Widget { try { this.element.scrollTop(scrollTop); this.element.scrollLeft(scrollLeft); - } catch (e) { - } + } catch (e) {} this._calculateChildrenToRender(); } setScrollLeft(scrollLeft) { diff --git a/src/base/combination/bubble.js b/src/base/combination/bubble.js index 143b73fe4..c4b143721 100644 --- a/src/base/combination/bubble.js +++ b/src/base/combination/bubble.js @@ -1,8 +1,26 @@ +import { BubblePopupView } from "@/case/combo/bubblecombo/popup.bubble"; +import { + VerticalLayout, + shortcut, + Widget, + Controller, + extend, + nextTick, + createWidget, + each, + defer, + debounce, + delay, + isNull, + isFunction, + contains, + bind +} from "@/core"; + /** * @class BI.Bubble * @extends BI.Widget */ -import { shortcut, Widget, Controller, extend, nextTick, createWidget, each, defer, debounce, delay, isNull, isFunction, contains, bind } from "../../core"; @shortcut() export class Bubble extends Widget { @@ -23,7 +41,7 @@ export class Bubble extends Widget { const conf = super._defaultConfig(...arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-popper", + baseCls: `${conf.baseCls || ""} bi-popper`, attributes: { tabIndex: -1, }, @@ -85,26 +103,32 @@ export class Bubble extends Widget { } }); - this.element.on("mouseenter." + this.getName(), (e) => { + this.element.on(`mouseenter.${this.getName()}`, (e) => { if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid()) { this.element.addClass(hoverClass); } }); - this.element.on("mouseleave." + this.getName(), (e) => { + this.element.on(`mouseleave.${this.getName()}`, (e) => { if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid()) { this.element.removeClass(hoverClass); } }); - createWidget(extend({ - element: this, - scrolly: false, - }, BI.LogicFactory.createLogic("vertical", extend(logic, { - items: [ - { el: this.combo } - ], - })))); - isDefaultInit && (this._assertPopupView()); + createWidget( + extend( + { + element: this, + scrolly: false, + }, + BI.LogicFactory.createLogic( + "vertical", + extend(logic, { + items: [{ el: this.combo }], + }) + ) + ) + ); + isDefaultInit && this._assertPopupView(); } _toggle(e) { @@ -129,39 +153,46 @@ export class Bubble extends Widget { if (stopPropagation) { e.stopPropagation(); } - } + }; let enterPopup = false; const hide = (e) => { - if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid() && toggle === true) { + if ( + this.isEnabled() && + this.isValid() && + this.combo.isEnabled() && + this.combo.isValid() && + toggle === true + ) { this._hideView(e); this.fireEvent(Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", this.combo); this.fireEvent(Bubble.EVENT_COLLAPSE); } - this.popupView && this.popupView.element.off("mouseenter." + this.getName()).off("mouseleave." + this.getName()); + this.popupView && + this.popupView.element.off(`mouseenter.${this.getName()}`).off(`mouseleave.${this.getName()}`); enterPopup = false; - } + }; each(evs, (i, ev) => { let debounced; switch (ev) { case "hover": - this.element.on("mouseenter." + this.getName(), (e) => { + this.element.on(`mouseenter.${this.getName()}`, (e) => { if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid()) { this._popupView(e); this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.combo); this.fireEvent(Bubble.EVENT_EXPAND); } }); - this.element.on("mouseleave." + this.getName(), (e) => { + this.element.on(`mouseleave.${this.getName()}`, (e) => { if (this.popupView) { - this.popupView.element.on("mouseenter." + this.getName(), (e) => { + this.popupView.element.on(`mouseenter.${this.getName()}`, (e) => { enterPopup = true; - this.popupView.element.on("mouseleave." + this.getName(), (e) => { + this.popupView.element.on(`mouseleave.${this.getName()}`, (e) => { hide(e); }); - this.popupView.element.off("mouseenter." + this.getName()); + this.popupView.element.off(`mouseenter.${this.getName()}`); }); defer(() => { if (!enterPopup) { @@ -172,61 +203,79 @@ export class Bubble extends Widget { }); break; case "click": - debounced = debounce((e) => { - if (this.combo.element.__isMouseInBounds__(e)) { - if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid()) { - // if (!o.toggle && this.isViewVisible()) { - // return; - // } - toggle ? this._toggle(e) : this._popupView(e); - if (this.isViewVisible()) { - this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.combo); - this.fireEvent(Bubble.EVENT_EXPAND); - } else { - this.fireEvent(Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", this.combo); - this.fireEvent(Bubble.EVENT_COLLAPSE); + debounced = debounce( + (e) => { + if (this.combo.element.__isMouseInBounds__(e)) { + if ( + this.isEnabled() && + this.isValid() && + this.combo.isEnabled() && + this.combo.isValid() + ) { + // if (!o.toggle && this.isViewVisible()) { + // return; + // } + toggle ? this._toggle(e) : this._popupView(e); + if (this.isViewVisible()) { + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.combo); + this.fireEvent(Bubble.EVENT_EXPAND); + } else { + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", this.combo); + this.fireEvent(Bubble.EVENT_COLLAPSE); + } } } + }, + BI.EVENT_RESPONSE_TIME, + { + leading: true, + trailing: false, } - }, BI.EVENT_RESPONSE_TIME, { - "leading": true, - "trailing": false, - }); - this.element.off(ev + "." + this.getName()).on(ev + "." + this.getName(), (e) => { + ); + this.element.off(`${ev}.${this.getName()}`).on(`${ev}.${this.getName()}`, (e) => { debounced(e); st(e); }); break; case "click-hover": - debounced = debounce((e) => { - if (this.combo.element.__isMouseInBounds__(e)) { - if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid()) { - // if (this.isViewVisible()) { - // return; - // } - this._popupView(e); - if (this.isViewVisible()) { - this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.combo); - this.fireEvent(Bubble.EVENT_EXPAND); + debounced = debounce( + (e) => { + if (this.combo.element.__isMouseInBounds__(e)) { + if ( + this.isEnabled() && + this.isValid() && + this.combo.isEnabled() && + this.combo.isValid() + ) { + // if (this.isViewVisible()) { + // return; + // } + this._popupView(e); + if (this.isViewVisible()) { + this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.combo); + this.fireEvent(Bubble.EVENT_EXPAND); + } } } + }, + BI.EVENT_RESPONSE_TIME, + { + leading: true, + trailing: false, } - }, BI.EVENT_RESPONSE_TIME, { - "leading": true, - "trailing": false, - }); - this.element.off("click." + this.getName()).on("click." + this.getName(), (e) => { + ); + this.element.off(`click.${this.getName()}`).on(`click.${this.getName()}`, (e) => { debounced(e); st(e); }); - this.element.on("mouseleave." + this.getName(), (e) => { + this.element.on(`mouseleave.${this.getName()}`, (e) => { if (this.popupView) { - this.popupView.element.on("mouseenter." + this.getName(), (e) => { + this.popupView.element.on(`mouseenter.${this.getName()}`, (e) => { enterPopup = true; - this.popupView.element.on("mouseleave." + this.getName(), (e) => { + this.popupView.element.on(`mouseleave.${this.getName()}`, (e) => { hide(e); }); - this.popupView.element.off("mouseenter." + this.getName()); + this.popupView.element.off(`mouseenter.${this.getName()}`); }); delay(() => { if (!enterPopup) { @@ -237,7 +286,7 @@ export class Bubble extends Widget { }); break; case "hover-click": - this.element.on("mouseenter." + this.getName(), (e) => { + this.element.on(`mouseenter.${this.getName()}`, (e) => { if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid()) { this._popupView(e); this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.combo); @@ -260,11 +309,15 @@ export class Bubble extends Widget { _assertPopupView() { const { showArrow, value } = this.options; if (isNull(this.popupView)) { - this.popupView = createWidget(isFunction(this.options.popup) ? this.options.popup() : this.options.popup, { - type: "bi.bubble_popup_view", - showArrow, - value, - }, this); + this.popupView = createWidget( + isFunction(this.options.popup) ? this.options.popup() : this.options.popup, + { + type: BubblePopupView.xtype, + showArrow, + value, + }, + this + ); this.popupView.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { if (type === BI.Events.CLICK) { this.combo.setValue(this.getValue()); @@ -283,12 +336,10 @@ export class Bubble extends Widget { this._assertPopupView(); if (!this._rendered) { createWidget({ - type: "bi.vertical", + type: VerticalLayout.xtype, scrolly: false, - element: isFunction(this.options.container) ? this.options.container() : (this.options.container || this), - items: [ - { el: this.popupView } - ], + element: isFunction(this.options.container) ? this.options.container() : this.options.container || this, + items: [{ el: this.popupView }], }); this._rendered = true; } @@ -299,9 +350,14 @@ export class Bubble extends Widget { // return; // } // BI-10290 公式combo双击公式内容会收起 - if (e && ((skipTriggerChecker !== true && this.element.find(e.target).length > 0) - || (this.popupView && this.popupView.element.find(e.target).length > 0) - || e.target.className === "CodeMirror-cursor" || Widget._renderEngine.createElement(e.target).closest(".CodeMirror-hints").length > 0)) {// BI-9887 CodeMirror的公式弹框需要特殊处理下 + if ( + e && + ((skipTriggerChecker !== true && this.element.find(e.target).length > 0) || + (this.popupView && this.popupView.element.find(e.target).length > 0) || + e.target.className === "CodeMirror-cursor" || + Widget._renderEngine.createElement(e.target).closest(".CodeMirror-hints").length > 0) + ) { + // BI-9887 CodeMirror的公式弹框需要特殊处理下 const directions = this.options.direction.split(","); if (contains(directions, "innerLeft") || contains(directions, "innerRight")) { // popup可以出现在trigger内部的combo,滚动时不需要消失,而是调整位置 @@ -344,13 +400,17 @@ export class Bubble extends Widget { this.element.removeClass(this.options.comboClass); - Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()).unbind("mousewheel." + this.getName()); - BI.EVENT_BLUR && hideWhenBlur && Widget._renderEngine.createElement(window).unbind("blur." + this.getName()); + Widget._renderEngine + .createElement(document) + .unbind(`mousedown.${this.getName()}`) + .unbind(`mousewheel.${this.getName()}`); + BI.EVENT_BLUR && hideWhenBlur && Widget._renderEngine.createElement(window).unbind(`blur.${this.getName()}`); this.fireEvent(Bubble.EVENT_AFTER_HIDEVIEW); } _popupView(e) { - const { adjustXOffset, showArrow, adjustYOffset, adjustLength, placement, hideWhenClickOutside, hideWhenBlur } = this.options; + const { adjustXOffset, showArrow, adjustYOffset, adjustLength, placement, hideWhenClickOutside, hideWhenBlur } = + this.options; this._assertPopupViewRender(); this.fireEvent(Bubble.EVENT_BEFORE_POPUPVIEW); // popupVisible是为了获取其宽高, 放到可视范围之外以防止在IE下闪一下 @@ -365,11 +425,9 @@ export class Bubble extends Widget { { name: "offset", options: { - offset: () => { - return [adjustXOffset, (showArrow ? 12 : 0) + (adjustYOffset + adjustLength)]; - }, + offset: () => [adjustXOffset, (showArrow ? 12 : 0) + (adjustYOffset + adjustLength)], }, - } + }, ]; if (this.options.showArrow) { modifiers.push({ @@ -389,11 +447,14 @@ export class Bubble extends Widget { // this.adjustHeight(e); this.element.addClass(this.options.comboClass); - hideWhenClickOutside && Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()); - BI.EVENT_BLUR && hideWhenBlur && Widget._renderEngine.createElement(window).unbind("blur." + this.getName()); - - hideWhenClickOutside && Widget._renderEngine.createElement(document).bind("mousedown." + this.getName(), bind(this._hideIf, this)); - BI.EVENT_BLUR && hideWhenBlur && Widget._renderEngine.createElement(window).bind("blur." + this.getName(), bind(this._hideIf, this)); + hideWhenClickOutside && Widget._renderEngine.createElement(document).unbind(`mousedown.${this.getName()}`); + BI.EVENT_BLUR && hideWhenBlur && Widget._renderEngine.createElement(window).unbind(`blur.${this.getName()}`); + + hideWhenClickOutside && + Widget._renderEngine.createElement(document).bind(`mousedown.${this.getName()}`, bind(this._hideIf, this)); + BI.EVENT_BLUR && + hideWhenBlur && + Widget._renderEngine.createElement(window).bind(`blur.${this.getName()}`, bind(this._hideIf, this)); this.fireEvent(Bubble.EVENT_AFTER_POPUPVIEW); } @@ -425,9 +486,7 @@ export class Bubble extends Widget { } } - adjustHeight() { - - } + adjustHeight() {} resetListHeight(h) { this._assertPopupView(); @@ -501,13 +560,13 @@ export class Bubble extends Widget { } destroyed() { - Widget._renderEngine.createElement(document) - .unbind("click." + this.getName()) - .unbind("mousedown." + this.getName()) - .unbind("mouseenter." + this.getName()) - .unbind("mouseleave." + this.getName()); - Widget._renderEngine.createElement(window) - .unbind("blur." + this.getName()); + Widget._renderEngine + .createElement(document) + .unbind(`click.${this.getName()}`) + .unbind(`mousedown.${this.getName()}`) + .unbind(`mouseenter.${this.getName()}`) + .unbind(`mouseleave.${this.getName()}`); + Widget._renderEngine.createElement(window).unbind(`blur.${this.getName()}`); this.popper && this.popper.destroy(); this.popper = null; this.popupView && this.popupView._destroy(); diff --git a/src/base/combination/combo.js b/src/base/combination/combo.js index 16d3f6468..187875fa8 100644 --- a/src/base/combination/combo.js +++ b/src/base/combination/combo.js @@ -1,12 +1,25 @@ +import { PopupView } from "../layer"; +import { Bubble } from "./bubble"; +import { + shortcut, + Widget, + Controller, + extend, + createWidget, + nextTick, + bind, + isNotNull, + isNull, + isFunction, + each +} from "@/core"; +import { Resizers } from "@/base/0.base"; + /** * @class BI.Combo * @extends BI.Widget */ -import { shortcut, Widget, Controller, extend, createWidget, nextTick, bind, isNotNull, isNull, isFunction, each } from "../../core"; -import { Bubble } from "./bubble"; -import { Resizers } from "../0.base"; - let needHideWhenAnotherComboOpen = {}; let currentOpenedCombos = {}; @@ -29,7 +42,7 @@ export class Combo extends Bubble { const conf = super._defaultConfig(...arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-combo" + (BI.isIE() ? " hack" : ""), + baseCls: `${conf.baseCls || ""} bi-combo${BI.isIE() ? " hack" : ""}`, attributes: { tabIndex: -1, }, @@ -96,42 +109,55 @@ export class Combo extends Bubble { } }); - this.element.on("mouseenter." + this.getName(), (e) => { + this.element.on(`mouseenter.${this.getName()}`, e => { if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid()) { this.element.addClass(hoverClass); } }); - this.element.on("mouseleave." + this.getName(), (e) => { + this.element.on(`mouseleave.${this.getName()}`, e => { if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid()) { this.element.removeClass(hoverClass); } }); - createWidget(extend({ - element: this, - scrolly: false, - }, BI.LogicFactory.createLogic("vertical", extend(logic, { - items: [ - { el: this.combo } - ], - })))); - isDefaultInit && (this._assertPopupView()); - Resizers.add(this.getName(), bind((e) => { - // 如果resize对象是combo的子元素,则不应该收起,或交由hideChecker去处理 - if (this.isViewVisible()) { - isNotNull(e) ? this._hideIf(e) : this._hideView(); - } - }, this)); + createWidget( + extend( + { + element: this, + scrolly: false, + }, + BI.LogicFactory.createLogic( + "vertical", + extend(logic, { + items: [{ el: this.combo }], + }) + ) + ) + ); + isDefaultInit && this._assertPopupView(); + Resizers.add( + this.getName(), + bind(e => { + // 如果resize对象是combo的子元素,则不应该收起,或交由hideChecker去处理 + if (this.isViewVisible()) { + isNotNull(e) ? this._hideIf(e) : this._hideView(); + } + }, this) + ); } _assertPopupView() { const { showArrow, value, hideWhenClickOutside, hideWhenBlur } = this.options; if (isNull(this.popupView)) { - this.popupView = createWidget(isFunction(this.options.popup) ? this.options.popup() : this.options.popup, { - type: "bi.popup_view", - showArrow, - value, - }, this); + this.popupView = createWidget( + isFunction(this.options.popup) ? this.options.popup() : this.options.popup, + { + type: PopupView.xtype, + showArrow, + value, + }, + this + ); this.popupView.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { if (type === BI.Events.CLICK) { this.combo.setValue(this.getValue()); @@ -167,8 +193,12 @@ export class Combo extends Bubble { delete needHideWhenAnotherComboOpen[this.getName()]; delete currentOpenedCombos[this.getName()]; - hideWhenClickOutside && Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()).unbind("mousewheel." + this.getName()); - BI.EVENT_BLUR && hideWhenBlur && Widget._renderEngine.createElement(window).unbind("blur." + this.getName()); + hideWhenClickOutside && + Widget._renderEngine + .createElement(document) + .unbind(`mousedown.${this.getName()}`) + .unbind(`mousewheel.${this.getName()}`); + BI.EVENT_BLUR && hideWhenBlur && Widget._renderEngine.createElement(window).unbind(`blur.${this.getName()}`); this.fireEvent(Combo.EVENT_AFTER_HIDEVIEW, e); } @@ -192,119 +222,272 @@ export class Combo extends Bubble { this.adjustHeight(e); this.element.addClass(this.options.comboClass); - hideWhenClickOutside && Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()).unbind("mousewheel." + this.getName()); - hideWhenClickOutside && Widget._renderEngine.createElement(document).unbind("mousewheel." + this.getName()); - BI.EVENT_BLUR && hideWhenBlur && Widget._renderEngine.createElement(window).unbind("blur." + this.getName()); + hideWhenClickOutside && + Widget._renderEngine + .createElement(document) + .unbind(`mousedown.${this.getName()}`) + .unbind(`mousewheel.${this.getName()}`); + hideWhenClickOutside && Widget._renderEngine.createElement(document).unbind(`mousewheel.${this.getName()}`); + BI.EVENT_BLUR && hideWhenBlur && Widget._renderEngine.createElement(window).unbind(`blur.${this.getName()}`); - hideWhenClickOutside && Widget._renderEngine.createElement(document).bind("mousewheel." + this.getName(), bind(this._hideIf, this)); - hideWhenClickOutside && Widget._renderEngine.createElement(document).bind("mousedown." + this.getName(), bind(this._hideIf, this)).bind("mousewheel." + this.getName(), bind(this._hideIf, this)); - BI.EVENT_BLUR && hideWhenBlur && Widget._renderEngine.createElement(window).bind("blur." + this.getName(), bind(this._hideIf, this)); + hideWhenClickOutside && + Widget._renderEngine.createElement(document).bind(`mousewheel.${this.getName()}`, bind(this._hideIf, this)); + hideWhenClickOutside && + Widget._renderEngine + .createElement(document) + .bind(`mousedown.${this.getName()}`, bind(this._hideIf, this)) + .bind(`mousewheel.${this.getName()}`, bind(this._hideIf, this)); + BI.EVENT_BLUR && + hideWhenBlur && + Widget._renderEngine.createElement(window).bind(`blur.${this.getName()}`, bind(this._hideIf, this)); this.fireEvent(Combo.EVENT_AFTER_POPUPVIEW); } adjustHeight(e) { - const { belowMouse, supportCSSTransform, container, direction, adjustXOffset, adjustYOffset, adjustLength, showArrow, isNeedAdjustHeight, offsetStyle } = this.options; + const { + belowMouse, + supportCSSTransform, + container, + direction, + adjustXOffset, + adjustYOffset, + adjustLength, + showArrow, + isNeedAdjustHeight, + offsetStyle, + } = this.options; let p = {}; if (!this.popupView) { return; } const isVisible = this.popupView.isVisible(); this.popupView.visible(); - const combo = (belowMouse && isNotNull(e)) ? { - element: { - 0: e.target, - offset: () => { - return { - left: e.pageX, - top: e.pageY, - }; - }, - bounds: () => { - // offset为其相对于父定位元素的偏移 - return { - x: e.offsetX, - y: e.offsetY, - width: 0, - height: 24, - }; - }, - outerWidth: () => { - return 0; - }, - outerHeight: () => { - return 24; - }, - }, - } : this.combo; - const positionRelativeElement = supportCSSTransform ? BI.DOM.getPositionRelativeContainingBlock(isNull(container) ? this.element[0] : Widget._renderEngine.createElement(isFunction(container) ? container() : container)[0]) : null; + const combo = + belowMouse && isNotNull(e) + ? { + element: { + 0: e.target, + offset: () => { + return { + left: e.pageX, + top: e.pageY, + }; + }, + bounds: () => { + // offset为其相对于父定位元素的偏移 + return { + x: e.offsetX, + y: e.offsetY, + width: 0, + height: 24, + }; + }, + outerWidth: () => 0, + outerHeight: () => 24, + }, + } + : this.combo; + const positionRelativeElement = supportCSSTransform + ? BI.DOM.getPositionRelativeContainingBlock( + isNull(container) + ? this.element[0] + : Widget._renderEngine.createElement(isFunction(container) ? container() : container)[0] + ) + : null; const TRIANGLE_LENGTH = 12; switch (direction) { - case "bottom": - case "bottom,right": - p = BI.DOM.getComboPosition(combo, this.popupView, adjustXOffset, (adjustYOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), isNeedAdjustHeight, ["bottom", "top", "right", "left"], offsetStyle, positionRelativeElement); - break; - case "top": - case "top,right": - p = BI.DOM.getComboPosition(combo, this.popupView, adjustXOffset, (adjustYOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), isNeedAdjustHeight, ["top", "bottom", "right", "left"], offsetStyle, positionRelativeElement); - break; - case "left": - case "left,bottom": - p = BI.DOM.getComboPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), adjustYOffset, isNeedAdjustHeight, ["left", "right", "bottom", "top"], offsetStyle, positionRelativeElement); - break; - case "right": - case "right,bottom": - p = BI.DOM.getComboPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), adjustYOffset, isNeedAdjustHeight, ["right", "left", "bottom", "top"], offsetStyle, positionRelativeElement); - break; - case "top,left": - p = BI.DOM.getComboPosition(combo, this.popupView, adjustXOffset, (adjustYOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), isNeedAdjustHeight, ["top", "bottom", "left", "right"], offsetStyle, positionRelativeElement); - break; - case "bottom,left": - p = BI.DOM.getComboPosition(combo, this.popupView, adjustXOffset, (adjustYOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), isNeedAdjustHeight, ["bottom", "top", "left", "right"], offsetStyle, positionRelativeElement); - break; - case "left,top": - p = BI.DOM.getComboPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), adjustYOffset, isNeedAdjustHeight, ["left", "right", "top", "bottom"], offsetStyle, positionRelativeElement); - break; - case "right,top": - p = BI.DOM.getComboPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), adjustYOffset, isNeedAdjustHeight, ["right", "left", "top", "bottom"], offsetStyle, positionRelativeElement); - break; - case "right,innerRight": - p = BI.DOM.getComboPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), adjustYOffset, isNeedAdjustHeight, ["right", "left", "innerRight", "innerLeft", "bottom", "top"], offsetStyle, positionRelativeElement); - break; - case "right,innerLeft": - p = BI.DOM.getComboPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), adjustYOffset, isNeedAdjustHeight, ["right", "left", "innerLeft", "innerRight", "bottom", "top"], offsetStyle, positionRelativeElement); - break; - case "innerRight": - p = BI.DOM.getComboPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), adjustYOffset, isNeedAdjustHeight, ["innerRight", "innerLeft", "right", "left", "bottom", "top"], offsetStyle, positionRelativeElement); - break; - case "innerLeft": - p = BI.DOM.getComboPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), adjustYOffset, isNeedAdjustHeight, ["innerLeft", "innerRight", "left", "right", "bottom", "top"], offsetStyle, positionRelativeElement); - break; - case "top,custom": - case "custom,top": - p = BI.DOM.getTopAdaptPosition(combo, this.popupView, (adjustYOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), isNeedAdjustHeight); - p.dir = "top"; - break; - case "custom,bottom": - case "bottom,custom": - p = BI.DOM.getBottomAdaptPosition(combo, this.popupView, (adjustYOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0), isNeedAdjustHeight); - p.dir = "bottom"; - break; - case "left,custom": - case "custom,left": - p = BI.DOM.getLeftAdaptPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0)); - delete p.top; - delete p.adaptHeight; - p.dir = "left"; - break; - case "custom,right": - case "right,custom": - p = BI.DOM.getRightAdaptPosition(combo, this.popupView, (adjustXOffset + adjustLength) + (showArrow ? TRIANGLE_LENGTH : 0)); - delete p.top; - delete p.adaptHeight; - p.dir = "right"; - break; - default: - break; + case "bottom": + case "bottom,right": + p = BI.DOM.getComboPosition( + combo, + this.popupView, + adjustXOffset, + adjustYOffset + adjustLength + (showArrow ? TRIANGLE_LENGTH : 0), + isNeedAdjustHeight, + ["bottom", "top", "right", "left"], + offsetStyle, + positionRelativeElement + ); + break; + case "top": + case "top,right": + p = BI.DOM.getComboPosition( + combo, + this.popupView, + adjustXOffset, + adjustYOffset + adjustLength + (showArrow ? TRIANGLE_LENGTH : 0), + isNeedAdjustHeight, + ["top", "bottom", "right", "left"], + offsetStyle, + positionRelativeElement + ); + break; + case "left": + case "left,bottom": + p = BI.DOM.getComboPosition( + combo, + this.popupView, + adjustXOffset + adjustLength + (showArrow ? TRIANGLE_LENGTH : 0), + adjustYOffset, + isNeedAdjustHeight, + ["left", "right", "bottom", "top"], + offsetStyle, + positionRelativeElement + ); + break; + case "right": + case "right,bottom": + p = BI.DOM.getComboPosition( + combo, + this.popupView, + adjustXOffset + adjustLength + (showArrow ? TRIANGLE_LENGTH : 0), + adjustYOffset, + isNeedAdjustHeight, + ["right", "left", "bottom", "top"], + offsetStyle, + positionRelativeElement + ); + break; + case "top,left": + p = BI.DOM.getComboPosition( + combo, + this.popupView, + adjustXOffset, + adjustYOffset + adjustLength + (showArrow ? TRIANGLE_LENGTH : 0), + isNeedAdjustHeight, + ["top", "bottom", "left", "right"], + offsetStyle, + positionRelativeElement + ); + break; + case "bottom,left": + p = BI.DOM.getComboPosition( + combo, + this.popupView, + adjustXOffset, + adjustYOffset + adjustLength + (showArrow ? TRIANGLE_LENGTH : 0), + isNeedAdjustHeight, + ["bottom", "top", "left", "right"], + offsetStyle, + positionRelativeElement + ); + break; + case "left,top": + p = BI.DOM.getComboPosition( + combo, + this.popupView, + adjustXOffset + adjustLength + (showArrow ? TRIANGLE_LENGTH : 0), + adjustYOffset, + isNeedAdjustHeight, + ["left", "right", "top", "bottom"], + offsetStyle, + positionRelativeElement + ); + break; + case "right,top": + p = BI.DOM.getComboPosition( + combo, + this.popupView, + adjustXOffset + adjustLength + (showArrow ? TRIANGLE_LENGTH : 0), + adjustYOffset, + isNeedAdjustHeight, + ["right", "left", "top", "bottom"], + offsetStyle, + positionRelativeElement + ); + break; + case "right,innerRight": + p = BI.DOM.getComboPosition( + combo, + this.popupView, + adjustXOffset + adjustLength + (showArrow ? TRIANGLE_LENGTH : 0), + adjustYOffset, + isNeedAdjustHeight, + ["right", "left", "innerRight", "innerLeft", "bottom", "top"], + offsetStyle, + positionRelativeElement + ); + break; + case "right,innerLeft": + p = BI.DOM.getComboPosition( + combo, + this.popupView, + adjustXOffset + adjustLength + (showArrow ? TRIANGLE_LENGTH : 0), + adjustYOffset, + isNeedAdjustHeight, + ["right", "left", "innerLeft", "innerRight", "bottom", "top"], + offsetStyle, + positionRelativeElement + ); + break; + case "innerRight": + p = BI.DOM.getComboPosition( + combo, + this.popupView, + adjustXOffset + adjustLength + (showArrow ? TRIANGLE_LENGTH : 0), + adjustYOffset, + isNeedAdjustHeight, + ["innerRight", "innerLeft", "right", "left", "bottom", "top"], + offsetStyle, + positionRelativeElement + ); + break; + case "innerLeft": + p = BI.DOM.getComboPosition( + combo, + this.popupView, + adjustXOffset + adjustLength + (showArrow ? TRIANGLE_LENGTH : 0), + adjustYOffset, + isNeedAdjustHeight, + ["innerLeft", "innerRight", "left", "right", "bottom", "top"], + offsetStyle, + positionRelativeElement + ); + break; + case "top,custom": + case "custom,top": + p = BI.DOM.getTopAdaptPosition( + combo, + this.popupView, + adjustYOffset + adjustLength + (showArrow ? TRIANGLE_LENGTH : 0), + isNeedAdjustHeight + ); + p.dir = "top"; + break; + case "custom,bottom": + case "bottom,custom": + p = BI.DOM.getBottomAdaptPosition( + combo, + this.popupView, + adjustYOffset + adjustLength + (showArrow ? TRIANGLE_LENGTH : 0), + isNeedAdjustHeight + ); + p.dir = "bottom"; + break; + case "left,custom": + case "custom,left": + p = BI.DOM.getLeftAdaptPosition( + combo, + this.popupView, + adjustXOffset + adjustLength + (showArrow ? TRIANGLE_LENGTH : 0) + ); + delete p.top; + delete p.adaptHeight; + p.dir = "left"; + break; + case "custom,right": + case "right,custom": + p = BI.DOM.getRightAdaptPosition( + combo, + this.popupView, + adjustXOffset + adjustLength + (showArrow ? TRIANGLE_LENGTH : 0) + ); + delete p.top; + delete p.adaptHeight; + p.dir = "right"; + break; + default: + break; } if ("adaptHeight" in p) { @@ -313,17 +496,17 @@ export class Combo extends Bubble { const width = this.combo.element.outerWidth(); const height = this.combo.element.outerHeight(); - this.popupView.setDirection && this.popupView.setDirection(p.dir, { - width, - height, - offsetStyle, - adjustXOffset, - adjustYOffset, - offset: this.combo.element.offset(), - }); + this.popupView.setDirection && + this.popupView.setDirection(p.dir, { + width, + height, + offsetStyle, + adjustXOffset, + adjustYOffset, + offset: this.combo.element.offset(), + }); if (supportCSSTransform) { - const positonedRect = positionRelativeElement.getBoundingClientRect(); const scaleX = positonedRect.width / positionRelativeElement.offsetWidth; @@ -348,14 +531,14 @@ export class Combo extends Bubble { } destroyed() { - Widget._renderEngine.createElement(document) - .unbind("click." + this.getName()) - .unbind("mousedown." + this.getName()) - .unbind("mousewheel." + this.getName()) - .unbind("mouseenter." + this.getName()) - .unbind("mouseleave." + this.getName()); - Widget._renderEngine.createElement(window) - .unbind("blur." + this.getName()); + Widget._renderEngine + .createElement(document) + .unbind(`click.${this.getName()}`) + .unbind(`mousedown.${this.getName()}`) + .unbind(`mousewheel.${this.getName()}`) + .unbind(`mouseenter.${this.getName()}`) + .unbind(`mouseleave.${this.getName()}`); + Widget._renderEngine.createElement(window).unbind(`blur.${this.getName()}`); Resizers.remove(this.getName()); this.popupView && this.popupView._destroy(); delete needHideWhenAnotherComboOpen[this.getName()]; diff --git a/src/base/combination/expander.js b/src/base/combination/expander.js index 8f7158470..3b56a5801 100644 --- a/src/base/combination/expander.js +++ b/src/base/combination/expander.js @@ -1,3 +1,17 @@ +import { + VerticalLayout, + shortcut, + Widget, + Controller, + extend, + nextTick, + each, + debounce, + isNull, + createWidget +} from "@/core"; +import { ButtonGroup } from "./group.button"; + /** * * 某个可以展开的节点 @@ -6,7 +20,6 @@ * @class BI.Expander * @extends BI.Widget */ -import { shortcut, Widget, Controller, extend, nextTick, each, debounce, isNull, createWidget } from "../../core"; @shortcut() export class Expander extends Widget { @@ -67,22 +80,23 @@ export class Expander extends Widget { } }); - this.element.hover(() => { - if (this.isEnabled() && this.isValid() && this.expander.isEnabled() && this.expander.isValid()) { - this.element.addClass(hoverClass); - } - }, () => { - if (this.isEnabled() && this.isValid() && this.expander.isEnabled() && this.expander.isValid()) { - this.element.removeClass(hoverClass); + this.element.hover( + () => { + if (this.isEnabled() && this.isValid() && this.expander.isEnabled() && this.expander.isValid()) { + this.element.addClass(hoverClass); + } + }, + () => { + if (this.isEnabled() && this.isValid() && this.expander.isEnabled() && this.expander.isValid()) { + this.element.removeClass(hoverClass); + } } - }); + ); createWidget({ - type: "bi.vertical", + type: VerticalLayout.xtype, scrolly: false, element: this, - items: [ - { el: this.expander } - ], + items: [{ el: this.expander }], }); isDefaultInit && this._assertPopupView(); if (this.expander.isOpened() === true) { @@ -106,44 +120,80 @@ export class Expander extends Widget { const evs = this.options.trigger.split(","); each(evs, (i, e) => { switch (e) { - case "hover": - this.element[e]((e) => { - if (this.isEnabled() && this.isValid() && this.expander.isEnabled() && this.expander.isValid()) { + case "hover": + this.element[e]( + e => { + if ( + this.isEnabled() && + this.isValid() && + this.expander.isEnabled() && + this.expander.isValid() + ) { this._popupView(); this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.expander); this.fireEvent(Expander.EVENT_EXPAND); } - }, () => { - if (this.isEnabled() && this.isValid() && this.expander.isEnabled() && this.expander.isValid() && toggle) { + }, + () => { + if ( + this.isEnabled() && + this.isValid() && + this.expander.isEnabled() && + this.expander.isValid() && + toggle + ) { this._hideView(); this.fireEvent(Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", this.expander); this.fireEvent(Expander.EVENT_COLLAPSE); } - }); - break; - case "click": - if (e) { - this.element.off(e + "." + this.getName()).on(e + "." + this.getName(), debounce((e) => { - if (this.expander.element.__isMouseInBounds__(e)) { - if (this.isEnabled() && this.isValid() && this.expander.isEnabled() && this.expander.isValid()) { - toggle ? this._toggle() : this._popupView(); - if (this.isExpanded()) { - this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.expander); - this.fireEvent(Expander.EVENT_EXPAND); - } else { - this.fireEvent(Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", this.expander); - this.fireEvent(Expander.EVENT_COLLAPSE); + } + ); + break; + case "click": + if (e) { + this.element.off(`${e}.${this.getName()}`).on( + `${e}.${this.getName()}`, + debounce( + e => { + if (this.expander.element.__isMouseInBounds__(e)) { + if ( + this.isEnabled() && + this.isValid() && + this.expander.isEnabled() && + this.expander.isValid() + ) { + toggle ? this._toggle() : this._popupView(); + if (this.isExpanded()) { + this.fireEvent( + Controller.EVENT_CHANGE, + BI.Events.EXPAND, + "", + this.expander + ); + this.fireEvent(Expander.EVENT_EXPAND); + } else { + this.fireEvent( + Controller.EVENT_CHANGE, + BI.Events.COLLAPSE, + "", + this.expander + ); + this.fireEvent(Expander.EVENT_COLLAPSE); + } } } + }, + BI.EVENT_RESPONSE_TIME, + { + leading: true, + trailing: false, } - }, BI.EVENT_RESPONSE_TIME, { - "leading": true, - "trailing": false, - })); - } - break; - default: - break; + ) + ); + } + break; + default: + break; } }); } @@ -155,17 +205,23 @@ export class Expander extends Widget { _assertPopupView() { const { value } = this.options; if (isNull(this.popupView)) { - this.popupView = createWidget(this.options.popup, { - type: "bi.button_group", - cls: "expander-popup", - layouts: [{ - type: "bi.vertical", - hgap: 0, - vgap: 0, - }], - value, - }, this); - this.popupView.on(Controller.EVENT_CHANGE, (type, value, obj, ...args)=> { + this.popupView = createWidget( + this.options.popup, + { + type: ButtonGroup.xtype, + cls: "expander-popup", + layouts: [ + { + type: VerticalLayout.xtype, + hgap: 0, + vgap: 0, + } + ], + value, + }, + this + ); + this.popupView.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); if (type === BI.Events.CLICK) { // self.setValue(self.getValue()); @@ -183,12 +239,10 @@ export class Expander extends Widget { this._assertPopupView(); if (!this._rendered) { createWidget({ - type: "bi.vertical", + type: VerticalLayout.xtype, scrolly: false, element: this, - items: [ - { el: this.popupView } - ], + items: [{ el: this.popupView }], }); this._rendered = true; } @@ -281,7 +335,7 @@ export class Expander extends Widget { if (this.expander.getValue() === value) { return this.expander; } - + return this.popupView && this.popupView.getNodeByValue(value); } diff --git a/src/base/combination/group.button.js b/src/base/combination/group.button.js index 814ce099e..5dca70655 100644 --- a/src/base/combination/group.button.js +++ b/src/base/combination/group.button.js @@ -1,9 +1,38 @@ +import { + CenterLayout, + shortcut, + Widget, + Controller, + extend, + createWidget, + createWidgets, + each, + isFunction, + isKey, + isNotEmptyArray, + createItems, + isArray, + remove, + map, + stripEL, + makeArrayByArray, + clone, + deepClone, + formatEL, + isEmpty, + concat, + removeAt, + deepContains, + has, + any +} from "@/core"; +import { TextButton } from "../single"; + /** * Created by GUY on 2015/6/26. * @class BI.ButtonGroup * @extends BI.Widget */ -import { shortcut, Widget, Controller, extend, createWidget, createWidgets, each, isFunction, isKey, isNotEmptyArray, createItems, isArray, remove, map, stripEL, makeArrayByArray, clone, deepClone, formatEL, isEmpty, concat, removeAt, deepContains, has, any } from "../../core"; @shortcut() export class ButtonGroup extends Widget { @@ -18,11 +47,13 @@ export class ButtonGroup extends Widget { items: [], value: "", chooseType: BI.Selection.Single, - layouts: [{ - type: "bi.center", - hgap: 0, - vgap: 0, - }], + layouts: [ + { + type: CenterLayout.xtype, + hgap: 0, + vgap: 0, + } + ], }); } @@ -35,13 +66,17 @@ export class ButtonGroup extends Widget { }); }); this.behaviors = behaviors; - const items = isFunction(optionsItems) ? this.__watch(optionsItems, (context, newValue) => { - this.populate(newValue); - }) : optionsItems; + const items = isFunction(optionsItems) + ? this.__watch(optionsItems, (context, newValue) => { + this.populate(newValue); + }) + : optionsItems; this.populate(items); - this.options.value = isFunction(value) ? this.__watch(value, (context, newValue) => { - this.setValue(newValue); - }) : value; + this.options.value = isFunction(value) + ? this.__watch(value, (context, newValue) => { + this.setValue(newValue); + }) + : value; if (isKey(value) || isNotEmptyArray(value)) { this.setValue(value); } @@ -50,9 +85,11 @@ export class ButtonGroup extends Widget { _createBtns(items) { let btns; Widget.execWithContext(this, () => { - btns = createWidgets(createItems(items, { - type: "bi.text_button", - })); + btns = createWidgets( + createItems(items, { + type: TextButton.xtype, + }) + ); }); return btns; @@ -99,13 +136,15 @@ export class ButtonGroup extends Widget { const { layouts: optionsLayouts } = this.options; const layouts = isArray(optionsLayouts) ? optionsLayouts : [optionsLayouts]; for (let i = layouts.length - 1; i > 0; i--) { - btns = map(btns, (k, it) => extend({}, layouts[i], { - items: [ - extend({}, layouts[i].el, { - el: it, - }) - ], - })); + btns = map(btns, (k, it) => + extend({}, layouts[i], { + items: [ + extend({}, layouts[i].el, { + el: it, + }) + ], + }) + ); } return btns; @@ -146,7 +185,7 @@ export class ButtonGroup extends Widget { _isSimpleLayout() { const { layouts, items } = this.options; - return isArray(layouts) ? (layouts.length === 1 && !isArray(items[0])) : true; + return isArray(layouts) ? layouts.length === 1 && !isArray(items[0]) : true; } doBehavior() { diff --git a/src/base/combination/group.combo.js b/src/base/combination/group.combo.js index 0fc637511..2987728e6 100644 --- a/src/base/combination/group.combo.js +++ b/src/base/combination/group.combo.js @@ -1,9 +1,23 @@ +import { TextButton } from "../single"; +import { ButtonTree } from "./tree.button"; +import { + VerticalLayout, + shortcut, + Widget, + Controller, + extend, + isEmpty, + each, + formatEL, + clone, + createWidget +} from "@/core"; +import { Combo } from "./combo"; + /** * Created by GUY on 2015/8/10. */ -import { shortcut, Widget, Controller, extend, isEmpty, each, formatEL, clone, createWidget } from "../../core"; - @shortcut() export class ComboGroup extends Widget { static xtype = "bi.combo_group"; @@ -22,16 +36,18 @@ export class ComboGroup extends Widget { isNeedAdjustHeight: false, isNeedAdjustWidth: false, - el: { type: "bi.text_button", text: "", value: "" }, + el: { type: TextButton.xtype, text: "", value: "" }, items: [], popup: { el: { - type: "bi.button_tree", + type: ButtonTree.xtype, chooseType: 0, - layouts: [{ - type: "bi.vertical", - }], + layouts: [ + { + type: VerticalLayout.xtype, + } + ], }, }, }); @@ -42,7 +58,19 @@ export class ComboGroup extends Widget { } _populate(item) { - const { items, action, height, direction, isDefaultInit, isNeedAdjustHeight, isNeedAdjustWidth, adjustLength, popup, container, trigger } = this.options; + const { + items, + action, + height, + direction, + isDefaultInit, + isNeedAdjustHeight, + isNeedAdjustWidth, + adjustLength, + popup, + container, + trigger, + } = this.options; const children = items; if (isEmpty(children)) { throw new Error("ComboGroup构造错误"); @@ -65,7 +93,7 @@ export class ComboGroup extends Widget { } }); this.combo = createWidget({ - type: "bi.combo", + type: Combo.xtype, element: this, container, height, @@ -77,9 +105,12 @@ export class ComboGroup extends Widget { adjustLength, el: item, popup: extend({}, popup, { - el: extend({ - items: children, - }, popup.el), + el: extend( + { + items: children, + }, + popup.el + ), }), }); this.combo.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { diff --git a/src/base/combination/group.virtual.js b/src/base/combination/group.virtual.js index a7e87c92c..5b7cd7e32 100644 --- a/src/base/combination/group.virtual.js +++ b/src/base/combination/group.virtual.js @@ -1,32 +1,54 @@ -import { shortcut, Widget, Controller, extend, isFunction, isKey, isArray, map, stripEL, deepClone, formatEL, isEmpty, each, createWidget } from "../../core"; +import { + CenterLayout, + shortcut, + Widget, + Controller, + extend, + isFunction, + isKey, + isArray, + map, + stripEL, + deepClone, + formatEL, + isEmpty, + each, + createWidget +} from "@/core"; @shortcut() export class VirtualGroup extends Widget { static xtype = "bi.virtual_group"; static EVENT_CHANGE = "EVENT_CHANGE"; - + _defaultConfig() { return extend(super._defaultConfig(...arguments), { baseCls: "bi-virtual-group", items: [], - layouts: [{ - type: "bi.center", - hgap: 0, - vgap: 0, - }], + layouts: [ + { + type: CenterLayout.xtype, + hgap: 0, + vgap: 0, + } + ], }); } render() { const { items: optionsItems, value } = this.options; - const items = isFunction(optionsItems) ? this.__watch(optionsItems, (context, newValue) => { - this.populate(newValue); - }) : optionsItems; + const items = isFunction(optionsItems) + ? this.__watch(optionsItems, (context, newValue) => { + this.populate(newValue); + }) + : optionsItems; this.populate(items); - this.options.value = isFunction(value) ? this.__watch(value, (context, newValue) => { - this.setValue(newValue); - }) : value; + this.options.value = isFunction(value) + ? this.__watch(value, (context, newValue) => { + this.setValue(newValue); + }) + : value; if (isKey(value)) { this.setValue(value); } @@ -34,7 +56,7 @@ export class VirtualGroup extends Widget { _packageBtns(items) { const o = this.options; - const map = this.buttonMap = {}; + const map = (this.buttonMap = {}); const layouts = isArray(o.layouts) ? o.layouts : [o.layouts]; for (let i = layouts.length - 1; i > 0; i--) { items = map(items, (k, it) => { @@ -43,19 +65,22 @@ export class VirtualGroup extends Widget { return extend({}, layouts[i], { items: [ extend({}, layouts[i].el, { - el: extend({ - ref: (_ref) => { - if (isKey(map[el.value])) { - map[el.value] = _ref; - } + el: extend( + { + ref: _ref => { + if (isKey(map[el.value])) { + map[el.value] = _ref; + } + }, }, - }, el), + el + ), }) ], }); }); } - + return items; } diff --git a/src/base/combination/index.js b/src/base/combination/index.js index 0a3b52bd1..d2a5bee80 100644 --- a/src/base/combination/index.js +++ b/src/base/combination/index.js @@ -9,4 +9,4 @@ export { Navigation } from "./navigation"; export { Searcher } from "./searcher"; export { Switcher } from "./switcher"; export { Tab } from "./tab"; -export { ButtonTree } from "./tree.button"; \ No newline at end of file +export { ButtonTree } from "./tree.button"; diff --git a/src/base/combination/loader.js b/src/base/combination/loader.js index 7cabb8f61..3c4998e90 100644 --- a/src/base/combination/loader.js +++ b/src/base/combination/loader.js @@ -1,3 +1,22 @@ +import { ButtonGroup } from "./group.button"; +import { LoadingBar } from "../single"; +import { + VerticalLayout, + shortcut, + Widget, + Controller, + extend, + createWidget, + isEmpty, + nextTick, + bind, + isFunction, + isNotEmptyArray, + isNumber, + isObject, + each +} from "@/core"; + /** * 加载控件 * @@ -5,12 +24,11 @@ * @class BI.Loader * @extends BI.Widget */ -import { shortcut, Widget, Controller, extend, createWidget, isEmpty, nextTick, bind, isFunction, isNotEmptyArray, isNumber, isObject, each } from "../../core"; @shortcut() export class Loader extends Widget { static xtype = "bi.loader"; - + static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { @@ -26,7 +44,7 @@ export class Loader extends Widget { // 下面是button_group的属性 el: { - type: "bi.button_group", + type: ButtonGroup.xtype, }, items: [], @@ -45,32 +63,53 @@ export class Loader extends Widget { _prevLoad() { const o = this.options; this.prev.setLoading(); - o.itemsCreator.apply(this, [{ times: --this.times }, (...args) => { - this.prev.setLoaded(); - this.prependItems.apply(this, args); - }]); + o.itemsCreator.apply(this, [ + { times: --this.times }, + (...args) => { + this.prev.setLoaded(); + this.prependItems.apply(this, args); + } + ]); } _nextLoad() { const o = this.options; this.next.setLoading(); - o.itemsCreator.apply(this, [{ times: ++this.times }, (...args) => { - this.next.setLoaded(); - this.addItems.apply(this, args); - }]); + o.itemsCreator.apply(this, [ + { times: ++this.times }, + (...args) => { + this.next.setLoaded(); + this.addItems.apply(this, args); + } + ]); } render() { - const { itemsCreator, prev, next, el, items: optionsItems, value, direction, logic, isDefaultInit } = this.options; + const { + itemsCreator, + prev, + next, + el, + items: optionsItems, + value, + direction, + logic, + isDefaultInit, + } = this.options; if (itemsCreator === false) { prev = false; next = false; } if (prev !== false) { - this.prev = createWidget(extend({ - type: "bi.loading_bar", - }, prev)); - this.prev.on(Controller.EVENT_CHANGE, (type) => { + this.prev = createWidget( + extend( + { + type: LoadingBar.xtype, + }, + prev + ) + ); + this.prev.on(Controller.EVENT_CHANGE, type => { if (type === BI.Events.CLICK) { this._prevLoad(); } @@ -78,13 +117,15 @@ export class Loader extends Widget { } this.button_group = createWidget(el, { - type: "bi.button_group", + type: ButtonGroup.xtype, chooseType: 0, items: optionsItems, behaviors: {}, - layouts: [{ - type: "bi.vertical", - }], + layouts: [ + { + type: VerticalLayout.xtype, + } + ], value, }); this.button_group.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { @@ -95,30 +136,58 @@ export class Loader extends Widget { }); if (next !== false) { - this.next = createWidget(extend({ - type: "bi.loading_bar", - }, next)); - this.next.on(Controller.EVENT_CHANGE, (type) => { + this.next = createWidget( + extend( + { + type: LoadingBar.xtype, + }, + next + ) + ); + this.next.on(Controller.EVENT_CHANGE, type => { if (type === BI.Events.CLICK) { this._nextLoad(); } }); } - createWidget(extend({ - element: this, - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(direction), extend({ - scrolly: true, - }, logic, { - items: BI.LogicFactory.createLogicItemsByDirection(direction, this.prev, this.button_group, this.next), - })))); - - isDefaultInit && isEmpty(optionsItems) && nextTick(bind(() => { - isDefaultInit && isEmpty(optionsItems) && this._populate(); - }, this)); - const items = isFunction(optionsItems) ? this.__watch(optionsItems, (context, newValue) => { - this.populate(newValue); - }) : optionsItems; + createWidget( + extend( + { + element: this, + }, + BI.LogicFactory.createLogic( + BI.LogicFactory.createLogicTypeByDirection(direction), + extend( + { + scrolly: true, + }, + logic, + { + items: BI.LogicFactory.createLogicItemsByDirection( + direction, + this.prev, + this.button_group, + this.next + ), + } + ) + ) + ) + ); + + isDefaultInit && + isEmpty(optionsItems) && + nextTick( + bind(() => { + isDefaultInit && isEmpty(optionsItems) && this._populate(); + }, this) + ); + const items = isFunction(optionsItems) + ? this.__watch(optionsItems, (context, newValue) => { + this.populate(newValue); + }) + : optionsItems; if (isNotEmptyArray(items)) { this._populate(items); } @@ -130,10 +199,12 @@ export class Loader extends Widget { return this.count < count; } - return !!hasPrev.apply(this, [{ - times: this.times, - count: this.count, - }]); + return !!hasPrev.apply(this, [ + { + times: this.times, + count: this.count, + } + ]); } hasNext() { @@ -142,10 +213,12 @@ export class Loader extends Widget { return this.count < count; } - return !!hasNext.apply(this, [{ - times: this.times, - count: this.count, - }]); + return !!hasNext.apply(this, [ + { + times: this.times, + count: this.count, + } + ]); } prependItems(items) { @@ -176,14 +249,17 @@ export class Loader extends Widget { _populate(items) { const o = this.options; - if (arguments.length === 0 && (isFunction(o.itemsCreator))) { - o.itemsCreator.apply(this, [{ times: 1 }, (...args) => { - if (args.length === 0) { - throw new Error("参数不能为空"); + if (arguments.length === 0 && isFunction(o.itemsCreator)) { + o.itemsCreator.apply(this, [ + { times: 1 }, + (...args) => { + if (args.length === 0) { + throw new Error("参数不能为空"); + } + this.populate.apply(this, args); + o.onLoaded(); } - this.populate.apply(this, args); - o.onLoaded(); - }]); + ]); return false; } @@ -205,7 +281,7 @@ export class Loader extends Widget { this.prev.invisible(); } } - + return true; } diff --git a/src/base/combination/navigation.js b/src/base/combination/navigation.js index 546cb4ff3..a3ebb50c4 100644 --- a/src/base/combination/navigation.js +++ b/src/base/combination/navigation.js @@ -1,12 +1,28 @@ +import { ButtonGroup } from "./group.button"; +import { + CardLayout, + shortcut, + Widget, + Controller, + extend, + createWidget, + bind, + ShowListener, + isFunction, + each, + nextTick, + isKey, + values +} from "@/core"; + /** * Created by GUY on 2015/6/26. */ -import { shortcut, Widget, Controller, extend, createWidget, bind, ShowListener, isFunction, each, nextTick, isKey, values } from "../../core"; @shortcut() export class Navigation extends Widget { static xtype = "bi.navigation"; - + static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { @@ -27,18 +43,25 @@ export class Navigation extends Widget { render() { const { direction, logic, cardCreator, showIndex } = this.options; - this.tab = createWidget(this.options.tab, { type: "bi.button_group" }); + this.tab = createWidget(this.options.tab, { type: ButtonGroup.xtype }); this.cardMap = {}; this.showIndex = 0; this.layout = createWidget({ - type: "bi.card", + type: CardLayout.xtype, }); - createWidget(extend({ - element: this, - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(direction), extend({}, logic, { - items: BI.LogicFactory.createLogicItemsByDirection(direction, this.tab, this.layout), - })))); - + createWidget( + extend( + { + element: this, + }, + BI.LogicFactory.createLogic( + BI.LogicFactory.createLogicTypeByDirection(direction), + extend({}, logic, { + items: BI.LogicFactory.createLogicItemsByDirection(direction, this.tab, this.layout), + }) + ) + ) + ); new ShowListener({ eventObj: this.tab, @@ -48,7 +71,7 @@ export class Navigation extends Widget { Widget.execWithContext(this, () => { this.cardMap[v] = cardCreator(v); }); - + return this.cardMap[v]; }, afterCardCreated: bind(this.afterCardCreated, this), @@ -73,7 +96,7 @@ export class Navigation extends Widget { const { single } = this.options; if (single === true) { each(this.cardMap, (name, card) => { - if (name !== (`${currCardName}`)) { + if (name !== `${currCardName}`) { this.layout.deleteCardByName(name); delete this.cardMap[name]; } @@ -168,4 +191,3 @@ export class Navigation extends Widget { super.destroy(arguments); } } - diff --git a/src/base/combination/searcher.js b/src/base/combination/searcher.js index 1004fb94e..aaa0a1694 100644 --- a/src/base/combination/searcher.js +++ b/src/base/combination/searcher.js @@ -1,11 +1,7 @@ -/** - * 搜索逻辑控件 - * - * Created by GUY on 2015/9/28. - * @class BI.Searcher - * @extends BI.Widget - */ +import { SearchEditor } from "@/widget/editor/editor.search.js"; +import { SearcherView } from "../layer"; import { + VerticalLayout, shortcut, Widget, Controller, @@ -18,9 +14,17 @@ import { nextTick, isEmptyString, isNull -} from "../../core"; +} from "@/core"; import { ButtonGroup } from "./group.button"; -import { Maskers } from "../0.base"; +import { Maskers } from "@/base/0.base"; + +/** + * 搜索逻辑控件 + * + * Created by GUY on 2015/9/28. + * @class BI.Searcher + * @extends BI.Widget + */ @shortcut() export class Searcher extends Widget { @@ -54,15 +58,16 @@ export class Searcher extends Widget { }, el: { - type: "bi.search_editor", + type: SearchEditor.xtype, }, popup: { - type: "bi.searcher_view", + type: SearcherView.xtype, }, adapter: null, - masker: { // masker层 + masker: { + // masker层 offset: {}, }, }); @@ -72,11 +77,11 @@ export class Searcher extends Widget { const { el, lgap, rgap, tgap, bgap, vgap, hgap, isDefaultInit } = this.options; this.editor = createWidget(el, { - type: "bi.search_editor", + type: SearchEditor.xtype, }); createWidget({ - type: "bi.vertical", + type: VerticalLayout.xtype, element: this, lgap, rgap, @@ -86,30 +91,30 @@ export class Searcher extends Widget { hgap, items: [this.editor], }); - isDefaultInit && (this._assertPopupView()); + isDefaultInit && this._assertPopupView(); const search = debounce(bind(this._search, this), BI.EVENT_RESPONSE_TIME, { - "leading": true, - "trailing": false, + leading: true, + trailing: false, }); - this.editor.on(Controller.EVENT_CHANGE, (type) => { + this.editor.on(Controller.EVENT_CHANGE, type => { switch (type) { - case BI.Events.STARTEDIT: - this._startSearch(); - break; - case BI.Events.EMPTY: - this._stopSearch(); - break; - case BI.Events.CHANGE: - search(); - break; - case BI.Events.PAUSE: - if (endWith(this.getValue(), BI.BlankSplitChar)) { - this._pauseSearch(); - } - break; - default: - break; + case BI.Events.STARTEDIT: + this._startSearch(); + break; + case BI.Events.EMPTY: + this._stopSearch(); + break; + case BI.Events.CHANGE: + search(); + break; + case BI.Events.PAUSE: + if (endWith(this.getValue(), BI.BlankSplitChar)) { + this._pauseSearch(); + } + break; + default: + break; } }); } @@ -118,8 +123,8 @@ export class Searcher extends Widget { const { masker, popup, chooseType, isAutoSync, adapter } = this.options; if ((masker && !Maskers.has(this.getName())) || (masker === false && !this.popupView)) { this.popupView = createWidget(popup, { - type: "bi.searcher_view", - chooseType: chooseType, + type: SearcherView.xtype, + chooseType, }); this.popupView.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); @@ -127,18 +132,18 @@ export class Searcher extends Widget { if (isAutoSync) { const values = adapter && adapter.getValue(); switch (chooseType) { - case ButtonGroup.CHOOSE_TYPE_SINGLE: - adapter && adapter.setValue([obj.getValue()]); - break; - case ButtonGroup.CHOOSE_TYPE_MULTI: - if (!obj.isSelected()) { - adapter && adapter.setValue(deepWithout(values, obj.getValue())); - } - values.push(obj.getValue()); - adapter && adapter.setValue(values); - break; - default: - break; + case ButtonGroup.CHOOSE_TYPE_SINGLE: + adapter && adapter.setValue([obj.getValue()]); + break; + case ButtonGroup.CHOOSE_TYPE_MULTI: + if (!obj.isSelected()) { + adapter && adapter.setValue(deepWithout(values, obj.getValue())); + } + values.push(obj.getValue()); + adapter && adapter.setValue(values); + break; + default: + break; } } this.fireEvent(Searcher.EVENT_CHANGE, value, obj); @@ -149,10 +154,18 @@ export class Searcher extends Widget { }); } if (masker && !Maskers.has(this.getName())) { - Maskers.create(this.getName(), adapter, extend({ - container: this, - render: this.popupView, - }, masker), this); + Maskers.create( + this.getName(), + adapter, + extend( + { + container: this, + render: this.popupView, + }, + masker + ), + this + ); } } @@ -164,14 +177,14 @@ export class Searcher extends Widget { this.popupView.startSearch && this.popupView.startSearch(); // 搜索前先清空dom // BI.Maskers.get(this.getName()).empty(); - nextTick((name) => { + nextTick(name => { Maskers.show(name); }, this.getName()); } _pauseSearch() { this._stop = true; - nextTick((name) => { + nextTick(name => { Maskers.hide(name); }, this.getName()); if (this._isSearching === true) { @@ -201,7 +214,8 @@ export class Searcher extends Widget { if (isAutoSearch) { const items = (adapter && ((adapter.getItems && adapter.getItems()) || adapter.attr("items"))) || []; const finding = BI.Func.getSearchResult(items, keyword); - const match = finding.match, find = finding.find; + const match = finding.match, + find = finding.find; this.popupView.populate(find, match, keyword); isAutoSync && adapter && adapter.getValue && this.popupView.setValue(adapter.getValue()); this.fireEvent(Searcher.EVENT_SEARCHING); @@ -209,23 +223,26 @@ export class Searcher extends Widget { return; } this.popupView.loading && this.popupView.loading(); - onSearch({ - times: 1, - keyword: keyword, - selectedValues: adapter && adapter.getValue(), - }, (searchResult, matchResult, ...arg) => { - if (!this._stop && keyword === this.editor.getValue()) { - const args = [searchResult, matchResult, ...arg]; - if (args.length > 0) { - args.push(keyword); + onSearch( + { + times: 1, + keyword, + selectedValues: adapter && adapter.getValue(), + }, + (searchResult, matchResult, ...arg) => { + if (!this._stop && keyword === this.editor.getValue()) { + const args = [searchResult, matchResult, ...arg]; + if (args.length > 0) { + args.push(keyword); + } + Maskers.show(this.getName()); + this.popupView.populate.apply(this.popupView, args); + isAutoSync && adapter && adapter.getValue && this.popupView.setValue(adapter.getValue()); + this.popupView.loaded && this.popupView.loaded(); + this.fireEvent(Searcher.EVENT_SEARCHING); } - Maskers.show(this.getName()); - this.popupView.populate.apply(this.popupView, args); - isAutoSync && adapter && adapter.getValue && this.popupView.setValue(adapter.getValue()); - this.popupView.loaded && this.popupView.loaded(); - this.fireEvent(Searcher.EVENT_SEARCHING); } - }); + ); } _getLastSearchKeyword() { @@ -251,7 +268,7 @@ export class Searcher extends Widget { } stopSearch() { - this._stopSearch();// 先停止搜索,然后再去设置editor为空 + this._stopSearch(); // 先停止搜索,然后再去设置editor为空 // important:停止搜索必须退出编辑状态,这里必须加上try(input框不显示时blur会抛异常) try { this.editor.blur(); diff --git a/src/base/combination/switcher.js b/src/base/combination/switcher.js index 7df64dff6..ba338abe8 100644 --- a/src/base/combination/switcher.js +++ b/src/base/combination/switcher.js @@ -1,3 +1,18 @@ +import { + VerticalLayout, + shortcut, + Widget, + Controller, + extend, + nextTick, + createWidget, + each, + debounce, + isNull +} from "@/core"; +import { ButtonGroup } from "./group.button"; +import { Maskers } from "@/base/0.base"; + /** * * 切换显示或隐藏面板 @@ -6,13 +21,11 @@ * @class BI.Switcher * @extends BI.Widget */ -import { shortcut, Widget, Controller, extend, nextTick, createWidget, each, debounce, isNull } from "../../core"; -import { Maskers } from "../0.base"; @shortcut() export class Switcher extends Widget { static xtype = "bi.switcher"; - + static EVENT_EXPAND = "EVENT_EXPAND"; static EVENT_COLLAPSE = "EVENT_COLLAPSE"; static EVENT_TRIGGER_CHANGE = "EVENT_TRIGGER_CHANGE"; @@ -68,24 +81,25 @@ export class Switcher extends Widget { } }); - this.element.hover(() => { - if (this.isEnabled() && this.switcher.isEnabled()) { - this.element.addClass(hoverClass); - } - }, () => { - if (this.isEnabled() && this.switcher.isEnabled()) { - this.element.removeClass(hoverClass); + this.element.hover( + () => { + if (this.isEnabled() && this.switcher.isEnabled()) { + this.element.addClass(hoverClass); + } + }, + () => { + if (this.isEnabled() && this.switcher.isEnabled()) { + this.element.removeClass(hoverClass); + } } - }); + ); createWidget({ - type: "bi.vertical", + type: VerticalLayout.xtype, scrolly: false, element: this, - items: [ - { el: this.switcher } - ], + items: [{ el: this.switcher }], }); - isDefaultInit && (this._assertPopupView()); + isDefaultInit && this._assertPopupView(); } _toggle() { @@ -104,42 +118,62 @@ export class Switcher extends Widget { const evs = this.options.trigger.split(","); each(evs, (i, e) => { switch (e) { - case "hover": - this.element[e]((e) => { + case "hover": + this.element[e]( + e => { if (this.isEnabled() && this.switcher.isEnabled()) { this._popupView(); this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.switcher); this.fireEvent(Switcher.EVENT_EXPAND); } - }, () => { + }, + () => { if (this.isEnabled() && this.switcher.isEnabled() && toggle) { this._hideView(); this.fireEvent(Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", this.switcher); this.fireEvent(Switcher.EVENT_COLLAPSE); } - }); - break; - default : - if (e) { - this.element.off(e + "." + this.getName()).on(e + "." + this.getName(), debounce((e) => { - if (this.switcher.element.__isMouseInBounds__(e)) { - if (this.isEnabled() && this.switcher.isEnabled()) { - toggle ? this._toggle() : this._popupView(); - if (this.isExpanded()) { - this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.switcher); - this.fireEvent(Switcher.EVENT_EXPAND); - } else { - this.fireEvent(Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", this.switcher); - this.fireEvent(Switcher.EVENT_COLLAPSE); + } + ); + break; + default: + if (e) { + this.element.off(`${e}.${this.getName()}`).on( + `${e}.${this.getName()}`, + debounce( + e => { + if (this.switcher.element.__isMouseInBounds__(e)) { + if (this.isEnabled() && this.switcher.isEnabled()) { + toggle ? this._toggle() : this._popupView(); + if (this.isExpanded()) { + this.fireEvent( + Controller.EVENT_CHANGE, + BI.Events.EXPAND, + "", + this.switcher + ); + this.fireEvent(Switcher.EVENT_EXPAND); + } else { + this.fireEvent( + Controller.EVENT_CHANGE, + BI.Events.COLLAPSE, + "", + this.switcher + ); + this.fireEvent(Switcher.EVENT_COLLAPSE); + } } } + }, + BI.EVENT_RESPONSE_TIME, + { + leading: true, + trailing: false, } - }, BI.EVENT_RESPONSE_TIME, { - "leading": true, - "trailing": false, - })); - } - break; + ) + ); + } + break; } }); } @@ -153,18 +187,24 @@ export class Switcher extends Widget { _assertPopupView() { const { popup, adapter, masker, value, direction } = this.options; if (!this._created) { - this.popupView = createWidget(popup, { - type: "bi.button_group", - element: adapter && Maskers.create(this.getName(), adapter, extend({ container: this }, masker)), - cls: "switcher-popup", - layouts: [{ - type: "bi.vertical", - hgap: 0, - vgap: 0, - }], - value, - }, this); - this.popupView.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { + this.popupView = createWidget( + popup, + { + type: ButtonGroup.xtype, + element: adapter && Maskers.create(this.getName(), adapter, extend({ container: this }, masker)), + cls: "switcher-popup", + layouts: [ + { + type: VerticalLayout.xtype, + hgap: 0, + vgap: 0, + } + ], + value, + }, + this + ); + this.popupView.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); if (type === BI.Events.CLICK) { this.fireEvent(Switcher.EVENT_CHANGE, value, obj); @@ -172,12 +212,10 @@ export class Switcher extends Widget { }); if (direction !== BI.Direction.Custom && !adapter) { createWidget({ - type: "bi.vertical", + type: VerticalLayout.xtype, scrolly: false, element: this, - items: [ - { el: this.popupView } - ], + items: [{ el: this.popupView }], }); } this._created = true; @@ -190,9 +228,9 @@ export class Switcher extends Widget { _hideView() { this.fireEvent(Switcher.EVENT_BEFORE_HIDEVIEW); const { adapter, switcherClass } = this.options; - adapter ? Maskers.hide(this.getName()) : (this.popupView && this.popupView.setVisible(false)); + adapter ? Maskers.hide(this.getName()) : this.popupView && this.popupView.setVisible(false); nextTick(() => { - adapter ? Maskers.hide(this.getName()) : (this.popupView && this.popupView.setVisible(false)); + adapter ? Maskers.hide(this.getName()) : this.popupView && this.popupView.setVisible(false); this.element.removeClass(switcherClass); this.fireEvent(Switcher.EVENT_AFTER_HIDEVIEW); }); @@ -203,7 +241,7 @@ export class Switcher extends Widget { this._assertPopupView(); this.fireEvent(Switcher.EVENT_BEFORE_POPUPVIEW); adapter ? Maskers.show(this.getName()) : this.popupView.setVisible(true); - nextTick((name) => { + nextTick(name => { adapter ? Maskers.show(name) : this.popupView.setVisible(true); this.element.addClass(switcherClass); this.fireEvent(Switcher.EVENT_AFTER_POPUPVIEW); @@ -248,8 +286,11 @@ export class Switcher extends Widget { } isViewVisible() { - return this.isEnabled() && this.switcher.isEnabled() && - (this.options.adapter ? Maskers.isVisible(this.getName()) : (this.popupView && this.popupView.isVisible())); + return ( + this.isEnabled() && + this.switcher.isEnabled() && + (this.options.adapter ? Maskers.isVisible(this.getName()) : this.popupView && this.popupView.isVisible()) + ); } isExpanded() { @@ -290,7 +331,7 @@ export class Switcher extends Widget { if (this.switcher.getValue() === value) { return this.switcher; } - + return this.popupView && this.popupView.getNodeByValue(value); } diff --git a/src/base/combination/tab.js b/src/base/combination/tab.js index d9d5a5cc7..8e797ce71 100644 --- a/src/base/combination/tab.js +++ b/src/base/combination/tab.js @@ -1,7 +1,23 @@ +import { ButtonGroup } from "./group.button"; +import { + CardLayout, + shortcut, + Widget, + Controller, + ShowListener, + extend, + createWidget, + isObject, + each, + isFunction, + contains, + any, + isEqual +} from "@/core"; + /** * Created by GUY on 2015/6/26. */ -import { shortcut, Widget, Controller, ShowListener, extend, createWidget, isObject, each, isFunction, contains, any, isEqual } from "../../core"; @shortcut() export class Tab extends Widget { @@ -19,9 +35,7 @@ export class Tab extends Widget { }, showIndex: false, tab: false, - cardCreator: (v) => { - return createWidget(); - }, + cardCreator: v => createWidget(), keepAlives: [], }); } @@ -29,38 +43,46 @@ export class Tab extends Widget { render() { const { tab, direction, logic, cardCreator } = this.options; if (isObject(tab)) { - this.tab = createWidget(this.options.tab, { type: "bi.button_group" }); + this.tab = createWidget(this.options.tab, { type: ButtonGroup.xtype }); this.tab.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => { this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args); }); } this.cardMap = {}; this.layout = createWidget({ - type: "bi.card", + type: CardLayout.xtype, }); - createWidget(extend({ - element: this, - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(direction), extend({}, logic, { - items: BI.LogicFactory.createLogicItemsByDirection(direction, this.tab, this.layout), - })))); + createWidget( + extend( + { + element: this, + }, + BI.LogicFactory.createLogic( + BI.LogicFactory.createLogicTypeByDirection(direction), + extend({}, logic, { + items: BI.LogicFactory.createLogicItemsByDirection(direction, this.tab, this.layout), + }) + ) + ) + ); const listener = new ShowListener({ eventObj: this.tab, cardLayout: this.layout, - cardCreator: (v) => { + cardCreator: v => { Widget.execWithContext(this, () => { this.cardMap[v] = cardCreator(v); }); return this.cardMap[v]; }, - afterCardShow: (v) => { + afterCardShow: v => { this._deleteOtherCards(v); this.curr = v; }, }); - listener.on(ShowListener.EVENT_CHANGE, (value) => { + listener.on(ShowListener.EVENT_CHANGE, value => { this.fireEvent(Tab.EVENT_CHANGE, value, this); }); } @@ -69,7 +91,7 @@ export class Tab extends Widget { const { single } = this.options; if (single === true) { each(this.cardMap, (name, card) => { - if (name !== (currCardName + "") && this._keepAlive(name) !== true) { + if (name !== `${currCardName}` && this._keepAlive(name) !== true) { this.layout.deleteCardByName(name); delete this.cardMap[name]; } @@ -122,7 +144,7 @@ export class Tab extends Widget { removeTab(cardname) { any(this.cardMap, (name, card) => { - if (isEqual(name, (cardname + ""))) { + if (isEqual(name, `${cardname}`)) { this.layout.deleteCardByName(name); delete this.cardMap[name]; @@ -179,5 +201,4 @@ export class Tab extends Widget { this.cardMap = {}; super.destroy(arguments); } - } diff --git a/src/base/combination/tree.button.js b/src/base/combination/tree.button.js index 79e4b4ed5..3f18102be 100644 --- a/src/base/combination/tree.button.js +++ b/src/base/combination/tree.button.js @@ -1,10 +1,11 @@ +import { ButtonGroup } from "./group.button"; +import { shortcut, Widget, extend, isArray, each, isFunction, deepContains, concat, any, contains } from "@/core"; + /** * Created by GUY on 2015/8/10. * @class BI.ButtonTree * @extends BI.ButtonGroup */ -import { shortcut, Widget, extend, isArray, each, isFunction, deepContains, concat, any, contains } from "../../core"; -import { ButtonGroup } from "./group.button"; @shortcut() export class ButtonTree extends ButtonGroup { @@ -119,7 +120,7 @@ export class ButtonTree extends ButtonGroup { each(this.buttons, (i, item) => { if (item.isEnabled() && !isFunction(item.setSelected)) { btns = btns.concat(item.getNotSelectedButtons()); - + return; } if (item.isSelected && !item.isSelected()) { @@ -167,7 +168,7 @@ export class ButtonTree extends ButtonGroup { if (item.isEnabled()) { if (item.attr("id") === id) { node = item; - + return true; } else if (isFunction(item.getNodeById)) { node = item.getNodeById(id); diff --git a/src/base/context.js b/src/base/context.js index 47fdd6c64..dc3a29326 100644 --- a/src/base/context.js +++ b/src/base/context.js @@ -1,47 +1,40 @@ -/** - * 表示当前对象 - * - * Created by GUY on 2015/9/7. - * @class BI.EL - * @extends BI.Widget - */ -BI.Context = BI.inherit(BI.Widget, { - props: { - context: "", - watch: {}, - el: {}, - items: [], - }, +import { shortcut, Widget, createWidget, Controller } from "@/core"; - render: function () { - var self = this, o = this.options; +@shortcut() +export class Context extends Widget { + static xtype = "bi.context"; + + props = { context: "", watch: {}, el: {}, items: [] }; + + render() { + const self = this, + o = this.options; if (o.context) { this.context = BI.useContext(o.context); } - this.widget = BI.createWidget((o.items[0] || o.el)(this.context), { + this.widget = createWidget((o.items[0] || o.el)(this.context), { element: this, }); - this.widget.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.widget.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - }, + } - __initWatch: function () { - BI.Context.superclass.__initWatch.call(this); - var o = this.options; + __initWatch() { + super.__initWatch.call(this); + const o = this.options; BI.watch(this.context, o.context, o.watch); - }, + } - setValue: function (v) { + setValue(v) { this.widget.setValue(v); - }, + } - getValue: function () { + getValue() { return this.widget.getValue(); - }, + } - populate: function () { + populate() { this.widget.populate.apply(this, arguments); - }, -}); -BI.shortcut("bi.context", BI.Context); + } +} diff --git a/src/base/el.js b/src/base/el.js index 885c04ac5..e258c3b0a 100644 --- a/src/base/el.js +++ b/src/base/el.js @@ -1,38 +1,36 @@ -/** - * 表示当前对象 - * - * Created by GUY on 2015/9/7. - * @class BI.EL - * @extends BI.Widget - */ -BI.EL = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.EL.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, Widget, extend, createWidget, Controller } from "@/core"; + +@shortcut() +export class EL extends Widget { + static xtype = "bi.el"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-el", el: {}, }); - }, + } - render: function () { - var self = this, o = this.options; - this.ele = BI.createWidget(o.el, { + render() { + const self = this, + o = this.options; + this.ele = createWidget(o.el, { element: this, }); - this.ele.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.ele.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - }, + } - setValue: function (v) { + setValue(v) { this.ele.setValue(v); - }, + } - getValue: function () { + getValue() { return this.ele.getValue(); - }, + } - populate: function () { + populate() { this.ele.populate.apply(this, arguments); - }, -}); -BI.shortcut("bi.el", BI.EL); + } +} diff --git a/src/base/foundation/message.js b/src/base/foundation/message.js index 40cbb90c5..f27aa7851 100644 --- a/src/base/foundation/message.js +++ b/src/base/foundation/message.js @@ -3,26 +3,26 @@ * 弹出提示消息框,用于模拟阻塞操作(通过回调函数实现) * @class BI.Msg */ -import { Widget, isString, isNull, isFunction, createWidget, remove, each } from "../../core" +import { Widget, isString, isNull, isFunction, createWidget, remove, each } from "../../core"; -export const Msg = ((() => { +export const Msg = (() => { let $mask, $pop; - let messageShows = []; + const messageShows = []; - let toastStack = []; + const toastStack = []; return { - alert: function (title, message, callback) { + alert (title, message, callback) { this._show(false, title, message, callback); }, - confirm: function (title, message, callback) { + confirm (title, message, callback) { this._show(true, title, message, callback); }, - prompt: function (title, message, value, callback, min_width) { + prompt (title, message, value, callback, min_width) { // BI.Msg.prompt(title, message, value, callback, min_width); }, - toast: function (message, options, context) { + toast (message, options, context) { isString(options) && (options = { level: options }); options = options || {}; context = context || Widget._renderEngine.createElement("body"); @@ -32,69 +32,81 @@ export const Msg = ((() => { const toast = createWidget({ type: "bi.toast", cls: "bi-message-animate bi-message-leave", - level: level, - autoClose: autoClose, + level, + autoClose, closable: options.closable, text: message, - listeners: [{ - eventName: BI.Toast.EVENT_DESTORY, - action: function () { - remove(toastStack, toast.element); - let _height = BI.SIZE_CONSANTS.TOAST_TOP; - each(toastStack, function (i, element) { - element.css({ "top": _height }); - _height += element.outerHeight() + 10; - }); - callback(); - }, - }], + listeners: [ + { + eventName: BI.Toast.EVENT_DESTORY, + action () { + remove(toastStack, toast.element); + let _height = BI.SIZE_CONSANTS.TOAST_TOP; + each(toastStack, (i, element) => { + element.css({ top: _height }); + _height += element.outerHeight() + 10; + }); + callback(); + }, + } + ], }); let height = BI.SIZE_CONSANTS.TOAST_TOP; - each(toastStack, function (i, element) { + each(toastStack, (i, element) => { height += element.outerHeight() + 10; }); createWidget({ type: "bi.absolute", element: context, - items: [{ - el: toast, - left: "50%", - top: height, - }], + items: [ + { + el: toast, + left: "50%", + top: height, + } + ], }); toastStack.push(toast.element); - toast.element.css({ "margin-left": -1 * toast.element.outerWidth() / 2 }); + toast.element.css({ "margin-left": (-1 * toast.element.outerWidth()) / 2 }); toast.element.removeClass("bi-message-leave").addClass("bi-message-enter"); - autoClose && BI.delay(function () { - toast.element.removeClass("bi-message-enter").addClass("bi-message-leave"); - toast.destroy?.(); - }, 5000); + autoClose && + BI.delay(() => { + toast.element.removeClass("bi-message-enter").addClass("bi-message-leave"); + toast.destroy?.(); + }, 5000); return function () { toast.element.removeClass("bi-message-enter").addClass("bi-message-leave"); toast.destroy?.(); }; }, - _show: function (hasCancel, title, message, callback) { - isNull($mask) && ($mask = Widget._renderEngine.createElement("
").css({ - position: "absolute", - zIndex: BI.zIndex_tip - 2, - top: 0, - left: 0, - right: 0, - bottom: 0, - opacity: 0.5, - }).appendTo("body")); - $pop = Widget._renderEngine.createElement("
").css({ - position: "absolute", - zIndex: BI.zIndex_tip - 1, - top: 0, - left: 0, - right: 0, - bottom: 0, - }).appendTo("body"); - function close () { + _show (hasCancel, title, message, callback) { + isNull($mask) && + ($mask = Widget._renderEngine + .createElement("
") + .css({ + position: "absolute", + zIndex: BI.zIndex_tip - 2, + top: 0, + left: 0, + right: 0, + bottom: 0, + opacity: 0.5, + }) + .appendTo("body")); + $pop = Widget._renderEngine + .createElement("
") + .css({ + position: "absolute", + zIndex: BI.zIndex_tip - 1, + top: 0, + left: 0, + right: 0, + bottom: 0, + }) + .appendTo("body"); + function close() { messageShows[messageShows.length - 1].destroy(); messageShows.pop(); if (messageShows.length === 0) { @@ -102,14 +114,14 @@ export const Msg = ((() => { $mask = null; } } - let controlItems = []; + const controlItems = []; if (hasCancel === true) { controlItems.push({ el: { type: "bi.button", text: BI.i18nText("BI-Basic_Cancel"), level: "ignore", - handler: function () { + handler () { close(); if (isFunction(callback)) { callback.apply(null, [false]); @@ -122,7 +134,7 @@ export const Msg = ((() => { el: { type: "bi.button", text: BI.i18nText("BI-Basic_OK"), - handler: function () { + handler () { close(); if (isFunction(callback)) { callback.apply(null, [true]); @@ -139,8 +151,8 @@ export const Msg = ((() => { attributes: { tabIndex: 1, }, - mounted: function () { - this.element.keyup(function (e) { + mounted () { + this.element.keyup(e => { if (e.keyCode === BI.KeyCode.ENTER) { close(); if (isFunction(callback)) { @@ -157,9 +169,7 @@ export const Msg = ((() => { }); try { this.element.focus(); - } catch (e) { - - } + } catch (e) {} }, cls: "bi-card", items: { @@ -183,7 +193,7 @@ export const Msg = ((() => { type: "bi.icon_button", cls: "bi-message-close close-font", // height: 50, - handler: function () { + handler () { close(); if (isFunction(callback)) { callback.apply(null, [false]); @@ -197,29 +207,32 @@ export const Msg = ((() => { height: 40, }, center: { - el: BI.isPlainObject(message) ? message : { - type: "bi.label", - vgap: 10, - hgap: 20, - whiteSpace: "normal", - text: message, - }, + el: BI.isPlainObject(message) + ? message + : { + type: "bi.label", + vgap: 10, + hgap: 20, + whiteSpace: "normal", + text: message, + }, }, south: { el: { type: "bi.absolute", - items: [{ - el: { - type: "bi.right_vertical_adapt", - lgap: 10, - items: controlItems, - }, - top: 0, - left: 20, - right: 20, - bottom: 0, - }], - + items: [ + { + el: { + type: "bi.right_vertical_adapt", + lgap: 10, + items: controlItems, + }, + top: 0, + left: 20, + right: 20, + bottom: 0, + } + ], }, height: 44, }, @@ -233,4 +246,4 @@ export const Msg = ((() => { messageShows[messageShows.length] = createWidget(conf); }, }; -})()); +})(); diff --git a/src/base/grid/grid.js b/src/base/grid/grid.js index 6e65a52e0..4aa78e88f 100644 --- a/src/base/grid/grid.js +++ b/src/base/grid/grid.js @@ -1,3 +1,22 @@ +import { + VerticalLayout, + AbsoluteLayout, + Widget, + shortcut, + extend, + emptyFn, + debounce, + _lazyCreateWidget, + isFunction, + each, + isNumber, + ScalingCellSizeAndPositionManager, + clamp, + isEmpty, + nextTick +} from "@/core"; +import { Label } from "../single"; + /** * GridView * @@ -5,7 +24,7 @@ * @class BI.GridView * @extends BI.Widget */ -import { Widget, shortcut, extend, emptyFn, debounce, _lazyCreateWidget, isFunction, each, isNumber, ScalingCellSizeAndPositionManager, clamp, isEmpty, nextTick } from "../../core"; + @shortcut() export class GridView extends Widget { _defaultConfig() { @@ -19,7 +38,7 @@ export class GridView extends Widget { overflowX: true, overflowY: true, el: { - type: "bi.vertical", + type: VerticalLayout.xtype, }, overscanColumnCount: 0, overscanRowCount: 0, @@ -48,7 +67,7 @@ export class GridView extends Widget { this._scrollLock = false; }, 1000 / 60); this.container = _lazyCreateWidget({ - type: "bi.absolute", + type: AbsoluteLayout.xtype, }); this.element.scroll(() => { if (this._scrollLock === true) { @@ -64,7 +83,8 @@ export class GridView extends Widget { }); // 兼容一下 let scrollable = o.scrollable; - const scrollx = o.scrollx, scrolly = o.scrolly; + const scrollx = o.scrollx, + scrolly = o.scrolly; if (overflowX === false) { if (overflowY === false) { scrollable = false; @@ -77,16 +97,18 @@ export class GridView extends Widget { } } _lazyCreateWidget(el, { - type: "bi.vertical", + type: VerticalLayout.xtype, element: this, scrollable, scrolly, scrollx, items: [this.container], }); - o.items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { - this.populate(newValue); - }) : o.items; + o.items = isFunction(o.items) + ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); + }) + : o.items; if (o.items.length > 0) { this._calculateSizeAndPositionData(); this._populate(); @@ -109,7 +131,15 @@ export class GridView extends Widget { } _calculateSizeAndPositionData() { - const { columnCount, items, rowCount, columnWidthGetter, estimatedColumnSize, rowHeightGetter, estimatedRowSize } = this.options; + const { + columnCount, + items, + rowCount, + columnWidthGetter, + estimatedColumnSize, + rowHeightGetter, + estimatedRowSize, + } = this.options; this.rowCount = 0; this.columnCount = 0; if (isNumber(columnCount)) { @@ -122,8 +152,16 @@ export class GridView extends Widget { } else { this.rowCount = items.length; } - this._columnSizeAndPositionManager = new ScalingCellSizeAndPositionManager(this.columnCount, columnWidthGetter, estimatedColumnSize); - this._rowSizeAndPositionManager = new ScalingCellSizeAndPositionManager(this.rowCount, rowHeightGetter, estimatedRowSize); + this._columnSizeAndPositionManager = new ScalingCellSizeAndPositionManager( + this.columnCount, + columnWidthGetter, + estimatedColumnSize + ); + this._rowSizeAndPositionManager = new ScalingCellSizeAndPositionManager( + this.rowCount, + rowHeightGetter, + estimatedRowSize + ); } _getOverscanIndices(cellCount, overscanCellsCount, startIndex, stopIndex) { @@ -138,19 +176,30 @@ export class GridView extends Widget { const { itemFormatter, items } = this.options; - const width = o.width, height = o.height, scrollLeft = clamp(o.scrollLeft, 0, this._getMaxScrollLeft()), + const width = o.width, + height = o.height, + scrollLeft = clamp(o.scrollLeft, 0, this._getMaxScrollLeft()), scrollTop = clamp(o.scrollTop, 0, this._getMaxScrollTop()), - overscanColumnCount = o.overscanColumnCount, overscanRowCount = o.overscanRowCount; + overscanColumnCount = o.overscanColumnCount, + overscanRowCount = o.overscanRowCount; if (height > 0 && width > 0) { const visibleColumnIndices = this._columnSizeAndPositionManager.getVisibleCellRange(width, scrollLeft); const visibleRowIndices = this._rowSizeAndPositionManager.getVisibleCellRange(height, scrollTop); - const renderedCells = [], renderedKeys = {}, renderedWidgets = {}; - let minX = this._getMaxScrollLeft(), minY = this._getMaxScrollTop(), maxX = 0, maxY = 0; + const renderedCells = [], + renderedKeys = {}, + renderedWidgets = {}; + let minX = this._getMaxScrollLeft(), + minY = this._getMaxScrollTop(), + maxX = 0, + maxY = 0; // 没有可见的单元格就干掉所有渲染过的 if (!isEmpty(visibleColumnIndices) && !isEmpty(visibleRowIndices)) { - const horizontalOffsetAdjustment = this._columnSizeAndPositionManager.getOffsetAdjustment(width, scrollLeft); + const horizontalOffsetAdjustment = this._columnSizeAndPositionManager.getOffsetAdjustment( + width, + scrollLeft + ); const verticalOffsetAdjustment = this._rowSizeAndPositionManager.getOffsetAdjustment(height, scrollTop); this._renderedColumnStartIndex = visibleColumnIndices.start; @@ -158,9 +207,19 @@ export class GridView extends Widget { this._renderedRowStartIndex = visibleRowIndices.start; this._renderedRowStopIndex = visibleRowIndices.stop; - const overscanColumnIndices = this._getOverscanIndices(this.columnCount, overscanColumnCount, this._renderedColumnStartIndex, this._renderedColumnStopIndex); + const overscanColumnIndices = this._getOverscanIndices( + this.columnCount, + overscanColumnCount, + this._renderedColumnStartIndex, + this._renderedColumnStopIndex + ); - const overscanRowIndices = this._getOverscanIndices(this.rowCount, overscanRowCount, this._renderedRowStartIndex, this._renderedRowStopIndex); + const overscanRowIndices = this._getOverscanIndices( + this.rowCount, + overscanRowCount, + this._renderedRowStartIndex, + this._renderedRowStopIndex + ); const columnStartIndex = overscanColumnIndices.overscanStartIndex; const columnStopIndex = overscanColumnIndices.overscanStopIndex; @@ -177,7 +236,12 @@ export class GridView extends Widget { const bottom = maxRowDatum.offset + verticalOffsetAdjustment + maxRowDatum.size; const right = maxColumnDatum.offset + horizontalOffsetAdjustment + maxColumnDatum.size; // 如果滚动的区间并没有超出渲染的范围 - if (top >= this.renderRange.minY && bottom <= this.renderRange.maxY && left >= this.renderRange.minX && right <= this.renderRange.maxX) { + if ( + top >= this.renderRange.minY && + bottom <= this.renderRange.maxY && + left >= this.renderRange.minX && + right <= this.renderRange.maxX + ) { return; } @@ -195,23 +259,38 @@ export class GridView extends Widget { this.renderedCells[index].el.setWidth(columnDatum.size); this.renderedCells[index].el.setHeight(rowDatum.size); // 这里只使用px - this.renderedCells[index].el.element.css("left", `${columnDatum.offset + horizontalOffsetAdjustment}px`); - this.renderedCells[index].el.element.css("top", `${rowDatum.offset + verticalOffsetAdjustment}px`); + this.renderedCells[index].el.element.css( + "left", + `${columnDatum.offset + horizontalOffsetAdjustment}px` + ); + this.renderedCells[index].el.element.css( + "top", + `${rowDatum.offset + verticalOffsetAdjustment}px` + ); child = this.renderedCells[index].el; renderedCells.push(this.renderedCells[index]); } else { const item = itemFormatter(items[rowIndex][columnIndex], rowIndex, columnIndex); - child = _lazyCreateWidget(extend({ - type: "bi.label", - width: columnDatum.size, - height: rowDatum.size, - }, item, { - cls: `${item.cls || ""} grid-cell${rowIndex === 0 ? " first-row" : ""}${columnIndex === 0 ? " first-col" : ""}`, - _rowIndex: rowIndex, - _columnIndex: columnIndex, - _left: columnDatum.offset + horizontalOffsetAdjustment, - _top: rowDatum.offset + verticalOffsetAdjustment, - }), this); + child = _lazyCreateWidget( + extend( + { + type: Label.xtype, + width: columnDatum.size, + height: rowDatum.size, + }, + item, + { + cls: `${item.cls || ""} grid-cell${rowIndex === 0 ? " first-row" : ""}${ + columnIndex === 0 ? " first-col" : "" + }`, + _rowIndex: rowIndex, + _columnIndex: columnIndex, + _left: columnDatum.offset + horizontalOffsetAdjustment, + _top: rowDatum.offset + verticalOffsetAdjustment, + } + ), + this + ); renderedCells.push({ el: child, left: `${columnDatum.offset + horizontalOffsetAdjustment}px`, @@ -233,7 +312,9 @@ export class GridView extends Widget { } } // 已存在的, 需要添加的和需要删除的 - const existSet = {}, addSet = {}, deleteArray = []; + const existSet = {}, + addSet = {}, + deleteArray = []; each(renderedKeys, (i, key) => { if (this.renderedKeys[i]) { existSet[i] = key; @@ -281,7 +362,7 @@ export class GridView extends Widget { if (scrollable === true || scrollable === "xy" || scrollable === "x") { return true; } - + return false; } @@ -298,16 +379,22 @@ export class GridView extends Widget { if (scrollable === true || scrollable === "xy" || scrollable === "y") { return true; } - + return false; } _getMaxScrollLeft() { - return Math.max(0, this._getContainerWidth() - this.options.width + (this._isOverflowX() ? BI.DOM.getScrollWidth() : 0)); + return Math.max( + 0, + this._getContainerWidth() - this.options.width + (this._isOverflowX() ? BI.DOM.getScrollWidth() : 0) + ); } _getMaxScrollTop() { - return Math.max(0, this._getContainerHeight() - this.options.height + (this._isOverflowY() ? BI.DOM.getScrollWidth() : 0)); + return Math.max( + 0, + this._getContainerHeight() - this.options.height + (this._isOverflowY() ? BI.DOM.getScrollWidth() : 0) + ); } _getContainerWidth() { @@ -333,8 +420,7 @@ export class GridView extends Widget { try { this.element.scrollTop(scrollTop); this.element.scrollLeft(scrollLeft); - } catch (e) { - } + } catch (e) {} this._calculateChildrenToRender(); } diff --git a/src/base/index.js b/src/base/index.js index 9188548ef..1dc04c850 100644 --- a/src/base/index.js +++ b/src/base/index.js @@ -29,11 +29,4 @@ export * from "./combination"; export * from "./layer"; export * from "./list"; export * from "./single"; -export { - Pane, - GridView, - Pager, - Msg, - CollectionView, - CustomTree -}; +export { Pane, GridView, Pager, Msg, CollectionView, CustomTree }; diff --git a/src/base/layer/layer.drawer.js b/src/base/layer/layer.drawer.js index b8e6bf2b7..395bd9a6c 100644 --- a/src/base/layer/layer.drawer.js +++ b/src/base/layer/layer.drawer.js @@ -1,236 +1,253 @@ +import { HTapeLayout, AbsoluteLayout, Layout, VerticalLayout, Widget, shortcut, isPlainObject, extend } from "@/core"; +import { Label, IconButton } from "../single"; + /** * Popover弹出层, * @class BI.Popover * @extends BI.Widget */ -import { Widget, shortcut, isPlainObject, extend } from "../../core"; @shortcut() export class Drawer extends Widget { - SIZE = { - SMALL: "small", - NORMAL: "normal", - BIG: "big", - } - props = { - baseCls: "bi-drawer bi-card", - size: "normal", - placement: "right", // top/bottom/left/right - header: null, - headerHeight: 40, - body: null, - closable: true, // BI-40839 是否显示右上角的关闭按钮 - bodyHgap: 20, - bodyTgap: 10, - bodyBgap: 10, - } - static xtype = "bi.drawer"; - static EVENT_CLOSE = "EVENT_CLOSE"; - static EVENT_OPEN = "EVENT_OPEN"; - _getSuitableSize() { - const { size, height, placement, width } = this.options; - let sizeValue = 0; - switch (size) { - case "big": - sizeValue = 736; - break; - case "small": - sizeValue = 200; - break; - case "normal": - default: - sizeValue = 378; - break; - } - if (placement === "top" || placement === "bottom") { - return { - height: height || sizeValue, - }; - } - if (placement === "left" || placement === "right") { - return { - width: width || sizeValue, - }; - } - } - render() { - const { header, headerHeight, closable, body, bodyHgap, bodyTgap, bodyBgap } = this.options; - const items = [{ - el: { - type: "bi.htape", - cls: "bi-message-title bi-header-background", - items: [{ - type: "bi.absolute", - items: [{ - el: isPlainObject(header) ? extend({}, header, { - extraCls: "bi-font-bold", - }) : { - type: "bi.label", - cls: "bi-font-bold", - height: headerHeight, - text: header, - title: header, - textAlign: "left", - }, - left: 20, - top: 0, - right: 0, - bottom: 0, - }], - }, { - el: closable ? { - type: "bi.icon_button", - cls: "bi-message-close close-font", - height: headerHeight, - handler: () => { - this.close(); - }, - } : { - type: "bi.layout", - }, - width: 56, - }], - height: headerHeight, - }, - height: headerHeight, - }, { - el: { - type: "bi.vertical", - scrolly: true, - cls: "drawer-body", - ref: _ref => { - this.body = _ref; - }, - items: [{ - el: body, - }], - }, - hgap: bodyHgap, - tgap: bodyTgap, - bgap: bodyBgap, - }]; + SIZE = { + SMALL: "small", + NORMAL: "normal", + BIG: "big", + }; + props = { + baseCls: "bi-drawer bi-card", + size: "normal", + placement: "right", // top/bottom/left/right + header: null, + headerHeight: 40, + body: null, + closable: true, // BI-40839 是否显示右上角的关闭按钮 + bodyHgap: 20, + bodyTgap: 10, + bodyBgap: 10, + }; + static xtype = "bi.drawer"; + static EVENT_CLOSE = "EVENT_CLOSE"; + static EVENT_OPEN = "EVENT_OPEN"; + _getSuitableSize() { + const { size, height, placement, width } = this.options; + let sizeValue = 0; + switch (size) { + case "big": + sizeValue = 736; + break; + case "small": + sizeValue = 200; + break; + case "normal": + default: + sizeValue = 378; + break; + } + if (placement === "top" || placement === "bottom") { + return { + height: height || sizeValue, + }; + } + if (placement === "left" || placement === "right") { + return { + width: width || sizeValue, + }; + } + } + render() { + const { header, headerHeight, closable, body, bodyHgap, bodyTgap, bodyBgap } = this.options; + const items = [ + { + el: { + type: HTapeLayout.xtype, + cls: "bi-message-title bi-header-background", + items: [ + { + type: AbsoluteLayout.xtype, + items: [ + { + el: isPlainObject(header) + ? extend({}, header, { + extraCls: "bi-font-bold", + }) + : { + type: Label.xtype, + cls: "bi-font-bold", + height: headerHeight, + text: header, + title: header, + textAlign: "left", + }, + left: 20, + top: 0, + right: 0, + bottom: 0, + } + ], + }, + { + el: closable + ? { + type: IconButton.xtype, + cls: "bi-message-close close-font", + height: headerHeight, + handler: () => { + this.close(); + }, + } + : { + type: Layout.xtype, + }, + width: 56, + } + ], + height: headerHeight, + }, + height: headerHeight, + }, + { + el: { + type: VerticalLayout.xtype, + scrolly: true, + cls: "drawer-body", + ref: _ref => { + this.body = _ref; + }, + items: [ + { + el: body, + } + ], + }, + hgap: bodyHgap, + tgap: bodyTgap, + bgap: bodyBgap, + } + ]; - return extend({ - type: "bi.vtape", - items, - }, this._getSuitableSize()); - } - mounted() { - const { placement } = this.options; - switch (placement) { - case "right": - this.element.css({ - top: 0, - left: "100%", - bottom: 0, - }); - break; - case "left": - this.element.css({ - top: 0, - right: "100%", - bottom: 0, - }); - break; - case "top": - this.element.css({ - left: 0, - right: 0, - bottom: "100%", - }); - break; - case "bottom": - this.element.css({ - left: 0, - right: 0, - top: "100%", - }); - break; - default: - break; - } - } + return extend( + { + type: "bi.vtape", + items, + }, + this._getSuitableSize() + ); + } + mounted() { + const { placement } = this.options; + switch (placement) { + case "right": + this.element.css({ + top: 0, + left: "100%", + bottom: 0, + }); + break; + case "left": + this.element.css({ + top: 0, + right: "100%", + bottom: 0, + }); + break; + case "top": + this.element.css({ + left: 0, + right: 0, + bottom: "100%", + }); + break; + case "bottom": + this.element.css({ + left: 0, + right: 0, + top: "100%", + }); + break; + default: + break; + } + } - show(callback) { - const { placement } = this.options; - requestAnimationFrame(() => { - const size = this._getSuitableSize(); - switch (placement) { - case "right": - this.element.css({ - left: `calc(100% - ${size.width}px)`, - }); - break; - case "left": - this.element.css({ - right: `calc(100% - ${size.width}px)`, - }); - break; - case "top": - this.element.css({ - bottom: `calc(100% - ${size.height}px)`, - }); - break; - case "bottom": - this.element.css({ - top: `calc(100% - ${size.height}px)`, - }); - break; - default: - break; - } - callback && callback(); - }); - } + show(callback) { + const { placement } = this.options; + requestAnimationFrame(() => { + const size = this._getSuitableSize(); + switch (placement) { + case "right": + this.element.css({ + left: `calc(100% - ${size.width}px)`, + }); + break; + case "left": + this.element.css({ + right: `calc(100% - ${size.width}px)`, + }); + break; + case "top": + this.element.css({ + bottom: `calc(100% - ${size.height}px)`, + }); + break; + case "bottom": + this.element.css({ + top: `calc(100% - ${size.height}px)`, + }); + break; + default: + break; + } + callback && callback(); + }); + } - hide(callback) { - const { placement } = this.options; - requestAnimationFrame(() => { - switch (placement) { - case "right": - this.element.css({ - left: "100%", - }); - break; - case "left": - this.element.css({ - right: "100%", - }); - break; - case "top": - this.element.css({ - bottom: "100%", - }); - break; - case "bottom": - this.element.css({ - top: "100%", - }); - break; - default: - break; - } - setTimeout(callback, 300); - }); - } + hide(callback) { + const { placement } = this.options; + requestAnimationFrame(() => { + switch (placement) { + case "right": + this.element.css({ + left: "100%", + }); + break; + case "left": + this.element.css({ + right: "100%", + }); + break; + case "top": + this.element.css({ + bottom: "100%", + }); + break; + case "bottom": + this.element.css({ + top: "100%", + }); + break; + default: + break; + } + setTimeout(callback, 300); + }); + } - open() { - this.show(() => { - this.fireEvent(Drawer.EVENT_OPEN); - }); - } + open() { + this.show(() => { + this.fireEvent(Drawer.EVENT_OPEN); + }); + } - close() { - this.hide(() => { - this.fireEvent(Drawer.EVENT_CLOSE); - }); - } + close() { + this.hide(() => { + this.fireEvent(Drawer.EVENT_CLOSE); + }); + } - setZindex(zindex) { - this.element.css({ "z-index": zindex }); - } + setZindex(zindex) { + this.element.css({ "z-index": zindex }); + } - destroyed() { - } + destroyed() {} } - diff --git a/src/base/layer/layer.popover.js b/src/base/layer/layer.popover.js index 3521af648..4b766acff 100644 --- a/src/base/layer/layer.popover.js +++ b/src/base/layer/layer.popover.js @@ -1,279 +1,331 @@ +import { + HTapeLayout, + AbsoluteLayout, + VerticalLayout, + Widget, + shortcut, + clamp, + isPlainObject, + extend, + isNotNull +} from "@/core"; +import { Label, IconButton, Button } from "../single"; + /** * Popover弹出层, * @class BI.Popover * @extends BI.Widget */ -import { Widget, shortcut, clamp, isPlainObject, extend, isNotNull } from "../../core"; @shortcut() export class Popover extends Widget { - _constant = { - SIZE: { - SMALL: "small", - NORMAL: "normal", - BIG: "big", - }, - MAX_HEIGHT: 600, - } - - props() { - return { - baseCls: "bi-popover bi-card bi-border-radius", - size: "normal", // small, normal, big - logic: { - dynamic: false, - }, - header: null, - headerHeight: 40, - body: null, - footer: null, - footerHeight: 44, - closable: true, // BI-40839 是否显示右上角的关闭按钮 - bodyHgap: BI.SIZE_CONSANTS.H_GAP_SIZE, - bodyTgap: BI.SIZE_CONSANTS.V_GAP_SIZE, - }; - } + _constant = { + SIZE: { + SMALL: "small", + NORMAL: "normal", + BIG: "big", + }, + MAX_HEIGHT: 600, + }; - static xtype = "bi.popover"; - static EVENT_CLOSE = "EVENT_CLOSE"; - static EVENT_OPEN = "EVENT_OPEN"; - static EVENT_CANCEL = "EVENT_CANCEL"; - static EVENT_CONFIRM = "EVENT_CONFIRM"; + props() { + return { + baseCls: "bi-popover bi-card bi-border-radius", + size: "normal", // small, normal, big + logic: { + dynamic: false, + }, + header: null, + headerHeight: 40, + body: null, + footer: null, + footerHeight: 44, + closable: true, // BI-40839 是否显示右上角的关闭按钮 + bodyHgap: BI.SIZE_CONSANTS.H_GAP_SIZE, + bodyTgap: BI.SIZE_CONSANTS.V_GAP_SIZE, + }; + } - render() { - // var self = this; - const { header, headerHeight, closable, logic, footer, footerHeight, body, bodyTgap, bodyHgap } = this.options; - const c = this._constant; - this.startX = 0; - this.startY = 0; - const size = this._calculateSize(); - this.tracker = new BI.MouseMoveTracker((deltaX, deltaY) => { - const W = Widget._renderEngine.createElement("body").width(); - const H = Widget._renderEngine.createElement("body").height(); - this.startX += deltaX; - this.startY += deltaY; - this.element.css({ - left: `${clamp(this.startX, 0, W - this.element.width())}px`, - top: `${clamp(this.startY, 0, H - this.element.height())}px`, - }); - // BI-12134 没有什么特别好的方法 - BI.Resizers._resize({ - target: this.element[0], - }); - }, () => { - this.tracker.releaseMouseMoves(); - }, _global); - const items = [{ - el: { - type: "bi.htape", - cls: "bi-message-title bi-header-background", - items: [{ - el: { - type: "bi.absolute", - ref: _ref => { - this.dragger = _ref; - }, - items: [{ - el: isPlainObject(header) ? extend({}, header, { - extraCls: "bi-font-bold", - }) : { - type: "bi.label", - cls: "bi-font-bold", - height: headerHeight, - text: header, - title: header, - textAlign: "left", - }, - top: 0, - bottom: 0, - left: BI.SIZE_CONSANTS.H_GAP_SIZE, - right: closable ? 0 : BI.SIZE_CONSANTS.H_GAP_SIZE, - }], - }, - }, closable ? { - el: { - type: "bi.icon_button", - cls: "bi-message-close close-font", - height: headerHeight, - handler: () => { - this.close(); - }, - }, - width: 56, - } : null], - height: headerHeight, - }, - height: headerHeight, - }, logic.dynamic ? { - el: { - type: "bi.vertical", - scrolly: true, - cls: "popover-body", - ref: _ref => { - this.body = _ref; - }, - css: { - "max-height": this._getSuitableBodyHeight(c.MAX_HEIGHT - headerHeight - (footer ? footerHeight : 0) - bodyTgap), - "min-height": this._getSuitableBodyHeight(size.height - headerHeight - (footer ? footerHeight : 0) - bodyTgap), - }, - items: [{ - el: body, - }], - hgap: bodyHgap, - tgap: bodyTgap, - }, - } : { - el: { - type: "bi.absolute", - items: [{ - el: body, - left: bodyHgap, - top: bodyTgap, - right: bodyHgap, - bottom: 0, - }], - }, - }]; - if (footer) { - items.push({ - el: { - type: "bi.absolute", - items: [{ - el: footer, - left: BI.SIZE_CONSANTS.H_GAP_SIZE, - top: 0, - right: BI.SIZE_CONSANTS.H_GAP_SIZE, - bottom: 0, - }], - height: footerHeight, - }, - height: footerHeight, - }); - } + static xtype = "bi.popover"; + static EVENT_CLOSE = "EVENT_CLOSE"; + static EVENT_OPEN = "EVENT_OPEN"; + static EVENT_CANCEL = "EVENT_CANCEL"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; - return extend({ - items, - width: this._getSuitableWidth(size.width), - }, logic.dynamic ? { - type: "bi.vertical", - scrolly: false, - } : { - type: "bi.vtape", - height: this._getSuitableHeight(size.height), - }); - } - // mounted之后绑定事件 - mounted() { - this.dragger.element.mousedown(e => { - if (this.options.draggable !== false) { - this.startX = this.element[0].offsetLeft; - this.startY = this.element[0].offsetTop; - this.tracker.captureMouseMoves(e); - } - }); - } + render() { + // var self = this; + const { header, headerHeight, closable, logic, footer, footerHeight, body, bodyTgap, bodyHgap } = this.options; + const c = this._constant; + this.startX = 0; + this.startY = 0; + const size = this._calculateSize(); + this.tracker = new BI.MouseMoveTracker( + (deltaX, deltaY) => { + const W = Widget._renderEngine.createElement("body").width(); + const H = Widget._renderEngine.createElement("body").height(); + this.startX += deltaX; + this.startY += deltaY; + this.element.css({ + left: `${clamp(this.startX, 0, W - this.element.width())}px`, + top: `${clamp(this.startY, 0, H - this.element.height())}px`, + }); + // BI-12134 没有什么特别好的方法 + BI.Resizers._resize({ + target: this.element[0], + }); + }, + () => { + this.tracker.releaseMouseMoves(); + }, + _global + ); + const items = [ + { + el: { + type: HTapeLayout.xtype, + cls: "bi-message-title bi-header-background", + items: [ + { + el: { + type: AbsoluteLayout.xtype, + ref: _ref => { + this.dragger = _ref; + }, + items: [ + { + el: isPlainObject(header) + ? extend({}, header, { + extraCls: "bi-font-bold", + }) + : { + type: Label.xtype, + cls: "bi-font-bold", + height: headerHeight, + text: header, + title: header, + textAlign: "left", + }, + top: 0, + bottom: 0, + left: BI.SIZE_CONSANTS.H_GAP_SIZE, + right: closable ? 0 : BI.SIZE_CONSANTS.H_GAP_SIZE, + } + ], + }, + }, + closable + ? { + el: { + type: IconButton.xtype, + cls: "bi-message-close close-font", + height: headerHeight, + handler: () => { + this.close(); + }, + }, + width: 56, + } + : null + ], + height: headerHeight, + }, + height: headerHeight, + }, + logic.dynamic + ? { + el: { + type: VerticalLayout.xtype, + scrolly: true, + cls: "popover-body", + ref: _ref => { + this.body = _ref; + }, + css: { + "max-height": this._getSuitableBodyHeight( + c.MAX_HEIGHT - headerHeight - (footer ? footerHeight : 0) - bodyTgap + ), + "min-height": this._getSuitableBodyHeight( + size.height - headerHeight - (footer ? footerHeight : 0) - bodyTgap + ), + }, + items: [ + { + el: body, + } + ], + hgap: bodyHgap, + tgap: bodyTgap, + }, + } + : { + el: { + type: AbsoluteLayout.xtype, + items: [ + { + el: body, + left: bodyHgap, + top: bodyTgap, + right: bodyHgap, + bottom: 0, + } + ], + }, + } + ]; + if (footer) { + items.push({ + el: { + type: AbsoluteLayout.xtype, + items: [ + { + el: footer, + left: BI.SIZE_CONSANTS.H_GAP_SIZE, + top: 0, + right: BI.SIZE_CONSANTS.H_GAP_SIZE, + bottom: 0, + } + ], + height: footerHeight, + }, + height: footerHeight, + }); + } - _getSuitableBodyHeight(height) { - const { headerHeight, footer, footerHeight, bodyTgap } = this.options; + return extend( + { + items, + width: this._getSuitableWidth(size.width), + }, + logic.dynamic + ? { + type: VerticalLayout.xtype, + scrolly: false, + } + : { + type: "bi.vtape", + height: this._getSuitableHeight(size.height), + } + ); + } + // mounted之后绑定事件 + mounted() { + this.dragger.element.mousedown(e => { + if (this.options.draggable !== false) { + this.startX = this.element[0].offsetLeft; + this.startY = this.element[0].offsetTop; + this.tracker.captureMouseMoves(e); + } + }); + } - return clamp(height, 0, Widget._renderEngine.createElement("body")[0].clientHeight - headerHeight - (footer ? footerHeight : 0) - bodyTgap); - } + _getSuitableBodyHeight(height) { + const { headerHeight, footer, footerHeight, bodyTgap } = this.options; - _getSuitableHeight(height) { - return clamp(height, 0, Widget._renderEngine.createElement("body")[0].clientHeight); - } + return clamp( + height, + 0, + Widget._renderEngine.createElement("body")[0].clientHeight - + headerHeight - + (footer ? footerHeight : 0) - + bodyTgap + ); + } - _getSuitableWidth(width) { - return clamp(width, 0, Widget._renderEngine.createElement("body").width()); - } + _getSuitableHeight(height) { + return clamp(height, 0, Widget._renderEngine.createElement("body")[0].clientHeight); + } - _calculateSize() { - const { size, width, height } = this.options; - const sizeValue = {}; - if (isNotNull(size)) { - switch (size) { - case this._constant.SIZE.SMALL: - sizeValue.width = 450; - sizeValue.height = 200; - sizeValue.type = "small"; - break; - case this._constant.SIZE.BIG: - sizeValue.width = 900; - sizeValue.height = 500; - sizeValue.type = "big"; - break; - default: - sizeValue.width = 550; - sizeValue.height = 500; - sizeValue.type = "default"; - } - } + _getSuitableWidth(width) { + return clamp(width, 0, Widget._renderEngine.createElement("body").width()); + } - return { - width: width || sizeValue.width, - height: height || sizeValue.height, - type: sizeValue.type || "default", - }; - } - setDraggable(b) { - this.options.draggable = b; - } + _calculateSize() { + const { size, width, height } = this.options; + const sizeValue = {}; + if (isNotNull(size)) { + switch (size) { + case this._constant.SIZE.SMALL: + sizeValue.width = 450; + sizeValue.height = 200; + sizeValue.type = "small"; + break; + case this._constant.SIZE.BIG: + sizeValue.width = 900; + sizeValue.height = 500; + sizeValue.type = "big"; + break; + default: + sizeValue.width = 550; + sizeValue.height = 500; + sizeValue.type = "default"; + } + } - hide() { + return { + width: width || sizeValue.width, + height: height || sizeValue.height, + type: sizeValue.type || "default", + }; + } + setDraggable(b) { + this.options.draggable = b; + } - } + hide() {} - open() { - this.show(); - this.fireEvent(Popover.EVENT_OPEN, arguments); - } + open() { + this.show(); + this.fireEvent(Popover.EVENT_OPEN, arguments); + } - close() { - this.hide(); - this.fireEvent(Popover.EVENT_CLOSE, arguments); - } + close() { + this.hide(); + this.fireEvent(Popover.EVENT_CLOSE, arguments); + } - setZindex(zindex) { - this.element.css({ "z-index": zindex }); - } + setZindex(zindex) { + this.element.css({ "z-index": zindex }); + } } @shortcut() export class BarPopover extends Popover { - static xtype = "bi.bar_popover"; + static xtype = "bi.bar_popover"; - _defaultConfig() { - return extend(super._defaultConfig(...arguments), { - btns: [BI.i18nText("BI-Basic_OK"), BI.i18nText("BI-Basic_Cancel")], - }); - } + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { + btns: [BI.i18nText("BI-Basic_OK"), BI.i18nText("BI-Basic_Cancel")], + }); + } - beforeCreate() { - const { footer, warningTitle } = this.options; - footer || (this.options.footer = { - type: "bi.right_vertical_adapt", - lgap: 10, - items: [{ - type: "bi.button", - text: this.options.btns[1], - value: 1, - level: "ignore", - handler: v => { - this.fireEvent(Popover.EVENT_CANCEL, v); - this.close(v); - }, - }, { - type: "bi.button", - text: this.options.btns[0], - warningTitle, - value: 0, - handler: v => { - this.fireEvent(Popover.EVENT_CONFIRM, v); - this.close(v); - }, - }], - }); - } + beforeCreate() { + const { footer, warningTitle } = this.options; + footer || + (this.options.footer = { + type: "bi.right_vertical_adapt", + lgap: 10, + items: [ + { + type: Button.xtype, + text: this.options.btns[1], + value: 1, + level: "ignore", + handler: v => { + this.fireEvent(Popover.EVENT_CANCEL, v); + this.close(v); + }, + }, + { + type: Button.xtype, + text: this.options.btns[0], + warningTitle, + value: 0, + handler: v => { + this.fireEvent(Popover.EVENT_CONFIRM, v); + this.close(v); + }, + } + ], + }); + } } - - diff --git a/src/base/layer/layer.popup.js b/src/base/layer/layer.popup.js index 6151faec0..9f654efd0 100644 --- a/src/base/layer/layer.popup.js +++ b/src/base/layer/layer.popup.js @@ -1,432 +1,511 @@ +import { ButtonGroup } from "../combination/group.button"; +import { + VerticalLayout, + AbsoluteLayout, + Layout, + CenterLayout, + Widget, + shortcut, + extend, + Controller, + createWidget, + createItems, + clamp +} from "@/core"; + /** * 下拉框弹出层, zIndex在1000w * @class BI.PopupView * @extends BI.Widget */ -import { Widget, shortcut, extend, Controller, createWidget, createItems, clamp } from "../../core"; @shortcut() export class PopupView extends Widget { - _const = { - TRIANGLE_LENGTH: 12, - } + _const = { + TRIANGLE_LENGTH: 12, + }; - static xtype = "bi.popup_view"; - static EVENT_CHANGE = "EVENT_CHANGE"; + static xtype = "bi.popup_view"; + static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig(props) { - return extend(super._defaultConfig(...arguments), { - _baseCls: `bi-popup-view${props.primary ? " bi-primary" : ""}`, - // 品牌色 - primary: false, - maxWidth: "auto", - minWidth: 100, - // maxHeight: 200, - minHeight: 24, - lgap: 0, - rgap: 0, - tgap: 0, - bgap: 0, - vgap: 0, - hgap: 0, - innerVgap: 0, - innerHgap: 0, - showArrow: false, - direction: BI.Direction.Top, // 工具栏的方向 - stopEvent: false, // 是否停止mousedown、mouseup事件 - stopPropagation: false, // 是否停止mousedown、mouseup向上冒泡 - logic: { - dynamic: true, - }, + _defaultConfig(props) { + return extend(super._defaultConfig(...arguments), { + _baseCls: `bi-popup-view${props.primary ? " bi-primary" : ""}`, + // 品牌色 + primary: false, + maxWidth: "auto", + minWidth: 100, + // maxHeight: 200, + minHeight: 24, + lgap: 0, + rgap: 0, + tgap: 0, + bgap: 0, + vgap: 0, + hgap: 0, + innerVgap: 0, + innerHgap: 0, + showArrow: false, + direction: BI.Direction.Top, // 工具栏的方向 + stopEvent: false, // 是否停止mousedown、mouseup事件 + stopPropagation: false, // 是否停止mousedown、mouseup向上冒泡 + logic: { + dynamic: true, + }, - tool: false, // 自定义工具栏 - tabs: [], // 导航栏 - buttons: [], // toolbar栏 + tool: false, // 自定义工具栏 + tabs: [], // 导航栏 + buttons: [], // toolbar栏 - el: { - type: "bi.button_group", - items: [], - chooseType: 0, - behaviors: {}, - layouts: [{ - type: "bi.vertical", - }], - }, - }); - } - render() { - const { minWidth, maxWidth, stopPropagation, stopEvent, - direction, logic, lgap, rgap, tgap, bgap, vgap, hgap, primary, showArrow } = this.options; - function fn (e) { - e.stopPropagation(); - } - function stop (e) { - e.stopEvent(); + el: { + type: ButtonGroup.xtype, + items: [], + chooseType: 0, + behaviors: {}, + layouts: [ + { + type: VerticalLayout.xtype, + } + ], + }, + }); + } + render() { + const { + minWidth, + maxWidth, + stopPropagation, + stopEvent, + direction, + logic, + lgap, + rgap, + tgap, + bgap, + vgap, + hgap, + primary, + showArrow, + } = this.options; + function fn(e) { + e.stopPropagation(); + } + function stop(e) { + e.stopEvent(); - return false; - } - this.element.css({ - "z-index": BI.zIndex_popup, - "min-width": BI.pixFormat(minWidth), - "max-width": BI.pixFormat(maxWidth), - }).bind({ click: fn }); + return false; + } + this.element + .css({ + "z-index": BI.zIndex_popup, + "min-width": BI.pixFormat(minWidth), + "max-width": BI.pixFormat(maxWidth), + }) + .bind({ click: fn }); - this.element.bind("mousewheel", fn); + this.element.bind("mousewheel", fn); - stopPropagation && this.element.bind({ mousedown: fn, mouseup: fn, mouseover: fn }); - stopEvent && this.element.bind({ mousedown: stop, mouseup: stop, mouseover: stop }); - this.tool = this._createTool(); - this.tab = this._createTab(); - this.view = this._createView(); - this.toolbar = this._createToolBar(); + stopPropagation && this.element.bind({ mousedown: fn, mouseup: fn, mouseover: fn }); + stopEvent && this.element.bind({ mousedown: stop, mouseup: stop, mouseover: stop }); + this.tool = this._createTool(); + this.tab = this._createTab(); + this.view = this._createView(); + this.toolbar = this._createToolBar(); - this.view.on(Controller.EVENT_CHANGE, (type, ...args) => { - this.fireEvent(Controller.EVENT_CHANGE, type, ...args); - if (type === BI.Events.CLICK) { - this.fireEvent(PopupView.EVENT_CHANGE); - } - }); + this.view.on(Controller.EVENT_CHANGE, (type, ...args) => { + this.fireEvent(Controller.EVENT_CHANGE, type, ...args); + if (type === BI.Events.CLICK) { + this.fireEvent(PopupView.EVENT_CHANGE); + } + }); - createWidget(extend({ - element: this, - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(direction), extend({}, logic, { - scrolly: false, - lgap, - rgap, - tgap, - bgap, - vgap, - hgap, - items: BI.LogicFactory.createLogicItemsByDirection(direction, extend({ - cls: `list-view-outer bi-card list-view-shadow${primary ? " bi-primary" : ""}`, - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(direction), extend({}, logic, { - items: BI.LogicFactory.createLogicItemsByDirection(direction, this.tool, this.tab, this.view, this.toolbar), - }))) - ), - })))); - if (showArrow) { - this.arrow = createWidget({ - type: "bi.absolute", - cls: "bi-bubble-arrow", - items: [{ - type: "bi.layout", - cls: "bubble-arrow", - }], - }); - this.arrowWrapper = createWidget({ - type: "bi.absolute", - cls: "bi-bubble-arrow-wrapper", - items: [{ - el: this.arrow, - }], - }); - // 因为三角符号的原因位置变大了,需要占位 - this.placeholder = createWidget({ - type: "bi.layout", - }); - createWidget({ - type: "bi.absolute", - element: this, - items: [{ - el: this.arrowWrapper, - left: 0, - top: 0, - }, { - el: this.placeholder, - }], - }); - } - } - _createView() { - const { el, value, minHeight, innerVgap, innerHgap } = this.options; - this.button_group = createWidget(el, { type: "bi.button_group", value }); - this.button_group.element.css({ - "min-height": BI.pixFormat(minHeight), - "padding-top": BI.pixFormat(innerVgap), - "padding-bottom": BI.pixFormat(innerVgap), - "padding-left": BI.pixFormat(innerHgap), - "padding-right": BI.pixFormat(innerHgap), - }); + createWidget( + extend( + { + element: this, + }, + BI.LogicFactory.createLogic( + BI.LogicFactory.createLogicTypeByDirection(direction), + extend({}, logic, { + scrolly: false, + lgap, + rgap, + tgap, + bgap, + vgap, + hgap, + items: BI.LogicFactory.createLogicItemsByDirection( + direction, + extend( + { + cls: `list-view-outer bi-card list-view-shadow${primary ? " bi-primary" : ""}`, + }, + BI.LogicFactory.createLogic( + BI.LogicFactory.createLogicTypeByDirection(direction), + extend({}, logic, { + items: BI.LogicFactory.createLogicItemsByDirection( + direction, + this.tool, + this.tab, + this.view, + this.toolbar + ), + }) + ) + ) + ), + }) + ) + ) + ); + if (showArrow) { + this.arrow = createWidget({ + type: AbsoluteLayout.xtype, + cls: "bi-bubble-arrow", + items: [ + { + type: Layout.xtype, + cls: "bubble-arrow", + } + ], + }); + this.arrowWrapper = createWidget({ + type: AbsoluteLayout.xtype, + cls: "bi-bubble-arrow-wrapper", + items: [ + { + el: this.arrow, + } + ], + }); + // 因为三角符号的原因位置变大了,需要占位 + this.placeholder = createWidget({ + type: Layout.xtype, + }); + createWidget({ + type: AbsoluteLayout.xtype, + element: this, + items: [ + { + el: this.arrowWrapper, + left: 0, + top: 0, + }, + { + el: this.placeholder, + } + ], + }); + } + } + _createView() { + const { el, value, minHeight, innerVgap, innerHgap } = this.options; + this.button_group = createWidget(el, { type: ButtonGroup.xtype, value }); + this.button_group.element.css({ + "min-height": BI.pixFormat(minHeight), + "padding-top": BI.pixFormat(innerVgap), + "padding-bottom": BI.pixFormat(innerVgap), + "padding-left": BI.pixFormat(innerHgap), + "padding-right": BI.pixFormat(innerHgap), + }); - return this.button_group; - } + return this.button_group; + } - _createTool() { - const { tool } = this.options; - if (false === tool) { - return; - } + _createTool() { + const { tool } = this.options; + if (false === tool) { + return; + } - return createWidget(tool); - } + return createWidget(tool); + } - _createTab() { - const { tabs, value } = this.options; - if (tabs.length === 0) { - return; - } + _createTab() { + const { tabs, value } = this.options; + if (tabs.length === 0) { + return; + } - return createWidget({ - type: "bi.center", - cls: "list-view-tab", - height: 25, - items: tabs, - value, - }); - } + return createWidget({ + type: CenterLayout.xtype, + cls: "list-view-tab", + height: 25, + items: tabs, + value, + }); + } - _createToolBar() { - const { buttons } = this.options; - if (buttons.length === 0) { - return; - } + _createToolBar() { + const { buttons } = this.options; + if (buttons.length === 0) { + return; + } - return createWidget({ - type: "bi.center", - cls: "list-view-toolbar bi-high-light bi-split-top", - height: 24, - items: createItems(buttons, { - once: false, - shadow: true, - isShadowShowingOnSelected: true, - }), - }); - } + return createWidget({ + type: CenterLayout.xtype, + cls: "list-view-toolbar bi-high-light bi-split-top", + height: 24, + items: createItems(buttons, { + once: false, + shadow: true, + isShadowShowingOnSelected: true, + }), + }); + } - setDirection(direction, position) { - const { showArrow, tgap, vgap, bgap, rgap, hgap, lgap } = this.options; - if (showArrow) { - let style = {}, wrapperStyle = {}, placeholderStyle = {}; - const adjustXOffset = position.adjustXOffset || 0; - const adjustYOffset = position.adjustYOffset || 0; - const bodyBounds = Widget._renderEngine.createElement("body").bounds(); - const bodyWidth = bodyBounds.width; - const bodyHeight = bodyBounds.height; - const popupWidth = this.element.outerWidth(); - const popupHeight = this.element.outerHeight(); - const offset = position.offset; - const offsetStyle = position.offsetStyle; - const middle = offsetStyle === "center" || offsetStyle === "middle"; + setDirection(direction, position) { + const { showArrow, tgap, vgap, bgap, rgap, hgap, lgap } = this.options; + if (showArrow) { + let style = {}, + wrapperStyle = {}, + placeholderStyle = {}; + const adjustXOffset = position.adjustXOffset || 0; + const adjustYOffset = position.adjustYOffset || 0; + const bodyBounds = Widget._renderEngine.createElement("body").bounds(); + const bodyWidth = bodyBounds.width; + const bodyHeight = bodyBounds.height; + const popupWidth = this.element.outerWidth(); + const popupHeight = this.element.outerHeight(); + const offset = position.offset; + const offsetStyle = position.offsetStyle; + const middle = offsetStyle === "center" || offsetStyle === "middle"; - const minLeft = Math.max(4, offset.left + 4 + popupWidth - bodyWidth); - const minRight = Math.max(4, popupWidth - (offset.left + 4)); - const minTop = Math.max(4, offset.top + 4 + popupHeight - bodyHeight); - const minBottom = Math.max(4, popupHeight - (offset.top + 4)); + const minLeft = Math.max(4, offset.left + 4 + popupWidth - bodyWidth); + const minRight = Math.max(4, popupWidth - (offset.left + 4)); + const minTop = Math.max(4, offset.top + 4 + popupHeight - bodyHeight); + const minBottom = Math.max(4, popupHeight - (offset.top + 4)); - const maxLeft = Math.min(popupWidth - 16 - 4, offset.left + position.width - 16 - 4); - const maxRight = Math.min(popupWidth - 16 - 4, bodyWidth - (offset.left + position.width - 16 - 4)); - const maxTop = Math.min(popupHeight - 16 - 4, offset.top + position.height - 16 - 4); - const maxBottom = Math.min(popupHeight - 16 - 4, bodyHeight - (offset.top + position.height - 16 - 4)); - switch (direction) { - case "bottom": - case "bottom,right": - direction = "bottom"; - style = { - // 5表示留出一定的空间 - left: clamp(((middle ? popupWidth : position.width) - adjustXOffset) / 2 - 8, minLeft, maxLeft), - }; - wrapperStyle = { - top: tgap + vgap, - left: 0, - right: "", - bottom: "", - }; - placeholderStyle = { - left: 0, - right: 0, - height: this._const.TRIANGLE_LENGTH, - top: -this._const.TRIANGLE_LENGTH, - bottom: "", - }; - break; - case "bottom,left": - direction = "bottom"; - style = { - right: clamp(((middle ? popupWidth : position.width) + adjustXOffset) / 2 - 8, minRight, maxRight), - }; - wrapperStyle = { - top: bgap + vgap, - left: "", - right: 0, - bottom: "", - }; - placeholderStyle = { - left: 0, - right: 0, - height: this._const.TRIANGLE_LENGTH, - top: -this._const.TRIANGLE_LENGTH, - bottom: "", - }; - break; - case "top": - case "top,right": - direction = "top"; - style = { - left: clamp(((middle ? popupWidth : position.width) - adjustXOffset) / 2 - 8, minLeft, maxLeft), - }; - wrapperStyle = { - bottom: bgap + vgap, - left: 0, - right: "", - top: "", - }; - placeholderStyle = { - left: 0, - right: 0, - height: this._const.TRIANGLE_LENGTH, - top: "", - bottom: -this._const.TRIANGLE_LENGTH, - }; - break; - case "top,left": - direction = "top"; - style = { - right: clamp(((middle ? popupWidth : position.width) + adjustXOffset) / 2 - 8, minRight, maxRight), - }; - wrapperStyle = { - bottom: bgap + vgap, - right: 0, - left: "", - top: "", - }; - placeholderStyle = { - left: 0, - right: 0, - height: this._const.TRIANGLE_LENGTH, - top: "", - bottom: -this._const.TRIANGLE_LENGTH, - }; - break; - case "left": - case "left,bottom": - direction = "left"; - style = { - top: clamp(((middle ? popupHeight : position.height) - adjustYOffset) / 2 - 8, minTop, maxTop), - }; - wrapperStyle = { - right: rgap + hgap, - top: 0, - bottom: "", - left: "", - }; - placeholderStyle = { - top: 0, - bottom: 0, - width: this._const.TRIANGLE_LENGTH, - right: -this._const.TRIANGLE_LENGTH, - left: "", - }; - break; - case "left,top": - direction = "left"; - style = { - bottom: clamp(((middle ? popupHeight : position.height) + adjustYOffset) / 2 - 8, minBottom, maxBottom), - }; - wrapperStyle = { - right: rgap + hgap, - bottom: 0, - top: "", - left: "", - }; - placeholderStyle = { - top: 0, - bottom: 0, - width: this._const.TRIANGLE_LENGTH, - right: -this._const.TRIANGLE_LENGTH, - left: "", - }; - break; - case "right": - case "right,bottom": - direction = "right"; - style = { - top: clamp(((middle ? popupHeight : position.height) - adjustYOffset) / 2 - 8, minTop, maxTop), - }; - wrapperStyle = { - left: lgap + hgap, - top: 0, - bottom: "", - right: "", - }; - placeholderStyle = { - top: 0, - bottom: 0, - width: this._const.TRIANGLE_LENGTH, - left: -this._const.TRIANGLE_LENGTH, - right: "", - }; - break; - case "right,top": - direction = "right"; - style = { - bottom: clamp(((middle ? popupHeight : position.height) + adjustYOffset) / 2 - 8, minBottom, maxBottom), - }; - wrapperStyle = { - left: lgap + hgap, - bottom: 0, - top: "", - right: "", - }; - placeholderStyle = { - top: 0, - bottom: 0, - width: this._const.TRIANGLE_LENGTH, - left: -this._const.TRIANGLE_LENGTH, - right: "", - }; - break; - case "right,innerRight": - break; - case "right,innerLeft": - break; - case "innerRight": - break; - case "innerLeft": - break; - default: - break; - } - this.element - .removeClass("left") - .removeClass("right") - .removeClass("top") - .removeClass("bottom") - .addClass(direction); - this.arrow.element.css(style); - this.arrowWrapper.element.css(wrapperStyle); - this.placeholder.element.css(placeholderStyle); - } - } + const maxLeft = Math.min(popupWidth - 16 - 4, offset.left + position.width - 16 - 4); + const maxRight = Math.min(popupWidth - 16 - 4, bodyWidth - (offset.left + position.width - 16 - 4)); + const maxTop = Math.min(popupHeight - 16 - 4, offset.top + position.height - 16 - 4); + const maxBottom = Math.min(popupHeight - 16 - 4, bodyHeight - (offset.top + position.height - 16 - 4)); + switch (direction) { + case "bottom": + case "bottom,right": + direction = "bottom"; + style = { + // 5表示留出一定的空间 + left: clamp(((middle ? popupWidth : position.width) - adjustXOffset) / 2 - 8, minLeft, maxLeft), + }; + wrapperStyle = { + top: tgap + vgap, + left: 0, + right: "", + bottom: "", + }; + placeholderStyle = { + left: 0, + right: 0, + height: this._const.TRIANGLE_LENGTH, + top: -this._const.TRIANGLE_LENGTH, + bottom: "", + }; + break; + case "bottom,left": + direction = "bottom"; + style = { + right: clamp( + ((middle ? popupWidth : position.width) + adjustXOffset) / 2 - 8, + minRight, + maxRight + ), + }; + wrapperStyle = { + top: bgap + vgap, + left: "", + right: 0, + bottom: "", + }; + placeholderStyle = { + left: 0, + right: 0, + height: this._const.TRIANGLE_LENGTH, + top: -this._const.TRIANGLE_LENGTH, + bottom: "", + }; + break; + case "top": + case "top,right": + direction = "top"; + style = { + left: clamp(((middle ? popupWidth : position.width) - adjustXOffset) / 2 - 8, minLeft, maxLeft), + }; + wrapperStyle = { + bottom: bgap + vgap, + left: 0, + right: "", + top: "", + }; + placeholderStyle = { + left: 0, + right: 0, + height: this._const.TRIANGLE_LENGTH, + top: "", + bottom: -this._const.TRIANGLE_LENGTH, + }; + break; + case "top,left": + direction = "top"; + style = { + right: clamp( + ((middle ? popupWidth : position.width) + adjustXOffset) / 2 - 8, + minRight, + maxRight + ), + }; + wrapperStyle = { + bottom: bgap + vgap, + right: 0, + left: "", + top: "", + }; + placeholderStyle = { + left: 0, + right: 0, + height: this._const.TRIANGLE_LENGTH, + top: "", + bottom: -this._const.TRIANGLE_LENGTH, + }; + break; + case "left": + case "left,bottom": + direction = "left"; + style = { + top: clamp(((middle ? popupHeight : position.height) - adjustYOffset) / 2 - 8, minTop, maxTop), + }; + wrapperStyle = { + right: rgap + hgap, + top: 0, + bottom: "", + left: "", + }; + placeholderStyle = { + top: 0, + bottom: 0, + width: this._const.TRIANGLE_LENGTH, + right: -this._const.TRIANGLE_LENGTH, + left: "", + }; + break; + case "left,top": + direction = "left"; + style = { + bottom: clamp( + ((middle ? popupHeight : position.height) + adjustYOffset) / 2 - 8, + minBottom, + maxBottom + ), + }; + wrapperStyle = { + right: rgap + hgap, + bottom: 0, + top: "", + left: "", + }; + placeholderStyle = { + top: 0, + bottom: 0, + width: this._const.TRIANGLE_LENGTH, + right: -this._const.TRIANGLE_LENGTH, + left: "", + }; + break; + case "right": + case "right,bottom": + direction = "right"; + style = { + top: clamp(((middle ? popupHeight : position.height) - adjustYOffset) / 2 - 8, minTop, maxTop), + }; + wrapperStyle = { + left: lgap + hgap, + top: 0, + bottom: "", + right: "", + }; + placeholderStyle = { + top: 0, + bottom: 0, + width: this._const.TRIANGLE_LENGTH, + left: -this._const.TRIANGLE_LENGTH, + right: "", + }; + break; + case "right,top": + direction = "right"; + style = { + bottom: clamp( + ((middle ? popupHeight : position.height) + adjustYOffset) / 2 - 8, + minBottom, + maxBottom + ), + }; + wrapperStyle = { + left: lgap + hgap, + bottom: 0, + top: "", + right: "", + }; + placeholderStyle = { + top: 0, + bottom: 0, + width: this._const.TRIANGLE_LENGTH, + left: -this._const.TRIANGLE_LENGTH, + right: "", + }; + break; + case "right,innerRight": + break; + case "right,innerLeft": + break; + case "innerRight": + break; + case "innerLeft": + break; + default: + break; + } + this.element + .removeClass("left") + .removeClass("right") + .removeClass("top") + .removeClass("bottom") + .addClass(direction); + this.arrow.element.css(style); + this.arrowWrapper.element.css(wrapperStyle); + this.placeholder.element.css(placeholderStyle); + } + } - getView() { - return this.view; - } + getView() { + return this.view; + } - populate(items) { - this.view.populate(...arguments); - } + populate(items) { + this.view.populate(...arguments); + } - resetWidth(w) { - this.options.width = w; - this.element.width(w); - } + resetWidth(w) { + this.options.width = w; + this.element.width(w); + } - resetHeight(h) { - const tbHeight = this.toolbar ? (this.toolbar.attr("height") || 24) : 0, - tabHeight = this.tab ? (this.tab.attr("height") || 24) : 0, - toolHeight = ((this.tool && this.tool.attr("height")) || 24) * ((this.tool && this.tool.isVisible()) ? 1 : 0); - const resetHeight = h - tbHeight - tabHeight - toolHeight - 2 * this.options.innerVgap; - this.view.resetHeight ? this.view.resetHeight(resetHeight) : - this.view.element.css({ "max-height": BI.pixFormat(resetHeight) }); - } + resetHeight(h) { + const tbHeight = this.toolbar ? this.toolbar.attr("height") || 24 : 0, + tabHeight = this.tab ? this.tab.attr("height") || 24 : 0, + toolHeight = ((this.tool && this.tool.attr("height")) || 24) * (this.tool && this.tool.isVisible() ? 1 : 0); + const resetHeight = h - tbHeight - tabHeight - toolHeight - 2 * this.options.innerVgap; + this.view.resetHeight + ? this.view.resetHeight(resetHeight) + : this.view.element.css({ "max-height": BI.pixFormat(resetHeight) }); + } - setValue(selectedValues) { - this.tab && this.tab.setValue(selectedValues); - this.view.setValue(selectedValues); - } + setValue(selectedValues) { + this.tab && this.tab.setValue(selectedValues); + this.view.setValue(selectedValues); + } - getValue() { - return this.view.getValue(); - } + getValue() { + return this.view.getValue(); + } } - diff --git a/src/base/layer/layer.searcher.js b/src/base/layer/layer.searcher.js index cf9d961db..e93cc9a0a 100644 --- a/src/base/layer/layer.searcher.js +++ b/src/base/layer/layer.searcher.js @@ -1,3 +1,7 @@ +import { ButtonGroup } from "../combination"; +import { VerticalLayout, Layout, shortcut, extend, createWidget, Controller, isNotEmptyArray } from "@/core"; +import { Pane } from "../1.pane"; + /** * 搜索面板 * @@ -6,132 +10,135 @@ * @extends BI.Pane */ -import { shortcut, extend, createWidget, Controller, isNotEmptyArray } from "../../core"; -import { Pane } from "../1.pane"; - @shortcut() export class SearcherView extends Pane { - static xtype = "bi.searcher_view"; - static EVENT_CHANGE = "EVENT_CHANGE"; - - _defaultConfig() { - const conf = super._defaultConfig(...arguments); - - return extend(conf, { - baseCls: `${conf.baseCls || ""} bi-searcher-view bi-card`, - tipText: BI.i18nText("BI-No_Select"), - chooseType: BI.Selection.Single, - - matcher: { // 完全匹配的构造器 - type: "bi.button_group", - behaviors: { - redmark: () => true, - }, - items: [], - layouts: [{ - type: "bi.vertical", - }], - }, - searcher: { - type: "bi.button_group", - behaviors: { - redmark: () => true, - }, - items: [], - layouts: [{ - type: "bi.vertical", - }], - }, - }); - } - render() { - const { matcher, chooseType, value, searcher } = this.options; - - this.matcher = createWidget(matcher, { - type: "bi.button_group", - chooseType, - behaviors: { - redmark: () => true, - }, - layouts: [{ - type: "bi.vertical", - }], - value, - }); - this.matcher.on(Controller.EVENT_CHANGE, (type, val, ob, ...args) => { - this.fireEvent(Controller.EVENT_CHANGE, type, val, ob, ...args); - if (type === BI.Events.CLICK) { - this.fireEvent(SearcherView.EVENT_CHANGE, val, ob); - } - }); - this.spliter = createWidget({ - type: "bi.vertical", - height: 1, - hgap: 10, - items: [{ - type: "bi.layout", - height: 1, - cls: "searcher-view-spliter bi-background", - }], - }); - this.searcher = createWidget(searcher, { - type: "bi.button_group", - chooseType, - behaviors: { - redmark: () => true, - }, - layouts: [{ - type: "bi.vertical", - }], - value, - }); - this.searcher.on(Controller.EVENT_CHANGE, (type, val, ob, ...args) => { - this.fireEvent(Controller.EVENT_CHANGE, type, val, ob, ...args); - if (type === BI.Events.CLICK) { - this.fireEvent(BI.SearcherView.EVENT_CHANGE, val, ob); - } - }); - - createWidget({ - type: "bi.vertical", - element: this, - items: [this.matcher, this.spliter, this.searcher], - }); - } - - startSearch() { - - } - - stopSearch() { - - } - - setValue(v) { - this.matcher.setValue(v); - this.searcher.setValue(v); - } - - getValue() { - return this.matcher.getValue().concat(this.searcher.getValue()); - } - - populate(searchResult, matchResult, keyword) { - searchResult || (searchResult = []); - matchResult || (matchResult = []); - this.setTipVisible(searchResult.length + matchResult.length === 0); - this.spliter.setVisible(isNotEmptyArray(matchResult) && isNotEmptyArray(searchResult)); - this.matcher.populate(matchResult, keyword); - this.searcher.populate(searchResult, keyword); - } - - empty() { - this.searcher.empty(); - this.matcher.empty(); - } - - hasMatched() { - return this.matcher.getAllButtons().length > 0; - } + static xtype = "bi.searcher_view"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-searcher-view bi-card`, + tipText: BI.i18nText("BI-No_Select"), + chooseType: BI.Selection.Single, + + matcher: { + // 完全匹配的构造器 + type: ButtonGroup.xtype, + behaviors: { + redmark: () => true, + }, + items: [], + layouts: [ + { + type: VerticalLayout.xtype, + } + ], + }, + searcher: { + type: ButtonGroup.xtype, + behaviors: { + redmark: () => true, + }, + items: [], + layouts: [ + { + type: VerticalLayout.xtype, + } + ], + }, + }); + } + render() { + const { matcher, chooseType, value, searcher } = this.options; + + this.matcher = createWidget(matcher, { + type: ButtonGroup.xtype, + chooseType, + behaviors: { + redmark: () => true, + }, + layouts: [ + { + type: VerticalLayout.xtype, + } + ], + value, + }); + this.matcher.on(Controller.EVENT_CHANGE, (type, val, ob, ...args) => { + this.fireEvent(Controller.EVENT_CHANGE, type, val, ob, ...args); + if (type === BI.Events.CLICK) { + this.fireEvent(SearcherView.EVENT_CHANGE, val, ob); + } + }); + this.spliter = createWidget({ + type: VerticalLayout.xtype, + height: 1, + hgap: 10, + items: [ + { + type: Layout.xtype, + height: 1, + cls: "searcher-view-spliter bi-background", + } + ], + }); + this.searcher = createWidget(searcher, { + type: ButtonGroup.xtype, + chooseType, + behaviors: { + redmark: () => true, + }, + layouts: [ + { + type: VerticalLayout.xtype, + } + ], + value, + }); + this.searcher.on(Controller.EVENT_CHANGE, (type, val, ob, ...args) => { + this.fireEvent(Controller.EVENT_CHANGE, type, val, ob, ...args); + if (type === BI.Events.CLICK) { + this.fireEvent(BI.SearcherView.EVENT_CHANGE, val, ob); + } + }); + + createWidget({ + type: VerticalLayout.xtype, + element: this, + items: [this.matcher, this.spliter, this.searcher], + }); + } + + startSearch() {} + + stopSearch() {} + + setValue(v) { + this.matcher.setValue(v); + this.searcher.setValue(v); + } + + getValue() { + return this.matcher.getValue().concat(this.searcher.getValue()); + } + + populate(searchResult, matchResult, keyword) { + searchResult || (searchResult = []); + matchResult || (matchResult = []); + this.setTipVisible(searchResult.length + matchResult.length === 0); + this.spliter.setVisible(isNotEmptyArray(matchResult) && isNotEmptyArray(searchResult)); + this.matcher.populate(matchResult, keyword); + this.searcher.populate(searchResult, keyword); + } + + empty() { + this.searcher.empty(); + this.matcher.empty(); + } + + hasMatched() { + return this.matcher.getAllButtons().length > 0; + } } - diff --git a/src/base/list/listview.js b/src/base/list/listview.js index f890a4986..75be306f5 100644 --- a/src/base/list/listview.js +++ b/src/base/list/listview.js @@ -1,3 +1,5 @@ +import { VerticalLayout, Widget, shortcut, extend, isFunction } from "@/core"; + /** * 边滚动边加载的列表控件 * @@ -5,7 +7,7 @@ * @class BI.ListView * @extends BI.Widget */ -import { Widget, shortcut, extend, isFunction } from "../../core"; + @shortcut() export class ListView extends Widget { props() { @@ -25,119 +27,128 @@ export class ListView extends Widget { this.cache = {}; } - static xtype = "bi.list_view"; + static xtype = "bi.list_view"; - render() { - const { el } = this.options; + render() { + const { el } = this.options; - return { - type: "bi.vertical", - items: [extend({ - type: "bi.vertical", - scrolly: false, - ref: _ref => { - this.container = _ref; - }, - }, el)], - element: this, - }; - } + return { + type: VerticalLayout.xtype, + items: [ + extend( + { + type: VerticalLayout.xtype, + scrolly: false, + ref: _ref => { + this.container = _ref; + }, + }, + el + ) + ], + element: this, + }; + } - // mounted之后绑定事件 - mounted() { - const o = this.options; - // 这里无法进行结构,因为存在赋值操作,如果使用结构则this.options的值不会跟随变化 - o.items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { - this.populate(newValue); - }) : o.items; - this._populate(); - this.element.scroll(e => { - o.scrollTop = this.element.scrollTop(); - this._calculateBlocksToRender(); - }); - let lastWidth = this.element.width(), - lastHeight = this.element.height(); - BI.ResizeDetector.addResizeListener(this, () => { - if (!this.element.is(":visible")) { - return; - } - const width = this.element.width(), - height = this.element.height(); - if (width !== lastWidth || height !== lastHeight) { - lastWidth = width; - lastHeight = height; - this._calculateBlocksToRender(); - } - }); - } + // mounted之后绑定事件 + mounted() { + const o = this.options; + // 这里无法进行结构,因为存在赋值操作,如果使用结构则this.options的值不会跟随变化 + o.items = isFunction(o.items) + ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); + }) + : o.items; + this._populate(); + this.element.scroll(e => { + o.scrollTop = this.element.scrollTop(); + this._calculateBlocksToRender(); + }); + let lastWidth = this.element.width(), + lastHeight = this.element.height(); + BI.ResizeDetector.addResizeListener(this, () => { + if (!this.element.is(":visible")) { + return; + } + const width = this.element.width(), + height = this.element.height(); + if (width !== lastWidth || height !== lastHeight) { + lastWidth = width; + lastHeight = height; + this._calculateBlocksToRender(); + } + }); + } - _renderMoreIf() { - const { scrollTop, overscanHeight, blockSize, items, itemFormatter } = this.options; - const height = this.element.height(); - const minContentHeight = scrollTop + height + overscanHeight; - let index = (this.cache[this.renderedIndex] && (this.cache[this.renderedIndex].index + blockSize)) || 0; - let cnt = this.renderedIndex + 1; - let lastHeight; + _renderMoreIf() { + const { scrollTop, overscanHeight, blockSize, items, itemFormatter } = this.options; + const height = this.element.height(); + const minContentHeight = scrollTop + height + overscanHeight; + let index = (this.cache[this.renderedIndex] && this.cache[this.renderedIndex].index + blockSize) || 0; + let cnt = this.renderedIndex + 1; + let lastHeight; - const getElementHeight = () => this.container.element.height(); + const getElementHeight = () => this.container.element.height(); - lastHeight = getElementHeight(); - while ((lastHeight) < minContentHeight && index < items.length) { - const itemsArr = items.slice(index, index + blockSize); - // eslint-disable-next-line no-loop-func - this.container.addItems(itemsArr.map((item, i) => itemFormatter(item, index + i)), this); - const addedHeight = getElementHeight() - lastHeight; - this.cache[cnt] = { - index, - scrollTop: lastHeight, - height: addedHeight, - }; - this.renderedIndex = cnt; - cnt++; - index += blockSize; - lastHeight = getElementHeight(); - } - } - _calculateBlocksToRender() { - // BI-115750 不可见状态下依赖元素实际尺寸构造的线段树会分段错误,所以不进行后续计算和线段树的初始化。 - // 这样从不可见状态变为可见状态能够重新触发线段树初始化 - if (!this.element.is(":visible")) { - return; - } - this._renderMoreIf(); - } + lastHeight = getElementHeight(); + while (lastHeight < minContentHeight && index < items.length) { + const itemsArr = items.slice(index, index + blockSize); + // eslint-disable-next-line no-loop-func + this.container.addItems( + itemsArr.map((item, i) => itemFormatter(item, index + i)), + this + ); + const addedHeight = getElementHeight() - lastHeight; + this.cache[cnt] = { + index, + scrollTop: lastHeight, + height: addedHeight, + }; + this.renderedIndex = cnt; + cnt++; + index += blockSize; + lastHeight = getElementHeight(); + } + } + _calculateBlocksToRender() { + // BI-115750 不可见状态下依赖元素实际尺寸构造的线段树会分段错误,所以不进行后续计算和线段树的初始化。 + // 这样从不可见状态变为可见状态能够重新触发线段树初始化 + if (!this.element.is(":visible")) { + return; + } + this._renderMoreIf(); + } - _populate(items) { - const { scrollTop } = this.options; - if (items && this.options.items !== items) { - this.options.items = items; - } - this._calculateBlocksToRender(); - this.element.scrollTop(scrollTop); - } + _populate(items) { + const { scrollTop } = this.options; + if (items && this.options.items !== items) { + this.options.items = items; + } + this._calculateBlocksToRender(); + this.element.scrollTop(scrollTop); + } - restore() { - this.renderedIndex = -1; - this.container.empty(); - this.cache = {}; - } + restore() { + this.renderedIndex = -1; + this.container.empty(); + this.cache = {}; + } - scrollTo(scrollTop) { - this.options.scrollTop = scrollTop; - this._calculateBlocksToRender(); - this.element.scrollTop(scrollTop); - } + scrollTo(scrollTop) { + this.options.scrollTop = scrollTop; + this._calculateBlocksToRender(); + this.element.scrollTop(scrollTop); + } - populate(items) { - if (items && this.options.items !== items) { - this.restore(); - } - this._populate(items); - } + populate(items) { + if (items && this.options.items !== items) { + this.restore(); + } + this._populate(items); + } - beforeDestroy() { - BI.ResizeDetector.removeResizeListener(this); - this.restore(); - } + beforeDestroy() { + BI.ResizeDetector.removeResizeListener(this); + this.restore(); + } } - diff --git a/src/base/list/virtualgrouplist.js b/src/base/list/virtualgrouplist.js index cb5d23e42..12c3c85be 100644 --- a/src/base/list/virtualgrouplist.js +++ b/src/base/list/virtualgrouplist.js @@ -1,3 +1,6 @@ +import { VerticalLayout, Layout, Widget, shortcut, extend, isFunction, isNumber, PrefixIntervalTree } from "@/core"; +import { VirtualGroup } from "../combination"; + /** * 同时用于virtualGroup和virtualList特性的虚拟列表 * @@ -6,7 +9,6 @@ * @extends BI.Widget */ -import { Widget, shortcut, extend, isFunction, isNumber, PrefixIntervalTree } from "../../core"; @shortcut() export class VirtualGroupList extends Widget { props() { @@ -26,167 +28,190 @@ export class VirtualGroupList extends Widget { this.renderedIndex = -1; } - static xtype = "bi.virtual_group_list"; + static xtype = "bi.virtual_group_list"; - render() { - const { rowHeight, items, el } = this.options; + render() { + const { rowHeight, items, el } = this.options; - return { - type: "bi.vertical", - items: [{ - type: "bi.layout", - ref: () => { - this.topBlank = this; - }, - }, { - type: "bi.virtual_group", - height: rowHeight * items.length, - ref: () => { - this.container = this; - }, - layouts: [extend({ - type: "bi.vertical", - scrolly: false, - }, el)], - }, { - type: "bi.layout", - ref: () => { - this.bottomBlank = this; - }, - }], - element: this, - }; - } - // mounted之后绑定事件 - mounted() { - // 这里无法进行结构,因为存在赋值操作,如果使用结构则this.options的值不会跟随变化 - const o = this.options; - o.items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { - this.populate(newValue); - }) : o.items; - this._populate(); - this.ticking = false; - this.element.scroll(() => { - o.scrollTop = this.element.scrollTop(); - if (!this.ticking) { - requestAnimationFrame(() => { - this._calculateBlocksToRender(); - this.ticking = false; - }); - this.ticking = true; - } - }); - BI.ResizeDetector.addResizeListener(this, () => { - if (this.element.is(":visible")) { - this._calculateBlocksToRender(); - } - }); - } + return { + type: VerticalLayout.xtype, + items: [ + { + type: Layout.xtype, + ref: () => { + this.topBlank = this; + }, + }, + { + type: VirtualGroup.xtype, + height: rowHeight * items.length, + ref: () => { + this.container = this; + }, + layouts: [ + extend( + { + type: VerticalLayout.xtype, + scrolly: false, + }, + el + ) + ], + }, + { + type: Layout.xtype, + ref: () => { + this.bottomBlank = this; + }, + } + ], + element: this, + }; + } + // mounted之后绑定事件 + mounted() { + // 这里无法进行结构,因为存在赋值操作,如果使用结构则this.options的值不会跟随变化 + const o = this.options; + o.items = isFunction(o.items) + ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); + }) + : o.items; + this._populate(); + this.ticking = false; + this.element.scroll(() => { + o.scrollTop = this.element.scrollTop(); + if (!this.ticking) { + requestAnimationFrame(() => { + this._calculateBlocksToRender(); + this.ticking = false; + }); + this.ticking = true; + } + }); + BI.ResizeDetector.addResizeListener(this, () => { + if (this.element.is(":visible")) { + this._calculateBlocksToRender(); + } + }); + } - _isAutoHeight() { - return !isNumber(this.options.rowHeight); - } + _isAutoHeight() { + return !isNumber(this.options.rowHeight); + } - _renderMoreIf() { - const { scrollTop, overscanHeight, blockSize, items, itemFormatter } = this.options; - const height = this.element.height(); - const minContentHeight = scrollTop + height + overscanHeight; - let index = (this.renderedIndex + 1) * blockSize, cnt = this.renderedIndex + 1; - let lastHeight; - const getElementHeight = () => this.container.element.height() + this.topBlank.element.height() + this.bottomBlank.element.height(); - lastHeight = this.renderedIndex === -1 ? 0 : getElementHeight(); - while (lastHeight < minContentHeight && index < items.length) { - const itemsArr = items.slice(index, index + blockSize); - // eslint-disable-next-line no-loop-func - this.container[this.renderedIndex === -1 ? "populate" : "addItems"](itemsArr.map((item, i) => itemFormatter(item, index + i)), this); - const elementHeight = getElementHeight(); - const addedHeight = elementHeight - lastHeight; - this.tree.set(cnt, addedHeight); - this.renderedIndex = cnt; - cnt++; - index += blockSize; - lastHeight = this.renderedIndex === -1 ? 0 : elementHeight; - } - } + _renderMoreIf() { + const { scrollTop, overscanHeight, blockSize, items, itemFormatter } = this.options; + const height = this.element.height(); + const minContentHeight = scrollTop + height + overscanHeight; + let index = (this.renderedIndex + 1) * blockSize, + cnt = this.renderedIndex + 1; + let lastHeight; + const getElementHeight = () => + this.container.element.height() + this.topBlank.element.height() + this.bottomBlank.element.height(); + lastHeight = this.renderedIndex === -1 ? 0 : getElementHeight(); + while (lastHeight < minContentHeight && index < items.length) { + const itemsArr = items.slice(index, index + blockSize); + // eslint-disable-next-line no-loop-func + this.container[this.renderedIndex === -1 ? "populate" : "addItems"]( + itemsArr.map((item, i) => itemFormatter(item, index + i)), + this + ); + const elementHeight = getElementHeight(); + const addedHeight = elementHeight - lastHeight; + this.tree.set(cnt, addedHeight); + this.renderedIndex = cnt; + cnt++; + index += blockSize; + lastHeight = this.renderedIndex === -1 ? 0 : elementHeight; + } + } - _calculateBlocksToRender() { - // BI-115750 不可见状态下依赖元素实际尺寸构造的线段树会分段错误,所以不进行后续计算和线段树的初始化。 - // 这样从不可见状态变为可见状态能够重新触发线段树初始化 - if (!this.element.is(":visible")) { - return; - } - const { scrollTop, overscanHeight, blockSize, items, itemFormatter, rowHeight } = this.options; - this._isAutoHeight() && this._renderMoreIf(); - const height = this.element.height(); - const minContentHeightFrom = scrollTop - overscanHeight; - const minContentHeightTo = scrollTop + height + overscanHeight; - const start = this.tree.greatestLowerBound(minContentHeightFrom); - const end = this.tree.leastUpperBound(minContentHeightTo); - const itemsArr = []; - const topHeight = this.tree.sumTo(Math.max(-1, start - 1)); - this.topBlank.setHeight(`${topHeight}px`); - if (this._isAutoHeight()) { - for (let i = (start < 0 ? 0 : start); i <= end && i <= this.renderedIndex; i++) { - const index = i * blockSize; - for (let j = index; j < index + blockSize && j < items.length; j++) { - itemsArr.push(items[j]); - } - } - this.bottomBlank.setHeight(`${this.tree.sumTo(this.renderedIndex) - this.tree.sumTo(Math.min(end, this.renderedIndex))}px`); - this.container.populate(itemsArr.map((item, i) => itemFormatter(item, (start < 0 ? 0 : start) * blockSize + i))); - } else { - for (let i = (start < 0 ? 0 : start); i <= end; i++) { - const index = i * blockSize; - for (let j = index; j < index + blockSize && j < items.length; j++) { - itemsArr.push(items[j]); - } - } - this.container.element.height(rowHeight * items.length - topHeight); - this.container.populate(itemsArr.map((item, i) => itemFormatter(item, (start < 0 ? 0 : start) * blockSize + i))); - } - } - _populate(items) { - const { blockSize, rowHeight, scrollTop } = this.options; - if (items && this.options.items !== items) { - // 重新populate一组items,需要重新对线段树分块 - this.options.items = items; - this._restore(); - } - this.tree = PrefixIntervalTree.uniform(Math.ceil(this.options.items.length / blockSize), this._isAutoHeight() ? 0 : rowHeight * blockSize); + _calculateBlocksToRender() { + // BI-115750 不可见状态下依赖元素实际尺寸构造的线段树会分段错误,所以不进行后续计算和线段树的初始化。 + // 这样从不可见状态变为可见状态能够重新触发线段树初始化 + if (!this.element.is(":visible")) { + return; + } + const { scrollTop, overscanHeight, blockSize, items, itemFormatter, rowHeight } = this.options; + this._isAutoHeight() && this._renderMoreIf(); + const height = this.element.height(); + const minContentHeightFrom = scrollTop - overscanHeight; + const minContentHeightTo = scrollTop + height + overscanHeight; + const start = this.tree.greatestLowerBound(minContentHeightFrom); + const end = this.tree.leastUpperBound(minContentHeightTo); + const itemsArr = []; + const topHeight = this.tree.sumTo(Math.max(-1, start - 1)); + this.topBlank.setHeight(`${topHeight}px`); + if (this._isAutoHeight()) { + for (let i = start < 0 ? 0 : start; i <= end && i <= this.renderedIndex; i++) { + const index = i * blockSize; + for (let j = index; j < index + blockSize && j < items.length; j++) { + itemsArr.push(items[j]); + } + } + this.bottomBlank.setHeight( + `${this.tree.sumTo(this.renderedIndex) - this.tree.sumTo(Math.min(end, this.renderedIndex))}px` + ); + this.container.populate( + itemsArr.map((item, i) => itemFormatter(item, (start < 0 ? 0 : start) * blockSize + i)) + ); + } else { + for (let i = start < 0 ? 0 : start; i <= end; i++) { + const index = i * blockSize; + for (let j = index; j < index + blockSize && j < items.length; j++) { + itemsArr.push(items[j]); + } + } + this.container.element.height(rowHeight * items.length - topHeight); + this.container.populate( + itemsArr.map((item, i) => itemFormatter(item, (start < 0 ? 0 : start) * blockSize + i)) + ); + } + } + _populate(items) { + const { blockSize, rowHeight, scrollTop } = this.options; + if (items && this.options.items !== items) { + // 重新populate一组items,需要重新对线段树分块 + this.options.items = items; + this._restore(); + } + this.tree = PrefixIntervalTree.uniform( + Math.ceil(this.options.items.length / blockSize), + this._isAutoHeight() ? 0 : rowHeight * blockSize + ); - this._calculateBlocksToRender(); - try { - this.element.scrollTop(scrollTop); - } catch (e) { - } - } + this._calculateBlocksToRender(); + try { + this.element.scrollTop(scrollTop); + } catch (e) {} + } - _restore() { - this.renderedIndex = -1; - // 依赖于cache的占位元素也要初始化 - this.topBlank.setHeight(0); - this.bottomBlank.setHeight(0); - } + _restore() { + this.renderedIndex = -1; + // 依赖于cache的占位元素也要初始化 + this.topBlank.setHeight(0); + this.bottomBlank.setHeight(0); + } - // 暂时只支持固定行高的场景 - scrollTo(scrollTop) { - this.options.scrollTop = scrollTop; - this._calculateBlocksToRender(); - this.element.scrollTop(scrollTop); - } + // 暂时只支持固定行高的场景 + scrollTo(scrollTop) { + this.options.scrollTop = scrollTop; + this._calculateBlocksToRender(); + this.element.scrollTop(scrollTop); + } - restore() { - this.options.scrollTop = 0; - this._restore(); - } + restore() { + this.options.scrollTop = 0; + this._restore(); + } - populate(items) { - this._populate(items); - } + populate(items) { + this._populate(items); + } - beforeDestroy() { - BI.ResizeDetector.removeResizeListener(this); - this.restore(); - } + beforeDestroy() { + BI.ResizeDetector.removeResizeListener(this); + this.restore(); + } } - diff --git a/src/base/list/virtuallist.js b/src/base/list/virtuallist.js index ec09f1b8d..7ba29103c 100644 --- a/src/base/list/virtuallist.js +++ b/src/base/list/virtuallist.js @@ -1,3 +1,5 @@ +import { VerticalLayout, Layout, Widget, shortcut, isFunction, each, PrefixIntervalTree } from "@/core"; + /** * 虚拟列表 * @@ -6,7 +8,6 @@ * @extends BI.Widget */ -import { Widget, shortcut, isFunction, each, PrefixIntervalTree } from "../../core"; @shortcut() export class VirtualList extends Widget { props() { @@ -29,33 +30,39 @@ export class VirtualList extends Widget { render() { return { - type: "bi.vertical", - items: [{ - type: "bi.layout", - ref: _ref => { - this.topBlank = _ref; - }, - }, { - type: "bi.vertical", - scrolly: false, - ref: _ref => { - this.container = _ref; + type: VerticalLayout.xtype, + items: [ + { + type: Layout.xtype, + ref: _ref => { + this.topBlank = _ref; + }, }, - }, { - type: "bi.layout", - ref: _ref => { - this.bottomBlank = _ref; + { + type: VerticalLayout.xtype, + scrolly: false, + ref: _ref => { + this.container = _ref; + }, }, - }], + { + type: Layout.xtype, + ref: _ref => { + this.bottomBlank = _ref; + }, + } + ], }; } // mounted之后绑定事件 mounted() { // 这里无法进行结构,因为存在赋值操作,如果使用结构则this.options的值不会跟随变化 const o = this.options; - o.items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { - this.populate(newValue); - }) : o.items; + o.items = isFunction(o.items) + ? this.__watch(o.items, (context, newValue) => { + this.populate(newValue); + }) + : o.items; this._populate(); this.element.scroll(e => { o.scrollTop = this.element.scrollTop(); @@ -72,14 +79,19 @@ export class VirtualList extends Widget { const { scrollTop, overscanHeight, blockSize, items, itemFormatter } = this.options; const height = this.element.height(); const minContentHeight = scrollTop + height + overscanHeight; - let index = (this.renderedIndex + 1) * blockSize, cnt = this.renderedIndex + 1; + let index = (this.renderedIndex + 1) * blockSize, + cnt = this.renderedIndex + 1; let lastHeight; - const getElementHeight = () => this.container.element.height() + this.topBlank.element.height() + this.bottomBlank.element.height(); + const getElementHeight = () => + this.container.element.height() + this.topBlank.element.height() + this.bottomBlank.element.height(); lastHeight = getElementHeight(); while (lastHeight < minContentHeight && index < items.length) { const itemsArr = items.slice(index, index + blockSize); // eslint-disable-next-line no-loop-func - this.container.addItems(itemsArr.map((item, i) => itemFormatter(item, index + i)), this); + this.container.addItems( + itemsArr.map((item, i) => itemFormatter(item, index + i)), + this + ); const addedHeight = getElementHeight() - lastHeight; this.tree.set(cnt, addedHeight); this.renderedIndex = cnt; @@ -102,7 +114,8 @@ export class VirtualList extends Widget { const minContentHeightTo = scrollTop + height + overscanHeight; const start = this.tree.greatestLowerBound(minContentHeightFrom); const end = this.tree.leastUpperBound(minContentHeightTo); - const needDestroyed = [], needMount = []; + const needDestroyed = [], + needMount = []; for (let i = 0; i < start; i++) { const index = i * blockSize; if (!this.cache[i]) { @@ -132,7 +145,7 @@ export class VirtualList extends Widget { const firstFragment = Widget._renderEngine.createFragment(), lastFragment = Widget._renderEngine.createFragment(); let currentFragment = firstFragment; - for (let i = (start < 0 ? 0 : start); i <= end && i <= this.renderedIndex; i++) { + for (let i = start < 0 ? 0 : start; i <= end && i <= this.renderedIndex; i++) { const index = i * blockSize; if (!this.cache[i]) { this.cache[i] = {}; @@ -152,7 +165,9 @@ export class VirtualList extends Widget { this.container.element.prepend(firstFragment); this.container.element.append(lastFragment); this.topBlank.setHeight(`${this.tree.sumTo(Math.max(-1, start - 1))}px`); - this.bottomBlank.setHeight(`${this.tree.sumTo(this.renderedIndex) - this.tree.sumTo(Math.min(end, this.renderedIndex))}px`); + this.bottomBlank.setHeight( + `${this.tree.sumTo(this.renderedIndex) - this.tree.sumTo(Math.min(end, this.renderedIndex))}px` + ); each(needMount, (i, child) => { child && child._mount(); }); @@ -170,8 +185,7 @@ export class VirtualList extends Widget { this._calculateBlocksToRender(); try { this.element.scrollTop(scrollTop); - } catch (e) { - } + } catch (e) {} } _clearChildren() { @@ -210,4 +224,3 @@ export class VirtualList extends Widget { this.restore(); } } - diff --git a/src/base/pager/pager.js b/src/base/pager/pager.js index 359d83616..1fbd2d43f 100644 --- a/src/base/pager/pager.js +++ b/src/base/pager/pager.js @@ -1,3 +1,20 @@ +import { + HorizontalLayout, + Widget, + shortcut, + extend, + emptyFn, + result, + isKey, + createWidget, + map, + stripEL, + formatEL, + Controller +} from "@/core"; +import { Label } from "../single"; +import { ButtonGroup } from "../combination"; + /** * 分页控件 * @@ -5,18 +22,20 @@ * @class BI.Pager * @extends BI.Widget */ -import { Widget, shortcut, extend, emptyFn, result, isKey, createWidget, map, stripEL, formatEL, Controller } from "../../core"; + @shortcut() export class Pager extends Widget { _defaultConfig() { return extend(super._defaultConfig(...arguments), { baseCls: "bi-pager", behaviors: {}, - layouts: [{ - type: "bi.horizontal", - hgap: 10, - vgap: 0, - }], + layouts: [ + { + type: HorizontalLayout.xtype, + hgap: 10, + vgap: 0, + } + ], dynamicShow: true, // 是否动态显示上一页、下一页、首页、尾页, 若为false,则指对其设置使能状态 // dynamicShow为false时以下两个有用 @@ -32,7 +51,8 @@ export class Pager extends Widget { next: "下一页", firstPage: 1, - lastPage: () => // 在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 + lastPage: () => + // 在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 1, hasPrev: emptyFn, // pages不可用时有效 hasNext: emptyFn, // pages不可用时有效 @@ -53,8 +73,11 @@ export class Pager extends Widget { } _populate() { - const o = this.options, view = [], dict = {}; - const { dynamicShow, dynamicShowPrevNext, hasPrev, dynamicShowFirstLast, hasNext, behaviors, layouts, jump } = this.options; + const o = this.options, + view = [], + dict = {}; + const { dynamicShow, dynamicShowPrevNext, hasPrev, dynamicShowFirstLast, hasNext, behaviors, layouts, jump } = + this.options; this.empty(); const pages = result(o, "pages"); const curr = result(this, "currPage"); @@ -73,7 +96,7 @@ export class Pager extends Widget { } // 计算当前组 - dict.index = Math.ceil((curr + ((groups > 1 && groups !== pages) ? 1 : 0)) / (groups === 0 ? 1 : groups)); + dict.index = Math.ceil((curr + (groups > 1 && groups !== pages ? 1 : 0)) / (groups === 0 ? 1 : groups)); // 当前页非首页,则输出上一页 if (((!dynamicShow && !dynamicShowPrevNext) || curr > 1) && prev !== false) { @@ -85,9 +108,12 @@ export class Pager extends Widget { }); } else { view.push({ - el: extend({ - disabled: pages === false ? hasPrev(curr) === false : !(curr > 1 && prev !== false), - }, prev), + el: extend( + { + disabled: pages === false ? hasPrev(curr) === false : !(curr > 1 && prev !== false), + }, + prev + ), }); } } @@ -101,7 +127,7 @@ export class Pager extends Widget { }); if (dict.index > 1 && groups !== 0 && groups !== pages - 1) { view.push({ - type: "bi.label", + type: Label.xtype, cls: "page-ellipsis", text: "\u2026", }); @@ -111,16 +137,21 @@ export class Pager extends Widget { // 输出当前页组 dict.poor = Math.floor((groups - 1) / 2); dict.start = dict.index > 1 ? curr - dict.poor : 1; - dict.end = dict.index > 1 ? (function () { - const max = curr + (groups - dict.poor - 1); + dict.end = + dict.index > 1 + ? (function () { + const max = curr + (groups - dict.poor - 1); - return max > pages ? pages : max; - }()) : groups; - if (dict.end - dict.start < groups - 1) { // 最后一组状态 + return max > pages ? pages : max; + }()) + : groups; + if (dict.end - dict.start < groups - 1) { + // 最后一组状态 dict.start = dict.end - groups + 1; } - let s = dict.start, e = dict.end; - if (first && last && (dict.index > 1 && groups !== 0) && (pages > groups && dict.end < pages && groups !== 0)) { + let s = dict.start, + e = dict.end; + if (first && last && dict.index > 1 && groups !== 0 && pages > groups && dict.end < pages && groups !== 0) { s++; e--; } @@ -143,7 +174,7 @@ export class Pager extends Widget { if (((!dynamicShow && !dynamicShowFirstLast) || (pages > groups && dict.end < pages && groups !== 0)) && last) { if (pages > groups && dict.end < pages && groups !== 0 && groups !== pages - 1) { view.push({ - type: "bi.label", + type: Label.xtype, cls: "page-ellipsis", text: "\u2026", }); @@ -157,38 +188,47 @@ export class Pager extends Widget { // 当前页不为尾页时,输出下一页 dict.flow = !prev && groups === 0; - if (((!dynamicShow && !dynamicShowPrevNext) && next) || (curr !== pages && next || dict.flow)) { - view.push((function () { - if (isKey(next)) { - if (pages === false) { - return { text: next, value: "next", disabled: hasNext(curr) === false }; - } + if ((!dynamicShow && !dynamicShowPrevNext && next) || (curr !== pages && next) || dict.flow) { + view.push( + (function () { + if (isKey(next)) { + if (pages === false) { + return { text: next, value: "next", disabled: hasNext(curr) === false }; + } - return (dict.flow && curr === pages) - ? - { text: next, value: "next", disabled: true } - : - { text: next, value: "next", disabled: !(curr !== pages && next || dict.flow) }; - } + return dict.flow && curr === pages + ? { text: next, value: "next", disabled: true } + : { text: next, value: "next", disabled: !((curr !== pages && next) || dict.flow) }; + } - return { - el: extend({ - disabled: pages === false ? hasNext(curr) === false : !(curr !== pages && next || dict.flow), - }, next), - }; - }())); + return { + el: extend( + { + disabled: + pages === false + ? hasNext(curr) === false + : !((curr !== pages && next) || dict.flow), + }, + next + ), + }; + })() + ); } this.button_group = createWidget({ - type: "bi.button_group", + type: ButtonGroup.xtype, element: this, items: map(view, (idx, v) => { - v = extend({ - cls: "bi-list-item-select bi-border-radius", - height: 23, - hgap: v.el ? 0 : 10, - stopPropagation: true, - }, stripEL(v)); + v = extend( + { + cls: "bi-list-item-select bi-border-radius", + height: 23, + hgap: v.el ? 0 : 10, + stopPropagation: true, + }, + stripEL(v) + ); return formatEL(v); }), @@ -220,10 +260,12 @@ export class Pager extends Widget { this.currPage = v; break; } - jump.apply(this, [{ - pages, - curr: this.currPage, - }]); + jump.apply(this, [ + { + pages, + curr: this.currPage, + } + ]); this._populate(); this.fireEvent(Pager.EVENT_CHANGE, obj); } @@ -251,7 +293,7 @@ export class Pager extends Widget { hasNext(v) { v || (v = 1); const { pages, hasNext } = this.options; - + return pages === false ? hasNext(v) : v < pages; } @@ -263,7 +305,8 @@ export class Pager extends Widget { if (pages === false) { const lastPage = result(o, "lastPage"); let firstPage = 1; - this.currPage = v > lastPage ? lastPage : ((firstPage = result(o, "firstPage")), (v < firstPage ? firstPage : v)); + this.currPage = + v > lastPage ? lastPage : ((firstPage = result(o, "firstPage")), v < firstPage ? firstPage : v); } else { v = v > pages ? pages : v; this.currPage = v; diff --git a/src/base/single/0.single.js b/src/base/single/0.single.js index cdfaaaca4..34ee4ca98 100644 --- a/src/base/single/0.single.js +++ b/src/base/single/0.single.js @@ -1,3 +1,6 @@ +import { Widget, shortcut, Actions, extend, isKey, isNotNull, isFunction, isPlainObject, isNull, delay } from "@/core"; +import { Tooltips } from "@/base"; + /** * guy * 这仅仅只是一个超类, 所有简单控件的基类 @@ -10,13 +13,10 @@ * @abstract */ -import { Widget, shortcut, Actions, extend, isKey, isNotNull, isFunction, isPlainObject, isNull, delay } from "../../core"; -import { Tooltips } from "../0.base"; - @shortcut() export class Single extends Widget { static xtype = "bi.single"; - + _defaultConfig() { const conf = super._defaultConfig(...arguments); @@ -35,7 +35,7 @@ export class Single extends Widget { const { action } = this.options; const title = this.getTitle(); - const showToolTip = (tooltipOpt) => { + const showToolTip = tooltipOpt => { if (isKey(tooltipOpt.text) && !Tooltips.has(this.getName())) { Tooltips.show(e, this.getName(), tooltipOpt, this, opt); if (action) { @@ -43,7 +43,7 @@ export class Single extends Widget { } Actions.runGlobalAction("hover", this.options, this); } - } + }; if (title instanceof Promise) { this.requestingTitle = title; @@ -54,7 +54,6 @@ export class Single extends Widget { } else { showToolTip(this._getTooltipOptions(title)); } - } _hideTooltip() { @@ -68,16 +67,17 @@ export class Single extends Widget { _init() { const { value } = this.options; - this.options.value = isFunction(value) ? this.__watch(value, (context, newValue) => { - this.setValue(newValue); - }) : value; + this.options.value = isFunction(value) + ? this.__watch(value, (context, newValue) => { + this.setValue(newValue); + }) + : value; super._init(arguments); } _mounted() { const { enableHover, title, warningTitle, belowMouse, container } = this.options; - if (enableHover || isKey(title) || isKey(warningTitle) - || isFunction(title) || isFunction(warningTitle)) { + if (enableHover || isKey(title) || isKey(warningTitle) || isFunction(title) || isFunction(warningTitle)) { this.enableHover({ belowMouse, container, @@ -105,11 +105,12 @@ export class Single extends Widget { tooltipOpt.level = this.getTipType() || "success"; // 由于以前的用法,存在大量disabled:true搭配warningTitle的情况,所以这里做一个兼容,disabled:true的情况下,依然优先显示warningTitle,避免只设置了warningTitle而没有设置title的情况 if (isNull(tipType) && !this.isEnabled()) { - tooltipOpt.text = (this.getWarningTitle() || title); + tooltipOpt.text = this.getWarningTitle() || title; } else { - tooltipOpt.text = tooltipOpt.level === "success" ? title : (this.getWarningTitle() || title); + tooltipOpt.text = tooltipOpt.level === "success" ? title : this.getWarningTitle() || title; } } + return tooltipOpt; } @@ -117,7 +118,7 @@ export class Single extends Widget { opt || (opt = {}); let delayingTooltips; if (!this._hoverBinded) { - this.element.unbind("mouseenter.title").on("mouseenter.title", (e) => { + this.element.unbind("mouseenter.title").on("mouseenter.title", e => { this._e = e; this.mouseOver = true; if (this.getTipType() === "warning" || (isKey(this.getWarningTitle()) && !this.isEnabled())) { @@ -136,7 +137,7 @@ export class Single extends Widget { }, 500); } }); - this.element.unbind("mousemove.title").on("mousemove.title", (e) => { + this.element.unbind("mousemove.title").on("mousemove.title", e => { this._e = e; if (isNotNull(this.showTimeout)) { clearTimeout(this.showTimeout); @@ -165,7 +166,7 @@ export class Single extends Widget { } }, 500); }); - this.element.unbind("mouseleave.title").on("mouseleave.title", (e) => { + this.element.unbind("mouseleave.title").on("mouseleave.title", e => { this._e = null; this.mouseOver = false; this._clearTimeOut(); @@ -179,9 +180,7 @@ export class Single extends Widget { // 取消hover事件 this._clearTimeOut(); this._hideTooltip(); - this.element.unbind("mouseenter.title") - .unbind("mousemove.title") - .unbind("mouseleave.title"); + this.element.unbind("mouseenter.title").unbind("mousemove.title").unbind("mouseleave.title"); this._hoverBinded = false; } diff --git a/src/base/single/1.text.js b/src/base/single/1.text.js index 294a2aaec..91f90291b 100644 --- a/src/base/single/1.text.js +++ b/src/base/single/1.text.js @@ -1,10 +1,11 @@ +import { Layout, DefaultLayout, shortcut } from "@/core"; +import { Single } from "./0.single"; + /** * guy 表示一行数据,通过position来定位位置的数据 * @class BI.Text * @extends BI.Single */ -import { shortcut } from "../../core"; -import { Single } from "./0.single"; @shortcut() export class Text extends Single { @@ -24,10 +25,29 @@ export class Text extends Single { bgap: 0, py: "", highLight: false, - } + }; render() { - const { vgap, hgap, lgap, rgap, tgap, bgap, height, lineHeight, maxWidth, textAlign, whiteSpace, handler, disabled, invalid, text: optionsText, value, keyword, highLight } = this.options; + const { + vgap, + hgap, + lgap, + rgap, + tgap, + bgap, + height, + lineHeight, + maxWidth, + textAlign, + whiteSpace, + handler, + disabled, + invalid, + text: optionsText, + value, + keyword, + highLight, + } = this.options; if (hgap + lgap > 0) { this.element.css({ "padding-left": BI.pixFormat(hgap + lgap), @@ -58,21 +78,21 @@ export class Text extends Single { this.element.css({ maxWidth: BI.pixFormat(maxWidth) }); } this.element.css({ - textAlign: textAlign, + textAlign, whiteSpace: this._getTextWrap(), textOverflow: whiteSpace === "nowrap" ? "ellipsis" : "", - overflow: whiteSpace === "nowrap" ? "" : (BI.isWidthOrHeight(height) ? "auto" : ""), + overflow: whiteSpace === "nowrap" ? "" : BI.isWidthOrHeight(height) ? "auto" : "", }); if (handler && handler !== BI.emptyFn) { this.text = BI.createWidget({ - type: "bi.layout", + type: Layout.xtype, tagName: "span", }); - this.text.element.click((e) => { + this.text.element.click(e => { !disabled && !invalid && handler.call(this, this.getValue(), this, e); }); BI.createWidget({ - type: "bi.default", + type: DefaultLayout.xtype, element: this, items: [this.text], }); @@ -80,9 +100,11 @@ export class Text extends Single { this.text = this; } - const text = BI.isFunction(optionsText) ? this.__watch(optionsText, (context, newValue) => { - this.setText(newValue); - }) : optionsText; + const text = BI.isFunction(optionsText) + ? this.__watch(optionsText, (context, newValue) => { + this.setText(newValue); + }) + : optionsText; // 只要不是undefined就可以显示text值,否则显示value if (!BI.isUndefined(text)) { this.setText(text); @@ -100,12 +122,12 @@ export class Text extends Single { _getTextWrap() { const { whiteSpace } = this.options; switch (whiteSpace) { - case "nowrap": - return "pre"; - case "normal": - return "pre-wrap"; - default: - return whiteSpace; + case "nowrap": + return "pre"; + case "normal": + return "pre-wrap"; + default: + return whiteSpace; } } @@ -113,7 +135,7 @@ export class Text extends Single { const { text: optionsText } = this.options; const text = BI.isFunction(optionsText) ? optionsText() : optionsText; - return BI.isKey(text) ? Text.formatText(text + "") : text; + return BI.isKey(text) ? Text.formatText(`${text}`) : text; } _doRedMark(keyword) { @@ -162,10 +184,10 @@ export class Text extends Single { } const formatters = []; -Text.addTextFormatter = (formatter) => { +Text.addTextFormatter = formatter => { formatters.push(formatter); }; -Text.formatText = (text) => { +Text.formatText = text => { if (formatters.length > 0) { for (let i = 0; i < formatters.length; i++) { text = formatters[i](text); diff --git a/src/base/single/a/a.js b/src/base/single/a/a.js index 41edbf3fb..7513b027f 100644 --- a/src/base/single/a/a.js +++ b/src/base/single/a/a.js @@ -1,3 +1,6 @@ +import { Text } from "../1.text"; +import { shortcut, extend, createWidget } from "@/core"; + /** * 超链接 * @@ -6,32 +9,31 @@ * @extends BI.Text * @abstract */ -import { shortcut, extend, createWidget } from "../../../core"; -import { Text } from "../1.text"; + @shortcut() export class A extends Text { - static xtype = "bi.a"; - - _defaultConfig() { - const conf = super._defaultConfig(...arguments); - - return extend(conf, { - baseCls: `${conf.baseCls || ""} bi-a display-block`, - href: "", - target: "_blank", - el: null, - tagName: "a", - }); - } + static xtype = "bi.a"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-a display-block`, + href: "", + target: "_blank", + el: null, + tagName: "a", + }); + } - render() { - const { href, target, el } = this.options; - super.render(); - this.element.attr({ href, target }); - if (el) { - createWidget(el, { - element: this, - }); - } - } + render() { + const { href, target, el } = this.options; + super.render(); + this.element.attr({ href, target }); + if (el) { + createWidget(el, { + element: this, + }); + } + } } diff --git a/src/base/single/bar/bar.loading.js b/src/base/single/bar/bar.loading.js index a4ab85a46..3bfa473b1 100644 --- a/src/base/single/bar/bar.loading.js +++ b/src/base/single/bar/bar.loading.js @@ -1,8 +1,9 @@ -import { shortcut, emptyFn } from "@/core"; +import { TextButton } from "../button"; +import { Layout, CenterAdaptLayout, CardLayout, shortcut, emptyFn } from "@/core"; import { Single } from "../0.single"; @shortcut() -class LoadingBar extends Single { +export class LoadingBar extends Single { static xtype = "bi.loading_bar"; _defaultConfig() { @@ -18,7 +19,7 @@ class LoadingBar extends Single { render() { this.loaded = BI.createWidget({ - type: "bi.text_button", + type: TextButton.xtype, cls: "loading-text bi-list-item-simple", text: BI.i18nText("BI-Load_More"), width: 120, @@ -29,27 +30,28 @@ class LoadingBar extends Single { }); this.loading = BI.createWidget({ - type: "bi.layout", + type: Layout.xtype, width: this.options.height, height: this.options.height, cls: "loading-background cursor-default", }); const loaded = BI.createWidget({ - type: "bi.center_adapt", + type: CenterAdaptLayout.xtype, items: [this.loaded], }); const loading = BI.createWidget({ - type: "bi.center_adapt", + type: CenterAdaptLayout.xtype, items: [this.loading], }); this.cardLayout = BI.createWidget({ - type: "bi.card", + type: CardLayout.xtype, element: this, items: [ { el: loaded, cardName: "loaded", - }, { + }, + { el: loading, cardName: "loading", } @@ -80,4 +82,3 @@ class LoadingBar extends Single { this.cardLayout.showCardByName("loading"); } } - diff --git a/src/base/single/button/button.basic.js b/src/base/single/button/button.basic.js index c5d067b68..fe952f2ac 100644 --- a/src/base/single/button/button.basic.js +++ b/src/base/single/button/button.basic.js @@ -1,5 +1,17 @@ +import { + Layout, + AbsoluteLayout, + emptyFn, + shortcut, + extend, + isFunction, + createWidget, + Widget, + isObject, + Controller +} from "@/core"; +import { BubbleCombo } from "@/case/combo/bubblecombo/combo.bubble"; import { Single } from "../0.single"; -import { emptyFn, shortcut, extend, isFunction, createWidget, Widget, isObject, Controller } from "../../../core"; /** * guy @@ -18,7 +30,9 @@ export class BasicButton extends Single { const conf = super._defaultConfig(...arguments); return extend(conf, { - _baseCls: `${conf._baseCls || ""} bi-basic-button${conf.invalid ? "" : " cursor-pointer"}${(BI.isIE() && BI.getIEVersion() < 10) ? " hack" : ""}`, + _baseCls: `${conf._baseCls || ""} bi-basic-button${conf.invalid ? "" : " cursor-pointer"}${ + BI.isIE() && BI.getIEVersion() < 10 ? " hack" : "" + }`, // el: {} // 可以通过el来创建button元素 value: "", stopEvent: false, @@ -40,9 +54,11 @@ export class BasicButton extends Single { _init() { const opts = this.options; - opts.selected = isFunction(opts.selected) ? this.__watch(opts.selected, (context, newValue) => { - this.setSelected(newValue); - }) : opts.selected; + opts.selected = isFunction(opts.selected) + ? this.__watch(opts.selected, (context, newValue) => { + this.setSelected(newValue); + }) + : opts.selected; super._init(arguments); if (opts.shadow) { @@ -75,20 +91,22 @@ export class BasicButton extends Single { const assertMask = () => { if (!this.$mask) { this.$mask = createWidget(isObject(o.shadow) ? o.shadow : {}, { - type: "bi.layout", + type: Layout.xtype, cls: "bi-button-mask", }); this.$mask.invisible(); createWidget({ - type: "bi.absolute", + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.$mask, - left: 0, - right: 0, - top: 0, - bottom: 0, - }], + items: [ + { + el: this.$mask, + left: 0, + right: 0, + top: 0, + bottom: 0, + }, + ], }); } }; @@ -99,7 +117,7 @@ export class BasicButton extends Single { this.$mask.invisible(); } }); - this.element.on(`mouseenter.${this.getName()}`, e => { + this.element.on(`mouseenter.${this.getName()}`, (e) => { if (this.element.__isMouseInBounds__(e)) { if (this.isEnabled() && !this._hover && (o.isShadowShowingOnSelected || !this.isSelected())) { assertMask(); @@ -107,7 +125,7 @@ export class BasicButton extends Single { } } }); - this.element.on(`mousemove.${this.getName()}`, e => { + this.element.on(`mousemove.${this.getName()}`, (e) => { if (!this.element.__isMouseInBounds__(e)) { if (this.isEnabled() && !this._hover) { assertMask(); @@ -140,7 +158,7 @@ export class BasicButton extends Single { return bubble; }; - const clk = e => { + const clk = (e) => { ev(e); if (!this.isEnabled() || !this.isValid()) { return; @@ -152,50 +170,56 @@ export class BasicButton extends Single { if (BI.isNull(this.combo)) { let popup; createWidget({ - type: "bi.absolute", + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: { - type: "bi.bubble_combo", - trigger: "", - // bubble的提示不需要一直存在在界面上 - destroyWhenHide: true, - ref: _ref => { - this.combo = _ref; - }, + items: [ + { el: { - type: "bi.layout", - height: "100%", - }, - popup: { - type: "bi.text_bubble_bar_popup_view", - text: getBubble(), - ref: _ref => { - popup = _ref; + type: BubbleCombo.xtype, + trigger: "", + // bubble的提示不需要一直存在在界面上 + destroyWhenHide: true, + ref: (_ref) => { + this.combo = _ref; + }, + el: { + type: Layout.xtype, + height: "100%", }, - listeners: [{ - eventName: BI.BubblePopupBarView.EVENT_CLICK_TOOLBAR_BUTTON, - action: (...args) => { - const [v] = args; - this.combo.hideView(); - if (v) { - onClick.apply(this, args); - } + popup: { + type: "bi.text_bubble_bar_popup_view", + text: getBubble(), + ref: (_ref) => { + popup = _ref; }, - }], - }, - listeners: [{ - eventName: BI.BubbleCombo.EVENT_BEFORE_POPUPVIEW, - action () { - popup.populate(getBubble()); + listeners: [ + { + eventName: BI.BubblePopupBarView.EVENT_CLICK_TOOLBAR_BUTTON, + action: (...args) => { + const [v] = args; + this.combo.hideView(); + if (v) { + onClick.apply(this, args); + } + }, + }, + ], }, - }], + listeners: [ + { + eventName: BubbleCombo.EVENT_BEFORE_POPUPVIEW, + action() { + popup.populate(getBubble()); + }, + }, + ], + }, + left: 0, + right: 0, + bottom: 0, + top: 0, }, - left: 0, - right: 0, - bottom: 0, - top: 0, - }], + ], }); } if (this.combo.isViewVisible()) { @@ -209,112 +233,119 @@ export class BasicButton extends Single { onClick.apply(this, arguments); }; - - const triggerArr = (o.trigger || "").split(","); - triggerArr.forEach(trigger => { + triggerArr.forEach((trigger) => { let mouseDown = false; let selected = false; let interval; switch (trigger) { - case "mouseup": - hand.mousedown(() => { - mouseDown = true; - }); - hand.mouseup(e => { - if (mouseDown === true) { - clk(e); - } - mouseDown = false; - ev(e); - }); - break; - case "mousedown": - // let mouseDown = false; - hand.mousedown(e => { - // if (e.button === 0) { - Widget._renderEngine.createElement(document).bind(`mouseup.${this.getName()}`, e => { - // if (e.button === 0) { - if (BI.DOM.isExist(this) && !hand.__isMouseInBounds__(e) && mouseDown === true && !selected) { - // self.setSelected(!self.isSelected()); - this._trigger(); + case "mouseup": + hand.mousedown(() => { + mouseDown = true; + }); + hand.mouseup((e) => { + if (mouseDown === true) { + clk(e); } mouseDown = false; - Widget._renderEngine.createElement(document).unbind(`mouseup.${this.getName()}`); + ev(e); + }); + break; + case "mousedown": + // let mouseDown = false; + hand.mousedown((e) => { + // if (e.button === 0) { + Widget._renderEngine.createElement(document).bind(`mouseup.${this.getName()}`, (e) => { + // if (e.button === 0) { + if ( + BI.DOM.isExist(this) && + !hand.__isMouseInBounds__(e) && + mouseDown === true && + !selected + ) { + // self.setSelected(!self.isSelected()); + this._trigger(); + } + mouseDown = false; + Widget._renderEngine.createElement(document).unbind(`mouseup.${this.getName()}`); + // } + }); + if (mouseDown === true) { + return; + } + if (this.isSelected()) { + selected = true; + } else { + clk(e); + } + mouseDown = true; + ev(e); // } }); - if (mouseDown === true) { - return; - } - if (this.isSelected()) { - selected = true; - } else { - clk(e); - } - mouseDown = true; - ev(e); - // } - }); - hand.mouseup(e => { - // if (e.button === 0) { - if (BI.DOM.isExist(this) && mouseDown === true && selected === true) { - clk(e); - } - mouseDown = false; - selected = false; - Widget._renderEngine.createElement(document).unbind(`mouseup.${this.getName()}`); - // } - }); - break; - case "dblclick": - hand.dblclick(clk); - break; - case "lclick": - hand.mousedown(e => { - Widget._renderEngine.createElement(document).bind(`mouseup.${this.getName()}`, () => { - interval && clearInterval(interval); - interval = null; + hand.mouseup((e) => { + // if (e.button === 0) { + if (BI.DOM.isExist(this) && mouseDown === true && selected === true) { + clk(e); + } mouseDown = false; + selected = false; Widget._renderEngine.createElement(document).unbind(`mouseup.${this.getName()}`); + // } }); - if (mouseDown === true) { - return; - } - if (!this.isEnabled() || !this.isValid()) { - return; - } - if (this.isOnce() && this.isSelected()) { - return; - } - interval = setInterval(() => { - clk(e); - }, 180); - mouseDown = true; - ev(e); - }); - break; - default: - if (o.stopEvent || o.stopPropagation) { - hand.mousedown(e => { + break; + case "dblclick": + hand.dblclick(clk); + break; + case "lclick": + hand.mousedown((e) => { + Widget._renderEngine.createElement(document).bind(`mouseup.${this.getName()}`, () => { + interval && clearInterval(interval); + interval = null; + mouseDown = false; + Widget._renderEngine.createElement(document).unbind(`mouseup.${this.getName()}`); + }); + if (mouseDown === true) { + return; + } + if (!this.isEnabled() || !this.isValid()) { + return; + } + if (this.isOnce() && this.isSelected()) { + return; + } + interval = setInterval(() => { + clk(e); + }, 180); + mouseDown = true; ev(e); }); - } - hand.click(clk); - // enter键等同于点击 - o.attributes && o.attributes.zIndex >= 0 && hand.keyup(e => { - if (e.keyCode === BI.KeyCode.ENTER) { - clk(e); + break; + default: + if (o.stopEvent || o.stopPropagation) { + hand.mousedown((e) => { + ev(e); + }); } - }); - break; + hand.click(clk); + // enter键等同于点击 + o.attributes && + o.attributes.zIndex >= 0 && + hand.keyup((e) => { + if (e.keyCode === BI.KeyCode.ENTER) { + clk(e); + } + }); + break; } }); // 之后的300ms点击无效 - const onClick = o.debounce ? BI.debounce(this._doClick, BI.EVENT_RESPONSE_TIME, { - leading: true, - trailing: false, - }) : this._doClick; + const onClick = o.debounce + ? BI.debounce(this._doClick, BI.EVENT_RESPONSE_TIME, { + leading: true, + trailing: false, + }) + : this._doClick; function ev(e) { if (o.stopEvent) { @@ -332,9 +363,11 @@ export class BasicButton extends Single { return; } if (!this.isDisableSelected()) { - this.isForceSelected() ? this.setSelected(true) : - (this.isForceNotSelected() ? this.setSelected(false) : - this.setSelected(!this.isSelected())); + this.isForceSelected() + ? this.setSelected(true) + : this.isForceNotSelected() + ? this.setSelected(false) + : this.setSelected(!this.isSelected()); } if (this.isValid()) { const v = this.getValue(); @@ -367,13 +400,9 @@ export class BasicButton extends Single { /** * 子类可以得写这个方法,如果返回为 true,则可以阻止 handler 的触发 */ - beforeClick() { + beforeClick() {} - } - - doClick() { - - } + doClick() {} handle() { return this; @@ -457,5 +486,3 @@ export class BasicButton extends Single { super.empty(...arguments); } } - - diff --git a/src/base/single/button/button.node.js b/src/base/single/button/button.node.js index 4684d0c72..e41e8ee13 100644 --- a/src/base/single/button/button.node.js +++ b/src/base/single/button/button.node.js @@ -1,5 +1,5 @@ import { BasicButton } from "./button.basic"; -import { shortcut, extend, Controller } from "../../../core"; +import { shortcut, extend, Controller } from "@/core"; /** * 表示一个可以展开的节点, 不仅有选中状态而且有展开状态 diff --git a/src/base/single/button/buttons/button.icon.js b/src/base/single/button/buttons/button.icon.js index edc65fc28..d3504501d 100644 --- a/src/base/single/button/buttons/button.icon.js +++ b/src/base/single/button/buttons/button.icon.js @@ -1,5 +1,6 @@ +import { Icon } from "../../icon/icon"; +import { DefaultLayout, CenterAdaptLayout, shortcut, extend, isNumber, createWidget, isNull } from "@/core"; import { BasicButton } from "../button.basic"; -import { shortcut, extend, isNumber, createWidget, isNull } from "../../../../core"; /** * @class IconButton @@ -33,14 +34,14 @@ export class IconButton extends BasicButton { textAlign: "center", }); this.icon = createWidget({ - type: "bi.icon", + type: Icon.xtype, width: o.iconWidth, height: o.iconHeight, }); if (isNumber(o.height) && o.height > 0 && isNull(o.iconWidth) && isNull(o.iconHeight)) { this.element.css("lineHeight", BI.pixFormat(o.height)); createWidget({ - type: "bi.default", + type: DefaultLayout.xtype, element: this, hgap: o.hgap, vgap: o.vgap, @@ -54,7 +55,7 @@ export class IconButton extends BasicButton { this.element.css("lineHeight", "1"); createWidget({ element: this, - type: "bi.center_adapt", + type: CenterAdaptLayout.xtype, hgap: o.hgap, vgap: o.vgap, lgap: o.lgap, diff --git a/src/base/single/button/buttons/button.image.js b/src/base/single/button/buttons/button.image.js index 9920ea784..f46b3f1f4 100644 --- a/src/base/single/button/buttons/button.image.js +++ b/src/base/single/button/buttons/button.image.js @@ -1,6 +1,6 @@ +import { Img } from "../../img/img"; +import { CenterAdaptLayout, AdaptiveLayout, shortcut, extend, isNumber, createWidget } from "@/core"; import { BasicButton } from "../button.basic"; -import { shortcut, extend, isNumber, createWidget } from "../../../../core"; - /** * 图片的button @@ -28,20 +28,20 @@ export class ImageButton extends BasicButton { render() { const o = this.options; this.image = createWidget({ - type: "bi.img", + type: Img.xtype, width: o.iconWidth, height: o.iconHeight, src: o.src, }); if (isNumber(o.iconWidth) || isNumber(o.iconHeight)) { createWidget({ - type: "bi.center_adapt", + type: CenterAdaptLayout.xtype, element: this, items: [this.image], }); } else { createWidget({ - type: "bi.adaptive", + type: AdaptiveLayout.xtype, element: this, items: [this.image], scrollable: false, diff --git a/src/base/single/button/buttons/button.js b/src/base/single/button/buttons/button.js index edc4cf32d..5ac980d30 100644 --- a/src/base/single/button/buttons/button.js +++ b/src/base/single/button/buttons/button.js @@ -1,5 +1,6 @@ +import { CenterAdaptLayout, isNumber, shortcut, isPlainObject, createWidget } from "@/core"; +import { Label, IconLabel } from "../../label"; import { BasicButton } from "../button.basic"; -import { isNumber, shortcut, isPlainObject, createWidget } from "../../../../core"; function isVertical(position) { return position === "top" || position === "bottom"; @@ -19,7 +20,7 @@ const loadingCls = "button-loading-font anim-rotate"; export class Button extends BasicButton { _const = { iconWidth: 18, - } + }; static xtype = "bi.button"; static EVENT_CHANGE = "EVENT_CHANGE"; @@ -34,14 +35,14 @@ export class Button extends BasicButton { adaptiveHeight += props.iconGap || 0; const tGap = props.tgap || props.vgap || 2; const bGap = props.bgap || props.vgap || 2; - adaptiveHeight += (tGap + bGap); + adaptiveHeight += tGap + bGap; } const clearMinWidth = props.block === true || props.clear === true || props.plain; return { ...conf, - baseCls: `${conf.baseCls || ""} bi-button${(BI.isIE() && BI.isIE9Below()) ? " hack" : ""}`, + baseCls: `${conf.baseCls || ""} bi-button${BI.isIE() && BI.isIE9Below() ? " hack" : ""}`, attributes: { tabIndex: 1, }, @@ -62,7 +63,7 @@ export class Button extends BasicButton { whiteSpace: "nowrap", textWidth: null, textHeight: null, - hgap: props.clear ? 0 : (props.plain && !props.text ? 4 : 10), + hgap: props.clear ? 0 : props.plain && !props.text ? 4 : 10, vgap: 0, tgap: 0, bgap: 0, @@ -79,7 +80,7 @@ export class Button extends BasicButton { // bi.center_adapt 作用:让 hgap 不影响 iconGap。 createWidget({ - type: "bi.center_adapt", + type: CenterAdaptLayout.xtype, horizontalAlign: o.textAlign, element: this, ref: ref => { @@ -107,7 +108,8 @@ export class Button extends BasicButton { const o = this.options; // 由于button默认情况下有个边框,所以要主动算行高 - let lineHeight, textHeight = o.textHeight; + let lineHeight, + textHeight = o.textHeight; let hasBorder = false; if (isNumber(o.height)) { if (!isVertical(o.iconPosition)) { @@ -128,13 +130,13 @@ export class Button extends BasicButton { const iconInvisible = !(o.loading || o.iconCls || o.icon || defaultRenderIcon); let maxTextWidth = Math.max(o.minWidth, o.width); - maxTextWidth -= (o.hgap * 2 + o.iconGap); + maxTextWidth -= o.hgap * 2 + o.iconGap; // 减去图标水平占位宽度 maxTextWidth -= iconInvisible || isVertical(o.iconPosition) ? 0 : this._const.iconWidth; const textWidth = BI.isNull(o.textWidth) ? maxTextWidth : Math.min(o.textWidth, maxTextWidth); - + this.text = createWidget({ - type: "bi.label", + type: Label.xtype, text: o.text, whiteSpace: o.whiteSpace, textAlign: o.textAlign, @@ -155,8 +157,8 @@ export class Button extends BasicButton { this.icon = createWidget(o.icon); } else { this.icon = createWidget({ - type: "bi.icon_label", - cls: o.loading ? loadingCls : (o.iconCls || o.icon), + type: IconLabel.xtype, + cls: o.loading ? loadingCls : o.iconCls || o.icon, width: this._const.iconWidth, height: BI.toPix(lineHeight, hasBorder ? 2 : 0), lineHeight: BI.toPix(lineHeight, hasBorder ? 2 : 0), @@ -179,12 +181,14 @@ export class Button extends BasicButton { items.reverse(); } - return [{ - type: isVertical(o.iconPosition) ? "bi.vertical" : "bi.horizontal", - horizontalAlign: "center", - verticalAlign: "middle", - items, - }]; + return [ + { + type: isVertical(o.iconPosition) ? "bi.vertical" : "bi.horizontal", + horizontalAlign: "center", + verticalAlign: "middle", + items, + } + ]; } doClick() { @@ -272,4 +276,3 @@ export class Button extends BasicButton { this.text.unHighLight(...arguments); } } - diff --git a/src/base/single/button/buttons/button.text.js b/src/base/single/button/buttons/button.text.js index 6f3a2d2ea..3404789e1 100644 --- a/src/base/single/button/buttons/button.text.js +++ b/src/base/single/button/buttons/button.text.js @@ -1,5 +1,6 @@ +import { Label } from "../../label"; import { BasicButton } from "../button.basic"; -import { shortcut, extend, createWidget, isArray } from "../../../../core"; +import { shortcut, extend, createWidget, isArray } from "@/core"; /** * guy @@ -33,7 +34,7 @@ export class TextButton extends BasicButton { render() { const o = this.options; this.text = createWidget({ - type: "bi.label", + type: Label.xtype, element: this, textAlign: o.textAlign, whiteSpace: o.whiteSpace, diff --git a/src/base/single/button/index.js b/src/base/single/button/index.js index 691aa85f7..bf1a0f903 100644 --- a/src/base/single/button/index.js +++ b/src/base/single/button/index.js @@ -1,17 +1,17 @@ -export { BasicButton } from "./button.basic"; -export { NodeButton } from "./button.node"; -export { Button } from "./buttons/button"; -export { IconButton } from "./buttons/button.icon"; -export { ImageButton } from "./buttons/button.image"; -export { TextButton } from "./buttons/button.text"; -export { BlankIconIconTextItem } from "./listitem/blankiconicontextitem"; -export { BlankIconTextIconItem } from "./listitem/blankicontexticonitem"; -export { BlankIconTextItem } from "./listitem/blankicontextitem"; -export { IconTextIconItem } from "./listitem/icontexticonitem"; -export { IconTextItem } from "./listitem/icontextitem"; -export { TextIconItem } from "./listitem/texticonitem"; -export { TextItem } from "./listitem/textitem"; -export { IconTextIconNode } from "./node/icontexticonnode"; -export { IconTextNode } from "./node/icontextnode"; -export { TextIconNode } from "./node/texticonnode"; -export { TextNode } from "./node/textnode"; +export { BasicButton } from "./button.basic"; +export { NodeButton } from "./button.node"; +export { Button } from "./buttons/button"; +export { IconButton } from "./buttons/button.icon"; +export { ImageButton } from "./buttons/button.image"; +export { TextButton } from "./buttons/button.text"; +export { BlankIconIconTextItem } from "./listitem/blankiconicontextitem"; +export { BlankIconTextIconItem } from "./listitem/blankicontexticonitem"; +export { BlankIconTextItem } from "./listitem/blankicontextitem"; +export { IconTextIconItem } from "./listitem/icontexticonitem"; +export { IconTextItem } from "./listitem/icontextitem"; +export { TextIconItem } from "./listitem/texticonitem"; +export { TextItem } from "./listitem/textitem"; +export { IconTextIconNode } from "./node/icontexticonnode"; +export { IconTextNode } from "./node/icontextnode"; +export { TextIconNode } from "./node/texticonnode"; +export { TextNode } from "./node/textnode"; diff --git a/src/base/single/button/listitem/blankiconicontextitem.js b/src/base/single/button/listitem/blankiconicontextitem.js index e0dd3ac0f..0dacbf150 100644 --- a/src/base/single/button/listitem/blankiconicontextitem.js +++ b/src/base/single/button/listitem/blankiconicontextitem.js @@ -1,5 +1,6 @@ +import { VerticalAdaptLayout, Layout, shortcut, extend } from "@/core"; +import { IconLabel, Label } from "../../label"; import { BasicButton } from "../button.basic"; -import { shortcut, extend } from "../../../../core"; /** * 带有一个占位 @@ -34,42 +35,47 @@ export class BlankIconIconTextItem extends BasicButton { const o = this.options; return { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, columnSize: [o.blankWidth, o.leftIconWrapperWidth || o.height, o.rightIconWrapperWidth || o.height, "fill"], - items: [{ - type: "bi.layout", - width: o.blankWidth, - }, { - type: "bi.icon_label", - cls: o.iconCls1, - width: o.leftIconWrapperWidth || o.height, - height: o.height, - iconWidth: o.iconWidth, - iconHeight: o.iconHeight, - }, { - type: "bi.icon_label", - cls: o.iconCls2, - width: o.rightIconWrapperWidth || o.height, - height: o.height, - iconWidth: o.iconWidth, - iconHeight: o.iconHeight, - }, { - el: { - type: "bi.label", - ref: _ref => { - this.text = _ref; - }, - textAlign: "left", - hgap: o.textHgap, - vgap: o.textVgap, - lgap: o.textLgap, - rgap: o.textRgap, - text: o.text, - value: o.value, - keyword: o.keyword, + items: [ + { + type: Layout.xtype, + width: o.blankWidth, + }, + { + type: IconLabel.xtype, + cls: o.iconCls1, + width: o.leftIconWrapperWidth || o.height, height: o.height, + iconWidth: o.iconWidth, + iconHeight: o.iconHeight, }, - }], + { + type: IconLabel.xtype, + cls: o.iconCls2, + width: o.rightIconWrapperWidth || o.height, + height: o.height, + iconWidth: o.iconWidth, + iconHeight: o.iconHeight, + }, + { + el: { + type: Label.xtype, + ref: _ref => { + this.text = _ref; + }, + textAlign: "left", + hgap: o.textHgap, + vgap: o.textVgap, + lgap: o.textLgap, + rgap: o.textRgap, + text: o.text, + value: o.value, + keyword: o.keyword, + height: o.height, + }, + } + ], }; } diff --git a/src/base/single/button/listitem/blankicontexticonitem.js b/src/base/single/button/listitem/blankicontexticonitem.js index 11ff0a64d..8bccc9c10 100644 --- a/src/base/single/button/listitem/blankicontexticonitem.js +++ b/src/base/single/button/listitem/blankicontexticonitem.js @@ -1,5 +1,6 @@ +import { VerticalAdaptLayout, Layout, shortcut, extend } from "@/core"; +import { IconLabel, Label } from "../../label"; import { BasicButton } from "../button.basic"; -import { shortcut, extend } from "../../../../core"; /** * guy @@ -35,42 +36,47 @@ export class BlankIconTextIconItem extends BasicButton { const o = this.options; return { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, columnSize: [o.blankWidth, o.leftIconWrapperWidth || o.height, "fill", o.rightIconWrapperWidth || o.height], - items: [{ - type: "bi.layout", - width: o.blankWidth, - }, { - type: "bi.icon_label", - cls: o.iconCls1, - width: o.leftIconWrapperWidth || o.height, - height: o.height, - iconWidth: o.iconWidth, - iconHeight: o.iconHeight, - }, { - el: { - type: "bi.label", - ref: _ref => { - this.text = _ref; - }, - textAlign: "left", - hgap: o.textHgap, - vgap: o.textVgap, - lgap: o.textLgap, - rgap: o.textRgap, - text: o.text, - value: o.value, - keyword: o.keyword, + items: [ + { + type: Layout.xtype, + width: o.blankWidth, + }, + { + type: IconLabel.xtype, + cls: o.iconCls1, + width: o.leftIconWrapperWidth || o.height, height: o.height, + iconWidth: o.iconWidth, + iconHeight: o.iconHeight, + }, + { + el: { + type: Label.xtype, + ref: _ref => { + this.text = _ref; + }, + textAlign: "left", + hgap: o.textHgap, + vgap: o.textVgap, + lgap: o.textLgap, + rgap: o.textRgap, + text: o.text, + value: o.value, + keyword: o.keyword, + height: o.height, + }, }, - }, { - type: "bi.icon_label", - cls: o.iconCls2, - width: o.rightIconWrapperWidth || o.height, - height: o.height, - iconWidth: o.iconWidth, - iconHeight: o.iconHeight, - }], + { + type: IconLabel.xtype, + cls: o.iconCls2, + width: o.rightIconWrapperWidth || o.height, + height: o.height, + iconWidth: o.iconWidth, + iconHeight: o.iconHeight, + } + ], }; } @@ -115,4 +121,3 @@ export class BlankIconTextIconItem extends BasicButton { return this.text.getText(); } } - diff --git a/src/base/single/button/listitem/blankicontextitem.js b/src/base/single/button/listitem/blankicontextitem.js index c80c8a2e2..df138881e 100644 --- a/src/base/single/button/listitem/blankicontextitem.js +++ b/src/base/single/button/listitem/blankicontextitem.js @@ -1,5 +1,6 @@ +import { VerticalAdaptLayout, Layout, extend, shortcut } from "@/core"; +import { IconLabel, Label } from "../../label"; import { BasicButton } from "../button.basic"; -import { extend, shortcut } from "../../../../core"; /** * 带有一个占位 @@ -33,36 +34,40 @@ export class BlankIconTextItem extends BasicButton { const o = this.options; return { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, columnSize: [o.blankWidth, o.iconWrapperWidth || o.height, "fill"], - items: [{ - type: "bi.layout", - width: o.blankWidth, - }, { - type: "bi.icon_label", - cls: o.iconCls, - width: o.iconWrapperWidth || o.height, - height: o.height, - iconWidth: o.iconWidth, - iconHeight: o.iconHeight, - }, { - el: { - type: "bi.label", - ref: _ref => { - this.text = _ref; - }, - cls: "list-item-text", - textAlign: "left", - hgap: o.textHgap, - vgap: o.textVgap, - lgap: o.textLgap, - rgap: o.textRgap, - text: o.text, - value: o.value, - keyword: o.keyword, + items: [ + { + type: Layout.xtype, + width: o.blankWidth, + }, + { + type: IconLabel.xtype, + cls: o.iconCls, + width: o.iconWrapperWidth || o.height, height: o.height, + iconWidth: o.iconWidth, + iconHeight: o.iconHeight, }, - }], + { + el: { + type: Label.xtype, + ref: _ref => { + this.text = _ref; + }, + cls: "list-item-text", + textAlign: "left", + hgap: o.textHgap, + vgap: o.textVgap, + lgap: o.textLgap, + rgap: o.textRgap, + text: o.text, + value: o.value, + keyword: o.keyword, + height: o.height, + }, + } + ], }; } diff --git a/src/base/single/button/listitem/icontexticonitem.js b/src/base/single/button/listitem/icontexticonitem.js index 2727191c1..2588d60d5 100644 --- a/src/base/single/button/listitem/icontexticonitem.js +++ b/src/base/single/button/listitem/icontexticonitem.js @@ -1,5 +1,6 @@ +import { VerticalAdaptLayout, extend, shortcut } from "@/core"; +import { IconLabel, Label } from "../../label"; import { BasicButton } from "../button.basic"; -import { extend, shortcut } from "../../../../core"; /** * guy @@ -35,39 +36,43 @@ export class IconTextIconItem extends BasicButton { const o = this.options; return { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, columnSize: [o.leftIconWrapperWidth || o.height, "fill", o.rightIconWrapperWidth || o.height], - items: [{ - type: "bi.icon_label", - cls: o.iconCls1, - width: o.leftIconWrapperWidth || o.height, - height: o.height, - iconWidth: o.iconWidth, - iconHeight: o.iconHeight, - }, { - el: { - type: "bi.label", - ref: _ref => { - this.text = _ref; - }, - textAlign: "left", - hgap: o.textHgap, - vgap: o.textVgap, - lgap: o.textLgap, - rgap: o.textRgap, - text: o.text, - value: o.value, - keyword: o.keyword, + items: [ + { + type: IconLabel.xtype, + cls: o.iconCls1, + width: o.leftIconWrapperWidth || o.height, height: o.height, + iconWidth: o.iconWidth, + iconHeight: o.iconHeight, + }, + { + el: { + type: Label.xtype, + ref: _ref => { + this.text = _ref; + }, + textAlign: "left", + hgap: o.textHgap, + vgap: o.textVgap, + lgap: o.textLgap, + rgap: o.textRgap, + text: o.text, + value: o.value, + keyword: o.keyword, + height: o.height, + }, }, - }, { - type: "bi.icon_label", - cls: o.iconCls2, - width: o.rightIconWrapperWidth || o.height, - height: o.height, - iconWidth: o.iconWidth, - iconHeight: o.iconHeight, - }], + { + type: IconLabel.xtype, + cls: o.iconCls2, + width: o.rightIconWrapperWidth || o.height, + height: o.height, + iconWidth: o.iconWidth, + iconHeight: o.iconHeight, + } + ], }; } diff --git a/src/base/single/button/listitem/icontextitem.js b/src/base/single/button/listitem/icontextitem.js index 074cacbca..3b562c795 100644 --- a/src/base/single/button/listitem/icontextitem.js +++ b/src/base/single/button/listitem/icontextitem.js @@ -1,5 +1,6 @@ +import { VerticalAdaptLayout, extend, shortcut } from "@/core"; +import { IconLabel, Label } from "../../label"; import { BasicButton } from "../button.basic"; -import { extend, shortcut } from "../../../../core"; /** * guy @@ -34,33 +35,36 @@ export class IconTextItem extends BasicButton { const o = this.options; return { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, columnSize: [o.iconWrapperWidth || o.height, "fill"], - items: [{ - type: "bi.icon_label", - cls: o.iconCls, - width: o.iconWrapperWidth || o.height, - height: o.height, - iconWidth: o.iconWidth, - iconHeight: o.iconHeight, - }, { - el: { - type: "bi.label", - ref: _ref => { - this.text = _ref; - }, - cls: "list-item-text", - textAlign: "left", - hgap: o.textHgap, - vgap: o.textVgap, - lgap: o.textLgap, - rgap: o.textRgap, - text: o.text, - value: o.value, - keyword: o.keyword, + items: [ + { + type: IconLabel.xtype, + cls: o.iconCls, + width: o.iconWrapperWidth || o.height, height: o.height, + iconWidth: o.iconWidth, + iconHeight: o.iconHeight, }, - }], + { + el: { + type: Label.xtype, + ref: _ref => { + this.text = _ref; + }, + cls: "list-item-text", + textAlign: "left", + hgap: o.textHgap, + vgap: o.textVgap, + lgap: o.textLgap, + rgap: o.textRgap, + text: o.text, + value: o.value, + keyword: o.keyword, + height: o.height, + }, + } + ], }; } diff --git a/src/base/single/button/listitem/texticonitem.js b/src/base/single/button/listitem/texticonitem.js index 4c8b53d08..84b7e1cfe 100644 --- a/src/base/single/button/listitem/texticonitem.js +++ b/src/base/single/button/listitem/texticonitem.js @@ -1,5 +1,6 @@ +import { VerticalAdaptLayout, extend, shortcut } from "@/core"; +import { Label, IconLabel } from "../../label"; import { BasicButton } from "../button.basic"; -import { extend, shortcut } from "../../../../core"; /** * @@ -12,7 +13,7 @@ import { extend, shortcut } from "../../../../core"; @shortcut() export class TextIconItem extends BasicButton { static xtype = "bi.text_icon_item"; - static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { const conf = super._defaultConfig(...arguments); @@ -34,33 +35,36 @@ export class TextIconItem extends BasicButton { const o = this.options; return { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, columnSize: ["fill", o.iconWrapperWidth || o.height], - items: [{ - el: { - type: "bi.label", - ref: _ref => { - this.text = _ref; + items: [ + { + el: { + type: Label.xtype, + ref: _ref => { + this.text = _ref; + }, + cls: "list-item-text", + textAlign: "left", + hgap: o.textHgap, + vgap: o.textVgap, + lgap: o.textLgap, + rgap: o.textRgap, + text: o.text, + value: o.value, + keyword: o.keyword, + height: o.height, }, - cls: "list-item-text", - textAlign: "left", - hgap: o.textHgap, - vgap: o.textVgap, - lgap: o.textLgap, - rgap: o.textRgap, - text: o.text, - value: o.value, - keyword: o.keyword, - height: o.height, }, - }, { - type: "bi.icon_label", - cls: o.iconCls, - width: o.iconWrapperWidth || o.height, - height: o.height, - iconWidth: o.iconWidth, - iconHeight: o.iconHeight, - }], + { + type: IconLabel.xtype, + cls: o.iconCls, + width: o.iconWrapperWidth || o.height, + height: o.height, + iconWidth: o.iconWidth, + iconHeight: o.iconHeight, + } + ], }; } diff --git a/src/base/single/button/listitem/textitem.js b/src/base/single/button/listitem/textitem.js index 62ca182ae..7f7ab21b5 100644 --- a/src/base/single/button/listitem/textitem.js +++ b/src/base/single/button/listitem/textitem.js @@ -1,5 +1,6 @@ +import { Label } from "../../label"; import { BasicButton } from "../button.basic"; -import { extend, shortcut, createWidget } from "../../../../core"; +import { extend, shortcut, createWidget } from "@/core"; /** * guy @@ -31,7 +32,7 @@ export class TextItem extends BasicButton { render() { const o = this.options; this.text = createWidget({ - type: "bi.label", + type: Label.xtype, element: this, textAlign: o.textAlign, whiteSpace: o.whiteSpace, diff --git a/src/base/single/button/node/icontexticonnode.js b/src/base/single/button/node/icontexticonnode.js index c80903d78..eb3ff0213 100644 --- a/src/base/single/button/node/icontexticonnode.js +++ b/src/base/single/button/node/icontexticonnode.js @@ -1,5 +1,6 @@ +import { VerticalAdaptLayout, extend, shortcut } from "@/core"; +import { IconLabel, Label } from "../../label"; import { NodeButton } from "../button.node"; -import { extend, shortcut } from "../../../../core"; /** * guy @@ -32,39 +33,43 @@ export class IconTextIconNode extends NodeButton { const o = this.options; return { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, columnSize: [o.leftIconWrapperWidth || o.height, "fill", o.rightIconWrapperWidth || o.height], - items: [{ - type: "bi.icon_label", - cls: o.iconCls1, - width: o.leftIconWrapperWidth || o.height, - height: o.height, - iconWidth: o.iconWidth, - iconHeight: o.iconHeight, - }, { - el: { - type: "bi.label", - ref: _ref => { - this.text = _ref; - }, - textAlign: "left", - hgap: o.textHgap, - vgap: o.textVgap, - lgap: o.textLgap, - rgap: o.textRgap, - text: o.text, - value: o.value, - keyword: o.keyword, + items: [ + { + type: IconLabel.xtype, + cls: o.iconCls1, + width: o.leftIconWrapperWidth || o.height, height: o.height, + iconWidth: o.iconWidth, + iconHeight: o.iconHeight, + }, + { + el: { + type: Label.xtype, + ref: _ref => { + this.text = _ref; + }, + textAlign: "left", + hgap: o.textHgap, + vgap: o.textVgap, + lgap: o.textLgap, + rgap: o.textRgap, + text: o.text, + value: o.value, + keyword: o.keyword, + height: o.height, + }, }, - }, { - type: "bi.icon_label", - cls: o.iconCls2, - width: o.rightIconWrapperWidth || o.height, - height: o.height, - iconWidth: o.iconWidth, - iconHeight: o.iconHeight, - }], + { + type: IconLabel.xtype, + cls: o.iconCls2, + width: o.rightIconWrapperWidth || o.height, + height: o.height, + iconWidth: o.iconWidth, + iconHeight: o.iconHeight, + } + ], }; } diff --git a/src/base/single/button/node/icontextnode.js b/src/base/single/button/node/icontextnode.js index b9281df80..130fa1570 100644 --- a/src/base/single/button/node/icontextnode.js +++ b/src/base/single/button/node/icontextnode.js @@ -1,5 +1,6 @@ +import { VerticalAdaptLayout, extend, shortcut } from "@/core"; +import { IconLabel, Label } from "../../label"; import { NodeButton } from "../button.node"; -import { extend, shortcut } from "../../../../core"; /** * guy @@ -31,33 +32,36 @@ export class IconTextNode extends NodeButton { const o = this.options; return { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, columnSize: [o.iconWrapperWidth || o.height, "fill"], - items: [{ - type: "bi.icon_label", - cls: o.iconCls, - width: o.iconWrapperWidth || o.height, - height: o.height, - iconWidth: o.iconWidth, - iconHeight: o.iconHeight, - }, { - el: { - type: "bi.label", - ref: _ref => { - this.text = _ref; - }, - cls: "list-item-text", - textAlign: "left", - hgap: o.textHgap, - vgap: o.textVgap, - lgap: o.textLgap, - rgap: o.textRgap, - text: o.text, - value: o.value, - keyword: o.keyword, + items: [ + { + type: IconLabel.xtype, + cls: o.iconCls, + width: o.iconWrapperWidth || o.height, height: o.height, + iconWidth: o.iconWidth, + iconHeight: o.iconHeight, }, - }], + { + el: { + type: Label.xtype, + ref: _ref => { + this.text = _ref; + }, + cls: "list-item-text", + textAlign: "left", + hgap: o.textHgap, + vgap: o.textVgap, + lgap: o.textLgap, + rgap: o.textRgap, + text: o.text, + value: o.value, + keyword: o.keyword, + height: o.height, + }, + } + ], }; } @@ -94,4 +98,3 @@ export class IconTextNode extends NodeButton { this.text.unRedMark(...arguments); } } - diff --git a/src/base/single/button/node/texticonnode.js b/src/base/single/button/node/texticonnode.js index 01066bb09..3f6dc8909 100644 --- a/src/base/single/button/node/texticonnode.js +++ b/src/base/single/button/node/texticonnode.js @@ -1,5 +1,6 @@ +import { VerticalAdaptLayout, extend, shortcut } from "@/core"; +import { Label, IconLabel } from "../../label"; import { NodeButton } from "../button.node"; -import { extend, shortcut } from "../../../../core"; /** * Created by GUY on 2015/9/9. @@ -8,7 +9,6 @@ import { extend, shortcut } from "../../../../core"; */ @shortcut() export class TextIconNode extends NodeButton { - static EVENT_CHANGE = "EVENT_CHANGE"; static xtype = "bi.text_icon_node"; @@ -31,33 +31,36 @@ export class TextIconNode extends NodeButton { const o = this.options; return { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, columnSize: ["fill", o.iconWrapperWidth || o.height], - items: [{ - el: { - type: "bi.label", - ref: _ref => { - this.text = _ref; + items: [ + { + el: { + type: Label.xtype, + ref: _ref => { + this.text = _ref; + }, + cls: "list-item-text", + textAlign: "left", + hgap: o.textHgap, + vgap: o.textVgap, + lgap: o.textLgap, + rgap: o.textRgap, + text: o.text, + value: o.value, + keyword: o.keyword, + height: o.height, }, - cls: "list-item-text", - textAlign: "left", - hgap: o.textHgap, - vgap: o.textVgap, - lgap: o.textLgap, - rgap: o.textRgap, - text: o.text, - value: o.value, - keyword: o.keyword, - height: o.height, }, - }, { - type: "bi.icon_label", - cls: o.iconCls, - width: o.iconWrapperWidth || o.height, - height: o.height, - iconWidth: o.iconWidth, - iconHeight: o.iconHeight, - }], + { + type: IconLabel.xtype, + cls: o.iconCls, + width: o.iconWrapperWidth || o.height, + height: o.height, + iconWidth: o.iconWidth, + iconHeight: o.iconHeight, + } + ], }; } diff --git a/src/base/single/button/node/textnode.js b/src/base/single/button/node/textnode.js index 2907b4c9d..5218c36ff 100644 --- a/src/base/single/button/node/textnode.js +++ b/src/base/single/button/node/textnode.js @@ -1,5 +1,6 @@ +import { Label } from "../../label"; import { NodeButton } from "../button.node"; -import { extend, shortcut, createWidget } from "../../../../core"; +import { extend, shortcut, createWidget } from "@/core"; /** * guy @@ -10,10 +11,9 @@ import { extend, shortcut, createWidget } from "../../../../core"; */ @shortcut() export class TextNode extends NodeButton { - static xtype = "bi.text_node" - - static EVENT_CHANGE = "EVENT_CHANGE" + static xtype = "bi.text_node"; + static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { const conf = super._defaultConfig(...arguments); @@ -32,7 +32,7 @@ export class TextNode extends NodeButton { render() { const o = this.options; this.text = createWidget({ - type: "bi.label", + type: Label.xtype, element: this, textAlign: o.textAlign, whiteSpace: o.whiteSpace, diff --git a/src/base/single/editor/editor.js b/src/base/single/editor/editor.js index af9196081..7aba92760 100644 --- a/src/base/single/editor/editor.js +++ b/src/base/single/editor/editor.js @@ -1,12 +1,25 @@ +import { Input } from "../input"; +import { + AbsoluteLayout, + shortcut, + Controller, + extend, + createWidget, + isKey, + isEmptyString, + isFunction, + isNull, + trim +} from "@/core"; +import { Label } from "../label"; +import { Single } from "../0.single"; +import { Bubbles } from "@/base"; + /** * Created by GUY on 2015/4/15. * @class BI.Editor * @extends BI.Single */ -import { shortcut, Controller, extend, createWidget, isKey, isEmptyString, isFunction, isNull, trim } from "../../../core"; -import { Single } from "../0.single"; -import { Input } from "../input/input"; -import { Bubbles } from "../../0.base"; @shortcut() export class Editor extends Single { @@ -57,19 +70,34 @@ export class Editor extends Single { } render() { - const { value, watermark, validationChecker, quitChecker, allowBlank, inputType, hgap, vgap, lgap, rgap, tgap, bgap } = this.options; - // 密码输入框设置autocomplete="new-password"的情况下Firefox和chrome不会自动填充密码 - const autocomplete = this.options.autocomplete ? ` autocomplete=${this.options.autocomplete}` : ""; - this.editor = this.addWidget(createWidget({ - type: "bi.input", - element: ``, - root: true, + const { value, watermark, validationChecker, quitChecker, allowBlank, - })); + inputType, + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, + } = this.options; + // 密码输入框设置autocomplete="new-password"的情况下Firefox和chrome不会自动填充密码 + const autocomplete = this.options.autocomplete ? ` autocomplete=${this.options.autocomplete}` : ""; + this.editor = this.addWidget( + createWidget({ + type: Input.xtype, + element: ``, + root: true, + value, + watermark, + validationChecker, + quitChecker, + allowBlank, + }) + ); this.editor.element.css({ width: "100%", height: "100%", @@ -82,7 +110,7 @@ export class Editor extends Single { const items = [ { el: { - type: "bi.absolute", + type: AbsoluteLayout.xtype, ref: _ref => { this.contentWrapper = _ref; }, @@ -104,7 +132,7 @@ export class Editor extends Single { ]; createWidget({ - type: "bi.absolute", + type: AbsoluteLayout.xtype, element: this, items, }); @@ -157,9 +185,10 @@ export class Editor extends Single { this.editor.on(Input.EVENT_RESTRICT, (...args) => { this._checkWaterMark(); const tip = this._setErrorVisible(true); - tip && tip.element.fadeOut(100, () => { - tip.element.fadeIn(100); - }); + tip && + tip.element.fadeOut(100, () => { + tip.element.fadeIn(100); + }); this.fireEvent(Editor.EVENT_RESTRICT, ...args); }); this.editor.on(Input.EVENT_EMPTY, (...args) => { @@ -224,7 +253,7 @@ export class Editor extends Single { const { height, vgap, tgap } = this.options; if (isNull(this.watermark)) { this.watermark = createWidget({ - type: "bi.label", + type: Label.xtype, cls: "bi-water-mark", text: this.options.watermark, height: height - 2 * vgap - tgap, @@ -281,7 +310,7 @@ export class Editor extends Single { if (isNull(this.watermark)) { this._assertWaterMark(); createWidget({ - type: "bi.absolute", + type: AbsoluteLayout.xtype, element: this.contentWrapper, items: [ { diff --git a/src/base/single/editor/editor.multifile.js b/src/base/single/editor/editor.multifile.js index 2f143c048..426034ce5 100644 --- a/src/base/single/editor/editor.multifile.js +++ b/src/base/single/editor/editor.multifile.js @@ -1,3 +1,6 @@ +import { File } from "../input"; +import { AbsoluteLayout, AdaptiveLayout, shortcut, Widget, createWidget, extend } from "@/core"; + /** * 多文件 * @@ -6,8 +9,6 @@ * @extends BI.Single * @abstract */ -import { shortcut, Widget, createWidget, extend } from "../../../core"; -import { File } from "../input/file"; @shortcut() export class MultifileEditor extends Widget { @@ -23,7 +24,7 @@ export class MultifileEditor extends Widget { const conf = super._defaultConfig(...arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-multifile-editor", + baseCls: `${conf.baseCls || ""} bi-multifile-editor`, multiple: false, maxSize: -1, // 1024 * 1024 accept: "", @@ -34,7 +35,7 @@ export class MultifileEditor extends Widget { render() { const { name, url, multiple, accept, maxSize, maxLength, title, errorText } = this.options; this.file = createWidget({ - type: "bi.file", + type: File.xtype, cls: "multifile-editor", width: "100%", height: "100%", @@ -64,19 +65,21 @@ export class MultifileEditor extends Widget { }); createWidget({ - type: "bi.absolute", + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: { - type: "bi.adaptive", - scrollable: false, - items: [this.file], - }, - top: 0, - right: 0, - left: 0, - bottom: 0, - }], + items: [ + { + el: { + type: AdaptiveLayout.xtype, + scrollable: false, + items: [this.file], + }, + top: 0, + right: 0, + left: 0, + bottom: 0, + } + ], }); } diff --git a/src/base/single/editor/editor.textarea.js b/src/base/single/editor/editor.textarea.js index 2ef9df43f..cdfa0966a 100644 --- a/src/base/single/editor/editor.textarea.js +++ b/src/base/single/editor/editor.textarea.js @@ -1,12 +1,29 @@ +import { + Layout, + AbsoluteLayout, + AdaptiveLayout, + shortcut, + Widget, + Controller, + createWidget, + extend, + isEmptyString, + isKey, + isNotEmptyString, + isNotNull, + trim, + isFunction +} from "@/core"; +import { Label } from "../label"; +import { Single } from "../0.single"; +import { Bubbles } from "@/base"; + /** * * Created by GUY on 2016/1/18. * @class BI.TextAreaEditor * @extends BI.Single */ -import { shortcut, Widget, Controller, createWidget, extend, isEmptyString, isKey, isNotEmptyString, isNotNull, trim, isFunction } from "../../../core"; -import { Single } from "../0.single"; -import { Bubbles } from "../../0.base"; @shortcut() export class TextAreaEditor extends Single { @@ -27,9 +44,7 @@ export class TextAreaEditor extends Single { adjustYOffset: conf.simple ? 0 : 2, adjustXOffset: 0, offsetStyle: "left", - validationChecker: () => { - return true; - }, + validationChecker: () => true, scrolly: true, }); } @@ -37,32 +52,36 @@ export class TextAreaEditor extends Single { render() { const { scrolly, value, style } = this.options; this.content = createWidget({ - type: "bi.layout", + type: Layout.xtype, tagName: "textarea", width: "100%", height: "100%", cls: "bi-textarea textarea-editor-content display-block", - css: scrolly ? null : { - overflowY: "hidden", - }, + css: scrolly + ? null + : { + overflowY: "hidden", + }, }); this.content.element.css({ resize: "none" }); createWidget({ - type: "bi.absolute", + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: { - type: "bi.adaptive", - items: [this.content], - }, - left: 4, - right: 4, - top: 2, - bottom: 2, - }], + items: [ + { + el: { + type: AdaptiveLayout.xtype, + items: [this.content], + }, + left: 4, + right: 4, + top: 2, + bottom: 2, + } + ], }); - this.content.element.on("input propertychange", (e) => { + this.content.element.on("input propertychange", e => { this._checkError(); this._checkWaterMark(); this.fireEvent(Controller.EVENT_CHANGE, BI.Events.CHANGE, this.getValue(), this); @@ -76,9 +95,9 @@ export class TextAreaEditor extends Single { this._checkError(); this._focus(); this.fireEvent(TextAreaEditor.EVENT_FOCUS); - Widget._renderEngine.createElement(document).bind("mousedown." + this.getName(), (e) => { + Widget._renderEngine.createElement(document).bind(`mousedown.${this.getName()}`, e => { if (BI.DOM.isExist(this) && !this.element.__isMouseInBounds__(e)) { - Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()); + Widget._renderEngine.createElement(document).unbind(`mousedown.${this.getName()}`); this.content.element.blur(); } }); @@ -90,16 +109,16 @@ export class TextAreaEditor extends Single { this.fireEvent(TextAreaEditor.EVENT_CONFIRM); } this.fireEvent(TextAreaEditor.EVENT_BLUR); - Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()); + Widget._renderEngine.createElement(document).unbind(`mousedown.${this.getName()}`); }); this.content.element.keydown(() => { // 水印快速消失 this._checkWaterMark(); }); - this.content.element.keyup((e) => { + this.content.element.keyup(e => { this.fireEvent(TextAreaEditor.EVENT_KEY_DOWN, e.keyCode); }); - this.content.element.click((e) => { + this.content.element.click(e => { e.stopPropagation(); }); if (isKey(value)) { @@ -121,7 +140,7 @@ export class TextAreaEditor extends Single { if (isNotEmptyString(watermark)) { if (!this.watermark) { this.watermark = createWidget({ - type: "bi.label", + type: Label.xtype, cls: "bi-water-mark textarea-watermark", textAlign: "left", whiteSpace: scrolly ? "normal" : "nowrap", @@ -133,7 +152,7 @@ export class TextAreaEditor extends Single { height: height > 24 ? "" : height, }); this.watermark.element.bind({ - mousedown: (e) => { + mousedown: e => { if (this.isEnabled()) { this.focus(); } else { @@ -141,19 +160,21 @@ export class TextAreaEditor extends Single { } e.stopEvent(); }, - click: (e) => { + click: e => { e.stopPropagation(); }, }); createWidget({ - type: "bi.absolute", + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.watermark, - left: 0, - top: 0, - right: 0, - }], + items: [ + { + el: this.watermark, + left: 0, + top: 0, + right: 0, + } + ], }); } else { this.watermark.setText(watermark); @@ -232,9 +253,17 @@ export class TextAreaEditor extends Single { setStyle(style) { this.style = style; this.element.css(style); - this.content.element.css(extend({}, style, { - color: style.color || BI.DOM.getContrastColor(BI.DOM.isRGBColor(style.backgroundColor) ? BI.DOM.rgb2hex(style.backgroundColor) : style.backgroundColor), - })); + this.content.element.css( + extend({}, style, { + color: + style.color || + BI.DOM.getContrastColor( + BI.DOM.isRGBColor(style.backgroundColor) + ? BI.DOM.rgb2hex(style.backgroundColor) + : style.backgroundColor + ), + }) + ); } getStyle() { diff --git a/src/base/single/editor/index.js b/src/base/single/editor/index.js index 0bd7cdf7d..bb303a1a0 100644 --- a/src/base/single/editor/index.js +++ b/src/base/single/editor/index.js @@ -1,3 +1,3 @@ -export { Editor } from "./editor"; -export { MultifileEditor } from "./editor.multifile"; -export { TextAreaEditor } from "./editor.textarea"; \ No newline at end of file +export { Editor } from "./editor"; +export { MultifileEditor } from "./editor.multifile"; +export { TextAreaEditor } from "./editor.textarea"; diff --git a/src/base/single/html/html.js b/src/base/single/html/html.js index 9e78c5364..6db0bf62c 100644 --- a/src/base/single/html/html.js +++ b/src/base/single/html/html.js @@ -1,10 +1,11 @@ +import { Layout, DefaultLayout, shortcut, isNumber, createWidget, isWidthOrHeight, isKey } from "@/core"; +import { Single } from "../0.single"; + /** * guy 表示一行数据,通过position来定位位置的数据 * @class BI.Html * @extends BI.Single */ -import { shortcut, isNumber, createWidget, isWidthOrHeight, isKey } from "../../../core"; -import { Single } from "../0.single"; @shortcut() export class Html extends Single { @@ -24,10 +25,26 @@ export class Html extends Single { bgap: 0, text: "", highLight: false, - } + }; render() { - const { vgap, hgap, lgap, rgap, tgap, bgap, height, lineHeight, maxWidth, textAlign, whiteSpace, handler, text, value, highLight } = this.options; + const { + vgap, + hgap, + lgap, + rgap, + tgap, + bgap, + height, + lineHeight, + maxWidth, + textAlign, + whiteSpace, + handler, + text, + value, + highLight, + } = this.options; if (hgap + lgap > 0) { this.element.css({ "padding-left": BI.pixFormat(hgap + lgap), @@ -68,14 +85,14 @@ export class Html extends Single { }); if (handler) { this.text = createWidget({ - type: "bi.layout", + type: Layout.xtype, tagName: "span", }); this.text.element.click(() => { handler(this.getValue()); }); createWidget({ - type: "bi.default", + type: DefaultLayout.xtype, element: this, items: [this.text], }); diff --git a/src/base/single/icon/icon.js b/src/base/single/icon/icon.js index 63b573a41..6692205b7 100644 --- a/src/base/single/icon/icon.js +++ b/src/base/single/icon/icon.js @@ -1,10 +1,11 @@ +import { Single } from "../0.single"; +import { shortcut, extend } from "@/core"; + /** * guy 图标 * @class BI.Icon * @extends BI.Single */ -import { shortcut, extend } from "../../../core"; -import { Single } from "../0.single"; @shortcut() export class Icon extends Single { @@ -15,7 +16,7 @@ export class Icon extends Single { return extend(conf, { tagName: "i", - baseCls: (conf.baseCls || "") + " x-icon b-font horizon-center display-block", + baseCls: `${conf.baseCls || ""} x-icon b-font horizon-center display-block`, }); } diff --git a/src/base/single/iframe/iframe.js b/src/base/single/iframe/iframe.js index 15f4d0d2a..bc537c1e5 100644 --- a/src/base/single/iframe/iframe.js +++ b/src/base/single/iframe/iframe.js @@ -1,11 +1,12 @@ +import { Single } from "../0.single"; +import { shortcut, extend } from "@/core"; + /** * @class Iframe * @extends Single * @abstract * Created by GameJian on 2016/3/2. */ -import { shortcut, extend } from "../../../core"; -import { Single } from "../0.single"; @shortcut() export class Iframe extends Single { @@ -13,9 +14,10 @@ export class Iframe extends Single { _defaultConfig(config) { const conf = super._defaultConfig(...arguments); + return extend(conf, { tagName: "iframe", - baseCls: (conf.baseCls || "") + " bi-iframe", + baseCls: `${conf.baseCls || ""} bi-iframe`, src: "", name: "", attributes: {}, @@ -31,13 +33,16 @@ export class Iframe extends Single { } _initProps() { - super._initProps(...arguments) + super._initProps(...arguments); const { src, name } = this.options; - this.options.attributes = extend({ - frameborder: 0, - src, - name, - }, this.options.attributes); + this.options.attributes = extend( + { + frameborder: 0, + src, + name, + }, + this.options.attributes + ); } setSrc(src) { diff --git a/src/base/single/img/img.js b/src/base/single/img/img.js index 92475ea8c..9f829ad7d 100644 --- a/src/base/single/img/img.js +++ b/src/base/single/img/img.js @@ -1,3 +1,6 @@ +import { Single } from "../0.single"; +import { shortcut, extend } from "@/core"; + /** * ͼƬ * @@ -6,8 +9,6 @@ * @extends BI.Single * @abstract */ -import { shortcut, extend } from "../../../core"; -import { Single } from "../0.single"; @shortcut() export class Img extends Single { @@ -18,7 +19,7 @@ export class Img extends Single { return extend(conf, { tagName: "img", - baseCls: (conf.baseCls || "") + " bi-img display-block", + baseCls: `${conf.baseCls || ""} bi-img display-block`, src: "", attributes: config.src ? { src: config.src } : {}, width: "100%", @@ -27,13 +28,16 @@ export class Img extends Single { } _initProps() { - super._initProps(...arguments) + super._initProps(...arguments); const { src } = this.options; - this.options.attributes = extend({ - src, - }, this.options.attributes); + this.options.attributes = extend( + { + src, + }, + this.options.attributes + ); } - + setSrc(src) { this.options.src = src; this.element.attr("src", src); diff --git a/src/base/single/input/checkbox/checkbox.image.js b/src/base/single/input/checkbox/checkbox.image.js index 3b7e445e7..48425c022 100644 --- a/src/base/single/input/checkbox/checkbox.image.js +++ b/src/base/single/input/checkbox/checkbox.image.js @@ -1,22 +1,23 @@ +import { IconButton } from "../../button"; +import { shortcut, extend } from "@/core"; + /** * guy * @extends Single * @type {*|void|Object} */ -import { shortcut, extend } from "../../../../core"; -import { IconButton } from "../../button"; @shortcut() export class ImageCheckbox extends IconButton { static xtype = "bi.image_checkbox"; static EVENT_CHANGE = IconButton.EVENT_CHANGE; - + _defaultConfig() { const conf = super._defaultConfig(...arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-image-checkbox check-box-icon", + baseCls: `${conf.baseCls || ""} bi-image-checkbox check-box-icon`, selected: false, handler: BI.emptyFn, width: 16, diff --git a/src/base/single/input/checkbox/checkbox.js b/src/base/single/input/checkbox/checkbox.js index ed5ef46f7..cec7a0031 100644 --- a/src/base/single/input/checkbox/checkbox.js +++ b/src/base/single/input/checkbox/checkbox.js @@ -1,10 +1,11 @@ +import { CenterAdaptLayout, DefaultLayout, shortcut } from "@/core"; +import { BasicButton } from "../../button"; + /** * guy * @extends Single * @type {*|void|Object} */ -import { shortcut } from "../../../../core"; -import { BasicButton } from "../../button"; @shortcut() export class Checkbox extends BasicButton { @@ -20,22 +21,24 @@ export class Checkbox extends BasicButton { height: 14, iconWidth: 14, iconHeight: 14, - } + }; render() { const { iconWidth, iconHeight } = this.options; return { - type: "bi.center_adapt", - items: [{ - type: "bi.default", - ref: (_ref) => { - this.checkbox = _ref; - }, - cls: "checkbox-content", - width: iconWidth, - height: iconHeight, - }], + type: CenterAdaptLayout.xtype, + items: [ + { + type: DefaultLayout.xtype, + ref: _ref => { + this.checkbox = _ref; + }, + cls: "checkbox-content", + width: iconWidth, + height: iconHeight, + } + ], }; } diff --git a/src/base/single/input/file.js b/src/base/single/input/file.js index 9f0e0e708..35fe93a9b 100644 --- a/src/base/single/input/file.js +++ b/src/base/single/input/file.js @@ -1,3 +1,6 @@ +import { Msg } from "../../foundation/message"; +import { shortcut, Widget, some, extend } from "@/core"; + /** * 文件 * @@ -6,27 +9,22 @@ * @extends BI.Single * @abstract */ -import { shortcut, Widget, some, extend } from "../../../core"; -import { Msg } from "../../foundation/message"; const document = _global.document || {}; + /** * @description normalize input.files. create if not present, add item method if not present * @param Object generated wrap object * @return Object the wrap object itself */ -const F = (((item) => { - return (input) => { - const files = input.files || [input]; - if (!files.item) { - files.item = item; - } +const F = (item => input => { + const files = input.files || [input]; + if (!files.item) { + files.item = item; + } - return files; - }; -})((i) => { - return this[i]; -})); + return files; +})(i => this[i]); const event = { @@ -37,14 +35,14 @@ const event = { * @param Function the callback to associate as event * @return Object noswfupload.event */ - add: document.addEventListener ? - (node, name, callback) => { + add: document.addEventListener + ? (node, name, callback) => { node.addEventListener(name, callback, false); return this; - } : - (node, name, callback) => { - node.attachEvent("on" + name, callback); + } + : (node, name, callback) => { + node.attachEvent(`on${name}`, callback); return this; }, @@ -56,14 +54,14 @@ const event = { * @param Function the callback associated as event * @return Object noswfupload.event */ - del: document.removeEventListener ? - (node, name, callback) => { + del: document.removeEventListener + ? (node, name, callback) => { node.removeEventListener(name, callback, false); - + return this; - } : - (node, name, callback) => { - node.detachEvent("on" + name, callback); + } + : (node, name, callback) => { + node.detachEvent(`on${name}`, callback); return this; }, @@ -79,34 +77,41 @@ const event = { event.returnValue = !(event.cancelBubble = true); } } else { - e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true; - e.preventDefault ? e.preventDefault() : e.returnValue = false; + e.stopPropagation ? e.stopPropagation() : (e.cancelBubble = true); + e.preventDefault ? e.preventDefault() : (e.returnValue = false); } return false; }, }; -const sendFile = (((toString) => { +const sendFile = (toString => { const split = "onabort.onerror.onloadstart.onprogress".split("."), length = split.length, CRLF = "\r\n"; - let xhr = new XMLHttpRequest, + let xhr = new XMLHttpRequest(), sendFile; - const multipart = (boundary, name, file) => { - return "--".concat( - boundary, CRLF, - "Content-Disposition: form-data; name=\"", name, "\"; filename=\"", _global.encodeURIComponent(file.fileName), "\"", CRLF, - "Content-Type: application/octet-stream", CRLF, + const multipart = (boundary, name, file) => + "--".concat( + boundary, + CRLF, + "Content-Disposition: form-data; name=\"", + name, + "\"; filename=\"", + _global.encodeURIComponent(file.fileName), + "\"", + CRLF, + "Content-Type: application/octet-stream", CRLF, - file.getAsBinary(), CRLF, - "--", boundary, "--", CRLF + CRLF, + file.getAsBinary(), + CRLF, + "--", + boundary, + "--", + CRLF ); - } - const isFunction = (Function) => { - return toString.call(Function) === "[object Function]"; - } - + const isFunction = Function => toString.call(Function) === "[object Function]"; // FireFox 3+, Safari 4 beta (Chrome 2 beta file is buggy and will not work) if (xhr.upload || xhr.sendAsBinary) { @@ -116,32 +121,30 @@ const sendFile = (((toString) => { if (isFunction(handler.onerror)) { handler.onerror(); } - - return; + + return; } - const xhr = new XMLHttpRequest, - upload = xhr.upload || { - addEventListener(event, callback) { - this["on" + event] = callback; - }, - }; - for (let i = 0;i < length;i++) { + const xhr = new XMLHttpRequest(), + upload = xhr.upload || { + addEventListener(event, callback) { + this[`on${event}`] = callback; + }, + }; + for (let i = 0; i < length; i++) { upload.addEventListener( split[i].substring(2), // eslint-disable-next-line no-loop-func - (((event) => { - return (rpe) => { - if (isFunction(handler[event])) { - handler[event](rpe, xhr); - } - }; - })(split[i])), + (event => rpe => { + if (isFunction(handler[event])) { + handler[event](rpe, xhr); + } + })(split[i]), false ); } upload.addEventListener( "load", - (rpe) => { + rpe => { if (handler.onreadystatechange === false) { if (isFunction(handler.onload)) { handler.onload(rpe, xhr); @@ -155,15 +158,19 @@ const sendFile = (((toString) => { } else { setTimeout(callback, 15); } - } + }; setTimeout(callback, 15); } }, false ); - xhr.open("post", BI.appendQuery(handler.url, { - filename: _global.encodeURIComponent(handler.file.fileName), - }), true); + xhr.open( + "post", + BI.appendQuery(handler.url, { + filename: _global.encodeURIComponent(handler.file.fileName), + }), + true + ); if (!xhr.upload) { const rpe = { loaded: 0, total: handler.file.fileSize || handler.file.size, simulation: true }; rpe.interval = setInterval(() => { @@ -181,61 +188,61 @@ const sendFile = (((toString) => { }; xhr.onreadystatechange = () => { switch (xhr.readyState) { - case 2: - case 3: - if (rpe.total <= rpe.loaded) { - rpe.loaded = rpe.total; - } - upload.onprogress(rpe); - break; - case 4: - clearInterval(rpe.interval); - rpe.interval = 0; + case 2: + case 3: + if (rpe.total <= rpe.loaded) { rpe.loaded = rpe.total; - upload.onprogress(rpe); - if (199 < xhr.status && xhr.status < 400) { - upload.onload({}); - const attachO = BI.jsonDecode(xhr.responseText); - attachO.filename = handler.file.fileName; - if (handler.file.type.indexOf("image") !== -1) { - attachO.attach_type = "image"; - } - handler.attach_array[current] = attachO; - } else { - upload.onerror({}); + } + upload.onprogress(rpe); + break; + case 4: + clearInterval(rpe.interval); + rpe.interval = 0; + rpe.loaded = rpe.total; + upload.onprogress(rpe); + if (199 < xhr.status && xhr.status < 400) { + upload.onload({}); + const attachO = BI.jsonDecode(xhr.responseText); + attachO.filename = handler.file.fileName; + if (handler.file.type.indexOf("image") !== -1) { + attachO.attach_type = "image"; } - break; - default: - break; + handler.attach_array[current] = attachO; + } else { + upload.onerror({}); + } + break; + default: + break; } }; upload.onloadstart(rpe); } else { xhr.onreadystatechange = () => { switch (xhr.readyState) { - case 4: - const attachO = BI.jsonDecode(xhr.responseText); - if (handler.file.type.indexOf("image") !== -1) { - attachO.attach_type = "image"; - } - attachO.filename = handler.file.fileName; - if (handler.maxLength === 1) { - handler.attach_array[0] = attachO; - // handler.attach_array.push(attachO); - } else { - handler.attach_array[current] = attachO; - } - break; - default: - break; + case 4: + const attachO = BI.jsonDecode(xhr.responseText); + if (handler.file.type.indexOf("image") !== -1) { + attachO.attach_type = "image"; + } + attachO.filename = handler.file.fileName; + if (handler.maxLength === 1) { + handler.attach_array[0] = attachO; + // handler.attach_array.push(attachO); + } else { + handler.attach_array[current] = attachO; + } + break; + default: + break; } }; if (isFunction(upload.onloadstart)) { upload.onloadstart(); } } - const boundary = "AjaxUploadBoundary" + (new Date).getTime(); - xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary); + const boundary = `AjaxUploadBoundary${new Date().getTime()}`; + xhr.setRequestHeader("Content-Type", `multipart/form-data; boundary=${boundary}`); if (handler.file.getAsBinary) { xhr[xhr.sendAsBinary ? "sendAsBinary" : "send"](multipart(boundary, handler.name, handler.file)); } else { @@ -246,7 +253,7 @@ const sendFile = (((toString) => { form.append("FileData", handler.file); xhr.send(form); } - + return handler; }; } else { @@ -256,7 +263,10 @@ const sendFile = (((toString) => { let iframe, form; const url = handler.url.concat(-1 === handler.url.indexOf("?") ? "?" : "&", "AjaxUploadFrame=true"), rpe = { - loaded: 1, total: 100, simulation: true, interval: setInterval(() => { + loaded: 1, + total: 100, + simulation: true, + interval: setInterval(() => { if (rpe.loaded < rpe.total) { ++rpe.loaded; } @@ -265,56 +275,62 @@ const sendFile = (((toString) => { } }, 100), }, - target = ["AjaxUpload", (new Date).getTime(), String(Math.random()).substring(2)].join("_"); - const onload = () => { - iframe.onreadystatechange = iframe.onload = iframe.onerror = null; - form.parentNode.removeChild(form); - form = null; - clearInterval(rpe.interval); - // rpe.loaded = rpe.total; - const responseText = (iframe.contentWindow.document || iframe.contentWindow.contentDocument).body.innerHTML; - try { - const attachO = BI.jsonDecode(responseText); - if (handler.file.type.indexOf("image") !== -1) { - attachO.attach_type = "image"; - } + target = ["AjaxUpload", new Date().getTime(), String(Math.random()).substring(2)].join("_"); + const onload = () => { + iframe.onreadystatechange = iframe.onload = iframe.onerror = null; + form.parentNode.removeChild(form); + form = null; + clearInterval(rpe.interval); + // rpe.loaded = rpe.total; + const responseText = (iframe.contentWindow.document || iframe.contentWindow.contentDocument).body + .innerHTML; + try { + const attachO = BI.jsonDecode(responseText); + if (handler.file.type.indexOf("image") !== -1) { + attachO.attach_type = "image"; + } - // attachO.fileSize = responseText.length; - try { - // decodeURIComponent特殊字符可能有问题, catch一下,保证能正常上传 - attachO.filename = _global.decodeURIComponent(handler.file.fileName); - } catch (e) { - attachO.filename = handler.file.fileName; - } - if (handler.maxLength === 1) { - handler.attach_array[0] = attachO; - } else { - handler.attach_array[current] = attachO; - } + // attachO.fileSize = responseText.length; + try { + // decodeURIComponent特殊字符可能有问题, catch一下,保证能正常上传 + attachO.filename = _global.decodeURIComponent(handler.file.fileName); } catch (e) { - if (isFunction(handler.onerror)) { - handler.onerror(rpe, event || _global.event); - } + attachO.filename = handler.file.fileName; } - if (isFunction(handler.onload)) { - handler.onload(rpe, { responseText: responseText }); + if (handler.maxLength === 1) { + handler.attach_array[0] = attachO; + } else { + handler.attach_array[current] = attachO; + } + } catch (e) { + if (isFunction(handler.onerror)) { + handler.onerror(rpe, event || _global.event); } } - - try { // IE < 8 does not accept enctype attribute ... + if (isFunction(handler.onload)) { + handler.onload(rpe, { responseText }); + } + }; + + try { + // IE < 8 does not accept enctype attribute ... const form = document.createElement("
"), - iframe = handler.iframe || (handler.iframe = document.createElement("")); + iframe = + handler.iframe || + (handler.iframe = document.createElement( + `` + )); } catch (e) { const form = document.createElement("form"), iframe = handler.iframe || (handler.iframe = document.createElement("iframe")); form.setAttribute("enctype", "multipart/form-data"); - iframe.setAttribute("name", iframe.id = target); + iframe.setAttribute("name", (iframe.id = target)); iframe.setAttribute("src", url); } iframe.style.position = "absolute"; iframe.style.left = iframe.style.top = "-10000px"; iframe.onload = onload; - iframe.onerror = (event) => { + iframe.onerror = event => { if (isFunction(handler.onerror)) { handler.onerror(rpe, event || _global.event); } @@ -329,16 +345,17 @@ const sendFile = (((toString) => { ++rpe.loaded; } handler.onloadprogress(rpe, { - readyState: { - loading: 2, - interactive: 3, - loaded: 4, - complete: 4, - }[iframe.readyState] || 1, + readyState: + { + loading: 2, + interactive: 3, + loaded: 4, + complete: 4, + }[iframe.readyState] || 1, }); } }; - form.setAttribute("action", handler.url + "&filename=" + _global.encodeURIComponent(handler.file.fileName)); + form.setAttribute("action", `${handler.url}&filename=${_global.encodeURIComponent(handler.file.fileName)}`); form.setAttribute("target", iframe.id); form.setAttribute("method", "post"); form.appendChild(handler.file); @@ -355,19 +372,19 @@ const sendFile = (((toString) => { }; } xhr = null; - + return sendFile; -})(Object.prototype.toString)); +})(Object.prototype.toString); const sendFiles = (handler, maxSize, width, height) => { const length = handler.files.length, - onload = handler.onload, - onloadstart = handler.onloadstart; + onload = handler.onload, + onloadstart = handler.onloadstart; handler.current = 0; handler.total = 0; handler.sent = 0; while (handler.current < length) { - handler.total += (handler.files[handler.current].fileSize || handler.files[handler.current].size); + handler.total += handler.files[handler.current].fileSize || handler.files[handler.current].size; handler.current++; } handler.current = 0; @@ -375,7 +392,7 @@ const sendFiles = (handler, maxSize, width, height) => { handler.file = handler.files[handler.current]; const callback = (rpe, xhr) => { handler.onloadstart = null; - handler.sent += (handler.files[handler.current].fileSize || handler.files[handler.current].size); + handler.sent += handler.files[handler.current].fileSize || handler.files[handler.current].size; if (++handler.current < length) { handler.file = handler.files[handler.current]; sendFile(handler, maxSize, width, height).onload = callback; @@ -415,7 +432,7 @@ const sendFiles = (handler, maxSize, width, height) => { } return handler; -} +}; const r1 = /\.([^.]+)$/; // .png const r2 = /\/([^/]+)$/; // image/png @@ -432,7 +449,7 @@ const fileTypeValidate = (fileName, fileType) => { } const mimes = fileType.split(","); if (mimes[0] === fileType) { - mimes = (fileType + "").split(";"); + mimes = `${fileType}`.split(";"); } return some(mimes, (index, mime) => { @@ -446,7 +463,7 @@ const fileTypeValidate = (fileName, fileType) => { return matches[1] === "*" ? true : fileName.toLowerCase().indexOf(matches[1]) > -1; } }); -} +}; @shortcut() export class File extends Widget { @@ -462,7 +479,7 @@ export class File extends Widget { const conf = super._defaultConfig(...arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-file display-block", + baseCls: `${conf.baseCls || ""} bi-file display-block`, tagName: "input", attributes: { type: "file", @@ -492,14 +509,14 @@ export class File extends Widget { // create the noswfupload.wrap Object // wrap.maxSize 文件大小限制 // wrap.maxLength 文件个数限制 - const _wrap = this.wrap = this._wrap(this.element[0], maxSize); + const _wrap = (this.wrap = this._wrap(this.element[0], maxSize)); // fileType could contain whatever text but filter checks *.{extension} // if present // handlerszhe _wrap.onloadstart = (...args) => { - this.fireEvent(File.EVENT_UPLOADSTART, ...args); + this.fireEvent(File.EVENT_UPLOADSTART, ...args); }; _wrap.onprogress = (rpe, xhr) => { @@ -586,20 +603,26 @@ export class File extends Widget { const validateFileType = fileTypeValidate(value, wrap.fileType); if (!validateFileType) { // 文件类型不支持 - Msg.toast(errorText({ - errorType: 0, - file: item, - }) || BI.i18nText("BI-Upload_File_Type_Error", wrap.fileType), { level: "error" }); + Msg.toast( + errorText({ + errorType: 0, + file: item, + }) || BI.i18nText("BI-Upload_File_Type_Error", wrap.fileType), + { level: "error" } + ); this.fireEvent(File.EVENT_ERROR, { errorType: 0, file: item, }); } else if (wrap.maxSize !== -1 && size && wrap.maxSize < size) { // 文件大小不支持 - Msg.toast(errorText({ - errorType: 1, - file: item, - }) || BI.i18nText("BI-Upload_File_Size_Error", Math.ceil(wrap.maxSize / 1024 / 1024)), { level: "error" }); + Msg.toast( + errorText({ + errorType: 1, + file: item, + }) || BI.i18nText("BI-Upload_File_Size_Error", Math.ceil(wrap.maxSize / 1024 / 1024)), + { level: "error" } + ); this.fireEvent(File.EVENT_ERROR, { errorType: 1, file: item, @@ -609,14 +632,15 @@ export class File extends Widget { } } } - wrap.files.length > 0 && this.fireEvent(File.EVENT_CHANGE, { - files: wrap.files, - }); + wrap.files.length > 0 && + this.fireEvent(File.EVENT_CHANGE, { + files: wrap.files, + }); input.value = ""; wrap.dom.input.parentNode.replaceChild(input, wrap.dom.input); wrap.dom.input = input; event.add(wrap.dom.input, "change", callback); - } + }; event.add(wrap.dom.input, "change", callback); return wrap; @@ -633,10 +657,9 @@ export class File extends Widget { // wrap Object return this._events({ - // DOM namespace dom: { - input: input, // input file + input, // input file disabled: false, // internal use, checks input file state }, name: input.name, // name to send for each file ($_FILES[{name}] in the server) @@ -655,7 +678,7 @@ export class File extends Widget { // something like {onload:function(){alert("OK")},onerror:function(){alert("Error")}, etc ...} upload(handler) { if (handler) { - for (let key in handler) { + for (const key in handler) { this[key] = handler[key]; } } diff --git a/src/base/single/input/index.js b/src/base/single/input/index.js index 35a8f9b60..32754291f 100644 --- a/src/base/single/input/index.js +++ b/src/base/single/input/index.js @@ -1,6 +1,6 @@ -export { Input } from "./input"; -export { File } from "./file"; -export { Checkbox } from "./checkbox/checkbox"; -export { ImageCheckbox } from "./checkbox/checkbox.image"; -export { Radio } from "./radio/radio"; -export { ImageRadio } from "./radio/radio.image"; \ No newline at end of file +export { Input } from "./input"; +export { File } from "./file"; +export { Checkbox } from "./checkbox/checkbox"; +export { ImageCheckbox } from "./checkbox/checkbox.image"; +export { Radio } from "./radio/radio"; +export { ImageRadio } from "./radio/radio.image"; diff --git a/src/base/single/input/input.js b/src/base/single/input/input.js index 59f3a7686..6a3dcdaff 100644 --- a/src/base/single/input/input.js +++ b/src/base/single/input/input.js @@ -1,11 +1,26 @@ +import { Single } from "../0.single"; +import { + shortcut, + Controller, + extend, + debounce, + bind, + isNull, + isEmptyString, + isKey, + delay, + trim, + isEqual, + nextTick, + isEndWithBlank +} from "@/core"; + /** * guy * @class BI.Input 一个button和一行数 组成的一行listitem * @extends BI.Single * @type {*|void|Object} */ -import { shortcut, Controller, extend, debounce, bind, isNull, isEmptyString, isKey, delay, trim, isEqual, nextTick, isEndWithBlank } from "../../../core"; -import { Single } from "../0.single"; @shortcut() export class Input extends Single { @@ -37,7 +52,7 @@ export class Input extends Single { const conf = super._defaultConfig(...arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-input display-block overflow-dot", + baseCls: `${conf.baseCls || ""} bi-input display-block overflow-dot`, tagName: "input", validationChecker: BI.emptyFn, quitChecker: BI.emptyFn, // 按确定键能否退出编辑 @@ -49,37 +64,37 @@ export class Input extends Single { let ctrlKey = false; let keyCode = null; let inputEventValid = false; - const _keydown = debounce((keyCode) => { + const _keydown = debounce(keyCode => { this.onKeyDown(keyCode, ctrlKey); this._keydown_ = false; }, BI.EVENT_RESPONSE_TIME); const _clk = debounce(bind(this._click, this), BI.EVENT_RESPONSE_TIME, { - "leading": true, - "trailing": false, + leading: true, + trailing: false, }); this._focusDebounce = debounce(bind(this._focus, this), BI.EVENT_RESPONSE_TIME, { - "leading": true, - "trailing": false, + leading: true, + trailing: false, }); this._blurDebounce = debounce(bind(this._blur, this), BI.EVENT_RESPONSE_TIME, { - "leading": true, - "trailing": false, + leading: true, + trailing: false, }); this.element - .keydown((e) => { + .keydown(e => { inputEventValid = false; ctrlKey = e.ctrlKey || e.metaKey; // mac的cmd支持一下 keyCode = e.keyCode; this.fireEvent(Input.EVENT_QUICK_DOWN, e); }) - .keyup((e) => { + .keyup(e => { keyCode = null; if (!(inputEventValid && e.keyCode === BI.KeyCode.ENTER)) { this._keydown_ = true; _keydown(e.keyCode); } }) - .on("input propertychange", (e) => { + .on("input propertychange", e => { // 输入内容全选并直接删光,如果按键没放开就失去焦点不会触发keyup,被focusout覆盖了 // 其中propertychange在元素属性发生改变的时候就会触发 是为了兼容IE8 // 通过keyCode判断会漏掉输入法点击输入(右键粘贴暂缓) @@ -91,17 +106,18 @@ export class Input extends Single { keyCode = null; } }) - .click((e) => { + .click(e => { e.stopPropagation(); _clk(); }) - .mousedown((e) => { + .mousedown(e => { this.element.val(this.element.val()); }) - .focus((e) => { // 可以不用冒泡 + .focus(e => { + // 可以不用冒泡 this._focusDebounce(); }) - .blur((e) => { + .blur(e => { // DEC-14919 IE11在浏览器重新获得焦点之后会先触发focusout再触发focus,要保持先获得焦点再失去焦点的顺序不变,因此采用blur this._blurDebounce(); }); @@ -141,8 +157,8 @@ export class Input extends Single { } } this.fireEvent(Input.EVENT_BLUR); - } - + }; + if (this._keydown_ === true) { delay(blur, BI.EVENT_RESPONSE_TIME); } else { @@ -166,8 +182,11 @@ export class Input extends Single { this._checkValidationOnValueChange(); } if (this.isValid() && trim(this.getValue()) !== "") { - if (trim(this.getValue()) !== this._lastValue && (!this._start || isNull(this._lastValue) || this._lastValue === "") - || (this._pause === true && !/(\s|\u00A0)$/.test(this.getValue()))) { + if ( + (trim(this.getValue()) !== this._lastValue && + (!this._start || isNull(this._lastValue) || this._lastValue === "")) || + (this._pause === true && !/(\s|\u00A0)$/.test(this.getValue())) + ) { this._start = true; this._pause = false; this.fireEvent(Controller.EVENT_CHANGE, BI.Events.STARTEDIT, this.getValue(), this); @@ -203,8 +222,12 @@ export class Input extends Single { this.fireEvent(Controller.EVENT_CHANGE, BI.Events.PAUSE, "", this); this.fireEvent(Input.EVENT_PAUSE); this._defaultState(); - } else if ((keyCode === BI.KeyCode.BACKSPACE || keyCode === BI.KeyCode.DELETE) && - trim(this.getValue()) === "" && (lastValue !== null && trim(lastValue) !== "")) { + } else if ( + (keyCode === BI.KeyCode.BACKSPACE || keyCode === BI.KeyCode.DELETE) && + trim(this.getValue()) === "" && + lastValue !== null && + trim(lastValue) !== "" + ) { this.fireEvent(Controller.EVENT_CHANGE, BI.Events.STOPEDIT, this.getValue(), this); this.fireEvent(Input.EVENT_STOP); } @@ -250,7 +273,7 @@ export class Input extends Single { } const checker = validationChecker.apply(this, [trim(v)]); if (checker instanceof Promise) { - checker.then((validate) => { + checker.then(validate => { this.setValid(validate !== false); callback && callback(); }); diff --git a/src/base/single/input/radio/radio.image.js b/src/base/single/input/radio/radio.image.js index 72921b79c..07c7dba9b 100644 --- a/src/base/single/input/radio/radio.image.js +++ b/src/base/single/input/radio/radio.image.js @@ -1,22 +1,23 @@ +import { IconButton } from "../../button"; +import { shortcut, extend } from "@/core"; + /** * guy * @extends Single * @type {*|void|Object} */ -import { shortcut, extend } from "../../../../core"; -import { IconButton } from "../../button"; @shortcut() export class ImageRadio extends IconButton { static xtype = "bi.image_radio"; static EVENT_CHANGE = IconButton.EVENT_CHANGE; - + _defaultConfig() { const conf = super._defaultConfig(...arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-radio radio-icon", + baseCls: `${conf.baseCls || ""} bi-radio radio-icon`, selected: false, handler: BI.emptyFn, width: 16, diff --git a/src/base/single/input/radio/radio.js b/src/base/single/input/radio/radio.js index 612cd98d8..e38ba3802 100644 --- a/src/base/single/input/radio/radio.js +++ b/src/base/single/input/radio/radio.js @@ -1,10 +1,11 @@ +import { CenterAdaptLayout, Layout, shortcut } from "@/core"; +import { BasicButton } from "../../button"; + /** * guy * @extends Single * @type {*|void|Object} */ -import { shortcut } from "../../../../core"; -import { BasicButton } from "../../button"; @shortcut() export class Radio extends BasicButton { @@ -18,23 +19,25 @@ export class Radio extends BasicButton { width: 16, height: 16, iconWidth: 16, - iconHeight: 16 - } + iconHeight: 16, + }; render() { const { iconWidth, iconHeight } = this.options; return { - type: "bi.center_adapt", - items: [{ - type: "bi.layout", - cls: "radio-content", - ref: (_ref) => { - this.radio = _ref; - }, - width: iconWidth, - height: iconHeight, - }], + type: CenterAdaptLayout.xtype, + items: [ + { + type: Layout.xtype, + cls: "radio-content", + ref: _ref => { + this.radio = _ref; + }, + width: iconWidth, + height: iconHeight, + } + ], }; } diff --git a/src/base/single/instruction/instruction.js b/src/base/single/instruction/instruction.js index eb0d8dacd..bf57c435b 100644 --- a/src/base/single/instruction/instruction.js +++ b/src/base/single/instruction/instruction.js @@ -1,4 +1,5 @@ -import { shortcut, Widget, extend } from "../../../core"; +import { Label } from "../label"; +import { shortcut, Widget, extend } from "@/core"; @shortcut() export class Instruction extends Widget { @@ -6,13 +7,14 @@ export class Instruction extends Widget { _defaultConfig() { const conf = super._defaultConfig(...arguments); + return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-instruction", + baseCls: `${conf.baseCls || ""} bi-instruction`, height: 20, level: "error", textAlign: "left", whiteSpace: "nowrap", - hgap: 5 + hgap: 5, }); } @@ -20,11 +22,11 @@ export class Instruction extends Widget { const { level, textAlign, whiteSpace, height, hgap, rgap, lgap, vgap, text, keyword, value, py } = this.options; return { - type: "bi.label", - ref: (_ref) => { + type: Label.xtype, + ref: _ref => { this.text = _ref; }, - cls: "instruction-" + level, + cls: `instruction-${level}`, textAlign, whiteSpace, textHeight: height, @@ -36,7 +38,7 @@ export class Instruction extends Widget { text, keyword, value, - py + py, }; } diff --git a/src/base/single/label/abstract.label.js b/src/base/single/label/abstract.label.js index 28332de3e..a57bdb94c 100644 --- a/src/base/single/label/abstract.label.js +++ b/src/base/single/label/abstract.label.js @@ -1,11 +1,12 @@ +import { Text } from "../1.text"; +import { CenterAdaptLayout, isNumber, createWidget, extend } from "@/core"; +import { Single } from "../0.single"; + /** * Created by dailer on 2019/6/19. */ -import { isNumber, createWidget, extend } from "../../../core"; -import { Single } from "../0.single"; export class AbstractLabel extends Single { - _defaultConfig(props) { const conf = super._defaultConfig(...arguments); @@ -30,7 +31,7 @@ export class AbstractLabel extends Single { const { textAlign, whiteSpace, textHeight, text, value, py, keyword, highLight, handler } = this.options; return { - type: "bi.text", + type: Text.xtype, textAlign, whiteSpace, lineHeight: textHeight, @@ -59,9 +60,10 @@ export class AbstractLabel extends Single { if (isNumber(width) && width > 0) { if (isNumber(textWidth) && textWidth > 0) { json.maxWidth = textWidth; - if (isNumber(height) && height > 0) { // 1.1 + if (isNumber(height) && height > 0) { + // 1.1 createWidget({ - type: "bi.center_adapt", + type: CenterAdaptLayout.xtype, height, columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 scrollable: whiteSpace === "normal", @@ -75,8 +77,9 @@ export class AbstractLabel extends Single { return; } - createWidget({ // 1.2 - type: "bi.center_adapt", + createWidget({ + // 1.2 + type: CenterAdaptLayout.xtype, columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 scrollable: whiteSpace === "normal", element: this, @@ -89,7 +92,8 @@ export class AbstractLabel extends Single { return; } - if (whiteSpace === "normal") { // 1.3 + if (whiteSpace === "normal") { + // 1.3 extend(json, { hgap, vgap, @@ -100,7 +104,7 @@ export class AbstractLabel extends Single { }); this.text = createWidget(json); createWidget({ - type: "bi.center_adapt", + type: CenterAdaptLayout.xtype, columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 scrollable: whiteSpace === "normal", element: this, @@ -109,25 +113,29 @@ export class AbstractLabel extends Single { return; } - if (isNumber(height) && height > 0) { // 1.4 + if (isNumber(height) && height > 0) { + // 1.4 this.element.css({ "line-height": BI.pixFormat(height), }); json.textAlign = textAlign; delete json.maxWidth; - this.text = createWidget(extend(json, { - element: this, - hgap, - vgap, - lgap, - rgap, - tgap, - bgap, - })); + this.text = createWidget( + extend(json, { + element: this, + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, + }) + ); return; } - extend(json, { // 1.5 + extend(json, { + // 1.5 hgap, vgap, lgap, @@ -138,7 +146,7 @@ export class AbstractLabel extends Single { }); this.text = createWidget(json); createWidget({ - type: "bi.center_adapt", + type: CenterAdaptLayout.xtype, columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 scrollable: whiteSpace === "normal", element: this, @@ -147,10 +155,11 @@ export class AbstractLabel extends Single { return; } - if (isNumber(textWidth) && textWidth > 0) { // 1.6 + if (isNumber(textWidth) && textWidth > 0) { + // 1.6 json.maxWidth = textWidth; createWidget({ - type: "bi.center_adapt", + type: CenterAdaptLayout.xtype, columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 scrollable: whiteSpace === "normal", element: this, @@ -163,7 +172,8 @@ export class AbstractLabel extends Single { return; } - if (whiteSpace === "normal") { // 1.7 + if (whiteSpace === "normal") { + // 1.7 extend(json, { hgap, vgap, @@ -174,7 +184,7 @@ export class AbstractLabel extends Single { }); this.text = createWidget(json); createWidget({ - type: "bi.center_adapt", + type: CenterAdaptLayout.xtype, columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 scrollable: true, element: this, @@ -183,34 +193,39 @@ export class AbstractLabel extends Single { return; } - if (isNumber(height) && height > 0) { // 1.8 + if (isNumber(height) && height > 0) { + // 1.8 this.element.css({ "line-height": BI.pixFormat(height), }); json.textAlign = textAlign; delete json.maxWidth; - this.text = createWidget(extend(json, { - element: this, + this.text = createWidget( + extend(json, { + element: this, + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, + }) + ); + + return; + } + this.text = createWidget( + extend(json, { hgap, vgap, lgap, rgap, tgap, bgap, - })); - - return; - } - this.text = createWidget(extend(json, { - hgap, - vgap, - lgap, - rgap, - tgap, - bgap, - })); + }) + ); createWidget({ - type: "bi.center_adapt", + type: CenterAdaptLayout.xtype, columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 element: this, items: [this.text], @@ -224,7 +239,8 @@ export class AbstractLabel extends Single { if (isNumber(width) && width > 0) { if (isNumber(textWidth) && textWidth > 0) { json.maxWidth = textWidth; - if (isNumber(height) && height > 0) { // 2.1 + if (isNumber(height) && height > 0) { + // 2.1 createWidget({ type: adaptLayout, horizontalAlign: textAlign, @@ -241,7 +257,8 @@ export class AbstractLabel extends Single { return; } - createWidget({ // 2.2 + createWidget({ + // 2.2 type: adaptLayout, horizontalAlign: textAlign, columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 @@ -262,27 +279,31 @@ export class AbstractLabel extends Single { return; } - if (isNumber(height) && height > 0) { // 2.3 + if (isNumber(height) && height > 0) { + // 2.3 if (whiteSpace !== "normal") { this.element.css({ - "line-height": BI.pixFormat(height - (vgap * 2)), + "line-height": BI.pixFormat(height - vgap * 2), }); } delete json.maxWidth; - this.text = createWidget(extend(json, { - element: this, - hgap, - vgap, - lgap, - rgap, - tgap, - bgap, - })); + this.text = createWidget( + extend(json, { + element: this, + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, + }) + ); return; } json.maxWidth = width - 2 * hgap - lgap - rgap; - createWidget({ // 2.4 + createWidget({ + // 2.4 type: adaptLayout, horizontalAlign: textAlign, columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 @@ -294,16 +315,19 @@ export class AbstractLabel extends Single { tgap, bgap, element: this, - items: [{ - el: (this.text = createWidget(json)), - }], + items: [ + { + el: (this.text = createWidget(json)), + } + ], }); return; } if (isNumber(textWidth) && textWidth > 0) { json.maxWidth = textWidth; - createWidget({ // 2.5 + createWidget({ + // 2.5 type: adaptLayout, horizontalAlign: textAlign, columnSize: ["auto"], // important! 让文字在flex布局下shrink为1 @@ -327,30 +351,35 @@ export class AbstractLabel extends Single { if (isNumber(height) && height > 0) { if (whiteSpace !== "normal") { this.element.css({ - "line-height": BI.pixFormat(height - (vgap * 2)), + "line-height": BI.pixFormat(height - vgap * 2), }); } delete json.maxWidth; - this.text = createWidget(extend(json, { // 2.6 - element: this, + this.text = createWidget( + extend(json, { + // 2.6 + element: this, + hgap, + vgap, + lgap, + rgap, + tgap, + bgap, + }) + ); + + return; + } + this.text = createWidget( + extend(json, { hgap, vgap, lgap, rgap, tgap, bgap, - })); - - return; - } - this.text = createWidget(extend(json, { - hgap, - vgap, - lgap, - rgap, - tgap, - bgap, - })); + }) + ); createWidget({ type: adaptLayout, horizontalAlign: textAlign, diff --git a/src/base/single/label/html.label.js b/src/base/single/label/html.label.js index d4a0af70b..9b643c3aa 100644 --- a/src/base/single/label/html.label.js +++ b/src/base/single/label/html.label.js @@ -1,8 +1,10 @@ +import { Html } from "../html/html"; +import { AbstractLabel } from "./abstract.label"; +import { shortcut } from "@/core"; + /** * Created by GUY on 2015/6/26. */ -import { shortcut } from "../../../core"; -import { AbstractLabel } from "./abstract.label"; @shortcut() export class HtmlLabel extends AbstractLabel { @@ -10,13 +12,13 @@ export class HtmlLabel extends AbstractLabel { props = { baseCls: "bi-html-label", - } + }; _createJson() { const { textAlign, whiteSpace, textHeight, text, value, handler } = this.options; return { - type: "bi.html", + type: Html.xtype, textAlign, whiteSpace, lineHeight: textHeight, diff --git a/src/base/single/label/icon.label.js b/src/base/single/label/icon.label.js index 0f4c1b432..8808ad848 100644 --- a/src/base/single/label/icon.label.js +++ b/src/base/single/label/icon.label.js @@ -1,10 +1,12 @@ +import { Icon } from "../icon/icon"; +import { DefaultLayout, CenterAdaptLayout, shortcut, createWidget, isNumber, isNull } from "@/core"; +import { Single } from "../0.single"; + /** * @class BI.IconLabel * @extends BI.Single * 图标标签 */ -import { shortcut, createWidget, isNumber, isNull } from "../../../core"; -import { Single } from "../0.single"; @shortcut() export class IconLabel extends Single { @@ -21,7 +23,7 @@ export class IconLabel extends Single { iconWidth: null, iconHeight: null, lineHeight: null, - } + }; render() { const { iconWidth, iconHeight, height, lineHeight, hgap, vgap, lgap, rgap, tgap, bgap } = this.options; @@ -29,14 +31,14 @@ export class IconLabel extends Single { textAlign: "center", }); this.icon = createWidget({ - type: "bi.icon", + type: Icon.xtype, width: iconWidth, height: iconHeight, }); if (isNumber(height) && height > 0 && isNull(iconWidth) && isNull(iconHeight)) { this.element.css("lineHeight", BI.pixFormat(lineHeight || height)); createWidget({ - type: "bi.default", + type: DefaultLayout.xtype, element: this, hgap, vgap, @@ -50,7 +52,7 @@ export class IconLabel extends Single { this.element.css("lineHeight", "1"); createWidget({ element: this, - type: "bi.center_adapt", + type: CenterAdaptLayout.xtype, hgap, vgap, lgap, diff --git a/src/base/single/label/index.js b/src/base/single/label/index.js index ae3d091db..3a80cb8db 100644 --- a/src/base/single/label/index.js +++ b/src/base/single/label/index.js @@ -1,4 +1,4 @@ -export { AbstractLabel } from "./abstract.label"; -export { HtmlLabel } from "./html.label"; -export { IconLabel } from "./icon.label"; -export { Label } from "./label"; \ No newline at end of file +export { AbstractLabel } from "./abstract.label"; +export { HtmlLabel } from "./html.label"; +export { IconLabel } from "./icon.label"; +export { Label } from "./label"; diff --git a/src/base/single/label/label.js b/src/base/single/label/label.js index e745c9965..c5a7e9774 100644 --- a/src/base/single/label/label.js +++ b/src/base/single/label/label.js @@ -1,8 +1,9 @@ +import { AbstractLabel } from "./abstract.label"; +import { shortcut, isFunction, isNotNull } from "@/core"; + /** * Created by GUY on 2015/6/26. */ -import { shortcut, isFunction, isNotNull } from "../../../core"; -import { AbstractLabel } from "./abstract.label"; @shortcut() export class Label extends AbstractLabel { @@ -12,7 +13,7 @@ export class Label extends AbstractLabel { baseCls: "bi-label", py: "", keyword: "", - } + }; getTitle() { const title = this.options.title; diff --git a/src/base/single/link/link.js b/src/base/single/link/link.js index 89fa1a57f..fd21f1901 100644 --- a/src/base/single/link/link.js +++ b/src/base/single/link/link.js @@ -1,10 +1,12 @@ +import { A } from "../a/a"; +import { Label } from "../label/label"; +import { shortcut, extend } from "@/core"; + /** * guy a元素 * @class BI.Link * @extends BI.Text */ -import { shortcut, extend } from "../../../core"; -import { Label } from "../label/label"; @shortcut() export class Link extends Label { @@ -14,7 +16,7 @@ export class Link extends Label { const conf = super._defaultConfig(...arguments); return extend(conf, { - baseCls: (conf.baseCls || "") + " bi-link display-block", + baseCls: `${conf.baseCls || ""} bi-link display-block`, tagName: "a", href: "", target: "_blank", @@ -25,7 +27,7 @@ export class Link extends Label { const { textAlign, whiteSpace, textHeight, text, keyword, value, py, href, target } = this.options; return { - type: "bi.a", + type: A.xtype, textAlign, whiteSpace, lineHeight: textHeight, diff --git a/src/base/single/text.pure.js b/src/base/single/text.pure.js index 1de22cca9..38d7935c5 100644 --- a/src/base/single/text.pure.js +++ b/src/base/single/text.pure.js @@ -1,22 +1,25 @@ +import { Text } from "./1.text"; +import { Widget, shortcut, isFunction, isKey, isNotNull } from "@/core"; + /** * 没有html标签的纯文本 */ -import { Widget, shortcut, isFunction, isKey, isNotNull } from "../../core"; -import { Text } from "./1.text"; @shortcut() export class PureText extends Widget { static xtype = "bi.pure_text"; - + props = { tagName: null, - } + }; render() { const { text: optionsText, value } = this.options; - const text = isFunction(optionsText) ? this.__watch(optionsText, (context, newValue) => { - this.setText(newValue); - }) : optionsText; + const text = isFunction(optionsText) + ? this.__watch(optionsText, (context, newValue) => { + this.setText(newValue); + }) + : optionsText; if (isKey(text)) { this.setText(text); } else if (isKey(value)) { @@ -32,7 +35,7 @@ export class PureText extends Widget { return ""; } - return Text.formatText(text + ""); + return Text.formatText(`${text}`); } setValue(value) { diff --git a/src/base/single/tip/0.tip.js b/src/base/single/tip/0.tip.js index 22f5e46da..b5c222e43 100644 --- a/src/base/single/tip/0.tip.js +++ b/src/base/single/tip/0.tip.js @@ -1,3 +1,6 @@ +import { Single } from "../0.single"; +import { extend } from "@/core"; + /** * guy * tip提示 @@ -7,12 +10,10 @@ * @abstract */ -import { Single } from "../0.single"; -import { extend } from "../../../core"; export class Tip extends Single { _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { _baseCls: `${conf._baseCls || ""} bi-tip`, zIndex: BI.zIndex_tip, @@ -24,4 +25,3 @@ export class Tip extends Single { this.element.css({ zIndex: this.options.zIndex }); } } - diff --git a/src/base/single/tip/tip.toast.js b/src/base/single/tip/tip.toast.js index e9467e34a..785abb0db 100644 --- a/src/base/single/tip/tip.toast.js +++ b/src/base/single/tip/tip.toast.js @@ -1,3 +1,8 @@ +import { IconLabel, Label } from "../label"; +import { IconButton } from "../button"; +import { HorizontalLayout, shortcut, extend, isPlainObject } from "@/core"; +import { Tip } from "./0.tip"; + /** * toast提示 * @@ -6,121 +11,123 @@ * @extends BI.Tip */ -import { shortcut, extend, isPlainObject } from "../../../core"; -import { Tip } from "./0.tip"; @shortcut() export class Toast extends Tip { - _const= { - closableMinWidth: 146, - minWidth: 100, - closableMaxWidth: 410, - maxWidth: 400, - } + _const = { + closableMinWidth: 146, + minWidth: 100, + closableMaxWidth: 410, + maxWidth: 400, + }; - static EVENT_DESTORY = "EVENT_DESTORY"; - static xtype = "bi.toast"; + static EVENT_DESTORY = "EVENT_DESTORY"; + static xtype = "bi.toast"; - _defaultConfig() { - return extend(super._defaultConfig(...arguments), { - extraCls: "bi-toast", - text: "", - level: "success", // success或warning - autoClose: true, - closable: null, - textHeight: 20, - vgap: 10, - innerHgap: 4, - hgap: 8, - }); - } + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { + extraCls: "bi-toast", + text: "", + level: "success", // success或warning + autoClose: true, + closable: null, + textHeight: 20, + vgap: 10, + innerHgap: 4, + hgap: 8, + }); + } - render() { - const { closable, level, autoClose, textHeight, text, hgap, vgap, innerHgap } = this.options; - const { closableMinWidth, minWidth, maxWidth, closableMaxWidth } = this._const; - this.element.css({ - minWidth: BI.pixFormat(closable ? closableMinWidth : minWidth), - maxWidth: BI.pixFormat(closable ? closableMaxWidth : maxWidth), - }); - this.element.addClass(`toast-${level}`); - function fn(e) { - e.stopPropagation(); - e.stopEvent(); - - return false; - } - this.element.bind({ - click: fn, - mousedown: fn, - mouseup: fn, - mouseover: fn, - mouseenter: fn, - mouseleave: fn, - mousemove: fn, - }); - let cls; - switch (level) { - case "success": - cls = "toast-success-font"; - break; - case "error": - cls = "toast-error-font"; - break; - case "warning": - cls = "toast-warning-font"; - break; - case "loading": - cls = "toast-loading-font anim-rotate"; - break; - case "normal": - default: - cls = "toast-message-font"; - break; - } + render() { + const { closable, level, autoClose, textHeight, text, hgap, vgap, innerHgap } = this.options; + const { closableMinWidth, minWidth, maxWidth, closableMaxWidth } = this._const; + this.element.css({ + minWidth: BI.pixFormat(closable ? closableMinWidth : minWidth), + maxWidth: BI.pixFormat(closable ? closableMaxWidth : maxWidth), + }); + this.element.addClass(`toast-${level}`); + function fn(e) { + e.stopPropagation(); + e.stopEvent(); - function hasCloseIcon() { - return closable === true || (closable === null && autoClose === false); - } - const items = [{ - type: "bi.icon_label", - cls: `${cls} toast-icon`, - height: textHeight, - }, { - el: isPlainObject(text) ? text : { - type: "bi.label", - whiteSpace: "normal", - text, - textHeight, - textAlign: "left", - }, - }]; + return false; + } + this.element.bind({ + click: fn, + mousedown: fn, + mouseup: fn, + mouseover: fn, + mouseenter: fn, + mouseleave: fn, + mousemove: fn, + }); + let cls; + switch (level) { + case "success": + cls = "toast-success-font"; + break; + case "error": + cls = "toast-error-font"; + break; + case "warning": + cls = "toast-warning-font"; + break; + case "loading": + cls = "toast-loading-font anim-rotate"; + break; + case "normal": + default: + cls = "toast-message-font"; + break; + } - const columnSize = ["", "fill"]; + function hasCloseIcon() { + return closable === true || (closable === null && autoClose === false); + } + const items = [ + { + type: IconLabel.xtype, + cls: `${cls} toast-icon`, + height: textHeight, + }, + { + el: isPlainObject(text) + ? text + : { + type: Label.xtype, + whiteSpace: "normal", + text, + textHeight, + textAlign: "left", + }, + } + ]; - if (hasCloseIcon()) { - items.push({ - type: "bi.icon_button", - cls: "close-font toast-icon", - handler: () => { - this.destroy(); - }, - height: textHeight, - }); - columnSize.push(""); - } + const columnSize = ["", "fill"]; - return { - type: "bi.horizontal", - horizontalAlign: BI.HorizontalAlign.Stretch, - items, - hgap, - vgap, - innerHgap, - columnSize, - }; - } + if (hasCloseIcon()) { + items.push({ + type: IconButton.xtype, + cls: "close-font toast-icon", + handler: () => { + this.destroy(); + }, + height: textHeight, + }); + columnSize.push(""); + } - beforeDestroy() { - this.fireEvent(Toast.EVENT_DESTORY); - } -} + return { + type: HorizontalLayout.xtype, + horizontalAlign: BI.HorizontalAlign.Stretch, + items, + hgap, + vgap, + innerHgap, + columnSize, + }; + } + beforeDestroy() { + this.fireEvent(Toast.EVENT_DESTORY); + } +} diff --git a/src/base/single/tip/tip.tooltip.js b/src/base/single/tip/tip.tooltip.js index 46926195e..5965e31aa 100644 --- a/src/base/single/tip/tip.tooltip.js +++ b/src/base/single/tip/tip.tooltip.js @@ -1,3 +1,7 @@ +import { VerticalLayout, shortcut, extend, createWidget, map } from "@/core"; +import { Label } from "../label"; +import { Tip } from "./0.tip"; + /** * title提示 * @@ -6,87 +10,85 @@ * @extends BI.Tip */ -import { shortcut, extend, createWidget, map } from "../../../core"; -import { Tip } from "./0.tip"; @shortcut() export class Tooltip extends Tip { _const = { hgap: 8, vgap: 4, + }; + static xtype = "bi.tooltip"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { + extraCls: "bi-tooltip", + text: "", + level: "success", // success或warning + stopEvent: false, + stopPropagation: false, + textAlign: "left", + }); } - static xtype = "bi.tooltip"; - - _defaultConfig() { - return extend(super._defaultConfig(...arguments), { - extraCls: "bi-tooltip", - text: "", - level: "success", // success或warning - stopEvent: false, - stopPropagation: false, - textAlign: "left", - }); - } - render () { - const { level, stopPropagation, stopEvent, text, textAlign } = this.options; - this.element.addClass(`tooltip-${level}`); - function fn(e) { - stopPropagation && e.stopPropagation(); - stopEvent && e.stopEvent(); - } - this.element.bind({ - click: fn, - mousedown: fn, - mouseup: fn, - mouseover: fn, - mouseenter: fn, - mouseleave: fn, - mousemove: fn, - }); + render() { + const { level, stopPropagation, stopEvent, text, textAlign } = this.options; + this.element.addClass(`tooltip-${level}`); + function fn(e) { + stopPropagation && e.stopPropagation(); + stopEvent && e.stopEvent(); + } + this.element.bind({ + click: fn, + mousedown: fn, + mouseup: fn, + mouseover: fn, + mouseenter: fn, + mouseleave: fn, + mousemove: fn, + }); - const texts = (`${text}`).split("\n"); - if (texts.length > 1) { - createWidget({ - type: "bi.vertical", - element: this, - hgap: this._const.hgap, - innerVgap: this._const.vgap, - items: map(texts, (i, text) => { - return { - type: "bi.label", - textAlign, - whiteSpace: "normal", - text, - textHeight: 18, - title: null, - }; - }), - }); - } else { - this.text = createWidget({ - type: "bi.label", - element: this, - textAlign, - whiteSpace: "normal", - text, - title: null, - textHeight: 18, - hgap: this._const.hgap, - vgap: this._const.vgap, - }); - } - } + const texts = `${text}`.split("\n"); + if (texts.length > 1) { + createWidget({ + type: VerticalLayout.xtype, + element: this, + hgap: this._const.hgap, + innerVgap: this._const.vgap, + items: map(texts, (i, text) => { + return { + type: Label.xtype, + textAlign, + whiteSpace: "normal", + text, + textHeight: 18, + title: null, + }; + }), + }); + } else { + this.text = createWidget({ + type: Label.xtype, + element: this, + textAlign, + whiteSpace: "normal", + text, + title: null, + textHeight: 18, + hgap: this._const.hgap, + vgap: this._const.vgap, + }); + } + } - setWidth(width) { - this.element.width(BI.pixFormat(width - 2 * this._const.hgap)); - } + setWidth(width) { + this.element.width(BI.pixFormat(width - 2 * this._const.hgap)); + } - setText(text) { - this.text && this.text.setText(text); - } + setText(text) { + this.text && this.text.setText(text); + } - setLevel(level) { - this.element.removeClass("tooltip-success").removeClass("tooltip-warning"); - this.element.addClass(`tooltip-${level}`); - } + setLevel(level) { + this.element.removeClass("tooltip-success").removeClass("tooltip-warning"); + this.element.addClass(`tooltip-${level}`); + } } diff --git a/src/base/single/trigger/trigger.js b/src/base/single/trigger/trigger.js index af9db4078..edbb788b6 100644 --- a/src/base/single/trigger/trigger.js +++ b/src/base/single/trigger/trigger.js @@ -1,11 +1,12 @@ +import { Single } from "../0.single"; +import { extend } from "@/core"; + /** * 下拉 * @class BI.Trigger * @extends BI.Single * @abstract */ -import { extend } from "../../../core"; -import { Single } from "../0.single"; export class Trigger extends Single { _defaultConfig() { @@ -17,11 +18,7 @@ export class Trigger extends Single { }); } - setKey() { + setKey() {} - } - - getKey() { - - } + getKey() {} } diff --git a/src/base/tree/customtree.js b/src/base/tree/customtree.js index 2e231cd4a..fd4077a84 100644 --- a/src/base/tree/customtree.js +++ b/src/base/tree/customtree.js @@ -1,3 +1,23 @@ +import { ButtonTree, Expander } from "../combination"; +import { + VerticalLayout, + Widget, + shortcut, + extend, + emptyFn, + Tree, + each, + isNotEmptyArray, + deepClone, + stripEL, + isWidget, + clone, + isNotNull, + isNull, + createWidget, + Controller +} from "@/core"; + /** * * 自定义树 @@ -6,7 +26,7 @@ * @class BI.CustomTree * @extends BI.Single */ -import { Widget, shortcut, extend, emptyFn, Tree, each, isNotEmptyArray, deepClone, stripEL, isWidget, clone, isNotNull, isNull, createWidget, Controller } from "../../core"; + @shortcut() export class CustomTree extends Widget { static xtype = "bi.custom_tree"; @@ -18,7 +38,7 @@ export class CustomTree extends Widget { expander: { el: {}, popup: { - type: "bi.custom_tree", + type: CustomTree.xtype, }, }, @@ -26,11 +46,13 @@ export class CustomTree extends Widget { itemsCreator: emptyFn, el: { - type: "bi.button_tree", + type: ButtonTree.xtype, chooseType: 0, - layouts: [{ - type: "bi.vertical", - }], + layouts: [ + { + type: VerticalLayout.xtype, + } + ], }, }); } @@ -46,16 +68,20 @@ export class CustomTree extends Widget { const items = []; each(nodes, (i, node) => { if (isNotEmptyArray(node.children) || node.isParent === true) { - const item = extend({ - type: "bi.expander", - el: { - value: node.value, + const item = extend( + { + type: Expander.xtype, + el: { + value: node.value, + }, + popup: { type: CustomTree.xtype }, }, - popup: { type: "bi.custom_tree" }, - }, deepClone(expander), { - id: node.id, - pId: node.pId, - }); + deepClone(expander), + { + id: node.id, + pId: node.pId, + } + ); let el = stripEL(node); if (!isWidget(el)) { el = clone(el); @@ -67,7 +93,8 @@ export class CustomTree extends Widget { item.popup.expander = deepClone(expander); item.items = item.popup.items = node.children; item.itemsCreator = item.popup.itemsCreator = (op, ...arg) => { - if (isNotNull(op.node)) {// 从子节点传过来的itemsCreator直接向上传递 + if (isNotNull(op.node)) { + // 从子节点传过来的itemsCreator直接向上传递 return itemsCreator(op, ...arg); } const args = Array.prototype.slice.call([op, ...arg], 0); @@ -91,11 +118,14 @@ export class CustomTree extends Widget { element: this, items: this._formatItems(nodes), itemsCreator: (op, callback) => { - itemsCreator.apply(this, [op, items => { - const args = Array.prototype.slice.call(arguments, 0); - args[0] = this._formatItems(items); - callback(...args); - }]); + itemsCreator.apply(this, [ + op, + items => { + const args = Array.prototype.slice.call(arguments, 0); + args[0] = this._formatItems(items); + callback(...args); + } + ]); }, value, }); diff --git a/src/case/combo/bubblecombo/popup.bubble.js b/src/case/combo/bubblecombo/popup.bubble.js index ef62146c7..2a6050af0 100644 --- a/src/case/combo/bubblecombo/popup.bubble.js +++ b/src/case/combo/bubblecombo/popup.bubble.js @@ -1,5 +1,6 @@ import { shortcut, extend } from "@/core"; -import { PopupView, Label } from "@/base"; +import { PopupView } from "@/base/layer/layer.popup"; +import { Label } from "@/base/single/label/label"; @shortcut() export class BubblePopupView extends PopupView { From 19ed4a665f8500c42633eb141e9e5d5edf712f59 Mon Sep 17 00:00:00 2001 From: zsmj Date: Fri, 13 Jan 2023 15:03:22 +0800 Subject: [PATCH 111/300] update --- src/case/button/index.js | 5 +- src/case/button/node/node.first.plus.js | 92 ---- src/case/button/node/node.last.plus.js | 89 ---- src/case/button/node/node.mid.plus.js | 91 ---- src/case/button/node/treenode.js | 142 ++++-- src/case/button/treeitem/treeitem.js | 28 +- src/widget/index.js | 7 + .../multilayerselecttree.combo.test.js | 83 ++-- src/widget/multilayerselecttree/index.js | 2 + .../multilayerselecttree.combo.js | 420 +++++++++++------- ...multilayerselecttree.insert.search.pane.js | 151 ++++--- .../multilayerselecttree.leveltree.js | 234 ++++++---- .../multilayerselecttree.popup.js | 86 ++-- .../multilayerselecttree.trigger.js | 334 ++++++++------ .../node/node.first.plus.js | 99 ----- .../node/node.last.plus.js | 88 ---- .../node/node.mid.plus.js | 88 ---- .../multilayerselecttree/node/node.plus.js | 92 ---- src/widget/multilayersingletree/index.js | 2 + .../multilayersingletree.combo.js | 402 ++++++++++------- ...multilayersingletree.insert.search.pane.js | 151 ++++--- .../multilayersingletree.leveltree.js | 232 ++++++---- .../multilayersingletree.popup.js | 86 ++-- .../multilayersingletree.trigger.js | 329 ++++++++------ .../node/node.first.plus.js | 91 ---- .../node/node.last.plus.js | 90 ---- .../node/node.mid.plus.js | 90 ---- .../multilayersingletree/node/node.plus.js | 102 ----- .../treeitem/item.first.treeleaf.js | 86 ---- .../treeitem/item.last.treeleaf.js | 86 ---- .../treeitem/item.mid.treeleaf.js | 86 ---- 31 files changed, 1623 insertions(+), 2341 deletions(-) delete mode 100644 src/case/button/node/node.first.plus.js delete mode 100644 src/case/button/node/node.last.plus.js delete mode 100644 src/case/button/node/node.mid.plus.js create mode 100644 src/widget/multilayerselecttree/index.js delete mode 100644 src/widget/multilayerselecttree/node/node.first.plus.js delete mode 100644 src/widget/multilayerselecttree/node/node.last.plus.js delete mode 100644 src/widget/multilayerselecttree/node/node.mid.plus.js delete mode 100644 src/widget/multilayerselecttree/node/node.plus.js create mode 100644 src/widget/multilayersingletree/index.js delete mode 100644 src/widget/multilayersingletree/node/node.first.plus.js delete mode 100644 src/widget/multilayersingletree/node/node.last.plus.js delete mode 100644 src/widget/multilayersingletree/node/node.mid.plus.js delete mode 100644 src/widget/multilayersingletree/node/node.plus.js delete mode 100644 src/widget/multilayersingletree/treeitem/item.first.treeleaf.js delete mode 100644 src/widget/multilayersingletree/treeitem/item.last.treeleaf.js delete mode 100644 src/widget/multilayersingletree/treeitem/item.mid.treeleaf.js diff --git a/src/case/button/index.js b/src/case/button/index.js index 8f366680c..0f144f94e 100644 --- a/src/case/button/index.js +++ b/src/case/button/index.js @@ -10,10 +10,7 @@ export { HalfIconButton } from "./icon/iconhalf/icon.half.image"; export { HalfButton } from "./icon/iconhalf/icon.half"; export { ArrowNode } from "./node/node.arrow"; -export { FirstPlusGroupNode } from "./node/node.first.plus"; export { IconArrowNode } from "./node/node.icon.arrow"; -export { LastPlusGroupNode } from "./node/node.last.plus"; -export { MidPlusGroupNode } from "./node/node.mid.plus"; export { MultiLayerIconArrowNode } from "./node/node.multilayer.icon.arrow"; export { PlusGroupNode } from "./node/node.plus"; export { TreeNodeSwitcher } from "./node/siwtcher.tree.node"; @@ -26,3 +23,5 @@ export { MultiLayerIconTreeLeafItem } from "./treeitem/item.multilayer.icon.tree export { BasicTreeItem, FirstTreeLeafItem, MidTreeLeafItem, LastTreeLeafItem, RootTreeLeafItem } from "./treeitem/treeitem"; + +export * from "./node/treenode"; diff --git a/src/case/button/node/node.first.plus.js b/src/case/button/node/node.first.plus.js deleted file mode 100644 index 8e895f801..000000000 --- a/src/case/button/node/node.first.plus.js +++ /dev/null @@ -1,92 +0,0 @@ -import { NodeButton } from "../../../base/single/button/button.node"; -import { shortcut, extend, createWidget, Controller } from "../../../core"; - - -/** - * 加号表示的组节点 - * Created by GUY on 2015/9/6. - * @class FirstPlusGroupNode - * @extends NodeButton - */ -@shortcut() -export class FirstPlusGroupNode extends NodeButton { - static xtype = "bi.first_plus_group_node"; - - _defaultConfig() { - const conf = super._defaultConfig(...arguments); - - return extend(conf, { - baseCls: `${conf.baseCls || ""} bi-first-plus-group-node bi-list-item`, - logic: { - dynamic: false, - }, - id: "", - pId: "", - open: false, - height: 24, - }); - } - - _init() { - super._init.apply(this, arguments); - const o = this.options; - this.checkbox = createWidget({ - type: "bi.first_tree_node_checkbox", - stopPropagation: true, - iconHeight: o.height, - iconWidth: o.height, - }); - this.text = createWidget({ - type: "bi.label", - textAlign: "left", - whiteSpace: "nowrap", - textHeight: o.height, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - py: o.py, - keyword: o.keyword, - }); - this.checkbox.on(Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) { - if (this.isSelected()) { - self.triggerExpand(); - } else { - self.triggerCollapse(); - } - } - }); - const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: this.checkbox, - }, this.text); - BI.createWidget(BI.extend({ - element: this, - }, BI.LogicFactory.createLogic(type, BI.extend(o.logic, { - items, - })))); - } - - doRedMark() { - this.text.doRedMark(...arguments); - } - - unRedMark() { - this.text.unRedMark(...arguments); - } - - doClick() { - super.doClick(...arguments); - this.checkbox.setSelected(this.isSelected()); - } - - setOpened(v) { - super.setOpened(...arguments); - if (BI.isNotNull(this.checkbox)) { - this.checkbox.setSelected(v); - } - } -} - diff --git a/src/case/button/node/node.last.plus.js b/src/case/button/node/node.last.plus.js deleted file mode 100644 index 95e745f4e..000000000 --- a/src/case/button/node/node.last.plus.js +++ /dev/null @@ -1,89 +0,0 @@ -import { NodeButton } from "../../../base/single/button/button.node"; -import { shortcut, extend, createWidget, isNotNull, Controller } from "../../../core"; - -/** - * 加号表示的组节点 - * Created by GUY on 2015/9/6. - * @class LastPlusGroupNode - * @extends NodeButton - */ -@shortcut() -export class LastPlusGroupNode extends NodeButton { - static xtype = "bi.last_plus_group_node"; - - _defaultConfig() { - const conf = super._defaultConfig(...arguments); - - return extend(conf, { - baseCls: `${conf.baseCls || ""} bi-last-plus-group-node bi-list-item`, - logic: { - dynamic: false, - }, - id: "", - pId: "", - open: false, - height: 24, - }); - } - _init() { - BI.LastPlusGroupNode.superclass._init.apply(this, arguments); - const o = this.options; - this.checkbox = createWidget({ - type: "bi.last_tree_node_checkbox", - stopPropagation: true, - iconHeight: o.height, - iconWidth: o.height, - }); - this.text = createWidget({ - type: "bi.label", - textAlign: "left", - whiteSpace: "nowrap", - textHeight: o.height, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - py: o.py, - keyword: o.keyword, - }); - this.checkbox.on(Controller.EVENT_CHANGE, type => { - if (type === BI.Events.CLICK) { - if (this.checkbox.isSelected()) { - this.triggerExpand(); - } else { - this.triggerCollapse(); - } - } - }); - const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: this.checkbox, - }, this.text); - createWidget(extend({ - element: this, - }, BI.LogicFactory.createLogic(type, extend(o.logic, { - items, - })))); - } - - doRedMark() { - this.text.doRedMark(...arguments); - } - - unRedMark() { - this.text.unRedMark(...arguments); - } - - doClick() { - super.doClick(...arguments); - this.checkbox.setSelected(this.isSelected()); - } - - setOpened(v) { - super.setOpened(...arguments); - if (isNotNull(this.checkbox)) { - this.checkbox.setSelected(v); - } - } -} diff --git a/src/case/button/node/node.mid.plus.js b/src/case/button/node/node.mid.plus.js deleted file mode 100644 index e1276d6ab..000000000 --- a/src/case/button/node/node.mid.plus.js +++ /dev/null @@ -1,91 +0,0 @@ -import { NodeButton } from "../../../base/single/button/button.node"; -import { shortcut, extend, createWidget, Controller } from "../../../core"; - -/** - * 加号表示的组节点 - * Created by GUY on 2015/9/6. - * @class BI.MidPlusGroupNode - * @extends BI.NodeButton - */ -@shortcut -export class MidPlusGroupNode extends NodeButton { - static xtype = "bi.mid_plus_group_node"; - - _defaultConfig() { - const conf = super._defaultConfig(...arguments); - - return extend(conf, { - baseCls: `${conf.baseCls || ""} bi-mid-plus-group-node bi-list-item`, - logic: { - dynamic: false, - }, - id: "", - pId: "", - open: false, - height: 24, - }); - } - - _init() { - super._init(...arguments); - const o = this.options; - this.checkbox = createWidget({ - type: "bi.mid_tree_node_checkbox", - stopPropagation: true, - iconHeight: o.height, - iconWidth: o.height, - }); - this.text = createWidget({ - type: "bi.label", - textAlign: "left", - whiteSpace: "nowrap", - textHeight: o.height, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - py: o.py, - keyword: o.keyword, - }); - this.checkbox.on(Controller.EVENT_CHANGE, type => { - if (type === BI.Events.CLICK) { - if (this.checkbox.isSelected()) { - this.triggerExpand(); - } else { - this.triggerCollapse(); - } - } - }); - const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: this.checkbox, - }, this.text); - createWidget(extend({ - element: this, - }, BI.LogicFactory.createLogic(type, extend(o.logic, { - items, - })))); - } - - doRedMark() { - this.text.doRedMark(...arguments); - } - - unRedMark() { - this.text.unRedMark(...arguments); - } - - doClick() { - super.doClick(...arguments); - this.checkbox.setSelected(this.isSelected()); - } - - setOpened(v) { - super.setOpened(...arguments); - if (BI.isNotNull(this.checkbox)) { - this.checkbox.setSelected(v); - } - } -} - diff --git a/src/case/button/node/treenode.js b/src/case/button/node/treenode.js index f6ef4c5bc..b09cf5830 100644 --- a/src/case/button/node/treenode.js +++ b/src/case/button/node/treenode.js @@ -1,5 +1,5 @@ -import { Label, NodeButton } from "@/base"; -import { shortcut, extend, VerticalAdaptLayout } from "@/core"; +import { IconLabel, Label, NodeButton } from "@/base"; +import { shortcut, extend, VerticalAdaptLayout, Layout, isKey, compact } from "@/core"; import { TreeNodeSwitcher } from "@/case"; @shortcut() @@ -25,21 +25,41 @@ export class BasicTreeNode extends NodeButton { } render() { - const o = this.options; + const { + open, + layer, + height, + hgap, + textHgap, + textVgap, + textLgap, + textRgap, + text, + value, + isFirstNode, + isLastNode, + keyword, + iconWidth, + iconHeight, + iconWrapperWidth, + iconCls, + switcherIcon, + selectable, + } = this.options; const checkbox = { type: TreeNodeSwitcher.xtype, ref: _ref => { this.switcher = _ref; }, - iconHeight: o.height, - iconWidth: o.iconWrapperWidth || o.height, - open: o.open, - isFirstNode: o.isFirstNode, - isLastNode: o.isLastNode, - layer: o.layer, - ...o.switcherIcon, - stopPropagation: o.selectable, + iconHeight: height, + iconWidth: iconWrapperWidth || height, + open, + isFirstNode, + isLastNode, + layer, + ...switcherIcon, + stopPropagation: selectable, mounted() { this.setEnable(true); }, @@ -47,7 +67,7 @@ export class BasicTreeNode extends NodeButton { { eventName: "EVENT_CHANGE", action: () => { - if (!this.isEnabled() || o.selectable) { + if (!this.isEnabled() || selectable) { this.isOpened() ? this.triggerCollapse() : this.triggerExpand(); } }, @@ -55,14 +75,39 @@ export class BasicTreeNode extends NodeButton { ], }; + // const indent = { + // el: { + // type: Layout.xtype, + // height, + // width: height, + // cls: this.getLineCls(), + // }, + // lgap: layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, // 偏移公式为每一层的偏移量为节点高度的一半 + // width: "", + // }; + + + const icon = isKey(iconCls) ? { + el: { + type: IconLabel.xtype, + // iconWidth, + // iconHeight, + cls: iconCls, + }, + // width: 24, + } : null; + + return { type: VerticalAdaptLayout.xtype, - columnSize: [o.iconWrapperWidth || o.height, "fill"], - items: [ + items: compact([ { el: checkbox, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, // 偏移公式为每一层的偏移量为节点高度的一半 - }, { + lgap: layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, // 偏移公式为每一层的偏移量为节点高度的一半 + width: iconWrapperWidth || height, + }, + icon, + { el: { type: Label.xtype, ref: _ref => { @@ -70,19 +115,19 @@ export class BasicTreeNode extends NodeButton { }, textAlign: "left", whiteSpace: "nowrap", - textHeight: o.height, - height: o.height, - hgap: o.hgap || o.textHgap, - vgap: o.textVgap, - lgap: o.textLgap, - rgap: o.textRgap, - text: o.text, - value: o.value, - keyword: o.keyword, - py: o.py, + textHeight: height, + height, + hgap: hgap || textHgap, + vgap: textVgap, + lgap: textLgap, + rgap: textRgap, + text, + value, + keyword, }, + width: "fill", } - ], + ]), }; } @@ -111,4 +156,47 @@ export class BasicTreeNode extends NodeButton { } } +@shortcut() +export class FirstPlusGroupNode extends BasicTreeNode { + static xtype = "bi.first_plus_group_node"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-first-plus-group-node`, + isFirstNode: true, + isLastNode: false, + }); + } +} + +@shortcut +export class MidPlusGroupNode extends BasicTreeNode { + static xtype = "bi.mid_plus_group_node"; + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-mid-plus-group-node`, + isFirstNode: false, + isLastNode: false, + }); + } +} + +@shortcut() +export class LastPlusGroupNode extends BasicTreeNode { + static xtype = "bi.last_plus_group_node"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { + baseCls: `${conf.baseCls || ""} bi-last-plus-group-node`, + isFirstNode: false, + isLastNode: true, + }); + } +} diff --git a/src/case/button/treeitem/treeitem.js b/src/case/button/treeitem/treeitem.js index 8a9bcae3b..297cb15a8 100644 --- a/src/case/button/treeitem/treeitem.js +++ b/src/case/button/treeitem/treeitem.js @@ -17,8 +17,8 @@ export class BasicTreeItem extends NodeButton { isFirstNode: false, isLastNode: false, layer: 0, - iconWidth: 16, - iconHeight: 16, + iconWidth: null, + iconHeight: null, iconCls: "", }); } @@ -34,6 +34,8 @@ export class BasicTreeItem extends NodeButton { textRgap, text, value, + isFirstNode, + isLastNode, py, keyword, iconWidth, @@ -41,15 +43,6 @@ export class BasicTreeItem extends NodeButton { iconCls, } = this.options; - const icon = isKey(iconCls) ? { - el: { - type: IconLabel.xtype, - iconWidth, - iconHeight, - cls: iconCls, - }, - width: 24, - } : null; const indent = { el: { @@ -62,11 +55,22 @@ export class BasicTreeItem extends NodeButton { width: "", }; + + const icon = isKey(iconCls) ? { + el: { + type: IconLabel.xtype, + // iconWidth, + // iconHeight, + cls: iconCls, + }, + // width: 24, + } : null; + return { type: VerticalAdaptLayout.xtype, items: compact([ - icon, indent, + icon, { el: { type: Label.xtype, diff --git a/src/widget/index.js b/src/widget/index.js index e86e9e362..08d813cd1 100644 --- a/src/widget/index.js +++ b/src/widget/index.js @@ -19,8 +19,11 @@ import { NumberEditor } from "./numbereditor/number.editor"; import { NumberInterval } from "./numberinterval/numberinterval"; import * as multiselect from "./multiselect"; import * as multiselectlist from "./multiselectlist"; +import * as multilayerselectree from "./multilayerselecttree"; +import * as multilayersingletree from "./multilayersingletree"; import * as year from "./year"; import { YearInterval } from "./yearinterval/yearinterval"; + Object.assign(BI, { Collapse, ...calendar, @@ -45,6 +48,8 @@ Object.assign(BI, { YearInterval, ...multiselect, ...multiselectlist, + ...multilayerselectree, + ...multilayersingletree, }); export * from "./date/calendar"; @@ -61,6 +66,8 @@ export * from "./downlist"; export * from "./singleslider"; export * from "./intervalslider"; export * from "./year"; +export * from "./multilayersingletree"; +export * from "./multilayerselecttree"; export { Collapse, NumberEditor, diff --git a/src/widget/multilayerselecttree/__test__/multilayerselecttree.combo.test.js b/src/widget/multilayerselecttree/__test__/multilayerselecttree.combo.test.js index 8674a4f8b..70d1d00a9 100644 --- a/src/widget/multilayerselecttree/__test__/multilayerselecttree.combo.test.js +++ b/src/widget/multilayerselecttree/__test__/multilayerselecttree.combo.test.js @@ -4,39 +4,40 @@ * Created by windy on 2019/9/18 */ -describe("multilayer_select_tree", function () { - - var items = [{id: -1, pId: -2, value: "根目录", text: "根目录"}, - {id: 1, pId: -1, value: "第一级目录1", text: "第一级目录1"}, - {id: 11, pId: 1, value: "第二级文件1", text: "第二级文件1"}, - {id: 12, pId: 1, value: "第二级目录2", text: "第二级目录2"}, - {id: 121, pId: 12, value: "第三级目录1", text: "第三级目录1"}, - {id: 122, pId: 12, value: "第三级文件1", text: "第三级文件1"}, - {id: 1211, pId: 121, value: "第四级目录1", text: "第四级目录1"}, +describe("multilayer_select_tree", () => { + const items = [ + { id: -1, pId: -2, value: "根目录", text: "根目录" }, + { id: 1, pId: -1, value: "第一级目录1", text: "第一级目录1" }, + { id: 11, pId: 1, value: "第二级文件1", text: "第二级文件1" }, + { id: 12, pId: 1, value: "第二级目录2", text: "第二级目录2" }, + { id: 121, pId: 12, value: "第三级目录1", text: "第三级目录1" }, + { id: 122, pId: 12, value: "第三级文件1", text: "第三级文件1" }, + { id: 1211, pId: 121, value: "第四级目录1", text: "第四级目录1" }, { id: 12111, pId: 1211, value: "第五级文件1", - text: "第五级文件111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" + text: "第五级文件111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", }, - {id: 2, pId: -1, value: "第一级目录2", text: "第一级目录2"}, - {id: 21, pId: 2, value: "第二级目录3", text: "第二级目录3"}, - {id: 22, pId: 2, value: "第二级文件2", text: "第二级文件2"}, - {id: 211, pId: 21, value: "第三级目录2", text: "第三级目录2"}, - {id: 212, pId: 21, value: "第三级文件2", text: "第三级文件2"}, - {id: 2111, pId: 211, value: "第四级文件1", text: "第四级文件1"}]; + { id: 2, pId: -1, value: "第一级目录2", text: "第一级目录2" }, + { id: 21, pId: 2, value: "第二级目录3", text: "第二级目录3" }, + { id: 22, pId: 2, value: "第二级文件2", text: "第二级文件2" }, + { id: 211, pId: 21, value: "第三级目录2", text: "第三级目录2" }, + { id: 212, pId: 21, value: "第三级文件2", text: "第三级文件2" }, + { id: 2111, pId: 211, value: "第四级文件1", text: "第四级文件1" } + ]; /** * test_author_windy **/ - it("defaultValue_allowEdit", function () { - var tree = BI.Test.createWidget({ + it("defaultValue_allowEdit", () => { + const tree = BI.Test.createWidget({ type: "bi.multilayer_select_tree_combo", width: 300, height: 24, allowEdit: true, items: BI.deepClone(items), - value: "第一级目录2" + value: "第一级目录2", }); expect(tree.getValue()).to.equal("第一级目录2"); tree.destroy(); @@ -45,13 +46,13 @@ describe("multilayer_select_tree", function () { /** * test_author_windy **/ - it("defaultValue_not_allowEdit", function () { - var tree = BI.Test.createWidget({ + it("defaultValue_not_allowEdit", () => { + const tree = BI.Test.createWidget({ type: "bi.multilayer_select_tree_combo", width: 300, height: 24, items: BI.deepClone(items), - value: "第一级目录2" + value: "第一级目录2", }); expect(tree.getValue()).to.equal("第一级目录2"); tree.destroy(); @@ -60,17 +61,17 @@ describe("multilayer_select_tree", function () { /** * test_author_windy **/ - it("点选选值", function (done) { - var tree = BI.Test.createWidget({ + it("点选选值", done => { + const tree = BI.Test.createWidget({ type: "bi.multilayer_select_tree_combo", width: 300, height: 24, allowEdit: true, items: BI.deepClone(items), - value: "第一级目录2" + value: "第一级目录2", }); tree.element.find(".bi-multi-layer-select-tree-trigger").click(); - BI.nextTick(function () { + BI.nextTick(() => { tree.element.find(".bi-select-tree-plus-group-node").click(); expect(tree.getValue()[0]).to.equal("根目录"); tree.destroy(); @@ -81,20 +82,20 @@ describe("multilayer_select_tree", function () { /** * test_author_windy **/ - it("搜索选值", function (done) { - var tree = BI.Test.createWidget({ + it("搜索选值", done => { + const tree = BI.Test.createWidget({ type: "bi.multilayer_select_tree_combo", width: 300, height: 24, allowEdit: true, - items: BI.deepClone(items) + items: BI.deepClone(items), }); - BI.nextTick(function () { + BI.nextTick(() => { tree.element.find(".bi-multi-layer-select-tree-trigger .tip-text-style").click(); // 这边为啥要加呢,因为input的setValue中有nextTick - BI.nextTick(function () { - BI.Test.triggerKeyDown(tree.element.find(".bi-multi-layer-select-tree-trigger .bi-input"), "2", 50, function () { - BI.nextTick(function () { + BI.nextTick(() => { + BI.Test.triggerKeyDown(tree.element.find(".bi-multi-layer-select-tree-trigger .bi-input"), "2", 50, () => { + BI.nextTick(() => { tree.element.find(".bi-select-tree-mid-plus-group-node").click(); expect(tree.getValue()[0]).to.equal("第一级目录2"); tree.destroy(); @@ -108,21 +109,21 @@ describe("multilayer_select_tree", function () { /** * test_author_windy **/ - it("新增值", function (done) { - var tree = BI.Test.createWidget({ + it("新增值", done => { + const tree = BI.Test.createWidget({ type: "bi.multilayer_select_tree_combo", width: 300, height: 24, allowEdit: true, allowInsertValue: true, - items: BI.deepClone(items) + items: BI.deepClone(items), }); - BI.nextTick(function () { + BI.nextTick(() => { tree.element.find(".bi-multi-layer-select-tree-trigger .tip-text-style").click(); // 这边为啥要加呢,因为input的setValue中有nextTick - BI.nextTick(function () { - BI.Test.triggerKeyDown(tree.element.find(".bi-multi-layer-select-tree-trigger .bi-input"), "z", 50, function () { - BI.nextTick(function () { + BI.nextTick(() => { + BI.Test.triggerKeyDown(tree.element.find(".bi-multi-layer-select-tree-trigger .bi-input"), "z", 50, () => { + BI.nextTick(() => { tree.element.find(".bi-text-button:contains(+点击新增\"z\")").click(); expect(tree.getValue()[0]).to.equal("z"); tree.destroy(); @@ -132,4 +133,4 @@ describe("multilayer_select_tree", function () { }); }); }); -}); \ No newline at end of file +}); diff --git a/src/widget/multilayerselecttree/index.js b/src/widget/multilayerselecttree/index.js new file mode 100644 index 000000000..436fdef6c --- /dev/null +++ b/src/widget/multilayerselecttree/index.js @@ -0,0 +1,2 @@ +export { MultiLayerSelectTreeCombo } from "./multilayerselecttree.combo"; +export { MultiLayerSelectLevelTree } from "./multilayerselecttree.leveltree"; diff --git a/src/widget/multilayerselecttree/multilayerselecttree.combo.js b/src/widget/multilayerselecttree/multilayerselecttree.combo.js index ec2a9a393..834a4fb40 100644 --- a/src/widget/multilayerselecttree/multilayerselecttree.combo.js +++ b/src/widget/multilayerselecttree/multilayerselecttree.combo.js @@ -1,17 +1,40 @@ -/** - * @class BI.MultiLayerSelectTreeCombo - * @extends BI.Widget - */ -BI.MultiLayerSelectTreeCombo = BI.inherit(BI.Widget, { +import { + shortcut, + Widget, + extend, + emptyFn, + isKey, + toPix, + AbsoluteLayout, + nextTick, + isArray +} from "@/core"; +import { SingleTreeTrigger } from "../singletree/singletree.trigger"; +import { MultiLayerSelectTreePopup } from "./multilayerselecttree.popup"; +import { Combo } from "@/base"; +import { MultiLayerSelectTreeTrigger } from "./multilayerselecttree.trigger"; +import { TriggerIconButton } from "@/case"; - _defaultConfig: function () { - return BI.extend(BI.MultiLayerSelectTreeCombo.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class MultiLayerSelectTreeCombo extends Widget { + static xtype = "bi.multilayer_select_tree_combo"; + + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + static EVENT_CLICK_ITEM = "EVENT_CLICK_ITEM"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multilayer-select-tree-combo", isDefaultInit: false, height: 24, text: "", defaultText: "", - itemsCreator: BI.emptyFn, + itemsCreator: emptyFn, items: [], allowEdit: false, allowSearchValue: false, @@ -19,268 +42,327 @@ BI.MultiLayerSelectTreeCombo = BI.inherit(BI.Widget, { isNeedAdjustWidth: true, status: "", // "error","warning" }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const self = this, + o = this.options; - var cls = (o.simple ? "bi-border-bottom " : "bi-border bi-border-radius ") + (BI.isKey(o.status) ? ("status-" + o.status) : ""); + const cls = + (o.simple ? "bi-border-bottom " : "bi-border bi-border-radius ") + + (isKey(o.status) ? `status-${o.status}` : ""); - var baseConfig = this._getBaseConfig(); + const baseConfig = this._getBaseConfig(); if (o.allowEdit) { return { - type: "bi.absolute", - width: BI.toPix(o.width, 2), - height: BI.toPix(o.height, 2), + type: AbsoluteLayout.xtype, + width: toPix(o.width, 2), + height: toPix(o.height, 2), cls, items: [ { - el: BI.extend(baseConfig, this._getSearchConfig()), - top: 0, bottom: 0, right: 0, left: 0 - }, { - el: self._getTriggerIconButton(), - top: 0, bottom: 0, right: 0, + el: extend(baseConfig, this._getSearchConfig()), + top: 0, + bottom: 0, + right: 0, + left: 0, }, - ] + { + el: self._getTriggerIconButton(), + top: 0, + bottom: 0, + right: 0, + } + ], }; } - return BI.extend(baseConfig, { - el: { - type: "bi.single_tree_trigger", - ref: function (_ref) { - self.textTrigger = _ref; + return extend( + baseConfig, + { + el: { + type: SingleTreeTrigger.xtype, + ref(_ref) { + self.textTrigger = _ref; + }, + text: o.text, + defaultText: o.defaultText, + height: toPix(o.height, 2), + items: o.items, + value: o.value, + tipType: o.tipType, + warningTitle: o.warningTitle, + valueFormatter: o.valueFormatter, }, - text: o.text, - defaultText: o.defaultText, - height: BI.toPix(o.height, 2), - items: o.items, - value: o.value, - tipType: o.tipType, - warningTitle: o.warningTitle, - valueFormatter: o.valueFormatter, - } - }, { cls }); - }, + }, + { cls } + ); + } + + _getBaseConfig() { + const self = this, + o = this.options; - _getBaseConfig: function () { - var self = this, o = this.options; return { - type: "bi.combo", - width: BI.toPix(o.width, 2), - height: BI.toPix(o.height, 2), + type: Combo.xtype, + width: toPix(o.width, 2), + height: toPix(o.height, 2), container: o.container, destroyWhenHide: o.destroyWhenHide, adjustLength: 2, - ref: function (_ref) { + ref(_ref) { self.combo = _ref; }, popup: { el: { - type: "bi.multilayer_select_tree_popup", + type: MultiLayerSelectTreePopup.xtype, isDefaultInit: o.isDefaultInit, itemsCreator: o.itemsCreator, items: o.items, - ref: function (_ref) { - self.trigger && self.trigger.getSearcher().setAdapter(_ref); + ref(_ref) { + self.trigger && + self.trigger.getSearcher().setAdapter(_ref); }, - listeners: [{ - eventName: BI.MultiLayerSelectTreePopup.EVENT_CHANGE, - action: function () { - self.setValue(this.getValue()); - self.combo.hideView(); - self.fireEvent(BI.MultiLayerSelectTreeCombo.EVENT_CHANGE); - self.fireEvent(BI.MultiLayerSelectTreeCombo.EVENT_CLICK_ITEM, self.combo.getValue()); + listeners: [ + { + eventName: MultiLayerSelectTreePopup.EVENT_CHANGE, + action() { + self.setValue(this.getValue()); + self.combo.hideView(); + self.fireEvent( + MultiLayerSelectTreeCombo.EVENT_CHANGE + ); + self.fireEvent( + MultiLayerSelectTreeCombo.EVENT_CLICK_ITEM, + self.combo.getValue() + ); + }, } - }], - onLoaded: function () { - BI.nextTick(function () { + ], + onLoaded() { + nextTick(() => { self.combo.adjustWidth(); self.combo.adjustHeight(); }); - } + }, }, value: o.value, maxHeight: 400, maxWidth: o.isNeedAdjustWidth ? "auto" : 500, - minHeight: 240 + minHeight: 240, }, isNeedAdjustWidth: o.isNeedAdjustWidth, - listeners: [{ - eventName: BI.Combo.EVENT_BEFORE_POPUPVIEW, - action: function () { - self.fireEvent(BI.MultiLayerSelectTreeCombo.EVENT_BEFORE_POPUPVIEW); + listeners: [ + { + eventName: Combo.EVENT_BEFORE_POPUPVIEW, + action() { + self.fireEvent( + MultiLayerSelectTreeCombo.EVENT_BEFORE_POPUPVIEW + ); + }, } - }] + ], }; - }, + } + + _getSearchConfig() { + const self = this, + o = this.options; - _getSearchConfig: function () { - var self = this, o = this.options; return { el: { - type: "bi.multilayer_select_tree_trigger", + type: MultiLayerSelectTreeTrigger.xtype, container: o.container, allowInsertValue: o.allowInsertValue, allowSearchValue: o.allowSearchValue, allowEdit: o.allowEdit, cls: "multilayer-select-tree-trigger", - ref: function (_ref) { + ref(_ref) { self.trigger = _ref; }, items: o.items, itemsCreator: o.itemsCreator, valueFormatter: o.valueFormatter, watermark: o.watermark, - height: BI.toPix(o.height, 2), + height: toPix(o.height, 2), text: o.text, defaultText: o.defaultText, value: o.value, tipType: o.tipType, warningTitle: o.warningTitle, title: o.title, - listeners: [{ - eventName: BI.MultiLayerSelectTreeTrigger.EVENT_CHANGE, - action: function () { - self.setValue(this.getValue()); - self.combo.hideView(); - self.fireEvent(BI.MultiLayerSelectTreeCombo.EVENT_CHANGE); - self.fireEvent(BI.MultiLayerSelectTreeCombo.EVENT_CLICK_ITEM, self.combo.getValue()); - } - }, { - eventName: BI.MultiLayerSelectTreeTrigger.EVENT_FOCUS, - action: function () { - self.fireEvent(BI.MultiLayerSelectTreeCombo.EVENT_FOCUS); - } - }, { - eventName: BI.MultiLayerSelectTreeTrigger.EVENT_BLUR, - action: function () { - self.fireEvent(BI.MultiLayerSelectTreeCombo.EVENT_BLUR); - } - }, { - eventName: BI.MultiLayerSelectTreeTrigger.EVENT_SEARCHING, - action: function () { - self.fireEvent(BI.MultiLayerSelectTreeCombo.EVENT_SEARCHING); - } - }, { - eventName: BI.MultiLayerSelectTreeTrigger.EVENT_STOP, - action: function () { - self.fireEvent(BI.MultiLayerSelectTreeCombo.EVENT_STOP); - } - }, { - eventName: BI.MultiLayerSelectTreeTrigger.EVENT_ADD_ITEM, - action: function () { - var value = self.trigger.getSearcher().getKeyword(); - self.combo.setValue([value]); - self.combo.hideView(); - self.fireEvent(BI.MultiLayerSelectTreeCombo.EVENT_CHANGE); + listeners: [ + { + eventName: MultiLayerSelectTreeTrigger.EVENT_CHANGE, + action() { + self.setValue(this.getValue()); + self.combo.hideView(); + self.fireEvent( + MultiLayerSelectTreeCombo.EVENT_CHANGE + ); + self.fireEvent( + MultiLayerSelectTreeCombo.EVENT_CLICK_ITEM, + self.combo.getValue() + ); + }, + }, + { + eventName: MultiLayerSelectTreeTrigger.EVENT_FOCUS, + action() { + self.fireEvent( + MultiLayerSelectTreeCombo.EVENT_FOCUS + ); + }, + }, + { + eventName: MultiLayerSelectTreeTrigger.EVENT_BLUR, + action() { + self.fireEvent( + MultiLayerSelectTreeCombo.EVENT_BLUR + ); + }, + }, + { + eventName: MultiLayerSelectTreeTrigger.EVENT_SEARCHING, + action() { + self.fireEvent( + MultiLayerSelectTreeCombo.EVENT_SEARCHING + ); + }, + }, + { + eventName: MultiLayerSelectTreeTrigger.EVENT_STOP, + action() { + self.fireEvent( + MultiLayerSelectTreeCombo.EVENT_STOP + ); + }, + }, + { + eventName: MultiLayerSelectTreeTrigger.EVENT_ADD_ITEM, + action() { + const value = self.trigger.getSearcher().getKeyword(); + self.combo.setValue([value]); + self.combo.hideView(); + self.fireEvent( + MultiLayerSelectTreeCombo.EVENT_CHANGE + ); + }, } - }] + ], }, toggle: !o.allowEdit, - hideChecker: function (e) { + hideChecker(e) { // 新增传配置container后对应hideChecker的修改 // IE11下,popover(position: fixed)下放置下拉控件(position: fixed), 滚动的时候会异常卡顿 // 通过container参数将popup放置于popover之外解决此问题, 其他下拉控件由于元素少或者有分页,所以 // 卡顿不明显, 先在此做尝试, 并在FineUI特殊处理待解决文档中标记跟踪 - return (o.container && self.trigger.getSearcher().isSearching() && self.trigger.getSearcher().getView().element.find(e.target).length > 0) ? false : self.triggerBtn?.element.find(e.target).length === 0; - + return o.container && + self.trigger.getSearcher().isSearching() && + self.trigger.getSearcher().getView().element.find(e.target) + .length > 0 + ? false + : self.triggerBtn?.element.find(e.target).length === 0; }, - listeners: [{ - eventName: BI.Combo.EVENT_AFTER_HIDEVIEW, - action: function () { - self.trigger.stopEditing(); - } - }, { - eventName: BI.Combo.EVENT_BEFORE_POPUPVIEW, - action: function () { - self.fireEvent(BI.MultiLayerSelectTreeCombo.EVENT_BEFORE_POPUPVIEW); + listeners: [ + { + eventName: Combo.EVENT_AFTER_HIDEVIEW, + action() { + self.trigger.stopEditing(); + }, + }, + { + eventName: Combo.EVENT_BEFORE_POPUPVIEW, + action() { + self.fireEvent( + MultiLayerSelectTreeCombo.EVENT_BEFORE_POPUPVIEW + ); + }, } - }] + ], }; - }, + } + + _getTriggerIconButton() { + const self = this, + o = this.options; - _getTriggerIconButton: function () { - var self = this, o = this.options; return { - type: "bi.trigger_icon_button", + type: TriggerIconButton.xtype, cls: "bi-trigger trigger-icon-button", - ref: function (_ref) { + ref(_ref) { self.triggerBtn = _ref; }, - width: BI.toPix(o.height, 2), - height: BI.toPix(o.height, 2), + width: toPix(o.height, 2), + height: toPix(o.height, 2), listeners: [ { - eventName: BI.TriggerIconButton.EVENT_CHANGE, - action: function () { + eventName: TriggerIconButton.EVENT_CHANGE, + action() { if (self.combo.isViewVisible()) { self.combo.hideView(); } else { self.combo.showView(); } - } + }, } - ] + ], }; - }, + } - setValue: function (v) { - v = BI.isArray(v) ? v : [v]; + setValue(v) { + v = isArray(v) ? v : [v]; this.combo.setValue(v); - }, + } - getValue: function () { + getValue() { return this.combo.getValue(); - }, + } - getSearcher: function () { - return this.trigger ? this.trigger.getSearcher() : this.textTrigger.getTextor(); - }, + getSearcher() { + return this.trigger + ? this.trigger.getSearcher() + : this.textTrigger.getTextor(); + } - clear: function () { + clear() { // do some work - }, + } - setStatus: function (status) { - if (BI.isKey(this.options.status)) { - this.element.removeClass("status-" + this.options.status); + setStatus(status) { + if (isKey(this.options.status)) { + this.element.removeClass(`status-${this.options.status}`); } - this.element.addClass("status-" + status); + this.element.addClass(`status-${status}`); this.options.status = status; - }, + } - setTipType: function (v) { - this.trigger ? this.trigger.setTipType(v) : this.textTrigger.setTipType(v); - }, + setTipType(v) { + this.trigger + ? this.trigger.setTipType(v) + : this.textTrigger.setTipType(v); + } - populate: function (items) { + populate(items) { this.combo.populate(items); - }, + } - focus: function () { + focus() { this.trigger ? this.trigger.focus() : this.textTrigger.focus(); - }, + } - blur: function () { + blur() { this.trigger ? this.trigger.blur() : this.textTrigger.blur(); - }, + } - showView: function () { + showView() { this.combo.showView(); - }, - - setWaterMark: function (v) { - this.trigger ? this.trigger.setWaterMark(v) : this.textTrigger.setWaterMark(v); } -}); -BI.MultiLayerSelectTreeCombo.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.MultiLayerSelectTreeCombo.EVENT_BLUR = "EVENT_BLUR"; -BI.MultiLayerSelectTreeCombo.EVENT_FOCUS = "EVENT_FOCUS"; -BI.MultiLayerSelectTreeCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiLayerSelectTreeCombo.EVENT_STOP = "EVENT_STOP"; -BI.MultiLayerSelectTreeCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.MultiLayerSelectTreeCombo.EVENT_CLICK_ITEM = "EVENT_CLICK_ITEM"; -BI.shortcut("bi.multilayer_select_tree_combo", BI.MultiLayerSelectTreeCombo); + setWaterMark(v) { + this.trigger + ? this.trigger.setWaterMark(v) + : this.textTrigger.setWaterMark(v); + } +} diff --git a/src/widget/multilayerselecttree/multilayerselecttree.insert.search.pane.js b/src/widget/multilayerselecttree/multilayerselecttree.insert.search.pane.js index 8c59f5992..058493c12 100644 --- a/src/widget/multilayerselecttree/multilayerselecttree.insert.search.pane.js +++ b/src/widget/multilayerselecttree/multilayerselecttree.insert.search.pane.js @@ -1,92 +1,119 @@ -/** - * Created by GUY on 2016/1/26. - * - * @class BI.MultiLayerSelectTreeInsertSearchPane - * @extends BI.Pane - */ +import { + shortcut, + Widget, + i18nText, + emptyFn, + createWidget, + Controller, + VerticalLayout, + isEmptyArray, + isArray +} from "@/core"; +import { MultiLayerSelectLevelTree } from "./multilayerselecttree.leveltree"; +import { TextButton } from "@/base"; -BI.MultiLayerSelectTreeInsertSearchPane = BI.inherit(BI.Widget, { +@shortcut() +export class MultiLayerSelectTreeInsertSearchPane extends Widget { + static xtype = "bi.multilayer_select_tree_insert_search_pane"; - props: function() { + static EVENT_ADD_ITEM = "EVENT_ADD_ITEM"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + props() { return { baseCls: "bi-multilayer-select-tree-popup", - tipText: BI.i18nText("BI-No_Selected_Item"), + tipText: i18nText("BI-No_Selected_Item"), isDefaultInit: false, - itemsCreator: BI.emptyFn, + itemsCreator: emptyFn, items: [], - value: "" + value: "", }; - }, + } - render: function() { - var self = this, o = this.options; - this.tree = BI.createWidget({ - type: "bi.multilayer_select_level_tree", + render() { + const self = this, + o = this.options; + this.tree = createWidget({ + type: MultiLayerSelectLevelTree.xtype, isDefaultInit: o.isDefaultInit, items: o.items, - itemsCreator: o.itemsCreator === BI.emptyFn ? BI.emptyFn : function (op, callback) { - o.itemsCreator(op, function (res) { - callback(res); - self.setKeyword(o.keywordGetter()); - }); - }, + itemsCreator: + o.itemsCreator === emptyFn + ? emptyFn + : function (op, callback) { + o.itemsCreator(op, res => { + callback(res); + self.setKeyword(o.keywordGetter()); + }); + }, keywordGetter: o.keywordGetter, value: o.value, scrollable: null, - listeners: [{ - eventName: BI.Controller.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - } - }, { - eventName: BI.MultiLayerSelectLevelTree.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.MultiLayerSelectTreeInsertSearchPane.EVENT_CHANGE); + listeners: [ + { + eventName: Controller.EVENT_CHANGE, + action() { + self.fireEvent(Controller.EVENT_CHANGE, arguments); + }, + }, + { + eventName: MultiLayerSelectLevelTree.EVENT_CHANGE, + action() { + self.fireEvent( + MultiLayerSelectTreeInsertSearchPane.EVENT_CHANGE + ); + }, } - }] + ], }); + return { - type: "bi.vertical", + type: VerticalLayout.xtype, scrolly: false, scrollable: true, vgap: 5, - items: [{ - type: "bi.text_button", - invisible: true, - text: BI.i18nText("BI-Basic_Click_To_Add_Text", ""), - height: 24, - cls: "bi-high-light", - hgap: 5, - ref: function (_ref) { - self.addNotMatchTip = _ref; + items: [ + { + type: TextButton.xtype, + invisible: true, + text: i18nText("BI-Basic_Click_To_Add_Text", ""), + height: 24, + cls: "bi-high-light", + hgap: 5, + ref(_ref) { + self.addNotMatchTip = _ref; + }, + handler() { + self.fireEvent( + MultiLayerSelectTreeInsertSearchPane.EVENT_ADD_ITEM, + o.keywordGetter() + ); + }, }, - handler: function () { - self.fireEvent(BI.MultiLayerSelectTreeInsertSearchPane.EVENT_ADD_ITEM, o.keywordGetter()); - } - }, this.tree] + this.tree + ], }; - }, + } - setKeyword: function (keyword) { - var showTip = BI.isEmptyArray(this.tree.getAllLeaves()); + setKeyword(keyword) { + const showTip = isEmptyArray(this.tree.getAllLeaves()); this.addNotMatchTip.setVisible(showTip); - showTip && this.addNotMatchTip.setText(BI.i18nText("BI-Basic_Click_To_Add_Text", keyword)); - }, + showTip && + this.addNotMatchTip.setText( + i18nText("BI-Basic_Click_To_Add_Text", keyword) + ); + } - getValue: function () { + getValue() { return this.tree.getValue(); - }, + } - setValue: function (v) { - v = BI.isArray(v) ? v : [v]; + setValue(v) { + v = isArray(v) ? v : [v]; this.tree.setValue(v); - }, + } - populate: function (items) { + populate(items) { this.tree.populate(items); } -}); - -BI.MultiLayerSelectTreeInsertSearchPane.EVENT_ADD_ITEM = "EVENT_ADD_ITEM"; -BI.MultiLayerSelectTreeInsertSearchPane.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multilayer_select_tree_insert_search_pane", BI.MultiLayerSelectTreeInsertSearchPane); \ No newline at end of file +} diff --git a/src/widget/multilayerselecttree/multilayerselecttree.leveltree.js b/src/widget/multilayerselecttree/multilayerselecttree.leveltree.js index 9072c3284..a307ffb2c 100644 --- a/src/widget/multilayerselecttree/multilayerselecttree.leveltree.js +++ b/src/widget/multilayerselecttree/multilayerselecttree.leveltree.js @@ -1,98 +1,135 @@ -/** - * guy - * 二级树 - * @class BI.MultiLayerSelectLevelTree - * @extends BI.Pane - */ -BI.MultiLayerSelectLevelTree = BI.inherit(BI.Pane, { - _defaultConfig: function () { - return BI.extend(BI.MultiLayerSelectLevelTree.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + emptyFn, + each, + isKey, + UUID, + isNotEmptyArray, + defaults, + createWidget, + Tree, + nextTick, + Selection, + Controller, + Events, + VerticalLayout, + AdaptiveLayout, + isNull, + isArray +} from "@/core"; +import { Pane, CustomTree, Loader, ButtonTree } from "@/base"; +import { BasicTreeNode, BasicTreeItem, TreeExpander } from "@/case"; + +@shortcut() +export class MultiLayerSelectLevelTree extends Pane { + static xtype = "bi.multilayer_select_level_tree"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multilayer-select-level-tree", isDefaultInit: false, items: [], - itemsCreator: BI.emptyFn, - keywordGetter: BI.emptyFn, + itemsCreator: emptyFn, + keywordGetter: emptyFn, value: "", - scrollable: true + scrollable: true, }); - }, + } - _init: function () { - var o = this.options; - BI.MultiLayerSelectLevelTree.superclass._init.apply(this, arguments); + _init() { + const o = this.options; + super._init(...arguments); this.storeValue = o.value; this.initTree(this.options.items); this.check(); - }, + } - _formatItems: function (nodes, layer, pNode) { - var self = this, o = this.options; - var keyword = o.keywordGetter(); - BI.each(nodes, function (i, node) { - var extend = { + _formatItems(nodes, layer, pNode) { + const self = this, + o = this.options; + const keyword = o.keywordGetter(); + each(nodes, (i, node) => { + const extend = { isFirstNode: i === 0, isLastNode: i === nodes.length - 1, - height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, }; node.layer = layer; - if (!BI.isKey(node.id)) { - node.id = BI.UUID(); + if (!isKey(node.id)) { + node.id = UUID(); } node.keyword = node.keyword || keyword; extend.pNode = pNode; - if (node.isParent === true || node.parent === true || BI.isNotEmptyArray(node.children)) { - extend.type = "bi.tree_node"; + if ( + node.isParent === true || + node.parent === true || + isNotEmptyArray(node.children) + ) { + extend.type = BasicTreeNode.xtype; extend.selectable = true; - BI.defaults(node, extend); + defaults(node, extend); self._formatItems(node.children, layer + 1, node); } else { - extend.type = "bi.tree_item"; - BI.defaults(node, extend); + extend.type = BasicTreeItem.xtype; + defaults(node, extend); } }); + return nodes; - }, + } - _assertId: function (sNodes) { - BI.each(sNodes, function (i, node) { - node.id = node.id || BI.UUID(); + _assertId(sNodes) { + each(sNodes, (i, node) => { + node.id = node.id || UUID(); }); - }, + } - // 构造树结构, - initTree: function (nodes) { - var self = this, o = this.options; - var hasNext = false; + initTree(nodes) { + const self = this, + o = this.options; + let hasNext = false; this.empty(); this._assertId(nodes); - this.tree = BI.createWidget({ - type: "bi.custom_tree", + this.tree = createWidget({ + type: CustomTree.xtype, cls: "tree-view display-table", expander: { - // type: "bi.select_tree_expander", - type: "bi.tree_expander", + type: TreeExpander.xtype, selectable: true, isDefaultInit: o.isDefaultInit, el: {}, popup: { - type: "bi.custom_tree" - } + type: CustomTree.xtype, + }, }, - items: this._formatItems(BI.Tree.transformToTreeFormat(nodes), 0), - itemsCreator: function (op, callback) { - (op.times === 1 && !op.node) && BI.nextTick(function () { + items: this._formatItems(Tree.transformToTreeFormat(nodes), 0), + itemsCreator(op, callback) { + op.times === 1 && + !op.node && + nextTick(() => { self.loading(); }); - o.itemsCreator(op, function (ob) { + o.itemsCreator(op, ob => { hasNext = ob.hasNext; - (op.times === 1 && !op.node) && self._populate(ob.items); - callback(self._formatItems(BI.Tree.transformToTreeFormat(ob.items), op.node ? op.node.layer + 1 : 0, op.node)); + op.times === 1 && !op.node && self._populate(ob.items); + callback( + self._formatItems( + Tree.transformToTreeFormat(ob.items), + op.node ? op.node.layer + 1 : 0, + op.node + ) + ); self.setValue(self.storeValue); - (op.times === 1 && !op.node) && BI.nextTick(function () { + op.times === 1 && + !op.node && + nextTick(() => { self.loaded(); }); }); @@ -100,73 +137,84 @@ BI.MultiLayerSelectLevelTree = BI.inherit(BI.Pane, { value: o.value, el: { - type: "bi.loader", - isDefaultInit: o.itemsCreator !== BI.emptyFn, + type: Loader.xtype, + isDefaultInit: o.itemsCreator !== emptyFn, el: { - type: "bi.button_tree", - chooseType: o.chooseType === BI.Selection.None ? BI.Selection.None : BI.Selection.Default, // 不使用buttontree内部getValue逻辑 + type: ButtonTree.xtype, + chooseType: + o.chooseType === Selection.None + ? Selection.None + : Selection.Default, // 不使用buttontree内部getValue逻辑 behaviors: o.behaviors, - layouts: [{ - type: "bi.vertical" - }] + layouts: [ + { + type: VerticalLayout.xtype, + } + ], }, - hasNext: function () { + hasNext() { return hasNext; - } - } + }, + }, }); - this.tree.on(BI.Controller.EVENT_CHANGE, function (type, value) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if (type === BI.Events.CLICK) { + this.tree.on(Controller.EVENT_CHANGE, function (type, value) { + self.fireEvent(Controller.EVENT_CHANGE, arguments); + if (type === Events.CLICK) { self.setValue(value); - self.fireEvent(BI.MultiLayerSelectLevelTree.EVENT_CHANGE, arguments); + self.fireEvent( + MultiLayerSelectLevelTree.EVENT_CHANGE, + arguments + ); } }); - BI.createWidget({ - type: "bi.adaptive", + createWidget({ + type: AdaptiveLayout.xtype, element: this, scrollable: o.scrollable, - items: [this.tree] + items: [this.tree], }); - }, + } - _populate: function () { - BI.MultiLayerSelectLevelTree.superclass.populate.apply(this, arguments); - }, + _populate() { + super.populate(...arguments); + } - populate: function (nodes) { + populate(nodes) { this._populate(nodes); - BI.isNull(nodes) ? this.tree.populate() : this.tree.populate(this._formatItems(BI.Tree.transformToTreeFormat(nodes), 0)); - }, + isNull(nodes) + ? this.tree.populate() + : this.tree.populate( + this._formatItems(Tree.transformToTreeFormat(nodes), 0) + ); + } - setValue: function (v) { + setValue(v) { // getValue依赖于storeValue, 那么不选的时候就不要更新storeValue了 - if (this.options.chooseType === BI.Selection.None) { + if (this.options.chooseType === Selection.None) { } else { this.storeValue = v; this.tree.setValue(v); } - }, + } - getValue: function () { - return BI.isArray(this.storeValue) ? - this.storeValue : BI.isNull(this.storeValue) ? - [] : [this.storeValue]; - }, + getValue() { + return isArray(this.storeValue) + ? this.storeValue + : isNull(this.storeValue) + ? [] + : [this.storeValue]; + } - getAllLeaves: function () { + getAllLeaves() { return this.tree.getAllLeaves(); - }, + } - getNodeById: function (id) { + getNodeById(id) { return this.tree.getNodeById(id); - }, + } - getNodeByValue: function (id) { + getNodeByValue(id) { return this.tree.getNodeByValue(id); } -}); -BI.MultiLayerSelectLevelTree.EVENT_CHANGE = "EVENT_CHANGE"; - -BI.shortcut("bi.multilayer_select_level_tree", BI.MultiLayerSelectLevelTree); +} diff --git a/src/widget/multilayerselecttree/multilayerselecttree.popup.js b/src/widget/multilayerselecttree/multilayerselecttree.popup.js index 34dce3a58..d5a781d4a 100644 --- a/src/widget/multilayerselecttree/multilayerselecttree.popup.js +++ b/src/widget/multilayerselecttree/multilayerselecttree.popup.js @@ -1,77 +1,85 @@ -/** - * Created by GUY on 2016/1/26. - * - * @class BI.MultiLayerSelectTreePopup - * @extends BI.Pane - */ +import { + shortcut, + Widget, + extend, + i18nText, + emptyFn, + createWidget, + Controller, + VerticalLayout, + isArray +} from "@/core"; +import { MultiLayerSelectLevelTree } from "./multilayerselecttree.leveltree"; -BI.MultiLayerSelectTreePopup = BI.inherit(BI.Widget, { +@shortcut() +export class MultiLayerSelectTreePopup extends Widget { + static xtype = "bi.multilayer_select_tree_popup"; - _defaultConfig: function () { - return BI.extend(BI.MultiLayerSelectTreePopup.superclass._defaultConfig.apply(this, arguments), { + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multilayer-select-tree-popup", - tipText: BI.i18nText("BI-No_Selected_Item"), + tipText: i18nText("BI-No_Selected_Item"), isDefaultInit: false, - itemsCreator: BI.emptyFn, + itemsCreator: emptyFn, items: [], value: "", - onLoaded: BI.emptyFn, - minHeight: 240 + onLoaded: emptyFn, + minHeight: 240, }); - }, + } - _init: function () { - BI.MultiLayerSelectTreePopup.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, o = this.options; + const self = this, + o = this.options; - this.tree = BI.createWidget({ - type: "bi.multilayer_select_level_tree", + this.tree = createWidget({ + type: MultiLayerSelectLevelTree.xtype, isDefaultInit: o.isDefaultInit, items: o.items, itemsCreator: o.itemsCreator, keywordGetter: o.keywordGetter, value: o.value, scrollable: null, - onLoaded: function () { + onLoaded() { self.tree.check(); o.onLoaded(); - } + }, }); - BI.createWidget({ - type: "bi.vertical", + createWidget({ + type: VerticalLayout.xtype, scrolly: false, scrollable: true, element: this, vgap: 5, - items: [this.tree] + items: [this.tree], }); - this.tree.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.tree.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.tree.on(BI.MultiLayerSelectLevelTree.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiLayerSelectTreePopup.EVENT_CHANGE); + this.tree.on(MultiLayerSelectLevelTree.EVENT_CHANGE, () => { + self.fireEvent(MultiLayerSelectTreePopup.EVENT_CHANGE); }); this.tree.css("min-height", BI.pixFormat(o.minHeight - 10)); - }, + } - getValue: function () { + getValue() { return this.tree.getValue(); - }, + } - setValue: function (v) { - v = BI.isArray(v) ? v : [v]; + setValue(v) { + v = isArray(v) ? v : [v]; this.tree.setValue(v); - }, + } - populate: function (items) { + populate(items) { this.tree.populate(items); } -}); - -BI.MultiLayerSelectTreePopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multilayer_select_tree_popup", BI.MultiLayerSelectTreePopup); \ No newline at end of file +} diff --git a/src/widget/multilayerselecttree/multilayerselecttree.trigger.js b/src/widget/multilayerselecttree/multilayerselecttree.trigger.js index 08f9f9a9e..36ce295a2 100644 --- a/src/widget/multilayerselecttree/multilayerselecttree.trigger.js +++ b/src/widget/multilayerselecttree/multilayerselecttree.trigger.js @@ -1,237 +1,301 @@ -/** - * Created by Windy on 2018/2/2. - */ -BI.MultiLayerSelectTreeTrigger = BI.inherit(BI.Trigger, { +import { + shortcut, + emptyFn, + i18nText, + isNotNull, + isKey, + HorizontalFillLayout, + Tree, + deepClone, + Func, + concat, + isNotEmptyArray, + each, + uniqBy, + map, + isFunction, + find +} from "@/core"; +import { Trigger, Searcher } from "@/base"; +import { StateEditor, DefaultTextEditor } from "@/case"; +import { MultiLayerSelectTreeInsertSearchPane } from "./multilayerselecttree.insert.search.pane"; +import { MultiLayerSelectTreePopup } from "./multilayerselecttree.popup"; - props: function () { +@shortcut() +export class MultiLayerSelectTreeTrigger extends Trigger { + static xtype = "bi.multilayer_select_tree_trigger"; + + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_START = "EVENT_START"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_ADD_ITEM = "EVENT_ADD_ITEM"; + + props() { return { extraCls: "bi-multi-layer-select-tree-trigger", height: 24, - itemsCreator: BI.emptyFn, - watermark: BI.i18nText("BI-Basic_Search"), + itemsCreator: emptyFn, + watermark: i18nText("BI-Basic_Search"), allowSearchValue: false, - title: BI.bind(this._getShowText, this) + title: () => this._getShowText(), }; - }, + } - render: function () { - var self = this, o = this.options; + render() { + const self = this, + o = this.options; if (o.itemsCreator === BI.emptyFn) { this._initData(); } return { - type: "bi.horizontal_fill", + type: HorizontalFillLayout.xtype, items: [ { el: { - type: "bi.searcher", - ref: function () { + type: Searcher.xtype, + ref() { self.searcher = this; }, - masker: BI.isNotNull(o.container) ? { - offset: {}, - container: o.container - } : { - offset: {} - }, + masker: isNotNull(o.container) + ? { + offset: {}, + container: o.container, + } + : { + offset: {}, + }, isAutoSearch: false, el: { - type: "bi.default_text_editor", - ref: function () { + type: DefaultTextEditor.xtype, + ref() { self.editor = this; }, defaultText: o.defaultText, - text: BI.isKey(o.value) ? this._digest(o.value) : o.text, + text: isKey(o.value) + ? this._digest(o.value) + : o.text, value: o.value, height: o.height, tipText: "", watermark: o.watermark, - listeners: [{ - eventName: BI.StateEditor.EVENT_FOCUS, - action: function () { - self.fireEvent(BI.MultiLayerSelectTreeTrigger.EVENT_FOCUS); - } - }, { - eventName: BI.StateEditor.EVENT_BLUR, - action: function () { - self.fireEvent(BI.MultiLayerSelectTreeTrigger.EVENT_BLUR); + listeners: [ + { + eventName: StateEditor.EVENT_FOCUS, + action() { + self.fireEvent( + MultiLayerSelectTreeTrigger.EVENT_FOCUS + ); + }, + }, + { + eventName: StateEditor.EVENT_BLUR, + action() { + self.fireEvent( + MultiLayerSelectTreeTrigger.EVENT_BLUR + ); + }, + }, + { + eventName: StateEditor.EVENT_CHANGE, + action() { + self.fireEvent( + MultiLayerSelectTreeTrigger.EVENT_SEARCHING + ); + }, } - }, { - eventName: BI.StateEditor.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.MultiLayerSelectTreeTrigger.EVENT_SEARCHING); - } - }] + ], }, popup: { - type: o.allowInsertValue ? "bi.multilayer_select_tree_insert_search_pane" : "bi.multilayer_select_tree_popup", - itemsCreator: o.itemsCreator === BI.emptyFn ? BI.emptyFn : function (op, callback) { - op.keyword = self.editor.getValue(); - o.itemsCreator(op, callback); - }, - keywordGetter: function () { + type: o.allowInsertValue + ? MultiLayerSelectTreeInsertSearchPane.xtype + : MultiLayerSelectTreePopup.xtype, + itemsCreator: + o.itemsCreator === emptyFn + ? emptyFn + : function (op, callback) { + op.keyword = self.editor.getValue(); + o.itemsCreator(op, callback); + }, + keywordGetter() { return self.editor.getValue(); }, cls: "bi-card", - listeners: [{ - eventName: BI.MultiLayerSelectTreeInsertSearchPane.EVENT_ADD_ITEM, - action: function () { - self.options.text = self.getSearcher().getKeyword(); - self.fireEvent(BI.MultiLayerSelectTreeTrigger.EVENT_ADD_ITEM); + listeners: [ + { + eventName: + MultiLayerSelectTreeInsertSearchPane.EVENT_ADD_ITEM, + action() { + self.options.text = self + .getSearcher() + .getKeyword(); + self.fireEvent( + MultiLayerSelectTreeTrigger.EVENT_ADD_ITEM + ); + }, } - }], - ref: function (_ref) { + ], + ref(_ref) { self.popup = _ref; - } + }, }, - onSearch: function (obj, callback) { - var keyword = obj.keyword; + onSearch(obj, callback) { + const keyword = obj.keyword; if (o.itemsCreator === BI.emptyFn) { callback(self._getSearchItems(keyword)); - o.allowInsertValue && self.popup.setKeyword(keyword); + o.allowInsertValue && + self.popup.setKeyword(keyword); } else { callback(); } }, - listeners: [{ - eventName: BI.Searcher.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.MultiLayerSelectTreeTrigger.EVENT_CHANGE); + listeners: [ + { + eventName: Searcher.EVENT_CHANGE, + action() { + self.fireEvent( + MultiLayerSelectTreeTrigger.EVENT_CHANGE + ); + }, } - }] + ], }, width: "fill", - rgap: 24 - }, - ] + rgap: 24, + } + ], }; - }, + } - _initData: function () { - var o = this.options; - this.tree = new BI.Tree(); - this.nodes = BI.Tree.treeFormat(BI.deepClone(o.items)); + _initData() { + const o = this.options; + this.tree = new Tree(); + this.nodes = Tree.treeFormat(deepClone(o.items)); this.tree.initTree(this.nodes); - }, + } - _getSearchItems: function (keyword) { - var self = this, o = this.options; + _getSearchItems(keyword) { + const self = this, + o = this.options; // 把数组搜索换成用BI.tree搜索节点, 搜到了就不再往下搜索 - var items = []; - this.tree.traverse(function (node) { - var find = BI.Func.getSearchResult(self.tree.isRoot(node) ? [] : BI.concat([node.text], (o.allowSearchValue ? [node.value] : [])), keyword); + const items = []; + this.tree.traverse(node => { + const find = Func.getSearchResult( + self.tree.isRoot(node) + ? [] + : concat( + [node.text], + o.allowSearchValue ? [node.value] : [] + ), + keyword + ); if (find.find.length > 0 || find.match.length > 0) { items.push(node); + return true; } }); + return this._fillTreeStructure4Search(items, "id"); - }, + } - _createJson: function (node, open) { + _createJson(node, open) { return { id: node.id, pId: node.pId, text: node.text, value: node.value, - isParent: BI.isNotEmptyArray(node.children), - open: open + isParent: isNotEmptyArray(node.children), + open, }; - }, + } - _getChildren: function (node) { - var self = this; + _getChildren(node) { + const self = this; node.children = node.children || []; - var nodes = []; - BI.each(node.children, function (idx, child) { - var children = self._getChildren(child); + let nodes = []; + each(node.children, (idx, child) => { + const children = self._getChildren(child); nodes = nodes.concat(children); }); + return node.children.concat(nodes); - }, - - // 将搜索到的节点进行补充,构造成一棵完整的树 - _fillTreeStructure4Search: function (leaves) { - var self = this; - var result = []; - var queue = []; - BI.each(leaves, function (idx, node) { + } + + _fillTreeStructure4Search(leaves) { + const self = this; + let result = []; + const queue = []; + each(leaves, (idx, node) => { queue.push({ pId: node.pId }); result.push(node); result = result.concat(self._getChildren(node)); }); queue.reverse(); - while (BI.isNotEmptyArray(queue)) { - var node = queue.pop(); - var pNode = this.tree.search(this.tree.getRoot(), node.pId, "id"); + while (isNotEmptyArray(queue)) { + const node = queue.pop(); + const pNode = this.tree.search(this.tree.getRoot(), node.pId, "id"); if (pNode != null) { pNode.open = true; queue.push({ pId: pNode.pId }); result.push(pNode); } } - return BI.uniqBy(BI.map(result, function (idx, node) { - return self._createJson(node, node.open); - }), "id"); - }, - - _digest: function (v) { - var o = this.options; - if (BI.isFunction(o.valueFormatter)) { + + return uniqBy( + map(result, (idx, node) => self._createJson(node, node.open)), + "id" + ); + } + + _digest(v) { + const o = this.options; + if (isFunction(o.valueFormatter)) { return o.valueFormatter(v); } - var result = BI.find(o.items, function (i, item) { - return item.value === v; - }); + const result = find(o.items, (i, item) => item.value === v); - return BI.isNotNull(result) ? result.text : (o.text ?? v); - }, + return isNotNull(result) ? result.text : o.text ?? v; + } - _getShowText: function () { + _getShowText() { return this.editor.getText(); - }, + } - stopEditing: function () { + stopEditing() { this.searcher.stopSearch(); - }, + } - getSearcher: function () { + getSearcher() { return this.searcher; - }, + } - populate: function (items) { + populate(items) { this.options.items = items; this._initData(items); - }, + } - setValue: function (v) { + setValue(v) { this.editor.setState(this._digest(v[0])); - }, + } - getValue: function () { + getValue() { return this.searcher.getValue(); - }, + } - focus: function () { + focus() { this.searcher.focus(); - }, + } - blur: function () { + blur() { this.searcher.blur(); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.searcher.setWaterMark(v); } -}); - -BI.MultiLayerSelectTreeTrigger.EVENT_FOCUS = "EVENT_FOCUS"; -BI.MultiLayerSelectTreeTrigger.EVENT_BLUR = "EVENT_BLUR"; -BI.MultiLayerSelectTreeTrigger.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.MultiLayerSelectTreeTrigger.EVENT_STOP = "EVENT_STOP"; -BI.MultiLayerSelectTreeTrigger.EVENT_START = "EVENT_START"; -BI.MultiLayerSelectTreeTrigger.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiLayerSelectTreeTrigger.EVENT_ADD_ITEM = "EVENT_ADD_ITEM"; -BI.shortcut("bi.multilayer_select_tree_trigger", BI.MultiLayerSelectTreeTrigger); +} diff --git a/src/widget/multilayerselecttree/node/node.first.plus.js b/src/widget/multilayerselecttree/node/node.first.plus.js deleted file mode 100644 index c187ab7a5..000000000 --- a/src/widget/multilayerselecttree/node/node.first.plus.js +++ /dev/null @@ -1,99 +0,0 @@ -/** - * 加号表示的组节点 - * - * Created by GUY on 2016/1/27. - * @class BI.MultiLayerSelectTreeFirstPlusGroupNode - * @extends BI.NodeButton - */ -BI.MultiLayerSelectTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.MultiLayerSelectTreeFirstPlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - extraCls: "bi-multilayer-select-tree-first-plus-group-node bi-list-item-active", - layer: 0, // 第几层级 - id: "", - pId: "", - readonly: true, - open: false, - height: 24 - }); - }, - _init: function () { - BI.MultiLayerSelectTreeFirstPlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.node = BI.createWidget({ - type: "bi.select_tree_first_plus_group_node", - cls: "bi-list-item-none", - stopPropagation: true, - logic: { - dynamic: true - }, - id: o.id, - pId: o.pId, - keyword: o.keyword, - open: o.open, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - py: o.py - }); - this.node.on(BI.Controller.EVENT_CHANGE, function (type) { - self.setSelected(self.isSelected()); - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }); - - var items = []; - // BI.count(0, o.layer, function (index) { - // items.push({ - // type: "bi.layout", - // cls: BI.contains(needBlankLayers, index) ? "" : "base-line-conn-background", - // width: 12, - // height: o.height - // }); - // }); - items.push({ - el: this.node, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2 - }); - BI.createWidget({ - type: "bi.horizontal_adapt", - element: this, - columnSize: BI.makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), - items: items - }); - }, - - isOnce: function () { - return true; - }, - - doRedMark: function () { - this.node.doRedMark.apply(this.node, arguments); - }, - - unRedMark: function () { - this.node.unRedMark.apply(this.node, arguments); - }, - - isSelected: function () { - return this.node.isSelected(); - }, - - setSelected: function (b) { - BI.MultiLayerSelectTreeFirstPlusGroupNode.superclass.setSelected.apply(this, arguments); - this.node.setSelected(b); - }, - - doClick: function () { - BI.NodeButton.superclass.doClick.apply(this, arguments); - this.node.setSelected(this.isSelected()); - }, - - setOpened: function (v) { - BI.MultiLayerSelectTreeFirstPlusGroupNode.superclass.setOpened.apply(this, arguments); - this.node.setOpened(v); - } -}); - -BI.shortcut("bi.multilayer_select_tree_first_plus_group_node", BI.MultiLayerSelectTreeFirstPlusGroupNode); diff --git a/src/widget/multilayerselecttree/node/node.last.plus.js b/src/widget/multilayerselecttree/node/node.last.plus.js deleted file mode 100644 index 89f4a1efa..000000000 --- a/src/widget/multilayerselecttree/node/node.last.plus.js +++ /dev/null @@ -1,88 +0,0 @@ -/** - * 加号表示的组节点 - * - * Created by GUY on 2016/1/27. - * @class BI.MultiLayerSelectTreeLastPlusGroupNode - * @extends BI.NodeButton - */ -BI.MultiLayerSelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.MultiLayerSelectTreeLastPlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - extraCls: "bi-multilayer-select-tree-last-plus-group-node bi-list-item-active", - layer: 0, // 第几层级 - id: "", - pId: "", - readonly: true, - open: false, - height: 24 - }); - }, - _init: function () { - BI.MultiLayerSelectTreeLastPlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.node = BI.createWidget({ - type: "bi.select_tree_last_plus_group_node", - cls: "bi-list-item-none", - stopPropagation: true, - logic: { - dynamic: true - }, - id: o.id, - pId: o.pId, - keyword: o.keyword, - open: o.open, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - py: o.py - }); - this.node.on(BI.Controller.EVENT_CHANGE, function (type) { - self.setSelected(self.isSelected()); - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }); - - var items = []; - - items.push({ - el: this.node, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2 - }); - BI.createWidget({ - type: "bi.horizontal_adapt", - element: this, - columnSize: BI.makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), - items: items - }); - }, - - doRedMark: function () { - this.node.doRedMark.apply(this.node, arguments); - }, - - unRedMark: function () { - this.node.unRedMark.apply(this.node, arguments); - }, - - isSelected: function () { - return this.node.isSelected(); - }, - - setSelected: function (b) { - BI.MultiLayerSelectTreeLastPlusGroupNode.superclass.setSelected.apply(this, arguments); - this.node.setSelected(b); - }, - - doClick: function () { - BI.MultiLayerSelectTreeLastPlusGroupNode.superclass.doClick.apply(this, arguments); - this.node.setSelected(this.isSelected()); - }, - - setOpened: function (v) { - BI.MultiLayerSelectTreeLastPlusGroupNode.superclass.setOpened.apply(this, arguments); - this.node.setOpened(v); - } -}); - -BI.shortcut("bi.multilayer_select_tree_last_plus_group_node", BI.MultiLayerSelectTreeLastPlusGroupNode); diff --git a/src/widget/multilayerselecttree/node/node.mid.plus.js b/src/widget/multilayerselecttree/node/node.mid.plus.js deleted file mode 100644 index 6dad3105f..000000000 --- a/src/widget/multilayerselecttree/node/node.mid.plus.js +++ /dev/null @@ -1,88 +0,0 @@ -/** - * 加号表示的组节点 - * - * Created by GUY on 2016/1/27. - * @class BI.MultiLayerSelectTreeMidPlusGroupNode - * @extends BI.NodeButton - */ -BI.MultiLayerSelectTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.MultiLayerSelectTreeMidPlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - extraCls: "bi-multilayer-select-tree-mid-plus-group-node bi-list-item-active", - layer: 0, // 第几层级 - id: "", - pId: "", - readonly: true, - open: false, - height: 24 - }); - }, - _init: function () { - BI.MultiLayerSelectTreeMidPlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.node = BI.createWidget({ - type: "bi.select_tree_mid_plus_group_node", - cls: "bi-list-item-none", - stopPropagation: true, - logic: { - dynamic: true - }, - id: o.id, - pId: o.pId, - keyword: o.keyword, - open: o.open, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - py: o.py - }); - this.node.on(BI.Controller.EVENT_CHANGE, function (type) { - self.setSelected(self.isSelected()); - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }); - - var items = []; - - items.push({ - el: this.node, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2 - }); - BI.createWidget({ - type: "bi.horizontal_adapt", - element: this, - columnSize: BI.makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), - items: items - }); - }, - - doRedMark: function () { - this.node.doRedMark.apply(this.node, arguments); - }, - - unRedMark: function () { - this.node.unRedMark.apply(this.node, arguments); - }, - - isSelected: function () { - return this.node.isSelected(); - }, - - setSelected: function (b) { - BI.MultiLayerSelectTreeMidPlusGroupNode.superclass.setSelected.apply(this, arguments); - this.node.setSelected(b); - }, - - doClick: function () { - BI.MultiLayerSelectTreeMidPlusGroupNode.superclass.doClick.apply(this, arguments); - this.node.setSelected(this.isSelected()); - }, - - setOpened: function (v) { - BI.MultiLayerSelectTreeMidPlusGroupNode.superclass.setOpened.apply(this, arguments); - this.node.setOpened(v); - } -}); - -BI.shortcut("bi.multilayer_select_tree_mid_plus_group_node", BI.MultiLayerSelectTreeMidPlusGroupNode); diff --git a/src/widget/multilayerselecttree/node/node.plus.js b/src/widget/multilayerselecttree/node/node.plus.js deleted file mode 100644 index d63d2d9d8..000000000 --- a/src/widget/multilayerselecttree/node/node.plus.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * 加号表示的组节点 - * - * Created by GUY on 2016/1/27. - * @class BI.MultiLayerSelectTreePlusGroupNode - * @extends BI.NodeButton - */ -BI.MultiLayerSelectTreePlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.MultiLayerSelectTreePlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - extraCls: "bi-multilayer-select-tree-first-plus-group-node bi-list-item-active", - layer: 0, // 第几层级 - id: "", - pId: "", - readonly: true, - open: false, - height: 24 - }); - }, - _init: function () { - BI.MultiLayerSelectTreePlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.node = BI.createWidget({ - type: "bi.select_tree_plus_group_node", - cls: "bi-list-item-none", - stopPropagation: true, - logic: { - dynamic: true - }, - id: o.id, - pId: o.pId, - keyword: o.keyword, - open: o.open, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - py: o.py - }); - this.node.on(BI.Controller.EVENT_CHANGE, function (type) { - self.setSelected(self.isSelected()); - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }); - - var items = []; - - items.push({ - el: this.node, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2 - }); - BI.createWidget({ - type: "bi.horizontal_adapt", - element: this, - columnSize: BI.makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), - items: items - }); - }, - - isOnce: function () { - return true; - }, - - doRedMark: function () { - this.node.doRedMark.apply(this.node, arguments); - }, - - unRedMark: function () { - this.node.unRedMark.apply(this.node, arguments); - }, - - isSelected: function () { - return this.node.isSelected(); - }, - - setSelected: function (b) { - BI.MultiLayerSelectTreePlusGroupNode.superclass.setSelected.apply(this, arguments); - this.node.setSelected(b); - }, - - doClick: function () { - BI.NodeButton.superclass.doClick.apply(this, arguments); - this.node.setSelected(this.isSelected()); - }, - - setOpened: function (v) { - BI.MultiLayerSelectTreePlusGroupNode.superclass.setOpened.apply(this, arguments); - this.node.setOpened(v); - } -}); - -BI.shortcut("bi.multilayer_select_tree_plus_group_node", BI.MultiLayerSelectTreePlusGroupNode); diff --git a/src/widget/multilayersingletree/index.js b/src/widget/multilayersingletree/index.js new file mode 100644 index 000000000..d36fabf95 --- /dev/null +++ b/src/widget/multilayersingletree/index.js @@ -0,0 +1,2 @@ +export { MultiLayerSingleTreeCombo } from "./multilayersingletree.combo"; +export { MultiLayerSingleLevelTree } from "./multilayersingletree.leveltree"; diff --git a/src/widget/multilayersingletree/multilayersingletree.combo.js b/src/widget/multilayersingletree/multilayersingletree.combo.js index 4e26c1a0c..058939d7d 100644 --- a/src/widget/multilayersingletree/multilayersingletree.combo.js +++ b/src/widget/multilayersingletree/multilayersingletree.combo.js @@ -1,279 +1,353 @@ -/** - * 多层级下拉单选树 - * Created by GUY on 2016/1/26. - * - * @class BI.MultiLayerSingleTreeCombo - * @extends BI.Widget - */ -BI.MultiLayerSingleTreeCombo = BI.inherit(BI.Widget, { +import { + shortcut, + Widget, + extend, + emptyFn, + isKey, + toPix, + AbsoluteLayout, + nextTick, + isArray +} from "@/core"; +import { SingleTreeTrigger } from "../singletree/singletree.trigger"; +import { MultiLayerSingleTreePopup } from "./multilayersingletree.popup"; +import { Combo } from "@/base"; +import { MultiLayerSingleTreeTrigger } from "./multilayersingletree.trigger"; +import { TriggerIconButton } from "@/case"; - _defaultConfig: function () { - return BI.extend(BI.MultiLayerSingleTreeCombo.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class MultiLayerSingleTreeCombo extends Widget { + static xtype = "bi.multilayer_single_tree_combo"; + + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multilayer-single-tree-combo", isDefaultInit: false, height: 24, text: "", defaultText: "", - itemsCreator: BI.emptyFn, + itemsCreator: emptyFn, items: [], allowEdit: false, allowSearchValue: false, allowInsertValue: false, isNeedAdjustWidth: true, }); - }, + } - render: function () { - var self = this, o = this.options; + render() { + const self = this, + o = this.options; - var cls = (o.simple ? "bi-border-bottom bi-focus-shadow " : "bi-border bi-border-radius bi-focus-shadow ") + (BI.isKey(o.status) ? ("status-" + o.status) : ""); + const cls = + (o.simple + ? "bi-border-bottom bi-focus-shadow " + : "bi-border bi-border-radius bi-focus-shadow ") + + (isKey(o.status) ? `status-${o.status}` : ""); - var baseConfig = this._getBaseConfig(); + const baseConfig = this._getBaseConfig(); if (o.allowEdit) { return { - type: "bi.absolute", - width: BI.toPix(o.width, 2), - height: BI.toPix(o.height, 2), + type: AbsoluteLayout.xtype, + width: toPix(o.width, 2), + height: toPix(o.height, 2), cls, items: [ { - el: BI.extend(baseConfig, this._getSearchConfig()), - top: 0, bottom: 0, right: 0, left: 0 - }, { - el: self._getTriggerIconButton(), - top: 0, bottom: 0, right: 0, + el: extend(baseConfig, this._getSearchConfig()), + top: 0, + bottom: 0, + right: 0, + left: 0, }, - ] + { + el: self._getTriggerIconButton(), + top: 0, + bottom: 0, + right: 0, + } + ], }; } - return BI.extend(baseConfig, { - width: BI.toPix(o.width, 2), - height: BI.toPix(o.height, 2), - el: { - type: "bi.single_tree_trigger", - ref: function (_ref) { - self.textTrigger = _ref; + return extend( + baseConfig, + { + width: toPix(o.width, 2), + height: toPix(o.height, 2), + el: { + type: SingleTreeTrigger.xtype, + ref(_ref) { + self.textTrigger = _ref; + }, + text: o.text, + defaultText: o.defaultText, + height: toPix(o.height, 2), + items: o.items, + value: o.value, + tipType: o.tipType, + warningTitle: o.warningTitle, + valueFormatter: o.valueFormatter, }, - text: o.text, - defaultText: o.defaultText, - height: BI.toPix(o.height, 2), - items: o.items, - value: o.value, - tipType: o.tipType, - warningTitle: o.warningTitle, - valueFormatter: o.valueFormatter, }, - }, { cls }); - }, + { cls } + ); + } + + _getBaseConfig() { + const self = this, + o = this.options; - _getBaseConfig: function () { - var self = this, o = this.options; return { - type: "bi.combo", + type: Combo.xtype, container: o.container, destroyWhenHide: o.destroyWhenHide, adjustLength: 2, - ref: function (_ref) { + ref(_ref) { self.combo = _ref; }, popup: { el: { - type: "bi.multilayer_single_tree_popup", + type: MultiLayerSingleTreePopup.xtype, isDefaultInit: o.isDefaultInit, itemsCreator: o.itemsCreator, items: o.items, - ref: function (_ref) { - self.trigger && self.trigger.getSearcher().setAdapter(_ref); + ref(_ref) { + self.trigger && + self.trigger.getSearcher().setAdapter(_ref); }, - listeners: [{ - eventName: BI.MultiLayerSingleTreePopup.EVENT_CHANGE, - action: function () { - self.setValue(this.getValue()); - self.combo.hideView(); - self.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_CHANGE); + listeners: [ + { + eventName: MultiLayerSingleTreePopup.EVENT_CHANGE, + action() { + self.setValue(this.getValue()); + self.combo.hideView(); + self.fireEvent( + MultiLayerSingleTreeCombo.EVENT_CHANGE + ); + }, } - }], - onLoaded: function () { - BI.nextTick(function () { + ], + onLoaded() { + nextTick(() => { self.combo.adjustWidth(); self.combo.adjustHeight(); }); - } + }, }, value: o.value, maxHeight: 400, maxWidth: o.isNeedAdjustWidth ? "auto" : 500, - minHeight: 240 + minHeight: 240, }, isNeedAdjustWidth: o.isNeedAdjustWidth, - listeners: [{ - eventName: BI.Combo.EVENT_BEFORE_POPUPVIEW, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_BEFORE_POPUPVIEW); + listeners: [ + { + eventName: Combo.EVENT_BEFORE_POPUPVIEW, + action() { + self.fireEvent( + MultiLayerSingleTreeCombo.EVENT_BEFORE_POPUPVIEW + ); + }, } - }] + ], }; - }, + } + + _getSearchConfig() { + const self = this, + o = this.options; - _getSearchConfig: function () { - var self = this, o = this.options; return { el: { - type: "bi.multilayer_single_tree_trigger", + type: MultiLayerSingleTreeTrigger.xtype, container: o.container, allowInsertValue: o.allowInsertValue, allowSearchValue: o.allowSearchValue, cls: "multilayer-single-tree-trigger", - ref: function (_ref) { + ref(_ref) { self.trigger = _ref; }, watermark: o.watermark, items: o.items, itemsCreator: o.itemsCreator, valueFormatter: o.valueFormatter, - height: BI.toPix(o.height, 2), + height: toPix(o.height, 2), text: o.text, defaultText: o.defaultText, value: o.value, tipType: o.tipType, warningTitle: o.warningTitle, title: o.title, - listeners: [{ - eventName: BI.MultiLayerSingleTreeTrigger.EVENT_CHANGE, - action: function () { - self.setValue(this.getValue()); - self.combo.hideView(); - self.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_CHANGE); - } - }, { - eventName: BI.MultiLayerSingleTreeTrigger.EVENT_FOCUS, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_FOCUS); - } - }, { - eventName: BI.MultiLayerSingleTreeTrigger.EVENT_BLUR, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_BLUR); - } - }, { - eventName: BI.MultiLayerSingleTreeTrigger.EVENT_SEARCHING, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_SEARCHING); - } - }, { - eventName: BI.MultiLayerSingleTreeTrigger.EVENT_STOP, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_STOP); - } - }, { - eventName: BI.MultiLayerSingleTreeTrigger.EVENT_ADD_ITEM, - action: function () { - var value = self.trigger.getSearcher().getKeyword(); - self.combo.setValue([value]); - self.combo.hideView(); - self.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_CHANGE); + listeners: [ + { + eventName: MultiLayerSingleTreeTrigger.EVENT_CHANGE, + action() { + self.setValue(this.getValue()); + self.combo.hideView(); + self.fireEvent( + MultiLayerSingleTreeCombo.EVENT_CHANGE + ); + }, + }, + { + eventName: MultiLayerSingleTreeTrigger.EVENT_FOCUS, + action() { + self.fireEvent( + MultiLayerSingleTreeCombo.EVENT_FOCUS + ); + }, + }, + { + eventName: MultiLayerSingleTreeTrigger.EVENT_BLUR, + action() { + self.fireEvent( + MultiLayerSingleTreeCombo.EVENT_BLUR + ); + }, + }, + { + eventName: MultiLayerSingleTreeTrigger.EVENT_SEARCHING, + action() { + self.fireEvent( + MultiLayerSingleTreeCombo.EVENT_SEARCHING + ); + }, + }, + { + eventName: MultiLayerSingleTreeTrigger.EVENT_STOP, + action() { + self.fireEvent( + MultiLayerSingleTreeCombo.EVENT_STOP + ); + }, + }, + { + eventName: MultiLayerSingleTreeTrigger.EVENT_ADD_ITEM, + action() { + const value = self.trigger.getSearcher().getKeyword(); + self.combo.setValue([value]); + self.combo.hideView(); + self.fireEvent( + MultiLayerSingleTreeCombo.EVENT_CHANGE + ); + }, } - }] + ], }, toggle: !o.allowEdit, - hideChecker: function (e) { + hideChecker(e) { // 新增传配置container后对应hideChecker的修改 // IE11下,popover(position: fixed)下放置下拉控件(position: fixed), 滚动的时候会异常卡顿 // 通过container参数将popup放置于popover之外解决此问题, 其他下拉控件由于元素少或者有分页,所以 // 卡顿不明显, 先在此做尝试, 并在FineUI特殊处理待解决文档中标记跟踪 - return (o.container && self.trigger.getSearcher().isSearching() && self.trigger.getSearcher().getView().element.find(e.target).length > 0) ? false : self.triggerBtn?.element.find(e.target).length === 0; + return o.container && + self.trigger.getSearcher().isSearching() && + self.trigger.getSearcher().getView().element.find(e.target) + .length > 0 + ? false + : self.triggerBtn?.element.find(e.target).length === 0; }, - listeners: [{ - eventName: BI.Combo.EVENT_AFTER_HIDEVIEW, - action: function () { - self.trigger.stopEditing(); - } - }, { - eventName: BI.Combo.EVENT_BEFORE_POPUPVIEW, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_BEFORE_POPUPVIEW); + listeners: [ + { + eventName: Combo.EVENT_AFTER_HIDEVIEW, + action() { + self.trigger.stopEditing(); + }, + }, + { + eventName: Combo.EVENT_BEFORE_POPUPVIEW, + action() { + self.fireEvent( + MultiLayerSingleTreeCombo.EVENT_BEFORE_POPUPVIEW + ); + }, } - }] + ], }; - }, + } + + _getTriggerIconButton() { + const self = this, + o = this.options; - _getTriggerIconButton: function () { - var self = this, o = this.options; return { - type: "bi.trigger_icon_button", + type: TriggerIconButton.xtype, cls: "bi-trigger trigger-icon-button", - ref: function (_ref) { + ref(_ref) { self.triggerBtn = _ref; }, - width: BI.toPix(o.height, 2), - height: BI.toPix(o.height, 2), + width: toPix(o.height, 2), + height: toPix(o.height, 2), listeners: [ { - eventName: BI.TriggerIconButton.EVENT_CHANGE, - action: function () { + eventName: TriggerIconButton.EVENT_CHANGE, + action() { if (self.combo.isViewVisible()) { self.combo.hideView(); } else { self.combo.showView(); } - } + }, } - ] + ], }; - }, + } - getSearcher: function () { - return this.trigger ? this.trigger.getSearcher() : this.textTrigger.getTextor(); - }, + getSearcher() { + return this.trigger + ? this.trigger.getSearcher() + : this.textTrigger.getTextor(); + } - setValue: function (v) { - v = BI.isArray(v) ? v : [v]; + setValue(v) { + v = isArray(v) ? v : [v]; this.combo.setValue(v); - }, + } - getValue: function () { + getValue() { return this.combo.getValue(); - }, + } - setStatus: function (status) { - if (BI.isKey(this.options.status)) { - this.element.removeClass("status-" + this.options.status); + setStatus(status) { + if (isKey(this.options.status)) { + this.element.removeClass(`status-${this.options.status}`); } - this.element.addClass("status-" + status); + this.element.addClass(`status-${status}`); this.options.status = status; - }, + } - setTipType: function (v) { - this.trigger ? this.trigger.setTipType(v) : this.textTrigger.setTipType(v); - }, + setTipType(v) { + this.trigger + ? this.trigger.setTipType(v) + : this.textTrigger.setTipType(v); + } - populate: function (items) { + populate(items) { this.combo.populate(items); - }, + } - focus: function () { + focus() { this.trigger.focus(); - }, + } - blur: function () { + blur() { this.trigger.blur(); - }, + } - showView: function () { + showView() { this.combo.showView(); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.trigger.setWaterMark(v); } -}); - -BI.MultiLayerSingleTreeCombo.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.MultiLayerSingleTreeCombo.EVENT_BLUR = "EVENT_BLUR"; -BI.MultiLayerSingleTreeCombo.EVENT_FOCUS = "EVENT_FOCUS"; -BI.MultiLayerSingleTreeCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiLayerSingleTreeCombo.EVENT_STOP = "EVENT_STOP"; -BI.MultiLayerSingleTreeCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut("bi.multilayer_single_tree_combo", BI.MultiLayerSingleTreeCombo); +} diff --git a/src/widget/multilayersingletree/multilayersingletree.insert.search.pane.js b/src/widget/multilayersingletree/multilayersingletree.insert.search.pane.js index 8e7fa06de..eb7a6d2a3 100644 --- a/src/widget/multilayersingletree/multilayersingletree.insert.search.pane.js +++ b/src/widget/multilayersingletree/multilayersingletree.insert.search.pane.js @@ -1,92 +1,119 @@ -/** - * Created by GUY on 2016/1/26. - * - * @class BI.MultiLayerSingleTreeInsertSearchPane - * @extends BI.Pane - */ +import { + shortcut, + Widget, + i18nText, + emptyFn, + createWidget, + Controller, + VerticalLayout, + isEmptyArray, + isArray +} from "@/core"; +import { TextButton } from "@/base"; +import { MultiLayerSingleLevelTree } from "./multilayersingletree.leveltree"; -BI.MultiLayerSingleTreeInsertSearchPane = BI.inherit(BI.Widget, { +@shortcut() +export class MultiLayerSingleTreeInsertSearchPane extends Widget { + static xtype = "bi.multilayer_single_tree_insert_search_pane"; - props: function() { + static EVENT_ADD_ITEM = "EVENT_ADD_ITEM"; + static EVENT_CHANGE = "EVENT_CHANGE"; + + props() { return { baseCls: "bi-multilayer-single-tree-popup", - tipText: BI.i18nText("BI-No_Selected_Item"), + tipText: i18nText("BI-No_Selected_Item"), isDefaultInit: false, - itemsCreator: BI.emptyFn, + itemsCreator: emptyFn, items: [], - value: "" + value: "", }; - }, + } - render: function() { - var self = this, o = this.options; - this.tree = BI.createWidget({ - type: "bi.multilayer_single_level_tree", + render() { + const self = this, + o = this.options; + this.tree = createWidget({ + type: MultiLayerSingleLevelTree.xtype, isDefaultInit: o.isDefaultInit, items: o.items, - itemsCreator: o.itemsCreator === BI.emptyFn ? BI.emptyFn : function (op, callback) { - o.itemsCreator(op, function (res) { - callback(res); - self.setKeyword(o.keywordGetter()); - }); - }, + itemsCreator: + o.itemsCreator === emptyFn + ? emptyFn + : function (op, callback) { + o.itemsCreator(op, res => { + callback(res); + self.setKeyword(o.keywordGetter()); + }); + }, keywordGetter: o.keywordGetter, value: o.value, scrollable: null, - listeners: [{ - eventName: BI.Controller.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - } - }, { - eventName: BI.MultiLayerSelectLevelTree.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeInsertSearchPane.EVENT_CHANGE); + listeners: [ + { + eventName: Controller.EVENT_CHANGE, + action() { + self.fireEvent(Controller.EVENT_CHANGE, arguments); + }, + }, + { + eventName: MultiLayerSingleLevelTree.EVENT_CHANGE, + action() { + self.fireEvent( + MultiLayerSingleTreeInsertSearchPane.EVENT_CHANGE + ); + }, } - }] + ], }); + return { - type: "bi.vertical", + type: VerticalLayout.xtype, scrolly: false, scrollable: true, vgap: 5, - items: [{ - type: "bi.text_button", - invisible: true, - text: BI.i18nText("BI-Basic_Click_To_Add_Text", ""), - height: 24, - cls: "bi-high-light", - hgap: 5, - ref: function (_ref) { - self.addNotMatchTip = _ref; + items: [ + { + type: TextButton.xtype, + invisible: true, + text: i18nText("BI-Basic_Click_To_Add_Text", ""), + height: 24, + cls: "bi-high-light", + hgap: 5, + ref(_ref) { + self.addNotMatchTip = _ref; + }, + handler() { + self.fireEvent( + MultiLayerSingleTreeInsertSearchPane.EVENT_ADD_ITEM, + o.keywordGetter() + ); + }, }, - handler: function () { - self.fireEvent(BI.MultiLayerSingleTreeInsertSearchPane.EVENT_ADD_ITEM, o.keywordGetter()); - } - }, this.tree] + this.tree + ], }; - }, + } - setKeyword: function (keyword) { - var showTip = BI.isEmptyArray(this.tree.getAllLeaves()); + setKeyword(keyword) { + const showTip = isEmptyArray(this.tree.getAllLeaves()); this.addNotMatchTip.setVisible(showTip); - showTip && this.addNotMatchTip.setText(BI.i18nText("BI-Basic_Click_To_Add_Text", keyword)); - }, + showTip && + this.addNotMatchTip.setText( + i18nText("BI-Basic_Click_To_Add_Text", keyword) + ); + } - getValue: function () { + getValue() { return this.tree.getValue(); - }, + } - setValue: function (v) { - v = BI.isArray(v) ? v : [v]; + setValue(v) { + v = isArray(v) ? v : [v]; this.tree.setValue(v); - }, + } - populate: function (items) { + populate(items) { this.tree.populate(items); } -}); - -BI.MultiLayerSingleTreeInsertSearchPane.EVENT_ADD_ITEM = "EVENT_ADD_ITEM"; -BI.MultiLayerSingleTreeInsertSearchPane.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multilayer_single_tree_insert_search_pane", BI.MultiLayerSingleTreeInsertSearchPane); \ No newline at end of file +} diff --git a/src/widget/multilayersingletree/multilayersingletree.leveltree.js b/src/widget/multilayersingletree/multilayersingletree.leveltree.js index 8e14aa749..06213988c 100644 --- a/src/widget/multilayersingletree/multilayersingletree.leveltree.js +++ b/src/widget/multilayersingletree/multilayersingletree.leveltree.js @@ -1,170 +1,216 @@ -/** - * guy - * 二级树 - * @class BI.MultiLayerSingleLevelTree - * @extends BI.Single - */ -BI.MultiLayerSingleLevelTree = BI.inherit(BI.Pane, { - _defaultConfig: function () { - return BI.extend(BI.MultiLayerSingleLevelTree.superclass._defaultConfig.apply(this, arguments), { +import { + shortcut, + extend, + emptyFn, + Selection, + each, + isKey, + UUID, + isNotEmptyArray, + defaults, + createWidget, + Tree, + nextTick, + Controller, + Events, + VerticalLayout, + AdaptiveLayout, + isNull, + isArray +} from "@/core"; +import { Pane, CustomTree, Loader, ButtonTree } from "@/base"; +import { BasicTreeNode, BasicTreeItem, TreeExpander } from "@/case"; + +@shortcut() +export class MultiLayerSingleLevelTree extends Pane { + static xtype = "bi.multilayer_single_level_tree"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multilayer-single-level-tree", isDefaultInit: false, items: [], - itemsCreator: BI.emptyFn, - keywordGetter: BI.emptyFn, - chooseType: BI.Selection.Single, - scrollable: true + itemsCreator: emptyFn, + keywordGetter: emptyFn, + chooseType: Selection.Single, + scrollable: true, }); - }, + } - _init: function () { - var o = this.options; - BI.MultiLayerSingleLevelTree.superclass._init.apply(this, arguments); + _init() { + const o = this.options; + super._init(...arguments); this.storeValue = o.value; this.initTree(this.options.items); this.check(); - }, + } - _formatItems: function (nodes, layer, pNode) { - var self = this, o = this.options; - var keyword = o.keywordGetter(); - BI.each(nodes, function (i, node) { - var extend = { + _formatItems(nodes, layer, pNode) { + const self = this, + o = this.options; + const keyword = o.keywordGetter(); + each(nodes, (i, node) => { + const extend = { isFirstNode: i === 0, isLastNode: i === nodes.length - 1, - height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, }; node.layer = layer; - if (!BI.isKey(node.id)) { - node.id = BI.UUID(); + if (!isKey(node.id)) { + node.id = UUID(); } node.keyword = node.keyword || keyword; extend.pNode = pNode; - if (node.isParent === true || node.parent === true || BI.isNotEmptyArray(node.children)) { - extend.type = "bi.tree_node"; + if ( + node.isParent === true || + node.parent === true || + isNotEmptyArray(node.children) + ) { + extend.type = BasicTreeNode.xtype; extend.selectable = false; - BI.defaults(node, extend); + defaults(node, extend); self._formatItems(node.children, layer + 1, node); } else { - extend.type = "bi.tree_item"; - BI.defaults(node, extend); + extend.type = BasicTreeItem.xtype; + defaults(node, extend); } }); + return nodes; - }, + } - _assertId: function (sNodes) { - BI.each(sNodes, function (i, node) { - node.id = node.id || BI.UUID(); + _assertId(sNodes) { + each(sNodes, (i, node) => { + node.id = node.id || UUID(); }); - }, + } - // 构造树结构, - initTree: function (nodes) { - var self = this, o = this.options; - var hasNext = false; + initTree(nodes) { + const self = this, + o = this.options; + let hasNext = false; this.empty(); this._assertId(nodes); - this.tree = BI.createWidget({ - type: "bi.custom_tree", + this.tree = createWidget({ + type: CustomTree.xtype, cls: "tree-view display-table", expander: { - type: "bi.tree_expander", + type: TreeExpander.xtype, isDefaultInit: o.isDefaultInit, el: {}, popup: { - type: "bi.custom_tree" - } + type: CustomTree.xtype, + }, }, - items: this._formatItems(BI.Tree.transformToTreeFormat(nodes), 0), + items: this._formatItems(Tree.transformToTreeFormat(nodes), 0), value: o.value, - itemsCreator: function (op, callback) { - (op.times === 1 && !op.node) && BI.nextTick(function () { + itemsCreator(op, callback) { + op.times === 1 && + !op.node && + nextTick(() => { self.loading(); }); - o.itemsCreator(op, function (ob) { + o.itemsCreator(op, ob => { hasNext = ob.hasNext; - (op.times === 1 && !op.node) && self._populate(ob.items); - callback(self._formatItems(BI.Tree.transformToTreeFormat(ob.items), op.node ? op.node.layer + 1 : 0, op.node)); + op.times === 1 && !op.node && self._populate(ob.items); + callback( + self._formatItems( + Tree.transformToTreeFormat(ob.items), + op.node ? op.node.layer + 1 : 0, + op.node + ) + ); self.setValue(self.storeValue); - (op.times === 1 && !op.node) && BI.nextTick(function () { + op.times === 1 && + !op.node && + nextTick(() => { self.loaded(); }); }); }, el: { - type: "bi.loader", - isDefaultInit: o.itemsCreator !== BI.emptyFn, + type: Loader.xtype, + isDefaultInit: o.itemsCreator !== emptyFn, el: { - type: "bi.button_tree", - chooseType: o.chooseType === BI.Selection.None ? BI.Selection.None : BI.Selection.Default, // 不使用buttontree内部getValue逻辑 + type: ButtonTree.xtype, + chooseType: + o.chooseType === Selection.None + ? Selection.None + : Selection.Default, // 不使用buttontree内部getValue逻辑 behaviors: o.behaviors, - layouts: [{ - type: "bi.vertical" - }] + layouts: [ + { + type: VerticalLayout.xtype, + } + ], }, - hasNext: function () { + hasNext() { return hasNext; - } - } + }, + }, }); - this.tree.on(BI.Controller.EVENT_CHANGE, function (type, v) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if (type === BI.Events.CLICK) { + this.tree.on(Controller.EVENT_CHANGE, function (type, v) { + self.fireEvent(Controller.EVENT_CHANGE, arguments); + if (type === Events.CLICK) { self.setValue(v); - self.fireEvent(BI.MultiLayerSingleLevelTree.EVENT_CHANGE, v); + self.fireEvent(MultiLayerSingleLevelTree.EVENT_CHANGE, v); } }); - BI.createWidget({ - type: "bi.adaptive", + createWidget({ + type: AdaptiveLayout.xtype, element: this, scrollable: o.scrollable, - items: [this.tree] + items: [this.tree], }); - }, + } - _populate: function () { - BI.MultiLayerSelectLevelTree.superclass.populate.apply(this, arguments); - }, + _populate() { + super.populate(...arguments); + } - populate: function (nodes) { + populate(nodes) { this._populate(nodes); - BI.isNull(nodes) ? this.tree.populate() : this.tree.populate(this._formatItems(BI.Tree.transformToTreeFormat(nodes), 0)); - }, + isNull(nodes) + ? this.tree.populate() + : this.tree.populate( + this._formatItems(Tree.transformToTreeFormat(nodes), 0) + ); + } - setValue: function (v) { + setValue(v) { // getValue依赖于storeValue, 那么不选的时候就不要更新storeValue了 - if (this.options.chooseType === BI.Selection.None) { + if (this.options.chooseType === Selection.None) { } else { this.storeValue = v; this.tree.setValue(v); } - }, + } - getValue: function () { - return BI.isArray(this.storeValue) ? - this.storeValue : BI.isNull(this.storeValue) ? - [] : [this.storeValue]; - }, + getValue() { + return isArray(this.storeValue) + ? this.storeValue + : isNull(this.storeValue) + ? [] + : [this.storeValue]; + } - getAllLeaves: function () { + getAllLeaves() { return this.tree.getAllLeaves(); - }, + } - getNodeById: function (id) { + getNodeById(id) { return this.tree.getNodeById(id); - }, + } - getNodeByValue: function (id) { + getNodeByValue(id) { return this.tree.getNodeByValue(id); } -}); -BI.MultiLayerSingleLevelTree.EVENT_CHANGE = "EVENT_CHANGE"; - -BI.shortcut("bi.multilayer_single_level_tree", BI.MultiLayerSingleLevelTree); +} diff --git a/src/widget/multilayersingletree/multilayersingletree.popup.js b/src/widget/multilayersingletree/multilayersingletree.popup.js index 630c38237..7e61cb184 100644 --- a/src/widget/multilayersingletree/multilayersingletree.popup.js +++ b/src/widget/multilayersingletree/multilayersingletree.popup.js @@ -1,76 +1,84 @@ -/** - * Created by GUY on 2016/1/26. - * - * @class BI.MultiLayerSingleTreePopup - * @extends BI.Pane - */ +import { + shortcut, + Widget, + extend, + i18nText, + emptyFn, + createWidget, + Controller, + VerticalLayout, + isArray +} from "@/core"; +import { MultiLayerSingleLevelTree } from "./multilayersingletree.leveltree"; -BI.MultiLayerSingleTreePopup = BI.inherit(BI.Widget, { +@shortcut() +export class MultiLayerSingleTreePopup extends Widget { + static xtype = "bi.multilayer_single_tree_popup"; - _defaultConfig: function () { - return BI.extend(BI.MultiLayerSingleTreePopup.superclass._defaultConfig.apply(this, arguments), { + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multilayer-singletree-popup", - tipText: BI.i18nText("BI-No_Selected_Item"), + tipText: i18nText("BI-No_Selected_Item"), isDefaultInit: false, - itemsCreator: BI.emptyFn, + itemsCreator: emptyFn, items: [], - onLoaded: BI.emptyFn, - minHeight: 240 + onLoaded: emptyFn, + minHeight: 240, }); - }, + } - _init: function () { - BI.MultiLayerSingleTreePopup.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, o = this.options; + const self = this, + o = this.options; - this.tree = BI.createWidget({ - type: "bi.multilayer_single_level_tree", + this.tree = createWidget({ + type: MultiLayerSingleLevelTree.xtype, isDefaultInit: o.isDefaultInit, items: o.items, itemsCreator: o.itemsCreator, keywordGetter: o.keywordGetter, value: o.value, scrollable: null, - onLoaded: function () { + onLoaded() { self.tree.check(); o.onLoaded(); - } + }, }); - BI.createWidget({ - type: "bi.vertical", + createWidget({ + type: VerticalLayout.xtype, scrolly: false, scrollable: true, element: this, vgap: 5, - items: [this.tree] + items: [this.tree], }); - this.tree.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.tree.on(Controller.EVENT_CHANGE, function () { + self.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.tree.on(BI.MultiLayerSingleLevelTree.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiLayerSingleTreePopup.EVENT_CHANGE); + this.tree.on(MultiLayerSingleLevelTree.EVENT_CHANGE, () => { + self.fireEvent(MultiLayerSingleTreePopup.EVENT_CHANGE); }); this.tree.css("min-height", BI.pixFormat(o.minHeight - 10)); - }, + } - getValue: function () { + getValue() { return this.tree.getValue(); - }, + } - setValue: function (v) { - v = BI.isArray(v) ? v : [v]; + setValue(v) { + v = isArray(v) ? v : [v]; this.tree.setValue(v); - }, + } - populate: function (items) { + populate(items) { this.tree.populate(items); } -}); - -BI.MultiLayerSingleTreePopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.multilayer_single_tree_popup", BI.MultiLayerSingleTreePopup); \ No newline at end of file +} diff --git a/src/widget/multilayersingletree/multilayersingletree.trigger.js b/src/widget/multilayersingletree/multilayersingletree.trigger.js index 617c70d7b..0deeae1d5 100644 --- a/src/widget/multilayersingletree/multilayersingletree.trigger.js +++ b/src/widget/multilayersingletree/multilayersingletree.trigger.js @@ -1,237 +1,302 @@ -/** - * Created by Windy on 2018/2/2. - */ -BI.MultiLayerSingleTreeTrigger = BI.inherit(BI.Trigger, { +import { + shortcut, + emptyFn, + i18nText, + isNotNull, + isKey, + HorizontalFillLayout, + Tree, + deepClone, + Func, + concat, + isNotEmptyArray, + each, + uniqBy, + map, + isFunction, + find +} from "@/core"; +import { Trigger, Searcher } from "@/base"; +import { StateEditor, DefaultTextEditor } from "@/case"; +import { MultiLayerSingleTreeInsertSearchPane } from "./multilayersingletree.insert.search.pane"; +import { MultiLayerSingleTreePopup } from "./multilayersingletree.popup"; - props: function () { +@shortcut() +export class MultiLayerSingleTreeTrigger extends Trigger { + static xtype = "bi.multilayer_single_tree_trigger"; + + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_START = "EVENT_START"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_ADD_ITEM = "EVENT_ADD_ITEM"; + + props() { return { extraCls: "bi-multi-layer-single-tree-trigger", height: 24, - itemsCreator: BI.emptyFn, - watermark: BI.i18nText("BI-Basic_Search"), + itemsCreator: emptyFn, + watermark: i18nText("BI-Basic_Search"), allowSearchValue: false, - title: BI.bind(this._getShowText, this) + title: () => this._getShowText(), }; - }, + } - render: function () { - var self = this, o = this.options; + render() { + const self = this, + o = this.options; if (o.itemsCreator === BI.emptyFn) { this._initData(); } return { - type: "bi.horizontal_fill", + type: HorizontalFillLayout.xtype, items: [ { el: { - type: "bi.searcher", - ref: function () { + type: Searcher.xtype, + ref() { self.searcher = this; }, - masker: BI.isNotNull(o.container) ? { - offset: {}, - container: o.container - } : { - offset: {} - }, + masker: isNotNull(o.container) + ? { + offset: {}, + container: o.container, + } + : { + offset: {}, + }, isAutoSearch: false, el: { - type: "bi.default_text_editor", - ref: function () { + type: DefaultTextEditor.xtype, + ref() { self.editor = this; }, defaultText: o.defaultText, - text: BI.isKey(o.value) ? this._digest(o.value) : o.text, + text: isKey(o.value) + ? this._digest(o.value) + : o.text, value: o.value, height: o.height, tipText: "", watermark: o.watermark, - listeners: [{ - eventName: BI.StateEditor.EVENT_FOCUS, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeTrigger.EVENT_FOCUS); - } - }, { - eventName: BI.StateEditor.EVENT_BLUR, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeTrigger.EVENT_BLUR); - } - }, { - eventName: BI.StateEditor.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeTrigger.EVENT_SEARCHING); + listeners: [ + { + eventName: StateEditor.EVENT_FOCUS, + action() { + self.fireEvent( + MultiLayerSingleTreeTrigger.EVENT_FOCUS + ); + }, + }, + { + eventName: StateEditor.EVENT_BLUR, + action() { + self.fireEvent( + MultiLayerSingleTreeTrigger.EVENT_BLUR + ); + }, + }, + { + eventName: StateEditor.EVENT_CHANGE, + action() { + self.fireEvent( + MultiLayerSingleTreeTrigger.EVENT_SEARCHING + ); + }, } - }] + ], }, popup: { - type: o.allowInsertValue ? "bi.multilayer_single_tree_insert_search_pane" : "bi.multilayer_single_tree_popup", - itemsCreator: o.itemsCreator === BI.emptyFn ? BI.emptyFn : function (op, callback) { - op.keyword = self.editor.getValue(); - o.itemsCreator(op, callback); - }, - keywordGetter: function () { + type: o.allowInsertValue + ? MultiLayerSingleTreeInsertSearchPane.xtype + : MultiLayerSingleTreePopup.xtype, + itemsCreator: + o.itemsCreator === emptyFn + ? emptyFn + : function (op, callback) { + op.keyword = self.editor.getValue(); + o.itemsCreator(op, callback); + }, + keywordGetter() { return self.editor.getValue(); }, cls: "bi-card", - listeners: [{ - eventName: BI.MultiLayerSingleTreeInsertSearchPane.EVENT_ADD_ITEM, - action: function () { - self.options.text = self.getSearcher().getKeyword(); - self.fireEvent(BI.MultiLayerSingleTreeTrigger.EVENT_ADD_ITEM); + listeners: [ + { + eventName: + MultiLayerSingleTreeInsertSearchPane.EVENT_ADD_ITEM, + action() { + self.options.text = self + .getSearcher() + .getKeyword(); + self.fireEvent( + MultiLayerSingleTreeTrigger.EVENT_ADD_ITEM + ); + }, } - }], - ref: function (_ref) { + ], + ref(_ref) { self.popup = _ref; - } + }, }, - onSearch: function (obj, callback) { - var keyword = obj.keyword; + onSearch(obj, callback) { + const keyword = obj.keyword; if (o.itemsCreator === BI.emptyFn) { callback(self._getSearchItems(keyword)); - o.allowInsertValue && self.popup.setKeyword(keyword); + o.allowInsertValue && + self.popup.setKeyword(keyword); } else { callback(); } }, - listeners: [{ - eventName: BI.Searcher.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.MultiLayerSingleTreeTrigger.EVENT_CHANGE); + listeners: [ + { + eventName: Searcher.EVENT_CHANGE, + action() { + self.fireEvent( + MultiLayerSingleTreeTrigger.EVENT_CHANGE + ); + }, } - }] + ], }, width: "fill", rgap: 24, - }, - ] + } + ], }; - }, + } - _initData: function () { - var o = this.options; - this.tree = new BI.Tree(); - this.nodes = BI.Tree.treeFormat(BI.deepClone(o.items)); + _initData() { + const o = this.options; + this.tree = new Tree(); + this.nodes = Tree.treeFormat(deepClone(o.items)); this.tree.initTree(this.nodes); - }, + } - _getSearchItems: function (keyword) { - var self = this, o = this.options; + _getSearchItems(keyword) { + const self = this, + o = this.options; // 把数组搜索换成用BI.tree搜索节点, 搜到了就不再往下搜索 - var items = []; - this.tree.traverse(function (node) { - var find = BI.Func.getSearchResult(self.tree.isRoot(node) ? [] : BI.concat([node.text], (o.allowSearchValue ? [node.value] : [])), keyword); + const items = []; + this.tree.traverse(node => { + const find = Func.getSearchResult( + self.tree.isRoot(node) + ? [] + : concat( + [node.text], + o.allowSearchValue ? [node.value] : [] + ), + keyword + ); if (find.find.length > 0 || find.match.length > 0) { items.push(node); + return true; } }); + return this._fillTreeStructure4Search(items, "id"); - }, + } - _createJson: function (node, open) { + _createJson(node, open) { return { id: node.id, pId: node.pId, text: node.text, value: node.value, - isParent: BI.isNotEmptyArray(node.children), - open: open + isParent: isNotEmptyArray(node.children), + open, }; - }, + } - _getChildren: function (node) { - var self = this; + _getChildren(node) { + const self = this; node.children = node.children || []; - var nodes = []; - BI.each(node.children, function (idx, child) { - var children = self._getChildren(child); + let nodes = []; + each(node.children, (idx, child) => { + const children = self._getChildren(child); nodes = nodes.concat(children); }); + return node.children.concat(nodes); - }, - - // 将搜索到的节点进行补充,构造成一棵完整的树 - _fillTreeStructure4Search: function (leaves) { - var self = this; - var result = []; - var queue = []; - BI.each(leaves, function (idx, node) { + } + + _fillTreeStructure4Search(leaves) { + const self = this; + let result = []; + const queue = []; + each(leaves, (idx, node) => { queue.push({ pId: node.pId }); result.push(node); result = result.concat(self._getChildren(node)); }); queue.reverse(); - while (BI.isNotEmptyArray(queue)) { - var node = queue.pop(); - var pNode = this.tree.search(this.tree.getRoot(), node.pId, "id"); + while (isNotEmptyArray(queue)) { + const node = queue.pop(); + const pNode = this.tree.search(this.tree.getRoot(), node.pId, "id"); if (pNode != null) { pNode.open = true; queue.push({ pId: pNode.pId }); result.push(pNode); } } - return BI.uniqBy(BI.map(result, function (idx, node) { - return self._createJson(node, node.open); - }), "id"); - }, - _digest: function (v) { - var o = this.options; + return uniqBy( + map(result, (idx, node) => self._createJson(node, node.open)), + "id" + ); + } + + _digest(v) { + const o = this.options; - if (BI.isFunction(o.valueFormatter)) { + if (isFunction(o.valueFormatter)) { return o.valueFormatter(v); } - var result = BI.find(o.items, function (i, item) { - return item.value === v; - }); + const result = find(o.items, (i, item) => item.value === v); - return BI.isNotNull(result) ? result.text : (o.text ?? v); - }, + return isNotNull(result) ? result.text : o.text ?? v; + } - _getShowText: function () { + _getShowText() { return this.editor.getText(); - }, + } - stopEditing: function () { + stopEditing() { this.searcher.stopSearch(); - }, + } - getSearcher: function () { + getSearcher() { return this.searcher; - }, + } - populate: function (items) { + populate(items) { this.options.items = items; this._initData(); - }, + } - setValue: function (v) { + setValue(v) { this.editor.setState(this._digest(v[0])); - }, + } - getValue: function () { + getValue() { return this.searcher.getValue(); - }, + } - focus: function () { + focus() { this.searcher.focus(); - }, + } - blur: function () { + blur() { this.searcher.blur(); - }, + } - setWaterMark: function (v) { + setWaterMark(v) { this.searcher.setWaterMark(v); } -}); -BI.MultiLayerSingleTreeTrigger.EVENT_FOCUS = "EVENT_FOCUS"; -BI.MultiLayerSingleTreeTrigger.EVENT_BLUR = "EVENT_BLUR"; -BI.MultiLayerSingleTreeTrigger.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.MultiLayerSingleTreeTrigger.EVENT_STOP = "EVENT_STOP"; -BI.MultiLayerSingleTreeTrigger.EVENT_START = "EVENT_START"; -BI.MultiLayerSingleTreeTrigger.EVENT_CHANGE = "EVENT_CHANGE"; -BI.MultiLayerSingleTreeTrigger.EVENT_ADD_ITEM = "EVENT_ADD_ITEM"; -BI.shortcut("bi.multilayer_single_tree_trigger", BI.MultiLayerSingleTreeTrigger); +} diff --git a/src/widget/multilayersingletree/node/node.first.plus.js b/src/widget/multilayersingletree/node/node.first.plus.js deleted file mode 100644 index 51177bcce..000000000 --- a/src/widget/multilayersingletree/node/node.first.plus.js +++ /dev/null @@ -1,91 +0,0 @@ -/** - * 加号表示的组节点 - * - * Created by GUY on 2016/1/27. - * @class BI.MultiLayerSingleTreeFirstPlusGroupNode - * @extends BI.NodeButton - */ -BI.MultiLayerSingleTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.MultiLayerSingleTreeFirstPlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - extraCls: "bi-multilayer-single-tree-first-plus-group-node bi-list-item", - layer: 0, // 第几层级 - id: "", - pId: "", - open: false, - height: 24 - }); - }, - _init: function () { - BI.MultiLayerSingleTreeFirstPlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.node = this._createNode(); - - var items = []; - - items.push({ - el: this.node, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2 - }); - BI.createWidget({ - type: "bi.horizontal_adapt", - element: this, - columnSize: BI.makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), - items: items - }); - }, - - doRedMark: function () { - this.node.doRedMark.apply(this.node, arguments); - }, - - unRedMark: function () { - this.node.unRedMark.apply(this.node, arguments); - }, - - doClick: function () { - BI.MultiLayerSingleTreeFirstPlusGroupNode.superclass.doClick.apply(this, arguments); - this.node.setSelected(this.isSelected()); - }, - - setOpened: function (v) { - BI.MultiLayerSingleTreeFirstPlusGroupNode.superclass.setOpened.apply(this, arguments); - if (BI.isNotNull(this.node)) { - this.node.setOpened(v); - } - }, - - _createNode: function () { - var self = this, o = this.options; - - return BI.createWidget({ - type: "bi.first_plus_group_node", - cls: "bi-list-item-none", - logic: { - dynamic: true - }, - id: o.id, - pId: o.pId, - open: o.open, - isLastNode: o.isLastNode, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - py: o.py, - keyword: o.keyword, - listeners: [{ - eventName: BI.Controller.EVENT_CHANGE, - action: function (type) { - if (type === BI.Events.CLICK) {// 本身实现click功能 - return; - } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - } - }] - }); - } -}); - -BI.shortcut("bi.multilayer_single_tree_first_plus_group_node", BI.MultiLayerSingleTreeFirstPlusGroupNode); diff --git a/src/widget/multilayersingletree/node/node.last.plus.js b/src/widget/multilayersingletree/node/node.last.plus.js deleted file mode 100644 index 007837f5c..000000000 --- a/src/widget/multilayersingletree/node/node.last.plus.js +++ /dev/null @@ -1,90 +0,0 @@ -/** - * 加号表示的组节点 - * - * Created by GUY on 2016/1/27. - * @class BI.MultiLayerSingleTreeLastPlusGroupNode - * @extends BI.NodeButton - */ -BI.MultiLayerSingleTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.MultiLayerSingleTreeLastPlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - extraCls: "bi-multilayer-single-tree-last-plus-group-node bi-list-item", - layer: 0, // 第几层级 - id: "", - pId: "", - open: false, - height: 24 - }); - }, - _init: function () { - BI.MultiLayerSingleTreeLastPlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.node = this._createNode(); - - var items = []; - - items.push({ - el: this.node, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2 - }); - BI.createWidget({ - type: "bi.horizontal_adapt", - element: this, - columnSize: BI.makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), - items: items - }); - }, - - doRedMark: function () { - this.node.doRedMark.apply(this.node, arguments); - }, - - unRedMark: function () { - this.node.unRedMark.apply(this.node, arguments); - }, - - doClick: function () { - BI.MultiLayerSingleTreeLastPlusGroupNode.superclass.doClick.apply(this, arguments); - this.node.setSelected(this.isSelected()); - }, - - setOpened: function (v) { - BI.MultiLayerSingleTreeLastPlusGroupNode.superclass.setOpened.apply(this, arguments); - if (BI.isNotNull(this.node)) { - this.node.setOpened(v); - } - }, - - _createNode: function () { - var self = this, o = this.options; - - return BI.createWidget({ - type: "bi.last_plus_group_node", - cls: "bi-list-item-none", - logic: { - dynamic: true - }, - id: o.id, - pId: o.pId, - open: o.open, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - py: o.py, - keyword: o.keyword, - listeners: [{ - eventName: BI.Controller.EVENT_CHANGE, - action: function (type) { - if (type === BI.Events.CLICK) {// 本身实现click功能 - return; - } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - } - }] - }); - } -}); - -BI.shortcut("bi.multilayer_single_tree_last_plus_group_node", BI.MultiLayerSingleTreeLastPlusGroupNode); diff --git a/src/widget/multilayersingletree/node/node.mid.plus.js b/src/widget/multilayersingletree/node/node.mid.plus.js deleted file mode 100644 index e8709cf78..000000000 --- a/src/widget/multilayersingletree/node/node.mid.plus.js +++ /dev/null @@ -1,90 +0,0 @@ -/** - * 加号表示的组节点 - * - * Created by GUY on 2016/1/27. - * @class BI.MultiLayerSingleTreeMidPlusGroupNode - * @extends BI.NodeButton - */ -BI.MultiLayerSingleTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.MultiLayerSingleTreeMidPlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - extraCls: "bi-multilayer-single-tree-mid-plus-group-node bi-list-item", - layer: 0, // 第几层级 - id: "", - pId: "", - open: false, - height: 24 - }); - }, - _init: function () { - BI.MultiLayerSingleTreeMidPlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.node = this._createNode(); - - var items = []; - - items.push({ - el: this.node, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2 - }); - BI.createWidget({ - type: "bi.horizontal_adapt", - element: this, - columnSize: BI.makeArray(o.layer, 12), - items: items - }); - }, - - doRedMark: function () { - this.node.doRedMark.apply(this.node, arguments); - }, - - unRedMark: function () { - this.node.unRedMark.apply(this.node, arguments); - }, - - doClick: function () { - BI.MultiLayerSingleTreeMidPlusGroupNode.superclass.doClick.apply(this, arguments); - this.node.setSelected(this.isSelected()); - }, - - setOpened: function (v) { - BI.MultiLayerSingleTreeMidPlusGroupNode.superclass.setOpened.apply(this, arguments); - if (BI.isNotNull(this.node)) { - this.node.setOpened(v); - } - }, - - _createNode: function () { - var self = this, o = this.options; - - return BI.createWidget({ - type: "bi.mid_plus_group_node", - cls: "bi-list-item-none", - logic: { - dynamic: true - }, - id: o.id, - pId: o.pId, - open: o.open, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - py: o.py, - keyword: o.keyword, - listeners: [{ - eventName: BI.Controller.EVENT_CHANGE, - action: function (type) { - if (type === BI.Events.CLICK) {// 本身实现click功能 - return; - } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - } - }] - }); - } -}); - -BI.shortcut("bi.multilayer_single_tree_mid_plus_group_node", BI.MultiLayerSingleTreeMidPlusGroupNode); diff --git a/src/widget/multilayersingletree/node/node.plus.js b/src/widget/multilayersingletree/node/node.plus.js deleted file mode 100644 index bcff49737..000000000 --- a/src/widget/multilayersingletree/node/node.plus.js +++ /dev/null @@ -1,102 +0,0 @@ -/** - *@desc 根节点,既是第一个又是最后一个 - *@author dailer - *@date 2018/09/16 - */ -BI.MultiLayerSingleTreePlusGroupNode = BI.inherit(BI.NodeButton, { - _defaultConfig: function () { - var conf = BI.MultiLayerSingleTreePlusGroupNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - extraCls: "bi-multilayer-single-tree-plus-group-node bi-list-item", - layer: 0, // 第几层级 - id: "", - pId: "", - open: false, - height: 24 - }); - }, - _init: function () { - BI.MultiLayerSingleTreePlusGroupNode.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.node = this._createNode(); - - var needBlankLayers = []; - var pNode = o.pNode; - while (pNode) { - if (pNode.isLastNode) { - needBlankLayers.push(pNode.layer) - } - pNode = pNode.pNode; - } - - var items = []; - BI.count(0, o.layer, function (index) { - items.push({ - type: "bi.layout", - cls: BI.contains(needBlankLayers, index) ? "" : "base-line-conn-background", - width: 12, - height: o.height - }); - }); - items.push(this.node); - BI.createWidget({ - type: "bi.horizontal_adapt", - element: this, - columnSize: BI.makeArray(o.layer, 12), - items: items - }); - }, - - doRedMark: function () { - this.node.doRedMark.apply(this.node, arguments); - }, - - unRedMark: function () { - this.node.unRedMark.apply(this.node, arguments); - }, - - doClick: function () { - BI.MultiLayerSingleTreePlusGroupNode.superclass.doClick.apply(this, arguments); - this.node.setSelected(this.isSelected()); - }, - - setOpened: function (v) { - BI.MultiLayerSingleTreePlusGroupNode.superclass.setOpened.apply(this, arguments); - if (BI.isNotNull(this.node)) { - this.node.setOpened(v); - } - }, - - _createNode: function () { - var self = this, o = this.options; - - return BI.createWidget({ - type: "bi.plus_group_node", - cls: "bi-list-item-none", - logic: { - dynamic: true - }, - id: o.id, - pId: o.pId, - open: o.open, - isLastNode: o.isLastNode, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - py: o.py, - keyword: o.keyword, - listeners: [{ - eventName: BI.Controller.EVENT_CHANGE, - action: function (type) { - if (type === BI.Events.CLICK) {// 本身实现click功能 - return; - } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - } - }] - }); - } -}); - -BI.shortcut("bi.multilayer_single_tree_plus_group_node", BI.MultiLayerSingleTreePlusGroupNode); \ No newline at end of file diff --git a/src/widget/multilayersingletree/treeitem/item.first.treeleaf.js b/src/widget/multilayersingletree/treeitem/item.first.treeleaf.js deleted file mode 100644 index 4cc5203e4..000000000 --- a/src/widget/multilayersingletree/treeitem/item.first.treeleaf.js +++ /dev/null @@ -1,86 +0,0 @@ -/** - * - * Created by GUY on 2016/1/27. - * @class BI.MultiLayerSingleTreeFirstTreeLeafItem - * @extends BI.BasicButton - */ -BI.MultiLayerSingleTreeFirstTreeLeafItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - return BI.extend(BI.MultiLayerSingleTreeFirstTreeLeafItem.superclass._defaultConfig.apply(this, arguments), { - extraCls: "bi-multilayer-single-tree-first-tree-leaf-item bi-list-item-active", - logic: { - dynamic: false - }, - layer: 0, - id: "", - pId: "", - height: 24 - }); - }, - _init: function () { - BI.MultiLayerSingleTreeFirstTreeLeafItem.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.item = BI.createWidget({ - type: "bi.first_tree_leaf_item", - cls: "bi-list-item-none", - logic: { - dynamic: true - }, - id: o.id, - pId: o.pId, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - py: o.py, - keyword: o.keyword - }); - this.item.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {// 本身实现click功能 - return; - } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }); - - var items = []; - - items.push({ - el: this.item, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2 - }); - BI.createWidget({ - type: "bi.horizontal_adapt", - element: this, - columnSize: BI.makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), - items: items - }); - }, - - doHighLight: function () { - this.item.doHighLight.apply(this.item, arguments); - }, - - unHighLight: function () { - this.item.unHighLight.apply(this.item, arguments); - }, - - getId: function () { - return this.options.id; - }, - - getPId: function () { - return this.options.pId; - }, - - doClick: function () { - BI.MultiLayerSingleTreeFirstTreeLeafItem.superclass.doClick.apply(this, arguments); - this.item.setSelected(this.isSelected()); - }, - - setSelected: function (v) { - BI.MultiLayerSingleTreeFirstTreeLeafItem.superclass.setSelected.apply(this, arguments); - this.item.setSelected(v); - } -}); - -BI.shortcut("bi.multilayer_single_tree_first_tree_leaf_item", BI.MultiLayerSingleTreeFirstTreeLeafItem); diff --git a/src/widget/multilayersingletree/treeitem/item.last.treeleaf.js b/src/widget/multilayersingletree/treeitem/item.last.treeleaf.js deleted file mode 100644 index 9aa604737..000000000 --- a/src/widget/multilayersingletree/treeitem/item.last.treeleaf.js +++ /dev/null @@ -1,86 +0,0 @@ -/** - * - * Created by GUY on 2016/1/27. - * @class BI.MultiLayerSingleTreeLastTreeLeafItem - * @extends BI.BasicButton - */ -BI.MultiLayerSingleTreeLastTreeLeafItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - return BI.extend(BI.MultiLayerSingleTreeLastTreeLeafItem.superclass._defaultConfig.apply(this, arguments), { - extraCls: "bi-multilayer-single-tree-last-tree-leaf-item bi-list-item-active", - logic: { - dynamic: false - }, - layer: 0, - id: "", - pId: "", - height: 24 - }); - }, - _init: function () { - BI.MultiLayerSingleTreeLastTreeLeafItem.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.item = BI.createWidget({ - type: "bi.last_tree_leaf_item", - cls: "bi-list-item-none", - logic: { - dynamic: true - }, - id: o.id, - pId: o.pId, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - py: o.py, - keyword: o.keyword - }); - this.item.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {// 本身实现click功能 - return; - } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }); - - var items = []; - - items.push({ - el: this.item, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2 - }); - BI.createWidget({ - type: "bi.horizontal_adapt", - element: this, - columnSize: BI.makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), - items: items - }); - }, - - doHighLight: function () { - this.item.doHighLight.apply(this.item, arguments); - }, - - unHighLight: function () { - this.item.unHighLight.apply(this.item, arguments); - }, - - getId: function () { - return this.options.id; - }, - - getPId: function () { - return this.options.pId; - }, - - doClick: function () { - BI.MultiLayerSingleTreeLastTreeLeafItem.superclass.doClick.apply(this, arguments); - this.item.setSelected(this.isSelected()); - }, - - setSelected: function (v) { - BI.MultiLayerSingleTreeLastTreeLeafItem.superclass.setSelected.apply(this, arguments); - this.item.setSelected(v); - } -}); - -BI.shortcut("bi.multilayer_single_tree_last_tree_leaf_item", BI.MultiLayerSingleTreeLastTreeLeafItem); diff --git a/src/widget/multilayersingletree/treeitem/item.mid.treeleaf.js b/src/widget/multilayersingletree/treeitem/item.mid.treeleaf.js deleted file mode 100644 index eed7d553c..000000000 --- a/src/widget/multilayersingletree/treeitem/item.mid.treeleaf.js +++ /dev/null @@ -1,86 +0,0 @@ -/** - * - * Created by GUY on 2016/1/27. - * @class BI.MultiLayerSingleTreeMidTreeLeafItem - * @extends BI.BasicButton - */ -BI.MultiLayerSingleTreeMidTreeLeafItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function () { - return BI.extend(BI.MultiLayerSingleTreeMidTreeLeafItem.superclass._defaultConfig.apply(this, arguments), { - extraCls: "bi-multilayer-single-tree-mid-tree-leaf-item bi-list-item-active", - logic: { - dynamic: false - }, - layer: 0, - id: "", - pId: "", - height: 24 - }); - }, - _init: function () { - BI.MultiLayerSingleTreeMidTreeLeafItem.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.item = BI.createWidget({ - type: "bi.mid_tree_leaf_item", - cls: "bi-list-item-none", - logic: { - dynamic: true - }, - id: o.id, - pId: o.pId, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - py: o.py, - keyword: o.keyword - }); - this.item.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {// 本身实现click功能 - return; - } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }); - - var items = []; - - items.push({ - el: this.item, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2 - }); - BI.createWidget({ - type: "bi.horizontal_adapt", - element: this, - columnSize: BI.makeArray(o.layer, BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2), - items: items - }); - }, - - doHighLight: function () { - this.item.doHighLight.apply(this.item, arguments); - }, - - unHighLight: function () { - this.item.unHighLight.apply(this.item, arguments); - }, - - getId: function () { - return this.options.id; - }, - - getPId: function () { - return this.options.pId; - }, - - doClick: function () { - BI.MultiLayerSingleTreeMidTreeLeafItem.superclass.doClick.apply(this, arguments); - this.item.setSelected(this.isSelected()); - }, - - setSelected: function (v) { - BI.MultiLayerSingleTreeMidTreeLeafItem.superclass.setSelected.apply(this, arguments); - this.item.setSelected(v); - } -}); - -BI.shortcut("bi.multilayer_single_tree_mid_tree_leaf_item", BI.MultiLayerSingleTreeMidTreeLeafItem); From ab2eb1f99678431adfa393c12f274263afd9445f Mon Sep 17 00:00:00 2001 From: "crawford.zhou" Date: Fri, 13 Jan 2023 15:11:19 +0800 Subject: [PATCH 112/300] =?UTF-8?q?KERNEL-14105=20feat:searchmultitextvalu?= =?UTF-8?q?ecombo=20=E7=9A=84es6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/widget/index.js | 3 + src/widget/multiselect/index.js | 6 + src/widget/searchmultitextvaluecombo/index.js | 5 + .../multitextvalue.combo.search.js | 648 +++++++++--------- .../multitextvalue.combo.trigger.search.js | 189 ++--- .../multitextvalue.loader.search.js | 238 ++++--- .../multitextvalue.popup.view.search.js | 112 +-- .../trigger/searcher.multitextvalue.js | 200 +++--- 8 files changed, 748 insertions(+), 653 deletions(-) create mode 100644 src/widget/searchmultitextvaluecombo/index.js diff --git a/src/widget/index.js b/src/widget/index.js index 2deb239a7..0d3a9cb59 100644 --- a/src/widget/index.js +++ b/src/widget/index.js @@ -25,6 +25,7 @@ import * as singleselect from "./singleselect"; import * as multilayerdownlist from "./multilayerdownlist"; import * as multilayersingletree from "./multilayersingletree"; +import * as searchmultitextvaluecombo from "./searchmultitextvaluecombo"; Object.assign(BI, { Collapse, ...calendar, @@ -52,6 +53,7 @@ Object.assign(BI, { ...singleselect, ...multilayerdownlist, ...multilayersingletree, + ...searchmultitextvaluecombo, }); export * from "./date/calendar"; @@ -68,6 +70,7 @@ export * from "./downlist"; export * from "./singleslider"; export * from "./intervalslider"; export * from "./year"; +export * from "./searchmultitextvaluecombo"; export * from "./singleselect"; export * from "./multilayerdownlist"; export * from "./multilayersingletree"; diff --git a/src/widget/multiselect/index.js b/src/widget/multiselect/index.js index 9e0934c14..9236080dd 100644 --- a/src/widget/multiselect/index.js +++ b/src/widget/multiselect/index.js @@ -1,3 +1,9 @@ +export { MultiSelectSearchPane } from "./search/multiselect.search.pane"; +export { MultiSelectEditor } from "./trigger/editor.multiselect"; +export { MultiSelectTrigger } from "./multiselect.trigger"; +export { MultiSelectPopupView } from "./multiselect.popup.view"; +export { MultiSelectSearcher } from "./trigger/searcher.multiselect"; +export { MultiSelectCheckSelectedSwitcher } from "./trigger/switcher.checkselected"; export { MultiSelectCombo } from "./multiselect.combo"; export { MultiSelectNoBarCombo } from "./multiselect.combo.nobar"; export { MultiSelectInsertCombo } from "./multiselect.insert.combo"; diff --git a/src/widget/searchmultitextvaluecombo/index.js b/src/widget/searchmultitextvaluecombo/index.js new file mode 100644 index 000000000..1e711286d --- /dev/null +++ b/src/widget/searchmultitextvaluecombo/index.js @@ -0,0 +1,5 @@ +export { SearchMultiTextValueCombo } from "./multitextvalue.combo.search"; +export { SearchMultiSelectPopupView } from "./multitextvalue.popup.view.search"; +export { SearchMultiSelectTrigger } from "./multitextvalue.combo.trigger.search"; +export { SearchMultiSelectLoader } from "./multitextvalue.loader.search"; +export { SearchMultiSelectSearcher } from "./trigger/searcher.multitextvalue"; diff --git a/src/widget/searchmultitextvaluecombo/multitextvalue.combo.search.js b/src/widget/searchmultitextvaluecombo/multitextvalue.combo.search.js index 4fdbf42ee..4b8b3dc91 100644 --- a/src/widget/searchmultitextvaluecombo/multitextvalue.combo.search.js +++ b/src/widget/searchmultitextvaluecombo/multitextvalue.combo.search.js @@ -1,29 +1,44 @@ -/** - * - * @class BI.SearchMultiTextValueCombo - * @extends BI.Single - */ -BI.SearchMultiTextValueCombo = BI.inherit(BI.Single, { +import { shortcut, extend, isKey, Selection, remove, last, pushDistinct, deepClone, createWidget, toPix, isNotNull, initial, endWith, bind, nextTick, AbsoluteLayout, contains, map, makeObject, each, values, isNull, Func, isNotEmptyArray, isArray, find } from "@/core"; +import { Single, Combo } from "@/base"; +import { MultiSelectTrigger, MultiSelectPopupView, MultiSelectCombo, SearchMultiSelectTrigger, SearchMultiSelectPopupView } from "@/widget"; +import { MultiSelectBar, TriggerIconButton } from "@/case"; - _defaultConfig: function () { - return BI.extend(BI.SearchMultiTextValueCombo.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class SearchMultiTextValueCombo extends Single { + static xtype = "bi.search_multi_text_value_combo"; + + static REQ_GET_DATA_LENGTH = 1; + static REQ_GET_ALL_DATA = -1; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-combo bi-search-multi-text-value-combo", height: 24, - items: [] + items: [], }); - }, + } - _init: function () { - var self = this, o = this.options; - BI.SearchMultiTextValueCombo.superclass._init.apply(this, arguments); - var assertShowValue = function () { - BI.isKey(self._startValue) && (self.storeValue.type === BI.Selection.All ? BI.remove(self.storeValue.value, self._startValue) : BI.pushDistinct(self.storeValue.value, self._startValue)); - self._updateAllValue(); - self._checkError(); - self.trigger.getSearcher().setState(self.storeValue); - self.trigger.getCounter().setButtonChecked(self.storeValue); + _init() { + const o = this.options; + const triggerBtn = createWidget({ + type: TriggerIconButton.xtype, + width: o.height, + height: o.height, + cls: "multi-select-trigger-icon-button", + }); + super._init(...arguments); + const assertShowValue = () => { + isKey(this._startValue) && + (this.storeValue.type === Selection.All + ? remove(this.storeValue.value, this._startValue) + : pushDistinct(this.storeValue.value, this._startValue)); + this._updateAllValue(); + this._checkError(); + this.trigger.getSearcher().setState(this.storeValue); + this.trigger.getCounter().setButtonChecked(this.storeValue); }; - this.storeValue = BI.deepClone(o.value || {}); + this.storeValue = deepClone(o.value || {}); this._updateAllValue(); this._assertValue(this.storeValue); @@ -32,10 +47,10 @@ BI.SearchMultiTextValueCombo = BI.inherit(BI.Single, { // 标记正在请求数据 this.requesting = false; - this.trigger = BI.createWidget({ - type: "bi.search_multi_select_trigger", + this.trigger = createWidget({ + type: SearchMultiSelectTrigger.xtype, text: o.text, - height: BI.toPix(o.height, o.simple ? 1 : 2), + height: toPix(o.height, o.simple ? 1 : 2), // adapter: this.popup, masker: { offset: { @@ -45,437 +60,450 @@ BI.SearchMultiTextValueCombo = BI.inherit(BI.Single, { bottom: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + 1, }, }, - allValueGetter: function () { - return self.allValue; - }, + allValueGetter: () => this.allValue, valueFormatter: o.valueFormatter, - itemsCreator: function (op, callback) { - self._itemsCreator(op, function (res) { - if (op.times === 1 && BI.isNotNull(op.keywords)) { + itemsCreator: (op, callback) => { + this._itemsCreator(op, res => { + if (op.times === 1 && isNotNull(op.keywords)) { // 预防trigger内部把当前的storeValue改掉 - self.trigger.setValue(BI.deepClone(self.getValue())); + this.trigger.setValue(deepClone(this.getValue())); } - callback.apply(self, arguments); + callback.apply(this, ...arguments); }); }, value: this.storeValue, - warningTitle: o.warningTitle + warningTitle: o.warningTitle, }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_START, function () { - self._setStartValue(""); - this.getSearcher().setValue(self.storeValue); + this.trigger.on(MultiSelectTrigger.EVENT_START, () => { + this._setStartValue(""); + this.getSearcher().setValue(this.storeValue); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_STOP, function () { - self._setStartValue(""); + this.trigger.on(MultiSelectTrigger.EVENT_STOP, () => { + this._setStartValue(""); }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_SEARCHING, function (keywords) { - var last = BI.last(keywords); - keywords = BI.initial(keywords || []); - if (keywords.length > 0) { - self._joinKeywords(keywords, function () { - if (BI.endWith(last, BI.BlankSplitChar)) { - self.combo.setValue(self.storeValue); - assertShowValue(); - self.combo.populate(); - self._setStartValue(""); - } else { - self.combo.setValue(self.storeValue); - assertShowValue(); - } - self._dataChange = true; - }); + this.trigger.on( + MultiSelectTrigger.EVENT_SEARCHING, + keywords => { + const lastKeyWord = last(keywords); + keywords = initial(keywords || []); + if (keywords.length > 0) { + this._joinKeywords(keywords, () => { + if (endWith(lastKeyWord, BI.BlankSplitChar)) { + this.combo.setValue(this.storeValue); + assertShowValue(); + this.combo.populate(); + this._setStartValue(""); + } else { + this.combo.setValue(this.storeValue); + assertShowValue(); + } + this._dataChange = true; + }); + } } - }); + ); - this.trigger.on(BI.MultiSelectTrigger.EVENT_CHANGE, function (value, obj) { - if (obj instanceof BI.MultiSelectBar) { - self._joinAll(this.getValue(), function () { + this.trigger.on(MultiSelectTrigger.EVENT_CHANGE, (value, obj) => { + if (obj instanceof MultiSelectBar) { + this._joinAll(this.getValue(), () => { assertShowValue(); }); } else { - self._join(this.getValue(), function () { + this._join(this.getValue(), () => { assertShowValue(); }); } - self._dataChange = true; + this._dataChange = true; }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW, function () { - this.getCounter().setValue(self.storeValue); - }); - this.trigger.on(BI.MultiSelectTrigger.EVENT_COUNTER_CLICK, function () { - if (!self.combo.isViewVisible()) { - self.combo.showView(); + this.trigger.on( + MultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW, + () => { + this.getCounter().setValue(this.storeValue); + } + ); + this.trigger.on(MultiSelectTrigger.EVENT_COUNTER_CLICK, () => { + if (!this.combo.isViewVisible()) { + this.combo.showView(); } }); - this.combo = BI.createWidget({ - type: "bi.combo", + this.combo = createWidget({ + type: Combo.xtype, cls: o.simple ? "bi-border-bottom" : "bi-border bi-border-radius", toggle: false, container: o.container, el: this.trigger, adjustLength: 1, popup: { - type: "bi.search_multi_select_popup_view", - ref: function () { - self.popup = this; - self.trigger.setAdapter(this); + type: SearchMultiSelectPopupView.xtype, + ref: _ref => { + this.popup = _ref; + this.trigger.setAdapter(_ref); }, - listeners: [{ - eventName: BI.MultiSelectPopupView.EVENT_CHANGE, - action: function () { - self._dataChange = true; - self.storeValue = this.getValue(); - self._adjust(function () { - assertShowValue(); - }); + listeners: [ + { + eventName: MultiSelectPopupView.EVENT_CHANGE, + action :() => { + this._dataChange = true; + this.storeValue = this.getValue(); + this._adjust(() => { + assertShowValue(); + }); + }, + }, + { + eventName: MultiSelectPopupView.EVENT_CLICK_CONFIRM, + action :() => { + this._defaultState(); + }, + }, + { + eventName: MultiSelectPopupView.EVENT_CLICK_CLEAR, + action: () => { + this._dataChange = true; + this.setValue(); + this._defaultState(); + }, } - }, { - eventName: BI.MultiSelectPopupView.EVENT_CLICK_CONFIRM, - action: function () { - self._defaultState(); - } - }, { - eventName: BI.MultiSelectPopupView.EVENT_CLICK_CLEAR, - action: function () { - self._dataChange = true; - self.setValue(); - self._defaultState(); - } - }], - itemsCreator: BI.bind(self._itemsCreator, this), + ], + itemsCreator: bind(this._itemsCreator, this), valueFormatter: o.valueFormatter, - onLoaded: function () { - BI.nextTick(function () { - self.combo.adjustWidth(); - self.combo.adjustHeight(); - self.trigger.getCounter().adjustView(); - self.trigger.getSearcher().adjustView(); + onLoaded: () => { + nextTick(() => { + this.combo.adjustWidth(); + this.combo.adjustHeight(); + this.trigger.getCounter().adjustView(); + this.trigger.getSearcher().adjustView(); }); - } + }, }, value: o.value, - hideChecker: function (e) { - return triggerBtn.element.find(e.target).length === 0; - } + hideChecker: e => triggerBtn.element.find(e.target).length === 0, }); - this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { + this.combo.on(Combo.EVENT_BEFORE_POPUPVIEW, () => { if (!this.isViewVisible()) { - self._dataChange = false;// 标记数据是否发生变化 + this._dataChange = false; // 标记数据是否发生变化 } - this.setValue(self.storeValue); - BI.nextTick(function () { - self._populate(); + this.setValue(this.storeValue); + nextTick(() => { + this._populate(); }); }); // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; - this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { + this.combo.on(Combo.EVENT_AFTER_HIDEVIEW, () => { // important:关闭弹出时又可能没有退出编辑状态 - self.trigger.stopEditing(); - if (self.requesting === true) { - self.wants2Quit = true; + this.trigger.stopEditing(); + if (this.requesting === true) { + this.wants2Quit = true; } else { /** * 在存在标红的情况,如果popover没有发生改变就确认需要同步trigger的值,否则对外value值和trigger样式不统一 */ assertShowValue(); - self._dataChange && self.fireEvent(BI.SearchMultiTextValueCombo.EVENT_CONFIRM); + this._dataChange && + this.fireEvent(SearchMultiTextValueCombo.EVENT_CONFIRM); } }); - var triggerBtn = BI.createWidget({ - type: "bi.trigger_icon_button", - width: o.height, - height: o.height, - cls: "multi-select-trigger-icon-button" - }); - triggerBtn.on(BI.TriggerIconButton.EVENT_CHANGE, function () { - self.trigger.getCounter().hideView(); - if (self.combo.isViewVisible()) { - self.combo.hideView(); + triggerBtn.on(TriggerIconButton.EVENT_CHANGE, () => { + this.trigger.getCounter().hideView(); + if (this.combo.isViewVisible()) { + this.combo.hideView(); } else { - self.combo.showView(); + this.combo.showView(); } }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.combo, - left: 0, - right: 0, - top: 0, - bottom: 0 - }, { - el: triggerBtn, - right: 0, - top: 0, - bottom: 0 - }] + items: [ + { + el: this.combo, + left: 0, + right: 0, + top: 0, + bottom: 0, + }, + { + el: triggerBtn, + right: 0, + top: 0, + bottom: 0, + } + ], }); this._checkError(); - }, + } - _defaultState: function () { + _defaultState() { this.trigger.stopEditing(); this.combo.hideView(); - }, + } - _assertValue: function (val) { - var o = this.options; + _assertValue(val) { + const o = this.options; val || (val = {}); - val.type || (val.type = BI.Selection.Multi); + val.type || (val.type = Selection.Multi); val.value || (val.value = []); - BI.remove(val.value, function (idx, value) { - return !BI.contains(BI.map(o.items, "value"), value); - }); - }, + remove(val.value, (idx, value) => !contains(map(o.items, "value"), value)); + } - _makeMap: function (values) { - return BI.makeObject(values || []); - }, + _makeMap(values) { + return makeObject(values || []); + } - _joinKeywords: function (keywords, callback) { - var self = this, o = this.options; + _joinKeywords(keywords, callback) { this._assertValue(this.storeValue); this.requesting = true; - this._itemsCreator({ - type: BI.SearchMultiTextValueCombo.REQ_GET_ALL_DATA, - keywords: keywords - }, function (ob) { - var values = BI.map(ob.items, "value"); - digest(values); - }); - - function digest (items) { - var selectedMap = self._makeMap(items); - BI.each(keywords, function (i, val) { - if (BI.isNotNull(selectedMap[val])) { - self.storeValue.type === BI.Selection.Multi ? BI.pushDistinct(self.storeValue.value, val) : BI.remove(self.storeValue.value, val); + const digest = items => { + const selectedMap = this._makeMap(items); + each(keywords, (i, val) => { + if (isNotNull(selectedMap[val])) { + this.storeValue.type === Selection.Multi + ? pushDistinct(this.storeValue.value, val) + : remove(this.storeValue.value, val); } }); - self._adjust(callback); - } - }, + this._adjust(callback); + }; + this._itemsCreator( + { + type: SearchMultiTextValueCombo.REQ_GET_ALL_DATA, + keywords, + }, + ob => { + const values = map(ob.items, "value"); + digest(values); + } + ); + } - _joinAll: function (res, callback) { - var self = this, o = this.options; + _joinAll(res, callback) { this._assertValue(res); this.requesting = true; - this._itemsCreator({ - type: BI.SearchMultiTextValueCombo.REQ_GET_ALL_DATA, - keywords: [this.trigger.getKey()] - }, function (ob) { - var items = BI.map(ob.items, "value"); - if (self.storeValue.type === res.type) { - var change = false; - var map = self._makeMap(self.storeValue.value); - BI.each(items, function (i, v) { - if (BI.isNotNull(map[v])) { - change = true; - self.storeValue.assist && self.storeValue.assist.push(map[v]); - delete map[v]; + this._itemsCreator( + { + type: SearchMultiTextValueCombo.REQ_GET_ALL_DATA, + keywords: [this.trigger.getKey()], + }, + ob => { + const map = this._makeMap(this.storeValue.value); + const items = map(ob.items, "value"); + if (this.storeValue.type === res.type) { + let change = false; + each(items, (i, v) => { + if (isNotNull(map[v])) { + change = true; + this.storeValue.assist && + this.storeValue.assist.push(map[v]); + delete map[v]; + } + }); + change && (this.storeValue.value = values(map)); + this._adjust(callback); + + return; + } + const selectedMap = this._makeMap(this.storeValue.value); + const notSelectedMap = this._makeMap(res.value); + const newItems = []; + each(items, (i, item) => { + if (isNotNull(selectedMap[items[i]])) { + this.storeValue.assist && + this.storeValue.assist.push(selectedMap[items[i]]); + delete selectedMap[items[i]]; + } + if (isNull(notSelectedMap[items[i]])) { + remove(this.storeValue.assist, item); + newItems.push(item); } }); - change && (self.storeValue.value = BI.values(map)); - self._adjust(callback); - return; + this.storeValue.value = newItems.concat(values(selectedMap)); + this._adjust(callback); } - var selectedMap = self._makeMap(self.storeValue.value); - var notSelectedMap = self._makeMap(res.value); - var newItems = []; - BI.each(items, function (i, item) { - if (BI.isNotNull(selectedMap[items[i]])) { - self.storeValue.assist && self.storeValue.assist.push(selectedMap[items[i]]); - delete selectedMap[items[i]]; - } - if (BI.isNull(notSelectedMap[items[i]])) { - BI.remove(self.storeValue.assist, item); - newItems.push(item); - } - }); - self.storeValue.value = newItems.concat(BI.values(selectedMap)); - self._adjust(callback); - }); - }, - - _adjust: function (callback) { - var self = this, o = this.options; - if (!this._count) { - this._itemsCreator({ - type: BI.SearchMultiTextValueCombo.REQ_GET_DATA_LENGTH - }, function (res) { - self._count = res.count; - adjust(); - callback(); - }); - } else { - adjust(); - callback(); - - } + ); + } - function adjust () { - if (self.storeValue.type === BI.Selection.All && self.storeValue.value.length >= self._count) { - self.storeValue = { - type: BI.Selection.Multi, - value: [] + _adjust(callback) { + const adjust = () => { + if ( + this.storeValue.type === Selection.All && + this.storeValue.value.length >= this._count + ) { + this.storeValue = { + type: Selection.Multi, + value: [], }; - } else if (self.storeValue.type === BI.Selection.Multi && self.storeValue.value.length >= self._count) { - self.storeValue = { - type: BI.Selection.All, - value: [] + } else if ( + this.storeValue.type === Selection.Multi && + this.storeValue.value.length >= this._count + ) { + this.storeValue = { + type: Selection.All, + value: [], }; } - self._updateAllValue(); - self._checkError(); - if (self.wants2Quit === true) { - self._dataChange && self.fireEvent(BI.SearchMultiTextValueCombo.EVENT_CONFIRM); - self.wants2Quit = false; + this._updateAllValue(); + this._checkError(); + if (this.wants2Quit === true) { + this._dataChange && + this.fireEvent(SearchMultiTextValueCombo.EVENT_CONFIRM); + this.wants2Quit = false; } - self.requesting = false; + this.requesting = false; + }; + if (!this._count) { + this._itemsCreator( + { + type: SearchMultiTextValueCombo.REQ_GET_DATA_LENGTH, + }, + res => { + this._count = res.count; + adjust(); + callback(); + } + ); + } else { + adjust(); + callback(); } - }, + } - _join: function (res, callback) { - var self = this, o = this.options; + _join(res, callback) { this._assertValue(res); this._assertValue(this.storeValue); if (this.storeValue.type === res.type) { - var map = this._makeMap(this.storeValue.value); - BI.each(res.value, function (i, v) { + const map = this._makeMap(this.storeValue.value); + each(res.value, (i, v) => { if (!map[v]) { - self.storeValue.value.push(v); - BI.remove(self.storeValue.assist, v); + this.storeValue.value.push(v); + remove(this.storeValue.assist, v); map[v] = v; } }); - var change = false; - BI.each(res.assist, function (i, v) { - if (BI.isNotNull(map[v])) { + let change = false; + each(res.assist, (i, v) => { + if (isNotNull(map[v])) { change = true; - self.storeValue.assist && self.storeValue.assist.push(map[v]); + this.storeValue.assist && + this.storeValue.assist.push(map[v]); delete map[v]; } }); - change && (this.storeValue.value = BI.values(map)); - self._adjust(callback); + change && (this.storeValue.value = values(map)); + this._adjust(callback); + return; } this._joinAll(res, callback); - }, + } - _setStartValue: function (value) { + _setStartValue(value) { this._startValue = value; this.popup.setStartValue(value); - }, + } - _getItemsByTimes: function (items, times) { - var res = []; - for (var i = (times - 1) * 100; items[i] && i < times * 100; i++) { + _getItemsByTimes(items, times) { + const res = []; + for (let i = (times - 1) * 100; items[i] && i < times * 100; i++) { res.push(items[i]); } + return res; - }, + } - _hasNextByTimes: function (items, times) { + _hasNextByTimes(items, times) { return times * 100 < items.length; - }, + } - _itemsCreator: function (options, callback) { - var self = this, o = this.options; - var items = o.items; - var keywords = (options.keywords || []).slice(); + _itemsCreator(options, callback) { + const o = this.options; + let items = o.items; + const keywords = (options.keywords || []).slice(); if (options.keyword) { keywords.push(options.keyword); } - BI.each(keywords, function (i, kw) { - var search = BI.Func.getSearchResult(items, kw); + each(keywords, (i, kw) => { + const search = Func.getSearchResult(items, kw); items = search.match.concat(search.find); }); - if (options.selectedValues) {// 过滤 - var filter = BI.makeObject(options.selectedValues, true); - items = BI.filter(items, function (i, ob) { - return !filter[ob.value]; - }); + if (options.selectedValues) { + // 过滤 + const filter = makeObject(options.selectedValues, true); + items = filter(items, (i, ob) => !filter[ob.value]); } - if (options.type == BI.MultiSelectCombo.REQ_GET_ALL_DATA) { + if (options.type === MultiSelectCombo.REQ_GET_ALL_DATA) { callback({ - items: items + items, }); + return; } - if (options.type == BI.MultiSelectCombo.REQ_GET_DATA_LENGTH) { - callback({count: items.length}); + if (options.type === MultiSelectCombo.REQ_GET_DATA_LENGTH) { + callback({ count: items.length }); + return; } callback({ - items: self._getItemsByTimes(items, options.times), - hasNext: self._hasNextByTimes(items, options.times) + items: this._getItemsByTimes(items, options.times), + hasNext: this._hasNextByTimes(items, options.times), }); - }, + } - _checkError: function () { - var v = this.storeValue.value || []; - if(BI.isNotEmptyArray(v)) { - v = BI.isArray(v) ? v : [v]; - var result = BI.find(this.allValue, function (idx, value) { - return !BI.contains(v, value); - }); - if (BI.isNull(result)) { - BI.isNotNull(this.trigger) && (this.trigger.setTipType("success")); + _checkError() { + let v = this.storeValue.value || []; + if (isNotEmptyArray(v)) { + v = isArray(v) ? v : [v]; + const result = find(this.allValue, (idx, value) => !contains(v, value)); + if (isNull(result)) { + isNotNull(this.trigger) && this.trigger.setTipType("success"); this.element.removeClass("combo-error"); } else { - BI.isNotNull(this.trigger) && (this.trigger.setTipType("warning")); + isNotNull(this.trigger) && this.trigger.setTipType("warning"); this.element.addClass("combo-error"); } } else { - if(v.length === this.allValue.length){ - BI.isNotNull(this.trigger) && (this.trigger.setTipType("success")); + if (v.length === this.allValue.length) { + isNotNull(this.trigger) && this.trigger.setTipType("success"); this.element.removeClass("combo-error"); - }else { - BI.isNotNull(this.trigger) && (this.trigger.setTipType("warning")); + } else { + isNotNull(this.trigger) && this.trigger.setTipType("warning"); this.element.addClass("combo-error"); } } - }, + } - _updateAllValue: function () { + _updateAllValue() { this.storeValue = this.storeValue || {}; - this.allValue = BI.deepClone(this.storeValue.value || []); - }, + this.allValue = deepClone(this.storeValue.value || []); + } - setValue: function (v) { - this.storeValue = BI.deepClone(v || {}); + setValue(v) { + this.storeValue = deepClone(v || {}); this._updateAllValue(); this._assertValue(this.storeValue); this.combo.setValue(this.storeValue); this._checkError(); - }, + } - getValue: function () { - return BI.deepClone(this.storeValue); - }, + getValue() { + return deepClone(this.storeValue); + } - _populate: function () { + _populate() { this._count = null; this.combo.populate(); - }, + } - populate: function (items) { + populate(items) { this.options.items = items; this._populate(); } -}); - -BI.extend(BI.SearchMultiTextValueCombo, { +} +extend(SearchMultiTextValueCombo, { REQ_GET_DATA_LENGTH: 1, - REQ_GET_ALL_DATA: -1 + REQ_GET_ALL_DATA: -1, }); - -BI.SearchMultiTextValueCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; - -BI.shortcut("bi.search_multi_text_value_combo", BI.SearchMultiTextValueCombo); diff --git a/src/widget/searchmultitextvaluecombo/multitextvalue.combo.trigger.search.js b/src/widget/searchmultitextvaluecombo/multitextvalue.combo.trigger.search.js index 3256994ae..ba9dae06a 100644 --- a/src/widget/searchmultitextvaluecombo/multitextvalue.combo.trigger.search.js +++ b/src/widget/searchmultitextvaluecombo/multitextvalue.combo.trigger.search.js @@ -1,31 +1,44 @@ -BI.SearchMultiSelectTrigger = BI.inherit(BI.Trigger, { +import { shortcut, extend, emptyFn, createWidget, Events, nextTick, HTapeLayout, RightVerticalAdaptLayout } from "@/core"; +import { Trigger } from "@/base"; +import { MultiSelectCheckSelectedSwitcher, MultiSelectSearcher, SearchMultiSelectSearcher } from "@/widget"; - constants: { - height: 14, - rgap: 4, - lgap: 4 - }, +@shortcut() +export class SearchMultiSelectTrigger extends Trigger { + static xtype = "bi.search_multi_select_trigger"; - _defaultConfig: function () { - return BI.extend(BI.SearchMultiSelectTrigger.superclass._defaultConfig.apply(this, arguments), { + constants = { height: 14, rgap: 4, lgap: 4 }; + + static EVENT_TRIGGER_CLICK = "EVENT_TRIGGER_CLICK"; + static EVENT_COUNTER_CLICK = "EVENT_COUNTER_CLICK"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_START = "EVENT_START"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + static EVENT_BEFORE_COUNTER_POPUPVIEW = "EVENT_BEFORE_COUNTER_POPUPVIEW"; + + _defaultConfig() { + const conf = super._defaultConfig(...arguments); + + return extend(conf, { baseCls: "bi-multi-select-trigger", - itemsCreator: BI.emptyFn, - valueFormatter: BI.emptyFn, + itemsCreator: emptyFn, + valueFormatter: emptyFn, searcher: {}, switcher: {}, adapter: null, - masker: {} + masker: {}, }); - }, + } - _init: function () { - BI.SearchMultiSelectTrigger.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, o = this.options; + const o = this.options; - this.searcher = BI.createWidget(o.searcher, { - type: "bi.search_multi_select_searcher", + this.searcher = createWidget(o.searcher, { + type: SearchMultiSelectSearcher.xtype, height: o.height, itemsCreator: o.itemsCreator, valueFormatter: o.valueFormatter, @@ -36,119 +49,125 @@ BI.SearchMultiSelectTrigger = BI.inherit(BI.Trigger, { value: o.value, text: o.text, tipType: o.tipType, - warningTitle: o.warningTitle + warningTitle: o.warningTitle, }); - this.searcher.on(BI.MultiSelectSearcher.EVENT_START, function () { - self.fireEvent(BI.SearchMultiSelectTrigger.EVENT_START); + this.searcher.on(MultiSelectSearcher.EVENT_START, () => { + this.fireEvent(SearchMultiSelectTrigger.EVENT_START); }); - this.searcher.on(BI.MultiSelectSearcher.EVENT_PAUSE, function () { - self.fireEvent(BI.SearchMultiSelectTrigger.EVENT_PAUSE); + this.searcher.on(MultiSelectSearcher.EVENT_PAUSE, () => { + this.fireEvent(SearchMultiSelectTrigger.EVENT_PAUSE); }); - this.searcher.on(BI.MultiSelectSearcher.EVENT_SEARCHING, function () { - self.fireEvent(BI.SearchMultiSelectTrigger.EVENT_SEARCHING, arguments); + this.searcher.on(MultiSelectSearcher.EVENT_SEARCHING, () => { + this.fireEvent(SearchMultiSelectTrigger.EVENT_SEARCHING, ...arguments); }); - this.searcher.on(BI.MultiSelectSearcher.EVENT_STOP, function () { - self.fireEvent(BI.SearchMultiSelectTrigger.EVENT_STOP); + this.searcher.on(MultiSelectSearcher.EVENT_STOP, () => { + this.fireEvent(SearchMultiSelectTrigger.EVENT_STOP); }); - this.searcher.on(BI.MultiSelectSearcher.EVENT_CHANGE, function () { - self.fireEvent(BI.SearchMultiSelectTrigger.EVENT_CHANGE, arguments); + this.searcher.on(MultiSelectSearcher.EVENT_CHANGE, () => { + this.fireEvent(SearchMultiSelectTrigger.EVENT_CHANGE, ...arguments); }); - this.numberCounter = BI.createWidget(o.switcher, { - type: "bi.multi_select_check_selected_switcher", + this.numberCounter = createWidget(o.switcher, { + type: MultiSelectCheckSelectedSwitcher.xtype, valueFormatter: o.valueFormatter, itemsCreator: o.itemsCreator, adapter: o.adapter, masker: o.masker, - value: o.value - }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE, function () { - self.fireEvent(BI.SearchMultiSelectTrigger.EVENT_COUNTER_CLICK); - }); - this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW, function () { - self.fireEvent(BI.SearchMultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW); + value: o.value, }); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE, + () => { + this.fireEvent(SearchMultiSelectTrigger.EVENT_COUNTER_CLICK); + } + ); + this.numberCounter.on( + MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW, + () => { + this.fireEvent( + SearchMultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW + ); + } + ); - var wrapNumberCounter = BI.createWidget({ - type: "bi.right_vertical_adapt", + const wrapNumberCounter = createWidget({ + type: RightVerticalAdaptLayout.xtype, hgap: 4, - items: [{ - el: this.numberCounter - }] + items: [ + { + el: this.numberCounter, + } + ], }); - var wrapper = BI.createWidget({ - type: "bi.htape", + const wrapper = createWidget({ + type: HTapeLayout.xtype, element: this, items: [ { el: this.searcher, - width: "fill" - }, { + width: "fill", + }, + { el: wrapNumberCounter, - width: 0 - }, { - el: BI.createWidget(), - width: 24 - }] + width: 0, + }, + { + el: createWidget(), + width: 24, + } + ], }); - this.numberCounter.on(BI.Events.VIEW, function (b) { - BI.nextTick(function () {// 自动调整宽度 - wrapper.attr("items")[1].width = (b === true ? self.numberCounter.element.outerWidth() + 8 : 0); + this.numberCounter.on(Events.VIEW, b => { + nextTick(() => { + // 自动调整宽度 + wrapper.attr("items")[1].width = + b === true + ? this.numberCounter.element.outerWidth() + 8 + : 0; wrapper.resize(); }); }); - this.element.click(function (e) { - if (self.element.find(e.target).length > 0) { - self.numberCounter.hideView(); + this.element.click(e => { + if (this.element.find(e.target).length > 0) { + this.numberCounter.hideView(); } }); - }, + } - getCounter: function () { + getCounter() { return this.numberCounter; - }, + } - getSearcher: function () { + getSearcher() { return this.searcher; - }, + } - stopEditing: function () { + stopEditing() { this.searcher.stopSearch(); this.numberCounter.hideView(); - }, + } - setAdapter: function (adapter) { + setAdapter(adapter) { this.searcher.setAdapter(adapter); this.numberCounter.setAdapter(adapter); - }, + } - setValue: function (ob) { + setValue(ob) { this.searcher.setValue(ob); this.numberCounter.setValue(ob); - }, + } - setTipType: function (v) { + setTipType(v) { this.searcher.setTipType(v); - }, + } - getKey: function () { + getKey() { return this.searcher.getKey(); - }, + } - getValue: function () { + getValue() { return this.searcher.getValue(); } -}); - -BI.SearchMultiSelectTrigger.EVENT_TRIGGER_CLICK = "EVENT_TRIGGER_CLICK"; -BI.SearchMultiSelectTrigger.EVENT_COUNTER_CLICK = "EVENT_COUNTER_CLICK"; -BI.SearchMultiSelectTrigger.EVENT_CHANGE = "EVENT_CHANGE"; -BI.SearchMultiSelectTrigger.EVENT_START = "EVENT_START"; -BI.SearchMultiSelectTrigger.EVENT_STOP = "EVENT_STOP"; -BI.SearchMultiSelectTrigger.EVENT_PAUSE = "EVENT_PAUSE"; -BI.SearchMultiSelectTrigger.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.SearchMultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW = "EVENT_BEFORE_COUNTER_POPUPVIEW"; - -BI.shortcut("bi.search_multi_select_trigger", BI.SearchMultiSelectTrigger); +} diff --git a/src/widget/searchmultitextvaluecombo/multitextvalue.loader.search.js b/src/widget/searchmultitextvaluecombo/multitextvalue.loader.search.js index 59113111e..d03a6865f 100644 --- a/src/widget/searchmultitextvaluecombo/multitextvalue.loader.search.js +++ b/src/widget/searchmultitextvaluecombo/multitextvalue.loader.search.js @@ -1,184 +1,202 @@ -/** - * 多选加载数据面板 - * Created by guy on 15/11/2. - * @class BI.SearchMultiSelectLoader - * @extends Widget - */ -BI.SearchMultiSelectLoader = BI.inherit(BI.Widget, { - - _defaultConfig: function () { - return BI.extend(BI.SearchMultiSelectLoader.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, Widget, extend, emptyFn, createWidget, isKey, Selection, map, contains, remove, pushDistinct, Controller, VerticalLayout, createItems, delay, isNotNull } from "@/core"; +import { ButtonGroup, Loader } from "@/base"; +import { SelectList, MultiSelectBar, MultiSelectItem } from "@/case"; + +@shortcut() +export class SearchMultiSelectLoader extends Widget { + static xtype = "bi.search_multi_select_loader"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-loader", logic: { - dynamic: true + dynamic: true, }, el: { - height: 400 + height: 400, }, - valueFormatter: BI.emptyFn, - itemsCreator: BI.emptyFn, + valueFormatter: emptyFn, + itemsCreator: emptyFn, itemHeight: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - onLoaded: BI.emptyFn + onLoaded: emptyFn, }); - }, + } - _init: function () { - BI.SearchMultiSelectLoader.superclass._init.apply(this, arguments); + _init() { + super._init(...arguments); - var self = this, opts = this.options; - var hasNext = false; + const opts = this.options; + let hasNext = false; this.storeValue = opts.value || {}; this._assertValue(this.storeValue); - this.button_group = BI.createWidget({ - type: "bi.select_list", + this.button_group = createWidget({ + type: SelectList.xtype, element: this, logic: opts.logic, toolbar: { - type: "bi.multi_select_bar", + type: MultiSelectBar.xtype, cls: "bi-list-item-active", height: this.options.itemHeight, - iconWrapperWidth: 36 + iconWrapperWidth: 36, }, - el: BI.extend({ - onLoaded: opts.onLoaded, - el: { - type: "bi.loader", - isDefaultInit: false, - logic: { - dynamic: true, - scrolly: true - }, + el: extend( + { + onLoaded: opts.onLoaded, el: { - chooseType: BI.ButtonGroup.CHOOSE_TYPE_MULTI, - behaviors: { - redmark: function () { - return true; - } + type: Loader.xtype, + isDefaultInit: false, + logic: { + dynamic: true, + scrolly: true, }, - layouts: [{ - type: "bi.vertical" - }] - } - } - }, opts.el), - itemsCreator: function (op, callback) { - var startValue = self._startValue; - self.storeValue && (op = BI.extend(op || {}, { - selectedValues: BI.isKey(startValue) && self.storeValue.type === BI.Selection.Multi - ? self.storeValue.value.concat(startValue) : self.storeValue.value - })); - opts.itemsCreator(op, function (ob) { + el: { + chooseType: ButtonGroup.CHOOSE_TYPE_MULTI, + behaviors: { + redmark: () => true, + }, + layouts: [ + { + type: VerticalLayout.xtype, + } + ], + }, + }, + }, + opts.el + ), + itemsCreator: (op, callback) => { + const startValue = this._startValue; + this.storeValue && + (op = extend(op || {}, { + selectedValues: + isKey(startValue) && + this.storeValue.type === Selection.Multi + ? this.storeValue.value.concat(startValue) + : this.storeValue.value, + })); + opts.itemsCreator(op, ob => { hasNext = ob.hasNext; - var firstItems = []; - if (op.times === 1 && self.storeValue) { - var json = BI.map(self.storeValue.value, function (i, v) { - var txt = opts.valueFormatter(v) || v; + let firstItems = []; + if (op.times === 1 && this.storeValue) { + const json = map(this.storeValue.value, (i, v) => { + const txt = opts.valueFormatter(v) || v; + return { text: txt, value: v, title: txt, - selected: self.storeValue.type === BI.Selection.Multi + selected: + this.storeValue.type === Selection.Multi, }; }); - if (BI.isKey(self._startValue) && !BI.contains(self.storeValue.value, self._startValue)) { - var txt = opts.valueFormatter(startValue) || startValue; + if ( + isKey(this._startValue) && + !contains(this.storeValue.value, this._startValue) + ) { + const txt = + opts.valueFormatter(startValue) || startValue; json.unshift({ text: txt, value: startValue, title: txt, - selected: true + selected: true, }); } - firstItems = self._createItems(json); + firstItems = this._createItems(json); } - callback(firstItems.concat(self._createItems(ob.items)), ob.keyword || ""); - if (op.times === 1 && self.storeValue) { - BI.isKey(startValue) && (self.storeValue.type === BI.Selection.All ? BI.remove(self.storeValue.value, startValue) : BI.pushDistinct(self.storeValue.value, startValue)); - self.setValue(self.storeValue); + callback( + firstItems.concat(this._createItems(ob.items)), + ob.keyword || "" + ); + if (op.times === 1 && this.storeValue) { + isKey(startValue) && + (this.storeValue.type === Selection.All + ? remove(this.storeValue.value, startValue) + : pushDistinct( + this.storeValue.value, + startValue + )); + this.setValue(this.storeValue); } - (op.times === 1) && self._scrollToTop(); + op.times === 1 && this._scrollToTop(); }); }, - hasNext: function () { - return hasNext; - }, - value: this.storeValue + hasNext: () => hasNext, + value: this.storeValue, }); - this.button_group.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + this.button_group.on(Controller.EVENT_CHANGE, () => { + this.fireEvent(Controller.EVENT_CHANGE, arguments); }); - this.button_group.on(BI.SelectList.EVENT_CHANGE, function () { - self.fireEvent(BI.SearchMultiSelectLoader.EVENT_CHANGE, arguments); + this.button_group.on(SelectList.EVENT_CHANGE, () => { + this.fireEvent(SearchMultiSelectLoader.EVENT_CHANGE, ...arguments); }); - }, + } - _createItems: function (items) { - return BI.createItems(items, { - type: "bi.multi_select_item", + _createItems(items) { + return createItems(items, { + type: MultiSelectItem.xtype, logic: this.options.logic, cls: "bi-list-item-active", height: this.options.itemHeight, selected: this.isAllSelected(), - iconWrapperWidth: 36 + iconWrapperWidth: 36, }); - }, + } - _scrollToTop: function () { - var self = this; - BI.delay(function () { - self.button_group.element.scrollTop(0); + _scrollToTop() { + delay(() => { + this.button_group.element.scrollTop(0); }, 30); - }, + } - isAllSelected: function () { + isAllSelected() { return this.button_group.isAllSelected(); - }, + } - _assertValue: function (val) { + _assertValue(val) { val || (val = {}); - val.type || (val.type = BI.Selection.Multi); + val.type || (val.type = Selection.Multi); val.value || (val.value = []); - }, + } - setStartValue: function (v) { + setStartValue(v) { this._startValue = v; - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v || {}; this._assertValue(this.storeValue); this.button_group.setValue(this.storeValue); - }, + } - getValue: function () { + getValue() { return this.button_group.getValue(); - }, + } - getAllButtons: function () { + getAllButtons() { return this.button_group.getAllButtons(); - }, + } - empty: function () { + empty() { this.button_group.empty(); - }, + } - populate: function (items) { - if (BI.isNotNull(items)) { + populate(items) { + if (isNotNull(items)) { arguments[0] = this._createItems(items); } - this.button_group.populate.apply(this.button_group, arguments); - }, + this.button_group.populate(...arguments); + } - resetHeight: function (h) { + resetHeight(h) { this.button_group.resetHeight(h); - }, + } - resetWidth: function (w) { + resetWidth(w) { this.button_group.resetWidth(w); } -}); - -BI.SearchMultiSelectLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.search_multi_select_loader", BI.SearchMultiSelectLoader); \ No newline at end of file +} diff --git a/src/widget/searchmultitextvaluecombo/multitextvalue.popup.view.search.js b/src/widget/searchmultitextvaluecombo/multitextvalue.popup.view.search.js index cb8027f0c..d2db9c7dd 100644 --- a/src/widget/searchmultitextvaluecombo/multitextvalue.popup.view.search.js +++ b/src/widget/searchmultitextvaluecombo/multitextvalue.popup.view.search.js @@ -1,92 +1,104 @@ -BI.SearchMultiSelectPopupView = BI.inherit(BI.Widget, { +import { shortcut, Widget, extend, emptyFn, createWidget, i18nText } from "@/core"; +import { MultiPopupView } from "@/case"; +import { SearchMultiSelectLoader } from "@/widget"; - _defaultConfig: function () { - return BI.extend(BI.SearchMultiSelectPopupView.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class SearchMultiSelectPopupView extends Widget { + static xtype = "bi.search_multi_select_popup_view"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_CLICK_CONFIRM = "EVENT_CLICK_CONFIRM"; + static EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-popup-view", maxWidth: "auto", minWidth: 135, maxHeight: 400, - valueFormatter: BI.emptyFn, - itemsCreator: BI.emptyFn, - onLoaded: BI.emptyFn + valueFormatter: emptyFn, + itemsCreator: emptyFn, + onLoaded: emptyFn, }); - }, + } - _init: function () { - BI.SearchMultiSelectPopupView.superclass._init.apply(this, arguments); - var self = this, opts = this.options; + _init() { + super._init(...arguments); + const opts = this.options; - this.loader = BI.createWidget({ - type: "bi.search_multi_select_loader", + this.loader = createWidget({ + type: SearchMultiSelectLoader.xtype, itemsCreator: opts.itemsCreator, valueFormatter: opts.valueFormatter, onLoaded: opts.onLoaded, - value: opts.value + value: opts.value, }); - this.popupView = BI.createWidget({ - type: "bi.multi_popup_view", + this.popupView = createWidget({ + type: MultiPopupView.xtype, stopPropagation: false, maxWidth: opts.maxWidth, minWidth: opts.minWidth, maxHeight: opts.maxHeight, element: this, - buttons: [BI.i18nText("BI-Basic_Clears"), BI.i18nText("BI-Basic_OK")], + buttons: [i18nText("BI-Basic_Clears"), i18nText("BI-Basic_OK")], el: this.loader, - value: opts.value + value: opts.value, }); - this.popupView.on(BI.MultiPopupView.EVENT_CHANGE, function () { - self.fireEvent(BI.SearchMultiSelectPopupView.EVENT_CHANGE); + this.popupView.on(MultiPopupView.EVENT_CHANGE, () => { + this.fireEvent(SearchMultiSelectPopupView.EVENT_CHANGE); }); - this.popupView.on(BI.MultiPopupView.EVENT_CLICK_TOOLBAR_BUTTON, function (index) { - switch (index) { + this.popupView.on( + MultiPopupView.EVENT_CLICK_TOOLBAR_BUTTON, + index => { + switch (index) { case 0: - self.fireEvent(BI.SearchMultiSelectPopupView.EVENT_CLICK_CLEAR); + this.fireEvent( + SearchMultiSelectPopupView.EVENT_CLICK_CLEAR + ); break; case 1: - self.fireEvent(BI.SearchMultiSelectPopupView.EVENT_CLICK_CONFIRM); + this.fireEvent( + SearchMultiSelectPopupView.EVENT_CLICK_CONFIRM + ); break; + default: + break; + } } - }); - }, + ); + } - isAllSelected: function () { + isAllSelected() { return this.loader.isAllSelected(); - }, + } - setStartValue: function (v) { + setStartValue(v) { this.loader.setStartValue(v); - }, + } - setValue: function (v) { + setValue(v) { this.popupView.setValue(v); - }, + } - getValue: function () { + getValue() { return this.popupView.getValue(); - }, + } - populate: function (items) { - this.popupView.populate.apply(this.popupView, arguments); - }, + populate(items) { + this.popupView.populate(...arguments); + } - resetHeight: function (h) { + resetHeight(h) { this.popupView.resetHeight(h); - }, + } - resetWidth: function (w) { + resetWidth(w) { this.popupView.resetWidth(w); - }, + } - setDirection: function (direction, position) { + setDirection(direction, position) { this.popupView.setDirection(direction, position); - }, -}); - -BI.SearchMultiSelectPopupView.EVENT_CHANGE = "EVENT_CHANGE"; -BI.SearchMultiSelectPopupView.EVENT_CLICK_CONFIRM = "EVENT_CLICK_CONFIRM"; -BI.SearchMultiSelectPopupView.EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; - - -BI.shortcut("bi.search_multi_select_popup_view", BI.SearchMultiSelectPopupView); + } +} diff --git a/src/widget/searchmultitextvaluecombo/trigger/searcher.multitextvalue.js b/src/widget/searchmultitextvaluecombo/trigger/searcher.multitextvalue.js index 506532b3c..a59d7582d 100644 --- a/src/widget/searchmultitextvaluecombo/trigger/searcher.multitextvalue.js +++ b/src/widget/searchmultitextvaluecombo/trigger/searcher.multitextvalue.js @@ -1,175 +1,179 @@ -BI.SearchMultiSelectSearcher = BI.inherit(BI.Widget, { - - _defaultConfig: function () { - return BI.extend(BI.SearchMultiSelectSearcher.superclass._defaultConfig.apply(this, arguments), { +import { shortcut, Widget, extend, emptyFn, createWidget, isNotNull, Selection, size, each } from "@/core"; +import { Searcher } from "@/base"; +import { MultiSelectEditor, MultiSelectSearchPane } from "@/widget"; + +@shortcut() +export class SearchMultiSelectSearcher extends Widget { + static xtype = "bi.search_multi_select_searcher"; + + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_START = "EVENT_START"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_SEARCHING = "EVENT_SEARCHING"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-multi-select-searcher", - itemsCreator: BI.emptyFn, + itemsCreator: emptyFn, el: {}, popup: {}, - valueFormatter: BI.emptyFn, + valueFormatter: emptyFn, adapter: null, - masker: {} + masker: {}, }); - }, + } - _init: function () { - BI.SearchMultiSelectSearcher.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.editor = BI.createWidget(o.el, { - type: "bi.multi_select_editor", + _init() { + super._init(...arguments); + const o = this.options; + this.editor = createWidget(o.el, { + type: MultiSelectEditor.xtype, height: o.height, text: o.text, tipType: o.tipType, - warningTitle: o.warningTitle + warningTitle: o.warningTitle, }); - this.searcher = BI.createWidget({ - type: "bi.searcher", + this.searcher = createWidget({ + type: Searcher.xtype, element: this, height: o.height, isAutoSearch: false, isAutoSync: false, - onSearch: function (op, callback) { + onSearch: (op, callback) => { callback(); }, el: this.editor, - popup: BI.extend({ - type: "bi.multi_select_search_pane", - valueFormatter: o.valueFormatter, - keywordGetter: function () { - return self.editor.getValue(); - }, - itemsCreator: function (op, callback) { - var keyword = self.editor.getValue(); - op.keywords = [keyword]; - o.itemsCreator(op, callback); + popup: extend( + { + type: MultiSelectSearchPane.xtype, + valueFormatter: o.valueFormatter, + keywordGetter: () => this.editor.getValue(), + itemsCreator: (op, callback) => { + const keyword = this.editor.getValue(); + op.keywords = [keyword]; + o.itemsCreator(op, callback); + }, + value: o.value, }, - value: o.value - }, o.popup), + o.popup + ), adapter: o.adapter, - masker: o.masker + masker: o.masker, }); - this.searcher.on(BI.Searcher.EVENT_START, function () { - self.fireEvent(BI.SearchMultiSelectSearcher.EVENT_START); + this.searcher.on(Searcher.EVENT_START, () => { + this.fireEvent(SearchMultiSelectSearcher.EVENT_START); }); - this.searcher.on(BI.Searcher.EVENT_PAUSE, function () { - if (this.hasMatched()) { - - } - self.fireEvent(BI.SearchMultiSelectSearcher.EVENT_PAUSE); + this.searcher.on(Searcher.EVENT_PAUSE, () => { + this.fireEvent(SearchMultiSelectSearcher.EVENT_PAUSE); }); - this.searcher.on(BI.Searcher.EVENT_STOP, function () { - self.fireEvent(BI.SearchMultiSelectSearcher.EVENT_STOP); + this.searcher.on(Searcher.EVENT_STOP, () => { + this.fireEvent(SearchMultiSelectSearcher.EVENT_STOP); }); - this.searcher.on(BI.Searcher.EVENT_CHANGE, function () { - self.fireEvent(BI.SearchMultiSelectSearcher.EVENT_CHANGE, arguments); + this.searcher.on(Searcher.EVENT_CHANGE, () => { + this.fireEvent(SearchMultiSelectSearcher.EVENT_CHANGE, ...arguments); }); - this.searcher.on(BI.Searcher.EVENT_SEARCHING, function () { - var keywords = this.getKeywords(); - self.fireEvent(BI.SearchMultiSelectSearcher.EVENT_SEARCHING, keywords); + this.searcher.on(Searcher.EVENT_SEARCHING, () => { + const keywords = this.getKeywords(); + this.fireEvent(SearchMultiSelectSearcher.EVENT_SEARCHING, keywords); }); - if(BI.isNotNull(o.value)) { + if (isNotNull(o.value)) { this.setState(o.value); } - }, + } - adjustView: function () { + adjustView() { this.searcher.adjustView(); - }, + } - isSearching: function () { + isSearching() { return this.searcher.isSearching(); - }, + } - stopSearch: function () { + stopSearch() { this.searcher.stopSearch(); - }, + } - getKeyword: function () { + getKeyword() { return this.editor.getValue(); - }, + } - hasMatched: function () { + hasMatched() { return this.searcher.hasMatched(); - }, + } - hasChecked: function () { + hasChecked() { return this.searcher.getView() && this.searcher.getView().hasChecked(); - }, + } - setAdapter: function (adapter) { + setAdapter(adapter) { this.searcher.setAdapter(adapter); - }, + } - setState: function (obj) { - var o = this.options; - var ob = {}; + setState(obj) { + let state; + const o = this.options; + const ob = {}; ob.type = obj.type; ob.value = o.allValueGetter() || []; ob.assist = obj.assist; - if (ob.type === BI.Selection.All) { + if (ob.type === Selection.All) { if (ob.value.length === 0) { - this.editor.setState(BI.Selection.All); - } else if (BI.size(ob.assist) <= 20) { - var state = ""; - BI.each(ob.assist, function (i, v) { + this.editor.setState(Selection.All); + } else if (size(ob.assist) <= 20) { + state = ""; + each(ob.assist, (i, v) => { if (i === 0) { - state += "" + (o.valueFormatter(v + "") || v); + state += `${o.valueFormatter(`${v}`) || v}`; } else { - state += "," + (o.valueFormatter(v + "") || v); + state += `,${o.valueFormatter(`${v}`) || v}`; } }); this.editor.setState(state); } else { - this.editor.setState(BI.Selection.Multi); + this.editor.setState(Selection.Multi); } } else { if (ob.value.length === 0) { - this.editor.setState(BI.Selection.None); - } else if (BI.size(ob.value) <= 20) { - var state = ""; - BI.each(ob.value, function (i, v) { + this.editor.setState(Selection.None); + } else if (size(ob.value) <= 20) { + state = ""; + each(ob.value, (i, v) => { if (i === 0) { - state += "" + (o.valueFormatter(v + "") || v); + state += `${o.valueFormatter(`${v}`) || v}`; } else { - state += "," + (o.valueFormatter(v + "") || v); + state += `,${o.valueFormatter(`${v}`) || v}`; } }); this.editor.setState(state); } else { - this.editor.setState(BI.Selection.Multi); + this.editor.setState(Selection.Multi); } } - }, + } - setTipType: function (v) { + setTipType(v) { this.editor.setTipType(v); - }, + } - setValue: function (ob) { + setValue(ob) { this.setState(ob); this.searcher.setValue(ob); - }, + } - getKey: function () { + getKey() { return this.editor.getValue(); - }, + } - getValue: function () { + getValue() { return this.searcher.getValue(); - }, + } - populate: function (items) { - this.searcher.populate.apply(this.searcher, arguments); + populate(items) { + this.searcher.populate(...arguments); } -}); - -BI.SearchMultiSelectSearcher.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.SearchMultiSelectSearcher.EVENT_CHANGE = "EVENT_CHANGE"; -BI.SearchMultiSelectSearcher.EVENT_START = "EVENT_START"; -BI.SearchMultiSelectSearcher.EVENT_STOP = "EVENT_STOP"; -BI.SearchMultiSelectSearcher.EVENT_PAUSE = "EVENT_PAUSE"; -BI.SearchMultiSelectSearcher.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.shortcut("bi.search_multi_select_searcher", BI.SearchMultiSelectSearcher); +} From f90147006b2c9a4bc79a59a94798327a0d57d1bf Mon Sep 17 00:00:00 2001 From: impact Date: Fri, 13 Jan 2023 15:22:53 +0800 Subject: [PATCH 113/300] =?UTF-8?q?KERNEL-14097=20refactor:=20widget/yearm?= =?UTF-8?q?onth=E3=80=81yearmonthinterval=20ES6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/widget/dynamicdate/dynamicdate.combo.js | 28 +- src/widget/index.js | 8 +- .../yearmonth/card.dynamic.yearmonth.js | 288 ++++++----- src/widget/yearmonth/card.static.yearmonth.js | 274 +++++----- src/widget/yearmonth/combo.yearmonth.js | 342 +++++++------ src/widget/yearmonth/index.js | 5 + src/widget/yearmonth/popup.yearmonth.js | 444 +++++++++------- src/widget/yearmonth/trigger.yearmonth.js | 481 +++++++++++------- .../yearmonthinterval/yearmonthinterval.js | 309 ++++++----- 9 files changed, 1279 insertions(+), 900 deletions(-) create mode 100644 src/widget/yearmonth/index.js diff --git a/src/widget/dynamicdate/dynamicdate.combo.js b/src/widget/dynamicdate/dynamicdate.combo.js index 173327f56..ddd793132 100644 --- a/src/widget/dynamicdate/dynamicdate.combo.js +++ b/src/widget/dynamicdate/dynamicdate.combo.js @@ -7,6 +7,20 @@ import { DynamicDatePopup } from "./dynamicdate.popup"; export class DynamicDateCombo extends Single { static xtype = "bi.dynamic_date_combo" + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" + static EVENT_CONFIRM = "EVENT_CONFIRM" + static EVENT_FOCUS = "EVENT_FOCUS" + static EVENT_BLUR = "EVENT_BLUR" + static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_VALID = "EVENT_VALID" + static EVENT_ERROR = "EVENT_ERROR" + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW" + static EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW" + static EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW" + + static Static = 1; + static Dynamic = 2; + constants = { popupHeight: 259, popupWidth: 270, @@ -30,20 +44,6 @@ export class DynamicDateCombo extends Single { isNeedAdjustWidth: false, }; - static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" - static EVENT_CONFIRM = "EVENT_CONFIRM" - static EVENT_FOCUS = "EVENT_FOCUS" - static EVENT_BLUR = "EVENT_BLUR" - static EVENT_CHANGE = "EVENT_CHANGE" - static EVENT_VALID = "EVENT_VALID" - static EVENT_ERROR = "EVENT_ERROR" - static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW" - static EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW" - static EVENT_BEFORE_YEAR_MONTH_POPUPVIEW = "EVENT_BEFORE_YEAR_MONTH_POPUPVIEW" - - static Static = 1; - static Dynamic = 2; - _init() { super._init(...arguments); } diff --git a/src/widget/index.js b/src/widget/index.js index acd1aaf9d..f53190f1f 100644 --- a/src/widget/index.js +++ b/src/widget/index.js @@ -17,6 +17,8 @@ import { MultiTreeInsertCombo } from "./multitree/multi.tree.insert.combo"; import { MultiTreeListCombo } from "./multitree/multi.tree.list.combo"; import { NumberEditor } from "./numbereditor/number.editor"; import { NumberInterval } from "./numberinterval/numberinterval"; +import { YearMonthInterval } from "./yearmonthinterval/yearmonthinterval"; +import * as yearmonth from "./yearmonth"; import * as multiselect from "./multiselect"; import * as multiselectlist from "./multiselectlist"; import * as multilayerselectree from "./multilayerselecttree"; @@ -49,6 +51,8 @@ Object.assign(BI, { NumberEditor, NumberInterval, YearInterval, + YearMonthInterval, + ...yearmonth, ...multiselect, ...multiselectlist, ...multilayerselectree, @@ -65,6 +69,7 @@ export * from "./datetimepane"; export * from "./dynamicdatetime"; export * from "./time"; export * from "./editor"; +export * from "./yearmonth"; export * from "./multiselect"; export * from "./multiselectlist"; export * from "./downlist"; @@ -86,5 +91,6 @@ export { MultiTreeCombo, MultiTreeInsertCombo, MultiTreeListCombo, - YearInterval + YearInterval, + YearMonthInterval }; diff --git a/src/widget/yearmonth/card.dynamic.yearmonth.js b/src/widget/yearmonth/card.dynamic.yearmonth.js index 786b22a00..bb11efd8c 100644 --- a/src/widget/yearmonth/card.dynamic.yearmonth.js +++ b/src/widget/yearmonth/card.dynamic.yearmonth.js @@ -1,166 +1,212 @@ -/** - * 年月展示面板 - * - * Created by GUY on 2015/9/2. - * @class BI.YearCard - * @extends BI.Trigger - */ -BI.DynamicYearMonthCard = BI.inherit(BI.Widget, { - - props: { - baseCls: "bi-year-month-card" - }, - - render: function () { - var self = this; +import { + shortcut, + Widget, + i18nText, + bind, + VerticalLayout, + parseDateTime, + extend, + checkDateVoid, + isNotEmptyString +} from "@/core"; +import { DynamicDateCard, DynamicDateParamItem, DynamicDateHelper } from "../dynamicdate"; +import { Label, Bubbles } from "@/base"; + +@shortcut() +export class DynamicYearMonthCard extends Widget { + static xtype = "bi.dynamic_year_month_card"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + props = { baseCls: "bi-year-month-card" }; + + render() { return { - type: "bi.vertical", - items: [{ - type: "bi.label", - text: BI.i18nText("BI-Multi_Date_Relative_Current_Time"), - textAlign: "left", - height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - }, { - type: "bi.vertical", - ref: function (_ref) { - self.wrapper = _ref; + type: VerticalLayout.xtype, + items: [ + { + type: Label.xtype, + text: i18nText("BI-Multi_Date_Relative_Current_Time"), + textAlign: "left", + height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, }, - items: [{ - el: { - type: "bi.dynamic_date_param_item", - validationChecker: BI.bind(self._checkDate, self), - ref: function () { - self.year = this; - }, - listeners: [{ - eventName: "EVENT_CHANGE", - action: function () { - self.fireEvent("EVENT_CHANGE"); - } - }, { - eventName: "EVENT_INPUT_CHANGE", - action: function () { - BI.Bubbles.hide("dynamic-year-month-error"); - } - }] - }, - bgap: 10, - }, { - type: "bi.dynamic_date_param_item", - dateType: BI.DynamicDateCard.TYPE.MONTH, - ref: function () { - self.month = this; + { + type: VerticalLayout.xtype, + ref: _ref => { + this.wrapper = _ref; }, - listeners: [{ - eventName: "EVENT_CHANGE", - action: function () { - self.fireEvent("EVENT_CHANGE"); - } - }, { - eventName: "EVENT_INPUT_CHANGE", - action: function () { - BI.Bubbles.hide("dynamic-year-month-error"); + items: [ + { + el: { + type: DynamicDateParamItem.xtype, + validationChecker: bind(this._checkDate, this), + ref: _ref => { + this.year = _ref; + }, + listeners: [ + { + eventName: "EVENT_CHANGE", + action: () => { + this.fireEvent("EVENT_CHANGE"); + }, + }, + { + eventName: "EVENT_INPUT_CHANGE", + action: () => { + Bubbles.hide( + "dynamic-year-month-error" + ); + }, + } + ], + }, + bgap: 10, + }, + { + type: DynamicDateParamItem.xtype, + dateType: DynamicDateCard.TYPE.MONTH, + ref: _ref => { + this.month = _ref; + }, + listeners: [ + { + eventName: "EVENT_CHANGE", + action: () => { + this.fireEvent("EVENT_CHANGE"); + }, + }, + { + eventName: "EVENT_INPUT_CHANGE", + action: () => { + Bubbles.hide( + "dynamic-year-month-error" + ); + }, + } + ], } - }] - }] - }], + ], + } + ], vgap: 10, - hgap: 10 + hgap: 10, }; - }, + } + + _getErrorText() { + const o = this.options; + const start = parseDateTime(o.min, "%Y-%X-%d"); + const end = parseDateTime(o.max, "%Y-%X-%d"); - _getErrorText: function () { - var o = this.options; - var start = BI.parseDateTime(o.min, "%Y-%X-%d"); - var end = BI.parseDateTime(o.max, "%Y-%X-%d"); - return BI.i18nText("BI-Basic_Year_Month_Range_Error", + return i18nText( + "BI-Basic_Year_Month_Range_Error", start.getFullYear(), start.getMonth() + 1, end.getFullYear(), end.getMonth() + 1 ); - }, + } - _checkDate: function (obj) { - var o = this.options; - var date = BI.DynamicDateHelper.getCalculation(BI.extend(this._getValue(), this._digestDateTypeValue(obj))); + _checkDate(obj) { + const o = this.options; + const date = DynamicDateHelper.getCalculation( + extend(this._getValue(), this._digestDateTypeValue(obj)) + ); - return !BI.checkDateVoid(date.getFullYear(), date.getMonth() + 1, date.getDate(), o.min, o.max)[0]; - }, + return !checkDateVoid( + date.getFullYear(), + date.getMonth() + 1, + date.getDate(), + o.min, + o.max + )[0]; + } - _digestDateTypeValue: function (value) { - var valueMap = {}; + _digestDateTypeValue(value) { + const valueMap = {}; switch (value.dateType) { - case BI.DynamicDateCard.TYPE.YEAR: - valueMap.year = (value.offset === 0 ? -value.value : +value.value); - break; - case BI.DynamicDateCard.TYPE.MONTH: - valueMap.month = (value.offset === 0 ? -value.value : +value.value); - break; - default: - break; + case DynamicDateCard.TYPE.YEAR: + valueMap.year = + value.offset === 0 ? -value.value : +value.value; + break; + case DynamicDateCard.TYPE.MONTH: + valueMap.month = + value.offset === 0 ? -value.value : +value.value; + break; + default: + break; } + return valueMap; - }, + } - _createValue: function (type, v) { + _createValue(type, v) { return { dateType: type, value: Math.abs(v), - offset: v > 0 ? 1 : 0 + offset: v > 0 ? 1 : 0, }; - }, + } - setMinDate: function(minDate) { - if (BI.isNotEmptyString(this.options.min)) { + setMinDate(minDate) { + if (isNotEmptyString(this.options.min)) { this.options.min = minDate; } - }, + } - setMaxDate: function (maxDate) { - if (BI.isNotEmptyString(this.options.max)) { + setMaxDate(maxDate) { + if (isNotEmptyString(this.options.max)) { this.options.max = maxDate; } - }, + } - setValue: function (v) { - v = v || {year: 0, month: 0}; - this.year.setValue(this._createValue(BI.DynamicDateCard.TYPE.YEAR, v.year)); - this.month.setValue(this._createValue(BI.DynamicDateCard.TYPE.MONTH, v.month)); - }, + setValue(v) { + v = v || { year: 0, month: 0 }; + this.year.setValue( + this._createValue(DynamicDateCard.TYPE.YEAR, v.year) + ); + this.month.setValue( + this._createValue(DynamicDateCard.TYPE.MONTH, v.month) + ); + } - _getValue: function () { - var year = this.year.getValue(); - var month = this.month.getValue(); + _getValue() { + const year = this.year.getValue(); + const month = this.month.getValue(); + return { - year: (year.offset === 0 ? -year.value : year.value), - month: (month.offset === 0 ? -month.value : month.value) + year: year.offset === 0 ? -year.value : year.value, + month: month.offset === 0 ? -month.value : month.value, }; - }, + } - getInputValue: function () { + getInputValue() { return this._getValue(); - }, + } - getValue: function () { + getValue() { return this.checkValidation() ? this._getValue() : {}; - }, + } - checkValidation: function (show) { - var errorText; - var yearInvalid = !this.year.checkValidation(); - var monthInvalid = !this.month.checkValidation(); - var invalid = yearInvalid || monthInvalid; + checkValidation(show) { + let errorText; + const yearInvalid = !this.year.checkValidation(); + const monthInvalid = !this.month.checkValidation(); + let invalid = yearInvalid || monthInvalid; if (invalid) { - errorText = BI.i18nText("BI-Please_Input_Natural_Number"); + errorText = i18nText("BI-Please_Input_Natural_Number"); } else { invalid = !this._checkDate(this._getValue()); errorText = this._getErrorText(); } - invalid && show && BI.Bubbles.show("dynamic-year-month-error", errorText, this.wrapper); + invalid && + show && + Bubbles.show( + "dynamic-year-month-error", + errorText, + this.wrapper + ); return !invalid; - }, -}); -BI.DynamicYearMonthCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.dynamic_year_month_card", BI.DynamicYearMonthCard); \ No newline at end of file + } +} diff --git a/src/widget/yearmonth/card.static.yearmonth.js b/src/widget/yearmonth/card.static.yearmonth.js index 6ba4a94bc..43a111491 100644 --- a/src/widget/yearmonth/card.static.yearmonth.js +++ b/src/widget/yearmonth/card.static.yearmonth.js @@ -1,171 +1,215 @@ -BI.StaticYearMonthCard = BI.inherit(BI.Widget, { +import { + shortcut, + Widget, + chunk, + map, + toPix, + extend, + VerticalLayout, + CenterAdaptLayout, + parseDateTime, + each, + checkDateVoid, + contains, + getDate, + parseInt +} from "@/core"; +import { TextItem, ButtonGroup } from "@/base"; +import { YearPicker } from "../date/calendar"; - props: { - baseCls: "bi-static-year-month-card", - behaviors: {} - }, +@shortcut() +export class StaticYearMonthCard extends Widget { + static xtype = "bi.static_year_month_card"; - _createMonths: function () { - var self = this; + static EVENT_CHANGE = "EVENT_CHANGE"; + + props = { baseCls: "bi-static-year-month-card", behaviors: {} }; + + _createMonths() { // 纵向排列月 - var month = [1, 7, 2, 8, 3, 9, 4, 10, 5, 11, 6, 12]; - var items = BI.chunk(month, 2); - return BI.map(items, function (i, item) { - return BI.map(item, function (j, td) { - return { - type: "bi.text_item", - cls: "bi-list-item-select", - textAlign: "center", - whiteSpace: "nowrap", - once: false, - forceSelected: true, - height: BI.toPix(BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, 1), - width: 38, - value: td, - text: td, - ref: function (_ref) { - self.monthMap[j === 0 ? i : i + 6] = _ref; - } - }; - }); - }); - }, + const month = [1, 7, 2, 8, 3, 9, 4, 10, 5, 11, 6, 12]; + const items = chunk(month, 2); + + return map(items, (i, item) => map(item, (j, td) => { + return { + type: TextItem.xtype, + cls: "bi-list-item-select", + textAlign: "center", + whiteSpace: "nowrap", + once: false, + forceSelected: true, + height: toPix(BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, 1), + width: 38, + value: td, + text: td, + ref: _ref => { + this.monthMap[j === 0 ? i : i + 6] = _ref; + }, + }; + })); + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; this.monthMap = {}; + return { - type: "bi.vertical", - items: [{ - type: "bi.year_picker", - cls: "bi-split-bottom", - min: o.min, - max: o.max, - ref: function () { - self.yearPicker = this; - }, - behaviors: o.behaviors, - height: 30, - listeners: [{ - eventName: BI.YearPicker.EVENT_CHANGE, - action: function () { - var value = this.getValue(); - self._checkMonthStatus(value); - self._setYear(value); - } - }] - }, { - el: { - type: "bi.button_group", - behaviors: o.behaviors, - ref: function () { - self.month = this; + type: VerticalLayout.xtype, + items: [ + { + type: YearPicker.xtype, + cls: "bi-split-bottom", + min: o.min, + max: o.max, + ref: _ref => { + this.yearPicker = _ref; }, - items: this._createMonths(), - layouts: [BI.LogicFactory.createLogic("table", BI.extend({ - dynamic: true - }, { - columns: 2, - rows: 6, - columnSize: [1 / 2, 1 / 2], - rowSize: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + 1 - })), { - type: "bi.center_adapt", - vgap: 1, - hgap: 2 - }], - value: o.value, - listeners: [{ - eventName: BI.ButtonGroup.EVENT_CHANGE, - action: function () { - self.selectedYear = self.yearPicker.getValue(); - self.selectedMonth = this.getValue()[0]; - self.fireEvent(BI.StaticYearMonthCard.EVENT_CHANGE); + behaviors: o.behaviors, + height: 30, + listeners: [ + { + eventName: YearPicker.EVENT_CHANGE, + action: () => { + const value = this.yearPicker.getValue(); + this._checkMonthStatus(value); + this._setYear(value); + }, } - }] + ], }, - vgap: 5 - }] + { + el: { + type: ButtonGroup.xtype, + behaviors: o.behaviors, + ref: _ref => { + this.month = _ref; + }, + items: this._createMonths(), + layouts: [ + BI.LogicFactory.createLogic( + "table", + extend( + { + dynamic: true, + }, + { + columns: 2, + rows: 6, + columnSize: [1 / 2, 1 / 2], + rowSize: + BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + + 1, + } + ) + ), + { + type: CenterAdaptLayout.xtype, + vgap: 1, + hgap: 2, + } + ], + value: o.value, + listeners: [ + { + eventName: ButtonGroup.EVENT_CHANGE, + action: () => { + this.selectedYear = this.yearPicker.getValue(); + this.selectedMonth = this.month.getValue()[0]; + this.fireEvent( + StaticYearMonthCard.EVENT_CHANGE + ); + }, + } + ], + }, + vgap: 5, + } + ], }; - }, + } - created: function() { + created() { this._checkMonthStatus(this.selectedYear); - }, + } - _checkMonthStatus: function (year) { - var o = this.options; - var minDate = BI.parseDateTime(o.min, "%Y-%X-%d"), maxDate = BI.parseDateTime(o.max, "%Y-%X-%d"); - var minYear = minDate.getFullYear(), maxYear = maxDate.getFullYear(); - var minMonth = 0; - var maxMonth = 11; + _checkMonthStatus(year) { + const o = this.options; + const minDate = parseDateTime(o.min, "%Y-%X-%d"), + maxDate = parseDateTime(o.max, "%Y-%X-%d"); + const minYear = minDate.getFullYear(), + maxYear = maxDate.getFullYear(); + let minMonth = 0; + let maxMonth = 11; minYear === year && (minMonth = minDate.getMonth()); maxYear === year && (maxMonth = maxDate.getMonth()); - var yearInvalid = year < minYear || year > maxYear; - BI.each(this.monthMap, function (month, obj) { - var monthInvalid = month < minMonth || month > maxMonth; + const yearInvalid = year < minYear || year > maxYear; + each(this.monthMap, (month, obj) => { + const monthInvalid = month < minMonth || month > maxMonth; obj.setEnable(!yearInvalid && !monthInvalid); }); - }, + } - _setYear: function (year) { - var o = this.options; - - var dateVoid = BI.checkDateVoid(year, this.selectedMonth, 1, o.min, o.max); + _setYear(year) { + const o = this.options; + + const dateVoid = checkDateVoid(year, this.selectedMonth, 1, o.min, o.max); // 在切换年的时候,如果月份不在区间内了,取消选中 - if (BI.contains(["y", "m"], dateVoid[0])) { + if (contains(["y", "m"], dateVoid[0])) { this.selectedYear = year; this.month.setValue(); + return; } this.selectedYear = year; this.month.setValue(this.selectedMonth); - }, + } - setMinDate: function (minDate) { + setMinDate(minDate) { if (this.options.min !== minDate) { this.options.min = minDate; this.yearPicker.setMinDate(minDate); this._checkMonthStatus(this.selectedYear); } - }, + } - setMaxDate: function (maxDate) { + setMaxDate(maxDate) { if (this.options.max !== maxDate) { this.options.max = maxDate; this.yearPicker.setMaxDate(maxDate); this._checkMonthStatus(this.selectedYear); } - }, + } - getValue: function () { + getValue() { return { year: this.selectedYear, - month: this.selectedMonth + month: this.selectedMonth, }; - }, + } - setValue: function (obj) { - var o = this.options; - var newObj = {}; + setValue(obj) { + const o = this.options; + const newObj = {}; newObj.year = obj.year || 0; newObj.month = obj.month || 0; - if (newObj.year === 0 || newObj.month === 0 || BI.checkDateVoid(newObj.year, newObj.month, 1, o.min, o.max)[0]) { - var year = newObj.year || BI.getDate().getFullYear(); + if ( + newObj.year === 0 || + newObj.month === 0 || + checkDateVoid(newObj.year, newObj.month, 1, o.min, o.max)[0] + ) { + const year = newObj.year || getDate().getFullYear(); this.selectedYear = year; this.selectedMonth = ""; this.yearPicker.setValue(year); this.month.setValue(); } else { - this.selectedYear = BI.parseInt(newObj.year); - this.selectedMonth = BI.parseInt(newObj.month); + this.selectedYear = parseInt(newObj.year); + this.selectedMonth = parseInt(newObj.month); this.yearPicker.setValue(this.selectedYear); this.month.setValue(this.selectedMonth); } this._checkMonthStatus(this.selectedYear); } -}); -BI.StaticYearMonthCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.static_year_month_card", BI.StaticYearMonthCard); +} diff --git a/src/widget/yearmonth/combo.yearmonth.js b/src/widget/yearmonth/combo.yearmonth.js index 0fc8cab5c..629d21d18 100644 --- a/src/widget/yearmonth/combo.yearmonth.js +++ b/src/widget/yearmonth/combo.yearmonth.js @@ -1,69 +1,98 @@ -BI.DynamicYearMonthCombo = BI.inherit(BI.Single, { +import { + shortcut, + createWidget, + toPix, + isEqual, + isNotEmptyString, + getDate, + AbsoluteLayout, + HorizontalFillLayout, + isNotNull, + isNotEmptyObject, + checkDateVoid +} from "@/core"; +import { Single, Combo, IconButton } from "@/base"; +import { DynamicYearMonthTrigger } from "./trigger.yearmonth"; +import { DynamicYearMonthPopup } from "./popup.yearmonth"; +import { DynamicDateCombo } from "../dynamicdate"; - props: { +@shortcut() +export class DynamicYearMonthCombo extends Single { + static xtype = "bi.dynamic_year_month_combo"; + + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_VALID = "EVENT_VALID"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + + static Static = 1; + static Dynamic = 2; + + props = { baseCls: "bi-year-month-combo", behaviors: {}, - minDate: "1900-01-01", // 最小日期 - maxDate: "2099-12-31", // 最大日期 + minDate: "1900-01-01", + maxDate: "2099-12-31", height: 24, supportDynamic: true, isNeedAdjustHeight: false, - isNeedAdjustWidth: false - }, - - _init: function () { - var self = this, o = this.options; - BI.DynamicYearMonthCombo.superclass._init.apply(this, arguments); + isNeedAdjustWidth: false, + }; + + _init() { + const o = this.options; + super._init(...arguments); this.storeValue = o.value; this.storeTriggerValue = ""; - var border = o.simple ? 1 : 2; - this.trigger = BI.createWidget({ + const border = o.simple ? 1 : 2; + this.trigger = createWidget({ type: "bi.dynamic_year_month_trigger", simple: o.simple, min: o.minDate, max: o.maxDate, - height: BI.toPix(o.height, border), + height: toPix(o.height, border), value: o.value || "", watermark: o.watermark, }); - this.trigger.on(BI.DynamicYearMonthTrigger.EVENT_KEY_DOWN, function () { - self.combo.isViewVisible() && self.combo.hideView(); + this.trigger.on(DynamicYearMonthTrigger.EVENT_KEY_DOWN, () => { + this.combo.isViewVisible() && this.combo.hideView(); }); - this.trigger.on(BI.DynamicYearMonthTrigger.EVENT_START, function () { - self.combo.isViewVisible() && self.combo.hideView(); + this.trigger.on(DynamicYearMonthTrigger.EVENT_START, () => { + this.combo.isViewVisible() && this.combo.hideView(); }); - this.trigger.on(BI.DynamicYearMonthTrigger.EVENT_STOP, function () { - self.combo.showView(); + this.trigger.on(DynamicYearMonthTrigger.EVENT_STOP, () => { + this.combo.showView(); }); - this.trigger.on(BI.DynamicYearMonthTrigger.EVENT_ERROR, function () { - self.combo.isViewVisible() && self.combo.hideView(); - self.comboWrapper.element.addClass("error"); - self.fireEvent(BI.DynamicYearMonthCombo.EVENT_ERROR); + this.trigger.on(DynamicYearMonthTrigger.EVENT_ERROR, () => { + this.combo.isViewVisible() && this.combo.hideView(); + this.comboWrapper.element.addClass("error"); + this.fireEvent(DynamicYearMonthCombo.EVENT_ERROR); }); - this.trigger.on(BI.DynamicYearMonthTrigger.EVENT_VALID, function () { - self.comboWrapper.element.removeClass("error"); - self.fireEvent(BI.DynamicYearMonthCombo.EVENT_VALID); + this.trigger.on(DynamicYearMonthTrigger.EVENT_VALID, () => { + this.comboWrapper.element.removeClass("error"); + this.fireEvent(DynamicYearMonthCombo.EVENT_VALID); }); - this.trigger.on(BI.DynamicYearMonthTrigger.EVENT_CONFIRM, function () { - var dateStore = self.storeTriggerValue; - var dateObj = self.trigger.getKey(); - if (BI.isEqual(dateObj, dateStore)) { + this.trigger.on(DynamicYearMonthTrigger.EVENT_CONFIRM, () => { + const dateStore = this.storeTriggerValue; + const dateObj = this.trigger.getKey(); + if (isEqual(dateObj, dateStore)) { return; } - if (BI.isNotEmptyString(dateObj) && !BI.isEqual(dateObj, dateStore)) { - self.storeValue = self.trigger.getValue(); - self.setValue(self.trigger.getValue()); + if (isNotEmptyString(dateObj) && !isEqual(dateObj, dateStore)) { + this.storeValue = this.trigger.getValue(); + this.setValue(this.trigger.getValue()); } - self._checkDynamicValue(self.storeValue); - self.fireEvent(BI.DynamicYearMonthCombo.EVENT_CONFIRM); + this._checkDynamicValue(this.storeValue); + this.fireEvent(DynamicYearMonthCombo.EVENT_CONFIRM); }); - this.trigger.on(BI.DynamicYearMonthTrigger.EVENT_FOCUS, function () { - self.storeTriggerValue = self.trigger.getKey(); - self.fireEvent(BI.DynamicYearMonthCombo.EVENT_FOCUS); + this.trigger.on(DynamicYearMonthTrigger.EVENT_FOCUS, () => { + this.storeTriggerValue = this.trigger.getKey(); + this.fireEvent(DynamicYearMonthCombo.EVENT_FOCUS); }); - this.combo = BI.createWidget({ - type: "bi.combo", + this.combo = createWidget({ + type: Combo.xtype, container: o.container, isNeedAdjustHeight: o.isNeedAdjustHeight, isNeedAdjustWidth: o.isNeedAdjustWidth, @@ -77,172 +106,185 @@ BI.DynamicYearMonthCombo = BI.inherit(BI.Single, { type: "bi.dynamic_year_month_popup", width: o.isNeedAdjustWidth ? o.width : undefined, supportDynamic: o.supportDynamic, - ref: function () { - self.popup = this; + ref: _ref => { + this.popup = _ref; }, listeners: [ { - eventName: BI.DynamicYearMonthPopup.EVENT_CHANGE, - action: function () { - self.setValue(self.popup.getValue()); - self.combo.hideView(); - self.fireEvent(BI.DynamicYearMonthCombo.EVENT_CONFIRM); - } - }, { - eventName: BI.DynamicYearMonthPopup.BUTTON_CLEAR_EVENT_CHANGE, - action: function () { - self.setValue(); - self.comboWrapper.element.removeClass("error"); - self.combo.hideView(); - self.fireEvent(BI.DynamicYearMonthCombo.EVENT_CONFIRM); - } - }, { - eventName: BI.DynamicYearMonthPopup.BUTTON_lABEL_EVENT_CHANGE, - action: function () { - var date = BI.getDate(); - self.setValue({ - type: BI.DynamicYearMonthCombo.Static, - value: { year: date.getFullYear(), month: date.getMonth() + 1 } + eventName: DynamicYearMonthPopup.EVENT_CHANGE, + action: () => { + this.setValue(this.popup.getValue()); + this.combo.hideView(); + this.fireEvent( + DynamicYearMonthCombo.EVENT_CONFIRM + ); + }, + }, + { + eventName: + DynamicYearMonthPopup.BUTTON_CLEAR_EVENT_CHANGE, + action: () => { + this.setValue(); + this.comboWrapper.element.removeClass("error"); + this.combo.hideView(); + this.fireEvent( + DynamicYearMonthCombo.EVENT_CONFIRM + ); + }, + }, + { + eventName: + DynamicYearMonthPopup.BUTTON_lABEL_EVENT_CHANGE, + action: () => { + const date = getDate(); + this.setValue({ + type: DynamicYearMonthCombo.Static, + value: { + year: date.getFullYear(), + month: date.getMonth() + 1, + }, }); - self.combo.hideView(); - self.fireEvent(BI.DynamicDateCombo.EVENT_CONFIRM); - } - }, { - eventName: BI.DynamicYearMonthPopup.BUTTON_OK_EVENT_CHANGE, - action: function () { - var value = self.popup.getValue(); - if (self._checkValue(value)) { - self.setValue(value); + this.combo.hideView(); + this.fireEvent(DynamicDateCombo.EVENT_CONFIRM); + }, + }, + { + eventName: + DynamicYearMonthPopup.BUTTON_OK_EVENT_CHANGE, + action: () => { + const value = this.popup.getValue(); + if (this._checkValue(value)) { + this.setValue(value); } - self.combo.hideView(); - self.fireEvent(BI.DynamicDateCombo.EVENT_CONFIRM); - } + this.combo.hideView(); + this.fireEvent(DynamicDateCombo.EVENT_CONFIRM); + }, } ], behaviors: o.behaviors, min: o.minDate, - max: o.maxDate + max: o.maxDate, }, - value: o.value || "" - } + value: o.value || "", + }, }); - this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { - self.popup.setMinDate(o.minDate); - self.popup.setMaxDate(o.maxDate); - self.popup.setValue(self.storeValue); - self.fireEvent(BI.DynamicYearMonthCombo.EVENT_BEFORE_POPUPVIEW); + this.combo.on(Combo.EVENT_BEFORE_POPUPVIEW, () => { + this.popup.setMinDate(o.minDate); + this.popup.setMaxDate(o.maxDate); + this.popup.setValue(this.storeValue); + this.fireEvent(DynamicYearMonthCombo.EVENT_BEFORE_POPUPVIEW); }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, items: [ { el: { - type: "bi.horizontal_fill", + type: HorizontalFillLayout.xtype, columnSize: ["", "fill"], - cls: (o.simple ? "bi-border-bottom" : "bi-border bi-border-radius") + " bi-focus-shadow", - ref: function () { - self.comboWrapper = this; + cls: + `${o.simple + ? "bi-border-bottom" + : "bi-border bi-border-radius" + } bi-focus-shadow`, + ref: _ref => { + this.comboWrapper = _ref; }, items: [ { el: { - type: "bi.icon_button", + type: IconButton.xtype, cls: "bi-trigger-icon-button date-change-h-font", - width: BI.toPix(o.height, border), - height: BI.toPix(o.height, border), - ref: function () { - self.changeIcon = this; - } - } - }, this.combo - ] + width: toPix(o.height, border), + height: toPix(o.height, border), + ref: _ref => { + this.changeIcon = _ref; + }, + }, + }, + this.combo + ], }, top: 0, left: 0, right: 0, - bottom: 0 + bottom: 0, } - ] + ], }); this._checkDynamicValue(o.value); - }, + } - _checkDynamicValue: function (v) { - var type = null; - if (BI.isNotNull(v)) { + _checkDynamicValue(v) { + let type = null; + if (isNotNull(v)) { type = v.type; } switch (type) { - case BI.DynamicYearMonthCombo.Dynamic: - this.changeIcon.setVisible(true); - break; - default: - this.changeIcon.setVisible(false); - break; + case DynamicYearMonthCombo.Dynamic: + this.changeIcon.setVisible(true); + break; + default: + this.changeIcon.setVisible(false); + break; } - }, + } - _checkValue: function (v) { - var o = this.options; + _checkValue(v) { + const o = this.options; switch (v.type) { - case BI.DynamicDateCombo.Dynamic: - return BI.isNotEmptyObject(v.value); - case BI.DynamicDateCombo.Static: - var value = v.value || {}; - - return !BI.checkDateVoid(value.year, value.month, 1, o.minDate, o.maxDate)[0]; - default: - return true; + case DynamicDateCombo.Dynamic: + return isNotEmptyObject(v.value); + case DynamicDateCombo.Static: { + const value = v.value || {}; + + return !checkDateVoid( + value.year, + value.month, + 1, + o.minDate, + o.maxDate + )[0]; } - }, + default: + return true; + } + } - setMinDate: function (minDate) { - var o = this.options; + setMinDate(minDate) { + const o = this.options; o.minDate = minDate; this.trigger.setMinDate(minDate); this.popup && this.popup.setMinDate(minDate); - }, + } - setMaxDate: function (maxDate) { - var o = this.options; + setMaxDate(maxDate) { + const o = this.options; o.maxDate = maxDate; this.trigger.setMaxDate(maxDate); this.popup && this.popup.setMaxDate(maxDate); - }, + } - hideView: function () { + hideView() { this.combo.hideView(); - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v; this.trigger.setValue(v); this._checkDynamicValue(v); - }, + } - getValue: function () { + getValue() { return this.storeValue; - }, + } - getKey: function () { + getKey() { return this.trigger.getKey(); - }, + } - isStateValid: function () { + isStateValid() { return this.trigger.isStateValid(); } - -}); -BI.DynamicYearMonthCombo.EVENT_ERROR = "EVENT_ERROR"; -BI.DynamicYearMonthCombo.EVENT_VALID = "EVENT_VALID"; -BI.DynamicYearMonthCombo.EVENT_FOCUS = "EVENT_FOCUS"; -BI.DynamicYearMonthCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.DynamicYearMonthCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut("bi.dynamic_year_month_combo", BI.DynamicYearMonthCombo); - -BI.extend(BI.DynamicYearMonthCombo, { - Static: 1, - Dynamic: 2 -}); +} diff --git a/src/widget/yearmonth/index.js b/src/widget/yearmonth/index.js new file mode 100644 index 000000000..234f6f78c --- /dev/null +++ b/src/widget/yearmonth/index.js @@ -0,0 +1,5 @@ +export { DynamicYearMonthCard } from "./card.dynamic.yearmonth"; +export { StaticYearMonthCard } from "./card.static.yearmonth"; +export { DynamicYearMonthCombo } from "./combo.yearmonth"; +export { DynamicYearMonthPopup } from "./popup.yearmonth"; +export { DynamicYearMonthTrigger } from "./trigger.yearmonth"; diff --git a/src/widget/yearmonth/popup.yearmonth.js b/src/widget/yearmonth/popup.yearmonth.js index 1b80214d7..ad8b432a1 100644 --- a/src/widget/yearmonth/popup.yearmonth.js +++ b/src/widget/yearmonth/popup.yearmonth.js @@ -1,241 +1,329 @@ -/** - * 年月 - * - * Created by GUY on 2015/9/2. - * @class BI.DynamicYearMonthPopup - * @extends BI.Trigger - */ -BI.DynamicYearMonthPopup = BI.inherit(BI.Widget, { - constants: { - tabHeight: 40, - }, +import { + shortcut, + Widget, + toPix, + i18nText, + VerticalLayout, + GridLayout, + print, + getDate, + checkDateVoid, + createItems +} from "@/core"; +import { DynamicYearMonthCombo } from "./combo.yearmonth"; +import { TextButton, Tab } from "@/base"; +import { DynamicDateCombo, DynamicDateHelper } from "../dynamicdate"; +// import { DynamicYearCombo } from "../year/combo.year"; +import { StaticYearMonthCard } from "./card.static.yearmonth"; +import { LinearSegment } from "@/case"; +import { DynamicYearMonthCard } from "./card.dynamic.yearmonth"; - props: { +@shortcut() +export class DynamicYearMonthPopup extends Widget { + static xtype = "bi.dynamic_year_month_popup"; + + constants = { tabHeight: 40 }; + props = { baseCls: "bi-year-month-popup", behaviors: {}, - min: "1900-01-01", // 最小日期 - max: "2099-12-31", // 最大日期, + min: "1900-01-01", + max: "2099-12-31", width: 180, supportDynamic: true, - }, + }; + + static BUTTON_CLEAR_EVENT_CHANGE = "BUTTON_CLEAR_EVENT_CHANGE"; + static BUTTON_lABEL_EVENT_CHANGE = "BUTTON_lABEL_EVENT_CHANGE"; + static BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE"; + static EVENT_CHANGE = "EVENT_CHANGE"; - render: function () { - var self = this, opts = this.options, c = this.constants; - this.storeValue = {type: BI.DynamicYearMonthCombo.Static}; + render() { + this.storeValue = { type: DynamicYearMonthCombo.Static }; + return { - type: "bi.vertical", - items: [{ - el: this._getTabJson() - }, { - el: { - type: "bi.grid", - items: [[{ - type: "bi.text_button", - cls: "bi-split-top bi-high-light", - textHeight: BI.toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), - shadow: true, - text: BI.i18nText("BI-Basic_Clear"), - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.DynamicYearMonthPopup.BUTTON_CLEAR_EVENT_CHANGE); - } - }] - }, { - type: "bi.text_button", - cls: "bi-split-left bi-split-right bi-high-light bi-split-top", - textHeight: BI.toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), - shadow: true, - text: BI.i18nText("BI-Basic_Current_Month"), - disabled: this._checkTodayValid(), - ref: function () { - self.textButton = this; - }, - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.DynamicYearMonthPopup.BUTTON_lABEL_EVENT_CHANGE); - } - }] - }, { - type: "bi.text_button", - cls: "bi-split-top bi-high-light", - textHeight: BI.toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), - shadow: true, - text: BI.i18nText("BI-Basic_OK"), - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - var type = self.dateTab.getSelect(); - if (type === BI.DynamicDateCombo.Dynamic) { - self.dynamicPane.checkValidation(true) && self.fireEvent(BI.DynamicYearMonthPopup.BUTTON_OK_EVENT_CHANGE); - } else { - self.fireEvent(BI.DynamicYearMonthPopup.BUTTON_OK_EVENT_CHANGE); - } - } - }] - }]], - height: BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT + type: VerticalLayout.xtype, + items: [ + { + el: this._getTabJson(), }, - }] + { + el: { + type: GridLayout.xtype, + items: [ + [ + { + type: TextButton.xtype, + cls: "bi-split-top bi-high-light", + textHeight: toPix( + BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, + 1 + ), + shadow: true, + text: i18nText("BI-Basic_Clear"), + listeners: [ + { + eventName: TextButton.EVENT_CHANGE, + action: () => { + this.fireEvent( + DynamicYearMonthPopup.BUTTON_CLEAR_EVENT_CHANGE + ); + }, + } + ], + }, + { + type: TextButton.xtype, + cls: "bi-split-left bi-split-right bi-high-light bi-split-top", + textHeight: toPix( + BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, + 1 + ), + shadow: true, + text: i18nText("BI-Basic_Current_Month"), + disabled: this._checkTodayValid(), + ref: _ref => { + this.textButton = _ref; + }, + listeners: [ + { + eventName: TextButton.EVENT_CHANGE, + action: () => { + this.fireEvent( + DynamicYearMonthPopup.BUTTON_lABEL_EVENT_CHANGE + ); + }, + } + ], + }, + { + type: TextButton.xtype, + cls: "bi-split-top bi-high-light", + textHeight: toPix( + BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, + 1 + ), + shadow: true, + text: i18nText("BI-Basic_OK"), + listeners: [ + { + eventName: TextButton.EVENT_CHANGE, + action: () => { + const type = + this.dateTab.getSelect(); + if ( + type === + DynamicDateCombo.Dynamic + ) { + this.dynamicPane.checkValidation( + true + ) && + this.fireEvent( + DynamicYearMonthPopup.BUTTON_OK_EVENT_CHANGE + ); + } else { + this.fireEvent( + DynamicYearMonthPopup.BUTTON_OK_EVENT_CHANGE + ); + } + }, + } + ], + } + ] + ], + height: BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, + }, + } + ], }; - }, + } - _setInnerValue: function () { - if (this.dateTab.getSelect() === BI.DynamicDateCombo.Static) { - this.textButton.setValue(BI.i18nText("BI-Basic_Current_Month")); + _setInnerValue() { + if (this.dateTab.getSelect() === DynamicDateCombo.Static) { + this.textButton.setValue(i18nText("BI-Basic_Current_Month")); this.textButton.setEnable(!this._checkTodayValid()); } else { - var date = BI.DynamicDateHelper.getCalculation(this.dynamicPane.getInputValue()); - date = BI.print(date, "%Y-%x"); + let date = DynamicDateHelper.getCalculation( + this.dynamicPane.getInputValue() + ); + date = print(date, "%Y-%x"); this.textButton.setValue(date); this.textButton.setEnable(false); } - }, + } - _checkTodayValid: function () { - var o = this.options; - var today = BI.getDate(); - return !!BI.checkDateVoid(today.getFullYear(), today.getMonth() + 1, today.getDate(), o.min, o.max)[0]; - }, + _checkTodayValid() { + const o = this.options; + const today = getDate(); + + return !!checkDateVoid( + today.getFullYear(), + today.getMonth() + 1, + today.getDate(), + o.min, + o.max + )[0]; + } - _getTabJson: function () { - var self = this, o = this.options; + _getTabJson() { + const o = this.options; + return { - type: "bi.tab", + type: Tab.xtype, logic: { - dynamic: true + dynamic: true, }, - ref: function () { - self.dateTab = this; + ref: _ref => { + this.dateTab = _ref; }, tab: { - type: "bi.linear_segment", + type: LinearSegment.xtype, cls: "bi-split-bottom", invisible: !o.supportDynamic, height: this.constants.tabHeight, - items: BI.createItems([{ - text: BI.i18nText("BI-Basic_Year_Month"), - value: BI.DynamicYearCombo.Static - }, { - text: BI.i18nText("BI-Basic_Dynamic_Title"), - value: BI.DynamicYearCombo.Dynamic - }], { - textAlign: "center" - }) + items: createItems( + [ + { + text: i18nText("BI-Basic_Year_Month"), + value: BI.DynamicYearCombo.Static, + }, + { + text: i18nText("BI-Basic_Dynamic_Title"), + value: BI.DynamicYearCombo.Dynamic, + } + ], + { + textAlign: "center", + } + ), }, - cardCreator: function (v) { + cardCreator: v => { switch (v) { - case BI.DynamicYearCombo.Dynamic: - return { - type: "bi.dynamic_year_month_card", - cls: "dynamic-year-month-pane", - min: self.options.min, - max: self.options.max, - listeners: [{ + case BI.DynamicYearCombo.Dynamic: + return { + type: DynamicYearMonthCard.xtype, + cls: "dynamic-year-month-pane", + min: this.options.min, + max: this.options.max, + listeners: [ + { eventName: "EVENT_CHANGE", - action: function () { - self._setInnerValue(self.year, v); - } - }], - ref: function () { - self.dynamicPane = this; + action: () => { + this._setInnerValue(this.year, v); + }, } - }; - case BI.DynamicYearCombo.Static: - default: - return { - type: "bi.static_year_month_card", - behaviors: o.behaviors, - min: self.options.min, - max: self.options.max, - listeners: [{ - eventName: BI.StaticYearMonthCard.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.DynamicYearMonthPopup.EVENT_CHANGE); - } - }], - ref: function () { - self.year = this; + ], + ref: _ref => { + this.dynamicPane = _ref; + }, + }; + case BI.DynamicYearCombo.Static: + default: + return { + type: StaticYearMonthCard.xtype, + behaviors: o.behaviors, + min: this.options.min, + max: this.options.max, + listeners: [ + { + eventName: StaticYearMonthCard.EVENT_CHANGE, + action: () => { + this.fireEvent( + DynamicYearMonthPopup.EVENT_CHANGE + ); + }, } - }; + ], + ref: _ref => { + this.year = _ref; + }, + }; } }, - listeners: [{ - eventName: BI.Tab.EVENT_CHANGE, - action: function () { - var v = self.dateTab.getSelect(); - switch (v) { - case BI.DynamicYearCombo.Static: - var date = BI.DynamicDateHelper.getCalculation(self.dynamicPane.getValue()); - self.year.setValue({year: date.getFullYear(), month: date.getMonth() + 1}); - self._setInnerValue(); + listeners: [ + { + eventName: Tab.EVENT_CHANGE, + action: () => { + const v = this.dateTab.getSelect(); + switch (v) { + case BI.DynamicYearCombo.Static: { + const date = DynamicDateHelper.getCalculation( + this.dynamicPane.getValue() + ); + this.year.setValue({ + year: date.getFullYear(), + month: date.getMonth() + 1, + }); + this._setInnerValue(); break; + } case BI.DynamicYearCombo.Dynamic: default: - if(self.storeValue && self.storeValue.type === BI.DynamicYearCombo.Dynamic) { - self.dynamicPane.setValue(self.storeValue.value); - }else{ - self.dynamicPane.setValue({ - year: 0 + if ( + this.storeValue && + this.storeValue.type === + BI.DynamicYearCombo.Dynamic + ) { + this.dynamicPane.setValue( + this.storeValue.value + ); + } else { + this.dynamicPane.setValue({ + year: 0, }); } - self._setInnerValue(); + this._setInnerValue(); break; - } + } + }, } - }] + ], }; - }, + } - setMinDate: function (minDate) { + setMinDate(minDate) { if (this.options.min !== minDate) { this.options.min = minDate; this.year && this.year.setMinDate(minDate); this.dynamicPane && this.dynamicPane.setMinDate(minDate); } - }, + } - setMaxDate: function (maxDate) { + setMaxDate(maxDate) { if (this.options.max !== maxDate) { this.options.max = maxDate; this.year && this.year.setMaxDate(maxDate); this.dynamicPane && this.dynamicPane.setMaxDate(maxDate); } - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v; - var self = this; - var type, value; v = v || {}; - type = v.type || BI.DynamicDateCombo.Static; - value = v.value || v; + const type = v.type || DynamicDateCombo.Static; + const value = v.value || v; + + + this.dateTab.setSelect(type); switch (type) { - case BI.DynamicDateCombo.Dynamic: - this.dynamicPane.setValue(value); - self._setInnerValue(); - break; - case BI.DynamicDateCombo.Static: - default: - this.year.setValue(value); - this.textButton.setValue(BI.i18nText("BI-Basic_Current_Month")); - this.textButton.setEnable(!this._checkTodayValid()); - break; + case DynamicDateCombo.Dynamic: + this.dynamicPane.setValue(value); + this._setInnerValue(); + break; + case DynamicDateCombo.Static: + default: + this.year.setValue(value); + this.textButton.setValue(i18nText("BI-Basic_Current_Month")); + this.textButton.setEnable(!this._checkTodayValid()); + break; } - }, + } - getValue: function () { + getValue() { return { type: this.dateTab.getSelect(), - value: this.dateTab.getValue() + value: this.dateTab.getValue(), }; } - -}); -BI.DynamicYearMonthPopup.BUTTON_CLEAR_EVENT_CHANGE = "BUTTON_CLEAR_EVENT_CHANGE"; -BI.DynamicYearMonthPopup.BUTTON_lABEL_EVENT_CHANGE = "BUTTON_lABEL_EVENT_CHANGE"; -BI.DynamicYearMonthPopup.BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE"; -BI.DynamicYearMonthPopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.dynamic_year_month_popup", BI.DynamicYearMonthPopup); \ No newline at end of file +} diff --git a/src/widget/yearmonth/trigger.yearmonth.js b/src/widget/yearmonth/trigger.yearmonth.js index 7995a007b..029366d2c 100644 --- a/src/widget/yearmonth/trigger.yearmonth.js +++ b/src/widget/yearmonth/trigger.yearmonth.js @@ -1,101 +1,174 @@ -BI.DynamicYearMonthTrigger = BI.inherit(BI.Trigger, { - _const: { - hgap: 4, - vgap: 2, - iconWidth: 24 - }, +import { + shortcut, + bind, + createWidget, + i18nText, + HTapeLayout, + CenterLayout, + HorizontalFillLayout, + isEmptyString, + parseDateTime, + isPositiveInteger, + checkDateVoid, + isNotEmptyString, + getDate, + print, + isNotNull, + checkDateLegal, + parseInt, + isNull +} from "@/core"; +import { Trigger, TextButton } from "@/base"; +import { TriggerIconButton, SignEditor } from "@/case"; +import { DynamicDateCombo, DynamicDateHelper } from "../dynamicdate"; - props: () => ({ - extraCls: "bi-year-month-trigger", - min: "1900-01-01", // 最小日期 - max: "2099-12-31", // 最大日期 - height: 24, - watermark: { - year: BI.i18nText("BI-Basic_Unrestricted"), - month: BI.i18nText("BI-Basic_Unrestricted"), - }, - }), +@shortcut() +export class DynamicYearMonthTrigger extends Trigger { + static xtype = "bi.dynamic_year_month_trigger"; - beforeInit: function (callback) { - var o = this.options; - o.title = BI.bind(this._titleCreator, this); + _const = { hgap: 4, vgap: 2, iconWidth: 24 }; + + static EVENT_VALID = "EVENT_VALID"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_START = "EVENT_START"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; + + props() { + return { + extraCls: "bi-year-month-trigger", + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 + height: 24, + watermark: { + year: i18nText("BI-Basic_Unrestricted"), + month: i18nText("BI-Basic_Unrestricted"), + }, + }; + } + + beforeInit(callback) { + const o = this.options; + o.title = bind(this._titleCreator, this); callback(); - }, + } - _init: function () { - BI.DynamicYearMonthTrigger.superclass._init.apply(this, arguments); - var o = this.options; + _init() { + super._init(...arguments); + const o = this.options; this.yearEditor = this._createEditor(true); this.monthEditor = this._createEditor(false); - BI.createWidget({ + createWidget({ element: this, - type: "bi.htape", - items: [{ - type: "bi.center", - items: [{ - type: "bi.horizontal_fill", - columnSize: ["fill", ""], - items: [this.yearEditor, { - el: { - type: "bi.text_button", - text: BI.i18nText("BI-Multi_Date_Year"), - }, - }] - }, { - type: "bi.horizontal_fill", - columnSize: ["fill", ""], - items: [this.monthEditor, { - el: { - type: "bi.text_button", - text: BI.i18nText("BI-Multi_Date_Month"), + type: HTapeLayout.xtype, + items: [ + { + type: CenterLayout.xtype, + items: [ + { + type: HorizontalFillLayout.xtype, + columnSize: ["fill", ""], + items: [ + this.yearEditor, + { + el: { + type: TextButton.xtype, + text: i18nText("BI-Multi_Date_Year"), + }, + } + ], }, - }] - }] - }, { - el: { - type: "bi.trigger_icon_button", - width: this._const.iconWidth + { + type: HorizontalFillLayout.xtype, + columnSize: ["fill", ""], + items: [ + this.monthEditor, + { + el: { + type: TextButton.xtype, + text: i18nText("BI-Multi_Date_Month"), + }, + } + ], + } + ], }, - width: this._const.iconWidth - }] + { + el: { + type: TriggerIconButton.xtype, + width: this._const.iconWidth, + }, + width: this._const.iconWidth, + } + ], }); this.setValue(o.value); - }, + } - _createEditor: function (isYear) { - var self = this, o = this.options, c = this._const; - var editor = BI.createWidget({ - type: "bi.sign_editor", + _createEditor(isYear) { + const o = this.options, + c = this._const; + const editor = createWidget({ + type: SignEditor.xtype, simple: o.simple, height: o.height, - validationChecker: function (v) { + validationChecker: v => { if (isYear) { - var month = self.monthEditor.getValue(); - if(BI.isEmptyString(month)) { - month = parseInt(v, 10) === BI.parseDateTime(o.min, "%Y-%X-%d").getFullYear() ? (BI.parseDateTime(o.min, "%Y-%X-%d").getMonth() + 1) : 1; + let month = this.monthEditor.getValue(); + if (isEmptyString(month)) { + month = + parseInt(v, 10) === + parseDateTime(o.min, "%Y-%X-%d").getFullYear() + ? parseDateTime(o.min, "%Y-%X-%d").getMonth() + + 1 + : 1; } - return v === "" || (BI.isPositiveInteger(v) && !BI.checkDateVoid(v, month, 1, o.min, o.max)[0]); + + return ( + v === "" || + (isPositiveInteger(v) && + !checkDateVoid(v, month, 1, o.min, o.max)[0]) + ); } - var year = self.yearEditor.getValue(); + const year = this.yearEditor.getValue(); - return v === "" || ((BI.isPositiveInteger(v) && v >= 1 && v <= 12) && (BI.isEmptyString(year) ? true : !BI.checkDateVoid(self.yearEditor.getValue(), v, 1, o.min, o.max)[0])); - }, - quitChecker: function () { - return false; + return ( + v === "" || + (isPositiveInteger(v) && + v >= 1 && + v <= 12 && + (isEmptyString(year) + ? true + : !checkDateVoid( + this.yearEditor.getValue(), + v, + 1, + o.min, + o.max + )[0])) + ); }, + quitChecker: () => false, watermark: isYear ? o.watermark?.year : o.watermark.month, - errorText: function (v) { - var year = isYear ? v : self.yearEditor.getValue(); - var month = isYear ? self.monthEditor.getValue() : v; - if (!BI.isPositiveInteger(year) || !BI.isPositiveInteger(month) || month > 12) { - return BI.i18nText("BI-Year_Trigger_Invalid_Text"); + errorText: v => { + const year = isYear ? v : this.yearEditor.getValue(); + const month = isYear ? this.monthEditor.getValue() : v; + if ( + !isPositiveInteger(year) || + !isPositiveInteger(month) || + month > 12 + ) { + return i18nText("BI-Year_Trigger_Invalid_Text"); } - var start = BI.parseDateTime(o.min, "%Y-%X-%d"); - var end = BI.parseDateTime(o.max, "%Y-%X-%d"); + const start = parseDateTime(o.min, "%Y-%X-%d"); + const end = parseDateTime(o.max, "%Y-%X-%d"); - return BI.i18nText("BI-Basic_Year_Month_Range_Error", + return i18nText( + "BI-Basic_Year_Month_Range_Error", start.getFullYear(), start.getMonth() + 1, end.getFullYear(), @@ -104,192 +177,212 @@ BI.DynamicYearMonthTrigger = BI.inherit(BI.Trigger, { }, hgap: c.hgap, vgap: c.vgap, - allowBlank: true + allowBlank: true, }); - editor.on(BI.SignEditor.EVENT_KEY_DOWN, function () { - self.fireEvent(BI.DynamicYearMonthTrigger.EVENT_KEY_DOWN); + editor.on(SignEditor.EVENT_KEY_DOWN, () => { + this.fireEvent(DynamicYearMonthTrigger.EVENT_KEY_DOWN); }); - editor.on(BI.SignEditor.EVENT_FOCUS, function () { - self.fireEvent(BI.DynamicYearMonthTrigger.EVENT_FOCUS); + editor.on(SignEditor.EVENT_FOCUS, () => { + this.fireEvent(DynamicYearMonthTrigger.EVENT_FOCUS); }); - editor.on(BI.SignEditor.EVENT_STOP, function () { - self.fireEvent(BI.DynamicYearMonthTrigger.EVENT_STOP); + editor.on(SignEditor.EVENT_STOP, () => { + this.fireEvent(DynamicYearMonthTrigger.EVENT_STOP); }); - editor.on(BI.SignEditor.EVENT_CONFIRM, function () { - self._doEditorConfirm(editor); - self.fireEvent(BI.DynamicYearMonthTrigger.EVENT_CONFIRM); + editor.on(SignEditor.EVENT_CONFIRM, () => { + this._doEditorConfirm(editor); + this.fireEvent(DynamicYearMonthTrigger.EVENT_CONFIRM); }); - editor.on(BI.SignEditor.EVENT_SPACE, function () { + editor.on(SignEditor.EVENT_SPACE, () => { if (editor.isValid()) { editor.blur(); } }); - editor.on(BI.SignEditor.EVENT_START, function () { - self.fireEvent(BI.DynamicYearMonthTrigger.EVENT_START); + editor.on(SignEditor.EVENT_START, () => { + this.fireEvent(DynamicYearMonthTrigger.EVENT_START); }); - editor.on(BI.SignEditor.EVENT_ERROR, function () { - self.fireEvent(BI.DynamicYearMonthTrigger.EVENT_ERROR); + editor.on(SignEditor.EVENT_ERROR, () => { + this.fireEvent(DynamicYearMonthTrigger.EVENT_ERROR); }); - editor.on(BI.SignEditor.EVENT_VALID, function () { - var year = self.yearEditor.getValue(); - var month = self.monthEditor.getValue(); - if(BI.isNotEmptyString(year) && BI.isNotEmptyString(month)) { - if(BI.isPositiveInteger(year) && month >= 1 && month <= 12 && !BI.checkDateVoid(year, month, 1, o.min, o.max)[0]) { - self.fireEvent(BI.DynamicYearMonthTrigger.EVENT_VALID); + editor.on(SignEditor.EVENT_VALID, () => { + const year = this.yearEditor.getValue(); + const month = this.monthEditor.getValue(); + if (isNotEmptyString(year) && isNotEmptyString(month)) { + if ( + isPositiveInteger(year) && + month >= 1 && + month <= 12 && + !checkDateVoid(year, month, 1, o.min, o.max)[0] + ) { + this.fireEvent(DynamicYearMonthTrigger.EVENT_VALID); } } }); - editor.on(BI.SignEditor.EVENT_CHANGE, function () { - if(isYear) { - self._autoSwitch(editor); + editor.on(SignEditor.EVENT_CHANGE, () => { + if (isYear) { + this._autoSwitch(editor); } }); return editor; - }, + } - _titleCreator: function () { - var storeValue = this.storeValue || {}; - var type = storeValue.type || BI.DynamicDateCombo.Static; - var value = storeValue.value; - if(!this.monthEditor.isValid() || !this.yearEditor.isValid()) { + _titleCreator() { + const storeValue = this.storeValue || {}; + const type = storeValue.type || DynamicDateCombo.Static; + let value = storeValue.value; + if (!this.monthEditor.isValid() || !this.yearEditor.isValid()) { return ""; } switch (type) { - case BI.DynamicDateCombo.Dynamic: - var text = this._getText(value); - var date = BI.getDate(); - date = BI.DynamicDateHelper.getCalculation(value); - var dateStr = BI.print(date, "%Y-%x"); - return BI.isEmptyString(text) ? dateStr : (text + ":" + dateStr); - case BI.DynamicDateCombo.Static: - default: - value = value || {}; - return this._getStaticTitle(value); + case DynamicDateCombo.Dynamic: { + const text = this._getText(value); + let date = getDate(); + date = DynamicDateHelper.getCalculation(value); + const dateStr = print(date, "%Y-%x"); + + return isEmptyString(text) ? dateStr : `${text}:${dateStr}`; + } + case DynamicDateCombo.Static: + default: + value = value || {}; + + return this._getStaticTitle(value); } - }, + } - _doEditorConfirm: function (editor) { - var value = editor.getValue(); - if (BI.isNotNull(value)) { + _doEditorConfirm(editor) { + const value = editor.getValue(); + if (isNotNull(value)) { editor.setValue(value); } - var monthValue = this.monthEditor.getValue(); + const monthValue = this.monthEditor.getValue(); this.storeValue = { - type: BI.DynamicDateCombo.Static, + type: DynamicDateCombo.Static, value: { year: this.yearEditor.getValue(), - month: BI.isEmptyString(this.monthEditor.getValue()) ? "" : monthValue - } + month: isEmptyString(this.monthEditor.getValue()) + ? "" + : monthValue, + }, }; - }, + } - _yearCheck: function (v) { - var date = BI.print(BI.parseDateTime(v, "%Y-%X-%d"), "%Y-%X-%d"); - return BI.print(BI.parseDateTime(v, "%Y"), "%Y") === v && date >= this.options.min && date <= this.options.max; - }, + _yearCheck(v) { + const date = print(parseDateTime(v, "%Y-%X-%d"), "%Y-%X-%d"); + + return ( + print(parseDateTime(v, "%Y"), "%Y") === v && + date >= this.options.min && + date <= this.options.max + ); + } - _autoSwitch: function (editor) { - var v = editor.getValue(); - if (BI.isNotEmptyString(v) && BI.checkDateLegal(v)) { + _autoSwitch(editor) { + const v = editor.getValue(); + if (isNotEmptyString(v) && checkDateLegal(v)) { if (v.length === 4 && this._yearCheck(v)) { this._doEditorConfirm(editor); - this.fireEvent(BI.DynamicYearMonthTrigger.EVENT_CONFIRM); + this.fireEvent(DynamicYearMonthTrigger.EVENT_CONFIRM); this.monthEditor.focus(); } } - }, + } - _getText: function (obj) { - var value = ""; - if(BI.isNotNull(obj.year) && BI.parseInt(obj.year) !== 0) { - value += Math.abs(obj.year) + BI.i18nText("BI-Basic_Year") + (obj.year < 0 ? BI.i18nText("BI-Basic_Front") : BI.i18nText("BI-Basic_Behind")); + _getText(obj) { + let value = ""; + if (isNotNull(obj.year) && parseInt(obj.year) !== 0) { + value += + Math.abs(obj.year) + + i18nText("BI-Basic_Year") + + (obj.year < 0 + ? i18nText("BI-Basic_Front") + : i18nText("BI-Basic_Behind")); } - if(BI.isNotNull(obj.month) && BI.parseInt(obj.month) !== 0) { - value += Math.abs(obj.month) + BI.i18nText("BI-Basic_Month") + (obj.month < 0 ? BI.i18nText("BI-Basic_Front") : BI.i18nText("BI-Basic_Behind")); + if (isNotNull(obj.month) && parseInt(obj.month) !== 0) { + value += + Math.abs(obj.month) + + i18nText("BI-Basic_Month") + + (obj.month < 0 + ? i18nText("BI-Basic_Front") + : i18nText("BI-Basic_Behind")); } + return value; - }, + } - _setInnerValue: function (date, text) { + _setInnerValue(date, text) { this.yearEditor.setValue(date.getFullYear()); this.monthEditor.setValue(date.getMonth() + 1); - }, + } - _getStaticTitle: function (value) { + _getStaticTitle(value) { value = value || {}; - var hasYear = !(BI.isNull(value.year) || BI.isEmptyString(value.year)); - var hasMonth = !(BI.isNull(value.month) || BI.isEmptyString(value.month)); + const hasYear = !(isNull(value.year) || isEmptyString(value.year)); + const hasMonth = !(isNull(value.month) || isEmptyString(value.month)); switch ((hasYear << 1) | hasMonth) { - // !hasYear && !hasMonth - case 0: - return ""; + // !hasYear && !hasMonth + case 0: + return ""; // !hasYear && hasMonth - case 1: - return value.month; + case 1: + return value.month; // hasYear && !hasMonth - case 2: - return value.year; + case 2: + return value.year; // hasYear && hasMonth - case 3: - default: - return value.year + "-" + value.month; + case 3: + default: + return `${value.year}-${value.month}`; } - }, + } - setMinDate: function (minDate) { - if (BI.isNotEmptyString(this.options.min)) { + setMinDate(minDate) { + if (isNotEmptyString(this.options.min)) { this.options.min = minDate; } - }, + } - setMaxDate: function (maxDate) { - if (BI.isNotEmptyString(this.options.max)) { + setMaxDate(maxDate) { + if (isNotEmptyString(this.options.max)) { this.options.max = maxDate; } - }, + } - setValue: function (v) { - var type, value; - var date = BI.getDate(); + setValue(v) { + let type, value; + let date = getDate(); this.storeValue = v; - if (BI.isNotNull(v)) { - type = v.type || BI.DynamicDateCombo.Static; + if (isNotNull(v)) { + type = v.type || DynamicDateCombo.Static; value = v.value || v; } switch (type) { - case BI.DynamicDateCombo.Dynamic: - var text = this._getText(value); - date = BI.DynamicDateHelper.getCalculation(value); - this._setInnerValue(date, text); - break; - case BI.DynamicDateCombo.Static: - default: - value = value || {}; - var month = BI.isNull(value.month) ? null : value.month; - this.yearEditor.setValue(value.year); - this.monthEditor.setValue(month); - break; + case DynamicDateCombo.Dynamic: { + const text = this._getText(value); + date = DynamicDateHelper.getCalculation(value); + this._setInnerValue(date, text); + break; + } + case DynamicDateCombo.Static: + default: { + value = value || {}; + const month = isNull(value.month) ? null : value.month; + this.yearEditor.setValue(value.year); + this.monthEditor.setValue(month); + break; + } } - }, + } - getValue: function () { + getValue() { return this.storeValue; - }, + } - getKey: function () { - return this.yearEditor.getValue() + "-" + this.monthEditor.getValue(); - }, + getKey() { + return `${this.yearEditor.getValue()}-${this.monthEditor.getValue()}`; + } - isStateValid: function () { + isStateValid() { return this.yearEditor.isValid() && this.monthEditor.isValid(); } -}); -BI.DynamicYearMonthTrigger.EVENT_VALID = "EVENT_VALID"; -BI.DynamicYearMonthTrigger.EVENT_FOCUS = "EVENT_FOCUS"; -BI.DynamicYearMonthTrigger.EVENT_ERROR = "EVENT_ERROR"; -BI.DynamicYearMonthTrigger.EVENT_START = "EVENT_START"; -BI.DynamicYearMonthTrigger.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.DynamicYearMonthTrigger.EVENT_STOP = "EVENT_STOP"; -BI.DynamicYearMonthTrigger.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.shortcut("bi.dynamic_year_month_trigger", BI.DynamicYearMonthTrigger); +} diff --git a/src/widget/yearmonthinterval/yearmonthinterval.js b/src/widget/yearmonthinterval/yearmonthinterval.js index 814123f67..c2721998e 100644 --- a/src/widget/yearmonthinterval/yearmonthinterval.js +++ b/src/widget/yearmonthinterval/yearmonthinterval.js @@ -1,49 +1,74 @@ -BI.YearMonthInterval = BI.inherit(BI.Single, { - constants: { +import { + shortcut, + HorizontalFillLayout, + createWidget, + i18nText, + print, + parseDateTime, + checkDateVoid, + isNotNull, + checkDateLegal +} from "@/core"; +import { Single, Label, Bubbles } from "@/base"; +import { DynamicYearMonthCombo } from "../yearmonth/combo.yearmonth"; + +@shortcut() +export class YearMonthInterval extends Single { + static xtype = "bi.year_month_interval"; + + static EVENT_VALID = "EVENT_VALID"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + + constants = { width: 25, lgap: 15, offset: -15, - timeErrorCls: "time-error" - }, - - props: { + timeErrorCls: "time-error", + }; + props = { extraCls: "bi-year-month-interval", minDate: "1900-01-01", maxDate: "2099-12-31", supportDynamic: true, - height: 24 - }, + height: 24, + }; - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; o.value = o.value || {}; this.left = this._createCombo(o.value.start, o.watermark?.start); this.right = this._createCombo(o.value.end, o.watermark?.end); - + return { - type: "bi.horizontal_fill", + type: HorizontalFillLayout.xtype, columnSize: ["fill", "", "fill"], - items: [{ - el: self.left - }, { - el: { - type: "bi.label", - height: o.height, - hgap: 5, - text: "-", - ref: function (_ref) { - self.label = _ref; - } + items: [ + { + el: this.left, + }, + { + el: { + type: Label.xtype, + height: o.height, + hgap: 5, + text: "-", + ref: _ref => { + this.label = _ref; + }, + }, + }, + { + el: this.right, } - }, { - el: self.right - }] + ], }; - }, + } - _createCombo: function (v, watermark) { - var self = this, o = this.options; - var combo = BI.createWidget({ + _createCombo(v, watermark) { + const o = this.options; + const combo = createWidget({ type: "bi.dynamic_year_month_combo", supportDynamic: o.supportDynamic, height: o.height, @@ -51,138 +76,168 @@ BI.YearMonthInterval = BI.inherit(BI.Single, { maxDate: o.maxDate, behaviors: o.behaviors, value: v, - watermark: watermark, - listeners: [{ - eventName: BI.DynamicYearMonthCombo.EVENT_BEFORE_POPUPVIEW, - action: function () { - self.fireEvent(BI.YearMonthInterval.EVENT_BEFORE_POPUPVIEW); + watermark, + listeners: [ + { + eventName: DynamicYearMonthCombo.EVENT_BEFORE_POPUPVIEW, + action: () => { + this.fireEvent( + YearMonthInterval.EVENT_BEFORE_POPUPVIEW + ); + }, } - }] + ], }); - combo.on(BI.DynamicYearMonthCombo.EVENT_ERROR, function () { - self._clearTitle(); - BI.Bubbles.hide("error"); - self.element.removeClass(self.constants.timeErrorCls); - self.fireEvent(BI.YearMonthInterval.EVENT_ERROR); + combo.on(DynamicYearMonthCombo.EVENT_ERROR, () => { + this._clearTitle(); + Bubbles.hide("error"); + this.element.removeClass(this.constants.timeErrorCls); + this.fireEvent(YearMonthInterval.EVENT_ERROR); }); - combo.on(BI.DynamicYearMonthCombo.EVENT_VALID, function () { - self._checkValid(); + combo.on(DynamicYearMonthCombo.EVENT_VALID, () => { + this._checkValid(); }); - combo.on(BI.DynamicYearMonthCombo.EVENT_FOCUS, function () { - self._checkValid(); + combo.on(DynamicYearMonthCombo.EVENT_FOCUS, () => { + this._checkValid(); }); - combo.on(BI.DynamicYearMonthCombo.EVENT_CONFIRM, function () { - BI.Bubbles.hide("error"); - var smallDate = self.left.getKey(), bigDate = self.right.getKey(); - if (self.left.isStateValid() && self.right.isStateValid() && self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { - self._setTitle(BI.i18nText("BI-Time_Interval_Error_Text")); - self.element.addClass(self.constants.timeErrorCls); - self.fireEvent(BI.YearMonthInterval.EVENT_ERROR); - }else{ - self._clearTitle(); - self.element.removeClass(self.constants.timeErrorCls); - self.fireEvent(BI.YearMonthInterval.EVENT_CHANGE); + combo.on(DynamicYearMonthCombo.EVENT_CONFIRM, () => { + Bubbles.hide("error"); + const smallDate = this.left.getKey(), + bigDate = this.right.getKey(); + if ( + this.left.isStateValid() && + this.right.isStateValid() && + this._check(smallDate, bigDate) && + this._compare(smallDate, bigDate) + ) { + this._setTitle(i18nText("BI-Time_Interval_Error_Text")); + this.element.addClass(this.constants.timeErrorCls); + this.fireEvent(YearMonthInterval.EVENT_ERROR); + } else { + this._clearTitle(); + this.element.removeClass(this.constants.timeErrorCls); + this.fireEvent(YearMonthInterval.EVENT_CHANGE); } }); + return combo; - }, - - - _dateCheck: function (date) { - return BI.print(BI.parseDateTime(date, "%Y-%x"), "%Y-%x") === date || BI.print(BI.parseDateTime(date, "%Y-%X"), "%Y-%X") === date; - }, + } + _dateCheck(date) { + return ( + print(parseDateTime(date, "%Y-%x"), "%Y-%x") === date || + print(parseDateTime(date, "%Y-%X"), "%Y-%X") === date + ); + } - // 判是否在最大最小之间 - _checkVoid: function (obj) { - var o = this.options; - return !BI.checkDateVoid(obj.year, obj.month, 1, o.minDate, o.maxDate)[0]; - }, + _checkVoid(obj) { + const o = this.options; + + return !checkDateVoid(obj.year, obj.month, 1, o.minDate, o.maxDate)[0]; + } - // 判格式合法 - _check: function (smallDate, bigDate) { - var smallObj = smallDate.match(/\d+/g), bigObj = bigDate.match(/\d+/g); + _check(smallDate, bigDate) { + const smallObj = smallDate.match(/\d+/g), + bigObj = bigDate.match(/\d+/g); - var smallDate4Check = ""; - if (BI.isNotNull(smallObj)) { - smallDate4Check = (smallObj[0] || "") + "-" + (smallObj[1] || 1); + let smallDate4Check = ""; + if (isNotNull(smallObj)) { + smallDate4Check = `${smallObj[0] || ""}-${smallObj[1] || 1}`; } - var bigDate4Check = ""; - if (BI.isNotNull(bigObj)) { - bigDate4Check = (bigObj[0] || "") + "-" + (bigObj[1] || 1); + let bigDate4Check = ""; + if (isNotNull(bigObj)) { + bigDate4Check = `${bigObj[0] || ""}-${bigObj[1] || 1}`; } - return this._dateCheck(smallDate4Check) && BI.checkDateLegal(smallDate4Check) && this._checkVoid({ - year: smallObj[0], - month: smallObj[1] || 1, - day: 1 - }) && this._dateCheck(bigDate4Check) && BI.checkDateLegal(bigDate4Check) && this._checkVoid({ - year: bigObj[0], - month: bigObj[1] || 1, - day: 1 - }); - }, - - _compare: function (smallDate, bigDate) { - smallDate = BI.print(BI.parseDateTime(smallDate, "%Y-%X"), "%Y-%X"); - bigDate = BI.print(BI.parseDateTime(bigDate, "%Y-%X"), "%Y-%X"); - return BI.isNotNull(smallDate) && BI.isNotNull(bigDate) && smallDate > bigDate; - }, - _setTitle: function (v) { + return ( + this._dateCheck(smallDate4Check) && + checkDateLegal(smallDate4Check) && + this._checkVoid({ + year: smallObj[0], + month: smallObj[1] || 1, + day: 1, + }) && + this._dateCheck(bigDate4Check) && + checkDateLegal(bigDate4Check) && + this._checkVoid({ + year: bigObj[0], + month: bigObj[1] || 1, + day: 1, + }) + ); + } + + _compare(smallDate, bigDate) { + smallDate = print(parseDateTime(smallDate, "%Y-%X"), "%Y-%X"); + bigDate = print(parseDateTime(bigDate, "%Y-%X"), "%Y-%X"); + + return ( + isNotNull(smallDate) && isNotNull(bigDate) && smallDate > bigDate + ); + } + + _setTitle(v) { this.setTitle(v); - }, - _clearTitle: function () { + } + + _clearTitle() { this.setTitle(""); - }, - _checkValid: function () { - var self = this; - - BI.Bubbles.hide("error"); - var smallDate = self.left.getKey(), bigDate = self.right.getKey(); - if (self.left.isValid() && self.right.isValid() && self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { - self._setTitle(BI.i18nText("BI-Time_Interval_Error_Text")); - self.element.addClass(self.constants.timeErrorCls); - BI.Bubbles.show("error", BI.i18nText("BI-Time_Interval_Error_Text"), self, { - offsetStyle: "center" - }); - self.fireEvent(BI.YearMonthInterval.EVENT_ERROR); + } + + _checkValid() { + Bubbles.hide("error"); + const smallDate = this.left.getKey(), + bigDate = this.right.getKey(); + if ( + this.left.isValid() && + this.right.isValid() && + this._check(smallDate, bigDate) && + this._compare(smallDate, bigDate) + ) { + this._setTitle(i18nText("BI-Time_Interval_Error_Text")); + this.element.addClass(this.constants.timeErrorCls); + Bubbles.show( + "error", + i18nText("BI-Time_Interval_Error_Text"), + this, + { + offsetStyle: "center", + } + ); + this.fireEvent(YearMonthInterval.EVENT_ERROR); } else { - self._clearTitle(); - self.element.removeClass(self.constants.timeErrorCls); + this._clearTitle(); + this.element.removeClass(this.constants.timeErrorCls); } - }, + } - setMinDate: function (minDate) { - var o = this.options; + setMinDate(minDate) { + const o = this.options; o.minDate = minDate; this.left.setMinDate(minDate); this.right.setMinDate(minDate); - }, + } - setMaxDate: function (maxDate) { - var o = this.options; + setMaxDate(maxDate) { + const o = this.options; o.maxDate = maxDate; this.left.setMaxDate(maxDate); this.right.setMaxDate(maxDate); - }, + } - setValue: function (date) { + setValue(date) { date = date || {}; this.left.setValue(date.start); this.right.setValue(date.end); this._checkValid(); - }, - getValue: function () { - return {start: this.left.getValue(), end: this.right.getValue()}; } -}); -BI.YearMonthInterval.EVENT_VALID = "EVENT_VALID"; -BI.YearMonthInterval.EVENT_ERROR = "EVENT_ERROR"; -BI.YearMonthInterval.EVENT_CHANGE = "EVENT_CHANGE"; -BI.YearMonthInterval.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut("bi.year_month_interval", BI.YearMonthInterval); + + getValue() { + return { start: this.left.getValue(), end: this.right.getValue() }; + } +} From 9335c4ef9387defb6a8badd793272365936b749a Mon Sep 17 00:00:00 2001 From: zsmj Date: Fri, 13 Jan 2023 15:38:14 +0800 Subject: [PATCH 114/300] update --- src/widget/multilayersingletree/index.js | 2 - .../selecttree/nodes/node.first.plus.js | 109 ------------------ src/widget/selecttree/nodes/node.last.plus.js | 109 ------------------ src/widget/selecttree/nodes/node.mid.plus.js | 109 ------------------ src/widget/selecttree/nodes/node.plus.js | 109 ------------------ 5 files changed, 438 deletions(-) delete mode 100644 src/widget/selecttree/nodes/node.first.plus.js delete mode 100644 src/widget/selecttree/nodes/node.last.plus.js delete mode 100644 src/widget/selecttree/nodes/node.mid.plus.js delete mode 100644 src/widget/selecttree/nodes/node.plus.js diff --git a/src/widget/multilayersingletree/index.js b/src/widget/multilayersingletree/index.js index 4098e74cc..d0f9e5497 100644 --- a/src/widget/multilayersingletree/index.js +++ b/src/widget/multilayersingletree/index.js @@ -3,5 +3,3 @@ export { MultiLayerSingleTreeInsertSearchPane } from "./multilayersingletree.ins export { MultiLayerSingleLevelTree } from "./multilayersingletree.leveltree"; export { MultiLayerSingleTreePopup } from "./multilayersingletree.popup"; export { MultiLayerSingleTreeTrigger } from "./multilayersingletree.trigger"; -export * from "./node"; -export * from "./treeitem"; diff --git a/src/widget/selecttree/nodes/node.first.plus.js b/src/widget/selecttree/nodes/node.first.plus.js deleted file mode 100644 index 484128e4d..000000000 --- a/src/widget/selecttree/nodes/node.first.plus.js +++ /dev/null @@ -1,109 +0,0 @@ -import { - shortcut, - extend, - createWidget, - Controller, - Events, - isNotNull, LogicFactory, Direction -} from "@/core"; -import { NodeButton, Label } from "@/base"; -import { FirstTreeNodeCheckbox } from "@/case"; - -@shortcut() -export class SelectTreeFirstPlusGroupNode extends NodeButton { - static xtype = "bi.select_tree_first_plus_group_node"; - - _defaultConfig() { - const conf = super._defaultConfig(...arguments); - - return extend(conf, { - baseCls: - `${conf.baseCls || "" - } bi-select-tree-first-plus-group-node bi-list-item-active`, - logic: { - dynamic: false, - }, - id: "", - pId: "", - readonly: true, - open: false, - height: 24, - }); - } - - _init() { - super._init(...arguments); - const self = this, - o = this.options; - this.checkbox = createWidget({ - type: FirstTreeNodeCheckbox.xtype, - stopPropagation: true, - iconHeight: o.height, - iconWidth: o.height, - }); - this.text = createWidget({ - type: Label.xtype, - textAlign: "left", - whiteSpace: "nowrap", - textHeight: o.height, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - keyword: o.keyword, - py: o.py, - }); - this.checkbox.on(Controller.EVENT_CHANGE, function (type) { - if (type === Events.CLICK) { - if (this.isSelected()) { - self.triggerExpand(); - } else { - self.triggerCollapse(); - } - } - }); - const type = LogicFactory.createLogicTypeByDirection( - Direction.Left - ); - const items = LogicFactory.createLogicItemsByDirection( - Direction.Left, - { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: this.checkbox, - }, - this.text - ); - createWidget( - extend( - { - element: this, - }, - LogicFactory.createLogic( - type, - extend(o.logic, { - items, - }) - ) - ) - ); - } - - isOnce() { - return true; - } - - doRedMark() { - this.text.doRedMark(...arguments); - } - - unRedMark() { - this.text.unRedMark(...arguments); - } - - setOpened(v) { - super.setOpened(...arguments); - if (isNotNull(this.checkbox)) { - this.checkbox.setSelected(v); - } - } -} diff --git a/src/widget/selecttree/nodes/node.last.plus.js b/src/widget/selecttree/nodes/node.last.plus.js deleted file mode 100644 index 572d66e55..000000000 --- a/src/widget/selecttree/nodes/node.last.plus.js +++ /dev/null @@ -1,109 +0,0 @@ -import { - shortcut, - extend, - createWidget, - Controller, - Events, - isNotNull, LogicFactory, Direction -} from "@/core"; -import { NodeButton, Label } from "@/base"; -import { LastTreeNodeCheckbox } from "@/case"; - -@shortcut() -export class SelectTreeLastPlusGroupNode extends NodeButton { - static xtype = "bi.select_tree_last_plus_group_node"; - - _defaultConfig() { - const conf = super._defaultConfig(...arguments); - - return extend(conf, { - baseCls: - `${conf.baseCls || "" - } bi-select-tree-last-plus-group-node bi-list-item-active`, - logic: { - dynamic: false, - }, - id: "", - pId: "", - readonly: true, - open: false, - height: 24, - }); - } - - _init() { - super._init(...arguments); - const self = this, - o = this.options; - this.checkbox = createWidget({ - type: LastTreeNodeCheckbox.xtype, - stopPropagation: true, - iconHeight: o.height, - iconWidth: o.height, - }); - this.text = createWidget({ - type: Label.xtype, - textAlign: "left", - whiteSpace: "nowrap", - textHeight: o.height, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - keyword: o.keyword, - py: o.py, - }); - this.checkbox.on(Controller.EVENT_CHANGE, function (type) { - if (type === Events.CLICK) { - if (this.isSelected()) { - self.triggerExpand(); - } else { - self.triggerCollapse(); - } - } - }); - const type = LogicFactory.createLogicTypeByDirection( - Direction.Left - ); - const items = LogicFactory.createLogicItemsByDirection( - Direction.Left, - { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: this.checkbox, - }, - this.text - ); - createWidget( - extend( - { - element: this, - }, - LogicFactory.createLogic( - type, - extend(o.logic, { - items, - }) - ) - ) - ); - } - - isOnce() { - return true; - } - - doRedMark() { - this.text.doRedMark(...arguments); - } - - unRedMark() { - this.text.unRedMark(...arguments); - } - - setOpened(v) { - super.setOpened(...arguments); - if (isNotNull(this.checkbox)) { - this.checkbox.setSelected(v); - } - } -} diff --git a/src/widget/selecttree/nodes/node.mid.plus.js b/src/widget/selecttree/nodes/node.mid.plus.js deleted file mode 100644 index 670533dd5..000000000 --- a/src/widget/selecttree/nodes/node.mid.plus.js +++ /dev/null @@ -1,109 +0,0 @@ -import { - shortcut, - extend, - createWidget, - Controller, - Events, - isNotNull, Direction, LogicFactory -} from "@/core"; -import { NodeButton, Label } from "@/base"; -import { MidTreeNodeCheckbox } from "@/case"; - -@shortcut() -export class SelectTreeMidPlusGroupNode extends NodeButton { - static xtype = "bi.select_tree_mid_plus_group_node"; - - _defaultConfig() { - const conf = super._defaultConfig(...arguments); - - return extend(conf, { - baseCls: - `${conf.baseCls || "" - } bi-select-tree-mid-plus-group-node bi-list-item-active`, - logic: { - dynamic: false, - }, - id: "", - pId: "", - readonly: true, - open: false, - height: 24, - }); - } - - _init() { - super._init(...arguments); - const self = this, - o = this.options; - this.checkbox = createWidget({ - type: MidTreeNodeCheckbox.xtype, - stopPropagation: true, - iconHeight: o.height, - iconWidth: o.height, - }); - this.text = createWidget({ - type: Label.xtype, - textAlign: "left", - whiteSpace: "nowrap", - textHeight: o.height, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - keyword: o.keyword, - py: o.py, - }); - this.checkbox.on(Controller.EVENT_CHANGE, function (type) { - if (type === Events.CLICK) { - if (this.isSelected()) { - self.triggerExpand(); - } else { - self.triggerCollapse(); - } - } - }); - const type = LogicFactory.createLogicTypeByDirection( - Direction.Left - ); - const items = LogicFactory.createLogicItemsByDirection( - Direction.Left, - { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: this.checkbox, - }, - this.text - ); - createWidget( - extend( - { - element: this, - }, - LogicFactory.createLogic( - type, - extend(o.logic, { - items, - }) - ) - ) - ); - } - - isOnce() { - return true; - } - - doRedMark() { - this.text.doRedMark(...arguments); - } - - unRedMark() { - this.text.unRedMark(...arguments); - } - - setOpened(v) { - super.setOpened(...arguments); - if (isNotNull(this.checkbox)) { - this.checkbox.setSelected(v); - } - } -} diff --git a/src/widget/selecttree/nodes/node.plus.js b/src/widget/selecttree/nodes/node.plus.js deleted file mode 100644 index e3e41de7f..000000000 --- a/src/widget/selecttree/nodes/node.plus.js +++ /dev/null @@ -1,109 +0,0 @@ -import { - shortcut, - extend, - createWidget, - Controller, - Events, - isNotNull, LogicFactory -} from "@/core"; -import { NodeButton, Label } from "@/base"; -import { TreeNodeCheckbox } from "@/case"; - -@shortcut() -export class SelectTreePlusGroupNode extends NodeButton { - static xtype = "bi.select_tree_plus_group_node"; - - _defaultConfig() { - const conf = super._defaultConfig(...arguments); - - return extend(conf, { - baseCls: - `${conf.baseCls || "" - } bi-select-tree-plus-group-node bi-list-item-active`, - logic: { - dynamic: false, - }, - id: "", - pId: "", - readonly: true, - open: false, - height: 24, - }); - } - - _init() { - super._init(...arguments); - const self = this, - o = this.options; - this.checkbox = createWidget({ - type: TreeNodeCheckbox.xtype, - stopPropagation: true, - iconHeight: o.height, - iconWidth: o.iconWrapperWidth || o.height, - }); - this.text = createWidget({ - type: Label.xtype, - textAlign: "left", - whiteSpace: "nowrap", - textHeight: o.height, - height: o.height, - hgap: o.hgap, - text: o.text, - value: o.value, - keyword: o.keyword, - py: o.py, - }); - this.checkbox.on(Controller.EVENT_CHANGE, function (type) { - if (type === Events.CLICK) { - if (this.isSelected()) { - self.triggerExpand(); - } else { - self.triggerCollapse(); - } - } - }); - const type = LogicFactory.createLogicTypeByDirection( - BI.Direction.Left - ); - const items = LogicFactory.createLogicItemsByDirection( - BI.Direction.Left, - { - width: 24, - el: this.checkbox, - }, - this.text - ); - createWidget( - extend( - { - element: this, - }, - LogicFactory.createLogic( - type, - extend(o.logic, { - items, - }) - ) - ) - ); - } - - isOnce() { - return true; - } - - doRedMark() { - this.text.doRedMark(...arguments); - } - - unRedMark() { - this.text.unRedMark(...arguments); - } - - setOpened(v) { - super.setOpened(...arguments); - if (isNotNull(this.checkbox)) { - this.checkbox.setSelected(v); - } - } -} From 6b225705fc7e0329aed15f74a349eec301de7f36 Mon Sep 17 00:00:00 2001 From: "Zhenfei.Li" Date: Fri, 13 Jan 2023 15:40:20 +0800 Subject: [PATCH 115/300] =?UTF-8?q?KERNEL-14116=20refactor:=20component/al?= =?UTF-8?q?lvaluechooser=E3=80=81allvaluemultitextvaluecombo=E3=80=81form?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../abstract.allvaluechooser.js | 125 +++++++------- .../allvaluechooser/combo.allvaluechooser.js | 92 +++++------ src/component/allvaluechooser/index.js | 3 + .../allvaluechooser/pane.allvaluechooser.js | 78 +++++---- .../allvalue.multitextvalue.combo.js | 82 ++++----- src/component/form/form.field.js | 155 ++++++++++-------- src/component/form/form.js | 105 ++++++------ src/component/form/index.js | 2 + src/component/index.js | 15 ++ 9 files changed, 350 insertions(+), 307 deletions(-) create mode 100644 src/component/allvaluechooser/index.js create mode 100644 src/component/form/index.js create mode 100644 src/component/index.js diff --git a/src/component/allvaluechooser/abstract.allvaluechooser.js b/src/component/allvaluechooser/abstract.allvaluechooser.js index c13d8a30f..1673d2866 100644 --- a/src/component/allvaluechooser/abstract.allvaluechooser.js +++ b/src/component/allvaluechooser/abstract.allvaluechooser.js @@ -1,61 +1,74 @@ -/** - * 简单的复选下拉框控件, 适用于数据量少的情况, 与valuechooser的区别是allvaluechooser setValue和getValue返回的是所有值 - * 封装了字段处理逻辑 - * - * Created by GUY on 2015/10/29. - * @class BI.AbstractAllValueChooser - * @extends BI.Widget - */ -BI.AbstractAllValueChooser = BI.inherit(BI.Widget, { +import { + shortcut, + Widget, + extend, + emptyFn, + isNotNull, + some, + isNotEmptyArray, + each, + Func, + uniq, + makeObject, + filter, + difference, + map, + Selection +} from "@/core"; +import { MultiSelectCombo } from "@/widget"; - _const: { - perPage: 100 - }, +@shortcut() +export class AbstractAllValueChooser extends Widget { + _const = { perPage: 100 }; - _defaultConfig: function () { - return BI.extend(BI.AbstractAllValueChooser.superclass._defaultConfig.apply(this, arguments), { + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { width: 200, height: 30, items: null, - itemsCreator: BI.emptyFn, - cache: true + itemsCreator: emptyFn, + cache: true, }); - }, + } - _valueFormatter: function (v) { - var text = v; + _valueFormatter(v) { + let text = v; if (this.options.valueFormatter) { return this.options.valueFormatter(v); } - if (BI.isNotNull(this.items)) { - BI.some(this.items, function (i, item) { + if (isNotNull(this.items)) { + some(this.items, (i, item) => { // 把value都换成字符串 // 需要考虑到value也可能是数字 - if (item.value === v || item.value + "" === v) { + if (item.value === v || `${item.value}` === v) { text = item.text; + return true; } }); } + return text; - }, + } - _getItemsByTimes: function (items, times) { - var res = []; - for (var i = (times - 1) * this._const.perPage; items[i] && i < times * this._const.perPage; i++) { + _getItemsByTimes(items, times) { + const res = []; + for (let i = (times - 1) * this._const.perPage; items[i] && i < times * this._const.perPage; i++) { res.push(items[i]); } + return res; - }, + } - _hasNextByTimes: function (items, times) { + _hasNextByTimes(items, times) { return times * this._const.perPage < items.length; - }, + } - _itemsCreator: function (options, callback) { - var self = this, o = this.options; + _itemsCreator(options, callback) { + const self = this, + o = this.options; if (!o.cache || !this.items) { - o.itemsCreator({}, function (items) { + o.itemsCreator({}, items => { self.items = items; call(items); }); @@ -64,54 +77,56 @@ BI.AbstractAllValueChooser = BI.inherit(BI.Widget, { } function call(items) { - var keywords = (options.keywords || []).slice(); + const keywords = (options.keywords || []).slice(); if (options.keyword) { keywords.push(options.keyword); } - var resultItems = items; - if (BI.isNotEmptyArray(keywords)) { + let resultItems = items; + if (isNotEmptyArray(keywords)) { resultItems = []; - BI.each(keywords, function (i, kw) { - var search = BI.Func.getSearchResult(items, kw); + each(keywords, (i, kw) => { + const search = Func.getSearchResult(items, kw); resultItems = resultItems.concat(search.match).concat(search.find); }); - resultItems = BI.uniq(resultItems); + resultItems = uniq(resultItems); } - if (options.selectedValues) {// 过滤 - var filter = BI.makeObject(options.selectedValues, true); - resultItems = BI.filter(resultItems, function (i, ob) { - return !filter[ob.value]; - }); + if (options.selectedValues) { + // 过滤 + const values = makeObject(options.selectedValues, true); + resultItems = filter(resultItems, (i, ob) => !values[ob.value]); } - if (options.type === BI.MultiSelectCombo.REQ_GET_ALL_DATA) { + if (options.type === MultiSelectCombo.REQ_GET_ALL_DATA) { callback({ - items: resultItems + items: resultItems, }); + return; } - if (options.type === BI.MultiSelectCombo.REQ_GET_DATA_LENGTH) { + if (options.type === MultiSelectCombo.REQ_GET_DATA_LENGTH) { callback({ count: resultItems.length }); + return; } callback({ items: self._getItemsByTimes(resultItems, options.times), - hasNext: self._hasNextByTimes(resultItems, options.times) + hasNext: self._hasNextByTimes(resultItems, options.times), }); } - }, + } - _assertValue: function (v) { + _assertValue(v) { v = v || {}; - var value = v; - if (BI.isNotNull(this.items)) { - var isAllSelect = BI.difference(BI.map(this.items, "value"), v.value).length === 0; + let value = v; + if (isNotNull(this.items)) { + const isAllSelect = difference(map(this.items, "value"), v.value).length === 0; if (isAllSelect) { value = { - type: BI.Selection.All, + type: Selection.All, value: [], }; } } + return value; - }, -}); + } +} diff --git a/src/component/allvaluechooser/combo.allvaluechooser.js b/src/component/allvaluechooser/combo.allvaluechooser.js index 11494b584..ed746ec3c 100644 --- a/src/component/allvaluechooser/combo.allvaluechooser.js +++ b/src/component/allvaluechooser/combo.allvaluechooser.js @@ -1,77 +1,77 @@ -/** - * 简单的复选下拉框控件, 适用于数据量少的情况, 与valuechooser的区别是allvaluechooser setValue和getValue返回的是所有值 - * 封装了字段处理逻辑 - * - * Created by GUY on 2015/10/29. - * @class BI.AllValueChooserCombo - * @extends BI.AbstractAllValueChooser - */ -BI.AllValueChooserCombo = BI.inherit(BI.AbstractAllValueChooser, { +import { shortcut, extend, emptyFn, isNotNull, createWidget, bind, Selection, difference, map } from "@/core"; +import { AbstractAllValueChooser } from "./abstract.allvaluechooser"; +import { MultiSelectCombo } from "@/widget"; - _defaultConfig: function () { - return BI.extend(BI.AllValueChooserCombo.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class AllValueChooserCombo extends AbstractAllValueChooser { + static xtype = "bi.all_value_chooser_combo"; + + static EVENT_CONFIRM = "EVENT_CONFIRM"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-all-value-chooser-combo", width: 200, height: 24, items: null, - itemsCreator: BI.emptyFn, - cache: true + itemsCreator: emptyFn, + cache: true, }); - }, + } - _init: function () { - BI.AllValueChooserCombo.superclass._init.apply(this, arguments); - var self = this, o = this.options; - if (BI.isNotNull(o.items)) { + _init() { + super._init(...arguments); + const o = this.options; + if (isNotNull(o.items)) { this.items = o.items; } - this.combo = BI.createWidget({ - type: "bi.multi_select_combo", + this.combo = createWidget({ + type: MultiSelectCombo.xtype, simple: o.simple, text: o.text, element: this, - itemsCreator: BI.bind(this._itemsCreator, this), - valueFormatter: BI.bind(this._valueFormatter, this), + itemsCreator: bind(this._itemsCreator, this), + valueFormatter: bind(this._valueFormatter, this), width: o.width, height: o.height, value: this._assertValue({ - type: BI.Selection.Multi, - value: o.value || [] - }) + type: Selection.Multi, + value: o.value || [], + }), }); - this.combo.on(BI.MultiSelectCombo.EVENT_CONFIRM, function () { - self.fireEvent(BI.AllValueChooserCombo.EVENT_CONFIRM); + this.combo.on(MultiSelectCombo.EVENT_CONFIRM, () => { + this.fireEvent(AllValueChooserCombo.EVENT_CONFIRM); }); - }, + } - setValue: function (v) { - this.combo.setValue(this._assertValue({ - type: BI.Selection.Multi, - value: v || [] - })); - }, + setValue(v) { + this.combo.setValue( + this._assertValue({ + type: Selection.Multi, + value: v || [], + }) + ); + } - getValue: function () { + getValue() { return this.getAllValue(); - }, + } - getAllValue: function () { - var val = this.combo.getValue() || {}; - if (val.type === BI.Selection.Multi) { + getAllValue() { + const val = this.combo.getValue() || {}; + if (val.type === Selection.Multi) { return val.value || []; } - return BI.difference(BI.map(this.items, "value"), val.value || []); - }, + return difference(map(this.items, "value"), val.value || []); + } - populate: function (items) { + populate(items) { // 直接用combo的populate不会作用到AbstractValueChooser上 - if (BI.isNotNull(items)) { + if (isNotNull(items)) { this.items = items; } this.combo.populate(); } -}); -BI.AllValueChooserCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut("bi.all_value_chooser_combo", BI.AllValueChooserCombo); +} diff --git a/src/component/allvaluechooser/index.js b/src/component/allvaluechooser/index.js new file mode 100644 index 000000000..d69b5f254 --- /dev/null +++ b/src/component/allvaluechooser/index.js @@ -0,0 +1,3 @@ +export { AbstractAllValueChooser } from "./abstract.allvaluechooser"; +export { AllValueChooserCombo } from "./combo.allvaluechooser"; +export { AllValueChooserPane } from "./pane.allvaluechooser"; diff --git a/src/component/allvaluechooser/pane.allvaluechooser.js b/src/component/allvaluechooser/pane.allvaluechooser.js index 6188f14ee..6ea534af7 100644 --- a/src/component/allvaluechooser/pane.allvaluechooser.js +++ b/src/component/allvaluechooser/pane.allvaluechooser.js @@ -1,69 +1,67 @@ -/** - * 简单的复选面板, 适用于数据量少的情况, 与valuechooser的区别是allvaluechooser setValue和getValue返回的是所有值 - * 封装了字段处理逻辑 - * - * Created by GUY on 2015/10/29. - * @class BI.AllValueChooserPane - * @extends BI.AbstractAllValueChooser - */ -BI.AllValueChooserPane = BI.inherit(BI.AbstractAllValueChooser, { +import { shortcut, extend, emptyFn, createWidget, bind, isNotNull, Selection, difference, map } from "@/core"; +import { AbstractAllValueChooser } from "./abstract.allvaluechooser"; +import { MultiSelectList } from "@/widget"; - _defaultConfig: function () { - return BI.extend(BI.AllValueChooserPane.superclass._defaultConfig.apply(this, arguments), { +@shortcut() +export class AllValueChooserPane extends AbstractAllValueChooser { + static xtype = "bi.all_value_chooser_pane"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _defaultConfig() { + return extend(super._defaultConfig(...arguments), { baseCls: "bi-all-value-chooser-pane", width: 200, height: 30, items: null, - itemsCreator: BI.emptyFn, - cache: true + itemsCreator: emptyFn, + cache: true, }); - }, + } - _init: function () { - BI.AllValueChooserPane.superclass._init.apply(this, arguments); - var self = this, o = this.options; - this.list = BI.createWidget({ - type: "bi.multi_select_list", + _init() { + super._init(...arguments); + const o = this.options; + this.list = createWidget({ + type: MultiSelectList.xtype, element: this, - itemsCreator: BI.bind(this._itemsCreator, this), - valueFormatter: BI.bind(this._valueFormatter, this), + itemsCreator: bind(this._itemsCreator, this), + valueFormatter: bind(this._valueFormatter, this), width: o.width, - height: o.height + height: o.height, }); - this.list.on(BI.MultiSelectList.EVENT_CHANGE, function () { - self.fireEvent(BI.AllValueChooserPane.EVENT_CHANGE); + this.list.on(MultiSelectList.EVENT_CHANGE, () => { + this.fireEvent(AllValueChooserPane.EVENT_CHANGE); }); - if (BI.isNotNull(o.items)) { + if (isNotNull(o.items)) { this.items = o.items; this.list.populate(); } - }, + } - setValue: function (v) { + setValue(v) { this.list.setValue({ - type: BI.Selection.Multi, - value: v || [] + type: Selection.Multi, + value: v || [], }); - }, + } - getValue: function () { - var val = this.list.getValue() || {}; - if (val.type === BI.Selection.Multi) { + getValue() { + const val = this.list.getValue() || {}; + if (val.type === Selection.Multi) { return val.value || []; } - return BI.difference(BI.map(this.items, "value"), val.value || []); - }, + return difference(map(this.items, "value"), val.value || []); + } - populate: function (items) { + populate(items) { // 直接用combo的populate不会作用到AbstractValueChooser上 - if (BI.isNotNull(items)) { + if (isNotNull(items)) { this.items = items; } this.list.populate(); } -}); -BI.AllValueChooserPane.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.all_value_chooser_pane", BI.AllValueChooserPane); +} diff --git a/src/component/allvaluemultitextvaluecombo/allvalue.multitextvalue.combo.js b/src/component/allvaluemultitextvaluecombo/allvalue.multitextvalue.combo.js index 2ac30295b..44e94b4b2 100644 --- a/src/component/allvaluemultitextvaluecombo/allvalue.multitextvalue.combo.js +++ b/src/component/allvaluemultitextvaluecombo/allvalue.multitextvalue.combo.js @@ -1,66 +1,72 @@ -BI.AllValueMultiTextValueCombo = BI.inherit(BI.Widget, { +import { shortcut, Widget, Selection, each, contains } from "@/core"; +import { SearchMultiTextValueCombo } from "@/widget"; - props: { - baseCls: "bi-all-value-multi-text-value-combo", - width: 200, - height: 24, - items: [] - }, +@shortcut() +export class AllValueMultiTextValueCombo extends Widget { + static xtype = "bi.all_value_multi_text_value_combo"; - render: function () { - var self = this, o = this.options; - var value = this._digestValue(o.value); + props = { baseCls: "bi-all-value-multi-text-value-combo", width: 200, height: 24, items: [] }; + + static EVENT_CONFIRM = "EVENT_CONFIRM"; + + render() { + const self = this, + o = this.options; + const value = this._digestValue(o.value); + return { type: "bi.search_multi_text_value_combo", simple: o.simple, text: o.text, height: o.height, items: o.items, - value: value, + value, numOfPage: 100, valueFormatter: o.valueFormatter, warningTitle: o.warningTitle, - listeners: [{ - eventName: BI.SearchMultiTextValueCombo.EVENT_CONFIRM, - action: function () { - self.fireEvent(BI.AllValueMultiTextValueCombo.EVENT_CONFIRM); + listeners: [ + { + eventName: SearchMultiTextValueCombo.EVENT_CONFIRM, + action () { + self.fireEvent(AllValueMultiTextValueCombo.EVENT_CONFIRM); + }, } - }], - ref: function () { + ], + ref () { self.combo = this; - } + }, }; - }, + } - setValue: function (v) { - var value = this._digestValue(v); + setValue(v) { + const value = this._digestValue(v); this.combo.setValue(value); - }, + } - getValue: function () { - var obj = this.combo.getValue() || {}; + getValue() { + const obj = this.combo.getValue() || {}; obj.value = obj.value || []; - if(obj.type === BI.Selection.All) { - var values = []; - BI.each(this.options.items, function (idx, item) { - !BI.contains(obj.value, item.value) && values.push(item.value); + if (obj.type === Selection.All) { + const values = []; + each(this.options.items, (idx, item) => { + !contains(obj.value, item.value) && values.push(item.value); }); + return values; } + return obj.value || []; - }, + } - populate: function (items) { + populate(items) { this.options.items = items; - this.combo.populate.apply(this.combo, arguments); - }, + this.combo.populate(...arguments); + } - _digestValue: function (v) { + _digestValue(v) { return { - type: BI.Selection.Multi, - value: v || [] + type: Selection.Multi, + value: v || [], }; } -}); -BI.AllValueMultiTextValueCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut("bi.all_value_multi_text_value_combo", BI.AllValueMultiTextValueCombo); +} diff --git a/src/component/form/form.field.js b/src/component/form/form.field.js index 0b67041b8..4bd064913 100644 --- a/src/component/form/form.field.js +++ b/src/component/form/form.field.js @@ -1,98 +1,111 @@ -/** - * @author windy - * @version 2.0 - * Created by windy on 2022/1/11 - */ - BI.FormField = BI.inherit(BI.Widget, { - props: { +import { shortcut, Widget, extend, concat, isKey, VerticalAlign } from "@/core"; + +@shortcut() +export class FormField extends Widget { + static xtype = "bi.form_field"; + + props = { baseCls: "bi-form-field", label: "", el: {}, headerCls: "", labelAlign: "right", // 文字默认右对齐 - validate: function () { + validate () { return true; - } // 默认返回true - }, + }, // 默认返回true + } - render: function () { - var self = this, o = this.options; + render () { + const self = this, + o = this.options; - var field = { + const field = { type: "bi.absolute", - items: [{ - el: BI.extend({}, o.el, { - ref: function (_ref) { - self.field = _ref; - o.el.ref && o.el.ref.call(this, _ref); - }, - height: o.el.height || 28, - listeners: BI.concat(o.el.listeners, [{ - eventName: "EVENT_CHANGE", - action: function () { - self.fireEvent("EVENT_CHANGE"); - } - }, { - eventName: "EVENT_CONFIRM", - action: function () { - self.fireEvent("EVENT_CONFIRM"); - } - }]) - }), - left: 0, - bottom: 0, - right: 0, - top: 0 - }, { - el: { - type: "bi.label", - cls: "error-tip bi-error", - ref: function (_ref) { - self.error = _ref; - }, - invisible: true + items: [ + { + el: extend({}, o.el, { + ref (_ref) { + self.field = _ref; + o.el.ref && o.el.ref.call(this, _ref); + }, + height: o.el.height || 28, + listeners: concat(o.el.listeners, [ + { + eventName: "EVENT_CHANGE", + action () { + self.fireEvent("EVENT_CHANGE"); + }, + }, + { + eventName: "EVENT_CONFIRM", + action () { + self.fireEvent("EVENT_CONFIRM"); + }, + } + ]), + }), + left: 0, + bottom: 0, + right: 0, + top: 0, }, - bottom: -20, - left: 0, - right: 0, - height: 20 - }] + { + el: { + type: "bi.label", + cls: "error-tip bi-error", + ref (_ref) { + self.error = _ref; + }, + invisible: true, + }, + bottom: -20, + left: 0, + right: 0, + height: 20, + } + ], }; return { type: "bi.vertical_adapt", columnSize: ["auto", "fill"], - verticalAlign: BI.VerticalAlign.Stretch, - items: BI.isKey(o.label) ? [{ - el: { - type: "bi.label", - textAlign: o.labelAlign, - text: o.label, - width: o.labelWidth, - cls: o.headerCls, - rgap: 20 // 表单文字与右侧输入间距均为20px - } - }, field] : [field] + verticalAlign: VerticalAlign.Stretch, + items: isKey(o.label) + ? [ + { + el: { + type: "bi.label", + textAlign: o.labelAlign, + text: o.label, + width: o.labelWidth, + cls: o.headerCls, + rgap: 20, // 表单文字与右侧输入间距均为20px + }, + }, + field + ] + : [field], }; - }, + } - getValue: function () { + getValue () { return this.field.getValue(); - }, + } - validate: function () { - var isValid = this.validateWithNoTip(); - !isValid && this.error.setText(this.options.tip(this.field.getValue(), this.field)); + validate () { + const isValid = this.validateWithNoTip(); + !isValid && + this.error.setText( + this.options.tip(this.field.getValue(), this.field) + ); this.error.setVisible(!isValid); this.field.element[isValid ? "removeClass" : "addClass"]("bi-error"); return isValid; - }, + } - validateWithNoTip: function () { + validateWithNoTip () { return this.options.validate(this.field.getValue(), this.field); } -}); - -BI.shortcut("bi.form_field", BI.FormField); +} diff --git a/src/component/form/form.js b/src/component/form/form.js index de8caeaea..d79714569 100644 --- a/src/component/form/form.js +++ b/src/component/form/form.js @@ -1,45 +1,39 @@ -/** - * @author windy - * @version 2.0 - * Created by windy on 2022/1/11 - */ - BI.Form = BI.inherit(BI.Widget, { +import { shortcut, Widget, map, some, each } from "@/core"; +import { ButtonGroup } from "@/base"; - props: { +@shortcut() +export class Form extends Widget { + static xtype = "bi.custom_form"; + + props = { baseCls: "bi-form", labelAlign: "right", - layout: { - type: "bi.vertical", - vgap: 20 - }, - items: [{ - validate: BI.emptyFn, - tip: BI.emptyFn, - label: "", - el: {} - }], + layout: { type: "bi.vertical", vgap: 20 }, + items: [{ label: "", el: {} }], labelWidth: "", - headerCls: "", // 左侧文字样式 - }, + headerCls: "", + }; + + static EVENT_CHANGE = "EVENT_CHANGE"; - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; return { - type: "bi.button_group", + type: ButtonGroup.xtype, items: this._createItems(), layouts: [o.layout], - ref: function (ref) { - self.group = ref; - } + ref: _ref => { + this.group = _ref; + }, }; - }, + } - _createItems: function () { - var self = this; - var o = this.options; + _createItems() { + const self = this; + const o = this.options; - return BI.map(o.items, function (idx, item) { + return map(o.items, (idx, item) => { return { type: "bi.form_field", height: item.el.height || 28, @@ -50,46 +44,43 @@ label: item.label, tip: item.tip, validate: item.validate, - listeners: [{ - eventName: "EVENT_CHANGE", - action: function () { - self.fireEvent(BI.Form.EVENT_CHANGE, this.validate()); + listeners: [ + { + eventName: "EVENT_CHANGE", + action () { + self.fireEvent(Form.EVENT_CHANGE, this.validate()); + }, } - }] + ], }; }); - }, + } - isAllValid: function () { - return !BI.some(this.validateWithNoTip(), function (idx, v) { - return !v; - }); - }, + isAllValid() { + return !some(this.validateWithNoTip(), (idx, v) => !v); + } - validateWithNoTip: function () { - var validInfo = []; - BI.each(this.group.getAllButtons(), function (idx, button) { + validateWithNoTip() { + const validInfo = []; + each(this.group.getAllButtons(), (idx, button) => { validInfo.push(button.validateWithNoTip()); }); return validInfo; - }, + } - validate: function () { - var validInfo = []; - BI.each(this.group.getAllButtons(), function (idx, button) { + validate() { + const validInfo = []; + each(this.group.getAllButtons(), (idx, button) => { validInfo.push(button.validate()); }); return validInfo; - }, - - getValue: function () { - return !this.isAllValid() ? null : BI.map(this.group.getAllButtons(), function (idx, button) { - return button.getValue(); - }); } -}); -BI.Form.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.custom_form", BI.Form); + getValue() { + return !this.isAllValid() + ? null + : map(this.group.getAllButtons(), (idx, button) => button.getValue()); + } +} diff --git a/src/component/form/index.js b/src/component/form/index.js new file mode 100644 index 000000000..c2ffb7651 --- /dev/null +++ b/src/component/form/index.js @@ -0,0 +1,2 @@ +export { Form } from "./form"; +export { FormField } from "./form.field"; diff --git a/src/component/index.js b/src/component/index.js new file mode 100644 index 000000000..c6978e185 --- /dev/null +++ b/src/component/index.js @@ -0,0 +1,15 @@ +import * as allvaluechooser from "./allvaluechooser"; +import * as form from "./form"; +import { AllValueMultiTextValueCombo } from "./allvaluemultitextvaluecombo/allvalue.multitextvalue.combo"; + +Object.assign(BI, { + ...allvaluechooser, + ...form, + AllValueMultiTextValueCombo, +}); + +export * from "./allvaluechooser"; +export * from "./form"; +export { + AllValueMultiTextValueCombo +}; From 176b402e0ba76e43385dd5060573bd466fceaef5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joker=2EWang-=E7=8E=8B=E9=A1=BA?= Date: Fri, 13 Jan 2023 16:10:30 +0800 Subject: [PATCH 116/300] =?UTF-8?q?KERNEL-14100=20refactor:=20widget/yearq?= =?UTF-8?q?uarter=E3=80=81yearquarterinterval=20es6=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/widget/index.js | 9 +- .../yearquarter/card.dynamic.yearquarter.js | 293 ++++++----- .../yearquarter/card.static.yearquarter.js | 260 +++++----- src/widget/yearquarter/combo.yearquarter.js | 345 +++++++------ src/widget/yearquarter/index.js | 6 + src/widget/yearquarter/popup.yearquarter.js | 437 ++++++++++------- src/widget/yearquarter/trigger.yearquarter.js | 461 +++++++++++------- .../yearquarterinterval.js | 315 +++++++----- 8 files changed, 1255 insertions(+), 871 deletions(-) create mode 100644 src/widget/yearquarter/index.js diff --git a/src/widget/index.js b/src/widget/index.js index acd1aaf9d..82404bf6a 100644 --- a/src/widget/index.js +++ b/src/widget/index.js @@ -10,6 +10,7 @@ import * as editor from "./editor"; import * as downList from "./downlist"; import * as singleSliderItem from "./singleslider"; import * as intervalSliderItem from "./intervalslider"; +import * as yearQuarter from "./yearquarter"; import { SelectTreeCombo } from "./selecttree/selecttree.combo"; import { SingleTreeCombo } from "./singletree/singletree.combo"; import { MultiTreeCombo } from "./multitree/multi.tree.combo"; @@ -17,6 +18,7 @@ import { MultiTreeInsertCombo } from "./multitree/multi.tree.insert.combo"; import { MultiTreeListCombo } from "./multitree/multi.tree.list.combo"; import { NumberEditor } from "./numbereditor/number.editor"; import { NumberInterval } from "./numberinterval/numberinterval"; +import { YearQuarterInterval } from "./yearquarterinterval/yearquarterinterval"; import * as multiselect from "./multiselect"; import * as multiselectlist from "./multiselectlist"; import * as multilayerselectree from "./multilayerselecttree"; @@ -41,6 +43,7 @@ Object.assign(BI, { ...downList, ...singleSliderItem, ...intervalSliderItem, + ...yearQuarter, SelectTreeCombo, SingleTreeCombo, MultiTreeCombo, @@ -49,6 +52,7 @@ Object.assign(BI, { NumberEditor, NumberInterval, YearInterval, + YearQuarterInterval, ...multiselect, ...multiselectlist, ...multilayerselectree, @@ -75,7 +79,7 @@ export * from "./multilayersingletree"; export * from "./multilayerselecttree"; export * from "./singleselect"; export * from "./multilayerdownlist"; -export * from "./multilayersingletree"; +export * from "./yearquarter"; export { Collapse, @@ -86,5 +90,6 @@ export { MultiTreeCombo, MultiTreeInsertCombo, MultiTreeListCombo, - YearInterval + YearInterval, + YearQuarterInterval }; diff --git a/src/widget/yearquarter/card.dynamic.yearquarter.js b/src/widget/yearquarter/card.dynamic.yearquarter.js index 9e66e5202..667d7f8c3 100644 --- a/src/widget/yearquarter/card.dynamic.yearquarter.js +++ b/src/widget/yearquarter/card.dynamic.yearquarter.js @@ -1,166 +1,213 @@ -/** - * 年季度展示面板 - * - * Created by GUY on 2015/9/2. - * @class BI.YearCard - * @extends BI.Trigger - */ -BI.DynamicYearQuarterCard = BI.inherit(BI.Widget, { - - props: { - baseCls: "bi-year-quarter-card" - }, - - render: function () { - var self = this; +import { + shortcut, + Widget, + i18nText, + bind, + VerticalLayout, + parseDateTime, + extend, + checkDateVoid, + isNotEmptyString, + getQuarter +} from "@/core"; +import { DynamicDateCard, DynamicDateParamItem, DynamicDateHelper } from "../dynamicdate"; +import { Label, Bubbles } from "@/base"; + +@shortcut() +export class DynamicYearQuarterCard extends Widget { + static xtype = "bi.dynamic_year_quarter_card"; + + props = { baseCls: "bi-year-quarter-card" }; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + render() { return { - type: "bi.vertical", - items: [{ - type: "bi.label", - text: BI.i18nText("BI-Multi_Date_Relative_Current_Time"), - textAlign: "left", - height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - }, { - type: "bi.vertical", - ref: function (_ref) { - self.wrapper = _ref; + type: VerticalLayout.xtype, + items: [ + { + type: Label.xtype, + text: i18nText("BI-Multi_Date_Relative_Current_Time"), + textAlign: "left", + height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, }, - items: [{ - el: { - type: "bi.dynamic_date_param_item", - validationChecker: BI.bind(self._checkDate, self), - ref: function () { - self.year = this; - }, - listeners: [{ - eventName: "EVENT_CHANGE", - action: function () { - self.fireEvent("EVENT_CHANGE"); - } - }, { - eventName: "EVENT_INPUT_CHANGE", - action: function () { - BI.Bubbles.hide("dynamic-year-quarter-error"); - } - }] - }, - bgap: 10 - }, { - type: "bi.dynamic_date_param_item", - dateType: BI.DynamicDateCard.TYPE.QUARTER, - ref: function () { - self.quarter = this; + { + type: VerticalLayout.xtype, + ref: _ref => { + this.wrapper = _ref; }, - listeners: [{ - eventName: "EVENT_CHANGE", - action: function () { - self.fireEvent("EVENT_CHANGE"); - } - }, { - eventName: "EVENT_INPUT_CHANGE", - action: function () { - BI.Bubbles.hide("dynamic-year-quarter-error"); + items: [ + { + el: { + type: DynamicDateParamItem.xtype, + validationChecker: bind(this._checkDate, this), + ref: _ref => { + this.year = _ref; + }, + listeners: [ + { + eventName: "EVENT_CHANGE", + action: () => { + this.fireEvent("EVENT_CHANGE"); + }, + }, + { + eventName: "EVENT_INPUT_CHANGE", + action: () => { + Bubbles.hide( + "dynamic-year-quarter-error" + ); + }, + } + ], + }, + bgap: 10, + }, + { + type: DynamicDateParamItem.xtype, + dateType: DynamicDateCard.TYPE.QUARTER, + ref: _ref => { + this.quarter = _ref; + }, + listeners: [ + { + eventName: "EVENT_CHANGE", + action: () => { + this.fireEvent("EVENT_CHANGE"); + }, + }, + { + eventName: "EVENT_INPUT_CHANGE", + action: () => { + Bubbles.hide( + "dynamic-year-quarter-error" + ); + }, + } + ], } - }] - }] - }], + ], + } + ], vgap: 10, - hgap: 10 + hgap: 10, }; - }, + } - _getErrorText: function () { - var o = this.options; - var start = BI.parseDateTime(o.min, "%Y-%X-%d"); - var end = BI.parseDateTime(o.max, "%Y-%X-%d"); - return BI.i18nText("BI-Basic_Year_Quarter_Range_Error", + _getErrorText() { + const o = this.options; + const start = parseDateTime(o.min, "%Y-%X-%d"); + const end = parseDateTime(o.max, "%Y-%X-%d"); + + return i18nText( + "BI-Basic_Year_Quarter_Range_Error", start.getFullYear(), - BI.getQuarter(start), + getQuarter(start), end.getFullYear(), - BI.getQuarter(end) + getQuarter(end) ); - }, + } - _checkDate: function (obj) { - var o = this.options; - var date = BI.DynamicDateHelper.getCalculation(BI.extend(this._getValue(), this._digestDateTypeValue(obj))); + _checkDate(obj) { + const o = this.options; + const date = DynamicDateHelper.getCalculation( + extend(this._getValue(), this._digestDateTypeValue(obj)) + ); - return !BI.checkDateVoid(date.getFullYear(), date.getMonth() + 1, date.getDate(), o.min, o.max)[0]; - }, + return !checkDateVoid( + date.getFullYear(), + date.getMonth() + 1, + date.getDate(), + o.min, + o.max + )[0]; + } - _digestDateTypeValue: function (value) { - var valueMap = {}; + _digestDateTypeValue(value) { + const valueMap = {}; switch (value.dateType) { - case BI.DynamicDateCard.TYPE.YEAR: - valueMap.year = (value.offset === 0 ? -value.value : +value.value); - break; - case BI.DynamicDateCard.TYPE.QUARTER: - valueMap.quarter = (value.offset === 0 ? -value.value : +value.value); - break; - default: - break; + case DynamicDateCard.TYPE.YEAR: + valueMap.year = + value.offset === 0 ? -value.value : +value.value; + break; + case DynamicDateCard.TYPE.QUARTER: + valueMap.quarter = + value.offset === 0 ? -value.value : +value.value; + break; + default: + break; } + return valueMap; - }, + } - _createValue: function (type, v) { + _createValue(type, v) { return { dateType: type, value: Math.abs(v), - offset: v > 0 ? 1 : 0 + offset: v > 0 ? 1 : 0, }; - }, + } - setMinDate: function(minDate) { - if (BI.isNotEmptyString(this.options.min)) { + setMinDate(minDate) { + if (isNotEmptyString(this.options.min)) { this.options.min = minDate; } - }, + } - setMaxDate: function (maxDate) { - if (BI.isNotEmptyString(this.options.max)) { + setMaxDate(maxDate) { + if (isNotEmptyString(this.options.max)) { this.options.max = maxDate; } - }, + } - setValue: function (v) { - v = v || {year: 0, quarter: 0}; - this.year.setValue(this._createValue(BI.DynamicDateCard.TYPE.YEAR, v.year)); - this.quarter.setValue(this._createValue(BI.DynamicDateCard.TYPE.QUARTER, v.quarter)); - }, + setValue(v) { + v = v || { year: 0, quarter: 0 }; + this.year.setValue( + this._createValue(DynamicDateCard.TYPE.YEAR, v.year) + ); + this.quarter.setValue( + this._createValue(DynamicDateCard.TYPE.QUARTER, v.quarter) + ); + } - _getValue: function () { - var year = this.year.getValue(); - var quarter = this.quarter.getValue(); + _getValue() { + const year = this.year.getValue(); + const quarter = this.quarter.getValue(); + return { - year: (year.offset === 0 ? -year.value : year.value), - quarter: (quarter.offset === 0 ? -quarter.value : quarter.value) + year: year.offset === 0 ? -year.value : year.value, + quarter: quarter.offset === 0 ? -quarter.value : quarter.value, }; - }, + } - getInputValue: function () { + getInputValue() { return this._getValue(); - }, + } - getValue: function () { + getValue() { return this.checkValidation() ? this._getValue() : {}; - }, + } - checkValidation: function (show) { - var errorText; - var yearInvalid = !this.year.checkValidation(); - var quarterInvalid = !this.quarter.checkValidation(); - var invalid = yearInvalid || quarterInvalid; + checkValidation(show) { + let errorText; + const yearInvalid = !this.year.checkValidation(); + const quarterInvalid = !this.quarter.checkValidation(); + let invalid = yearInvalid || quarterInvalid; if (invalid) { - errorText = BI.i18nText("BI-Please_Input_Natural_Number"); + errorText = i18nText("BI-Please_Input_Natural_Number"); } else { invalid = !this._checkDate(this._getValue()); errorText = this._getErrorText(); } - invalid && show && BI.Bubbles.show("dynamic-year-quarter-error", errorText, this.wrapper); + invalid && + show && + Bubbles.show( + "dynamic-year-quarter-error", + errorText, + this.wrapper + ); return !invalid; - }, -}); -BI.DynamicYearQuarterCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.dynamic_year_quarter_card", BI.DynamicYearQuarterCard); \ No newline at end of file + } +} diff --git a/src/widget/yearquarter/card.static.yearquarter.js b/src/widget/yearquarter/card.static.yearquarter.js index cf54c6fcf..811b430e4 100644 --- a/src/widget/yearquarter/card.static.yearquarter.js +++ b/src/widget/yearquarter/card.static.yearquarter.js @@ -1,152 +1,190 @@ -BI.StaticYearQuarterCard = BI.inherit(BI.Widget, { +import { + shortcut, + Widget, + map, + extend, + VerticalLayout, + parseDateTime, + parseInt, + each, + checkDateVoid, + getDate, + getQuarterName, + getQuarter +} from "@/core"; +import { TextItem, ButtonGroup } from "@/base"; +import { YearPicker } from "../date/calendar"; - props: { - baseCls: "bi-static-year-quarter-card", - behaviors: {} - }, +@shortcut() +export class StaticYearQuarterCard extends Widget { + static xtype = "bi.static_year_quarter_card"; - _createQuarter: function () { - var self = this; - var items = [{ - text: BI.getQuarterName(1), - value: 1 - }, { - text: BI.getQuarterName(2), - value: 2 - }, { - text: BI.getQuarterName(3), - value: 3 - }, { - text: BI.getQuarterName(4), - value: 4 - }]; - return BI.map(items, function (j, item) { - return BI.extend(item, { - type: "bi.text_item", - cls: "bi-border-radius bi-list-item-select", - textAlign: "center", - whiteSpace: "nowrap", - once: false, - forceSelected: true, - height: BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, - ref: function (_ref) { - self.quarterMap[j + 1] = _ref; - } - }); - }); - }, + props = { baseCls: "bi-static-year-quarter-card", behaviors: {} }; + + static EVENT_CHANGE = "EVENT_CHANGE"; + + _createQuarter() { + const items = [ + { + text: getQuarterName(1), + value: 1, + }, + { + text: getQuarterName(2), + value: 2, + }, + { + text: getQuarterName(3), + value: 3, + }, + { + text: getQuarterName(4), + value: 4, + } + ]; + + return map(items, (j, item) => extend(item, { + type: TextItem.xtype, + cls: "bi-border-radius bi-list-item-select", + textAlign: "center", + whiteSpace: "nowrap", + once: false, + forceSelected: true, + height: BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, + ref: _ref => { + this.quarterMap[j + 1] = _ref; + }, + })); + } - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; this.quarterMap = {}; + return { - type: "bi.vertical", - items: [{ - type: "bi.year_picker", - cls: "bi-split-bottom", - ref: function () { - self.yearPicker = this; - }, - min: o.min, - max: o.max, - behaviors: o.behaviors, - height: 30, - listeners: [{ - eventName: BI.YearPicker.EVENT_CHANGE, - action: function () { - var value = this.getValue(); - self._checkQuarterStatus(value); - self.setValue({ - year: value, - quarter: self.selectedQuarter - }); - } - }] - }, { - el: { - type: "bi.button_group", - behaviors: o.behaviors, - ref: function () { - self.quarter = this; + type: VerticalLayout.xtype, + items: [ + { + type: YearPicker.xtype, + cls: "bi-split-bottom", + ref: _ref => { + this.yearPicker = _ref; }, - items: this._createQuarter(), - layouts: [{ - type: "bi.vertical", - vgap: 10, - hgap: 12, - }], - value: o.value, - listeners: [{ - eventName: BI.ButtonGroup.EVENT_CHANGE, - action: function () { - self.selectedYear = self.yearPicker.getValue(); - self.selectedQuarter = this.getValue()[0]; - self.fireEvent(BI.StaticYearQuarterCard.EVENT_CHANGE); + min: o.min, + max: o.max, + behaviors: o.behaviors, + height: 30, + listeners: [ + { + eventName: YearPicker.EVENT_CHANGE, + action: () => { + const value = this.yearPicker.getValue(); + this._checkQuarterStatus(value); + this.setValue({ + year: value, + quarter: this.selectedQuarter, + }); + }, } - }] + ], }, - vgap: 5 - }] + { + el: { + type: ButtonGroup.xtype, + behaviors: o.behaviors, + ref: _ref => { + this.quarter = _ref; + }, + items: this._createQuarter(), + layouts: [ + { + type: VerticalLayout.xtype, + vgap: 10, + hgap: 12, + } + ], + value: o.value, + listeners: [ + { + eventName: ButtonGroup.EVENT_CHANGE, + action: () => { + this.selectedYear = + this.yearPicker.getValue(); + this.selectedQuarter = this.quarter.getValue()[0]; + this.fireEvent( + StaticYearQuarterCard.EVENT_CHANGE + ); + }, + } + ], + }, + vgap: 5, + } + ], }; - }, + } - _checkQuarterStatus: function (year) { - var o = this.options; - var minDate = BI.parseDateTime(o.min, "%Y-%X-%d"), maxDate = BI.parseDateTime(o.max, "%Y-%X-%d"); - var minYear = minDate.getFullYear(), maxYear = maxDate.getFullYear(); - var minQuarter = 1; var maxQuarter = 4; - minYear === year && (minQuarter = BI.parseInt(BI.getQuarter(minDate))); - maxYear === year && (maxQuarter = BI.parseInt(BI.getQuarter(maxDate))); - var yearInvalid = year < minYear || year > maxYear; - BI.each(this.quarterMap, function (quarter, obj) { - var quarterInvalid = quarter < minQuarter || quarter > maxQuarter; + _checkQuarterStatus(year) { + const o = this.options; + const minDate = parseDateTime(o.min, "%Y-%X-%d"), + maxDate = parseDateTime(o.max, "%Y-%X-%d"); + const minYear = minDate.getFullYear(), + maxYear = maxDate.getFullYear(); + let minQuarter = 1; + let maxQuarter = 4; + minYear === year && (minQuarter = parseInt(getQuarter(minDate))); + maxYear === year && (maxQuarter = parseInt(getQuarter(maxDate))); + const yearInvalid = year < minYear || year > maxYear; + each(this.quarterMap, (quarter, obj) => { + const quarterInvalid = quarter < minQuarter || quarter > maxQuarter; obj.setEnable(!yearInvalid && !quarterInvalid); }); - }, + } - setMinDate: function (minDate) { + setMinDate(minDate) { if (this.options.min !== minDate) { this.options.min = minDate; this.yearPicker.setMinDate(minDate); this._checkQuarterStatus(this.selectedYear); } - }, + } - setMaxDate: function (maxDate) { + setMaxDate(maxDate) { if (this.options.max !== maxDate) { this.options.max = maxDate; this.yearPicker.setMaxDate(maxDate); this._checkQuarterStatus(this.selectedYear); } - }, - + } - getValue: function () { + getValue() { return { year: this.selectedYear, - quarter: this.selectedQuarter + quarter: this.selectedQuarter, }; - }, + } - setValue: function (obj) { - var o = this.options; - var newObj = {}; + setValue(obj) { + const o = this.options; + const newObj = {}; newObj.year = obj.year || 0; newObj.quarter = obj.quarter || 0; - if (newObj.quarter === 0 || newObj.year === 0 || BI.checkDateVoid(newObj.year, newObj.quarter, 1, o.min, o.max)[0]) { - var year = newObj.year || BI.getDate().getFullYear(); + if ( + newObj.quarter === 0 || + newObj.year === 0 || + checkDateVoid(newObj.year, newObj.quarter, 1, o.min, o.max)[0] + ) { + const year = newObj.year || getDate().getFullYear(); this.selectedYear = year; this.selectedQuarter = ""; this.yearPicker.setValue(year); this.quarter.setValue(); } else { - this.selectedYear = BI.parseInt(newObj.year); - this.selectedQuarter = BI.parseInt(newObj.quarter); + this.selectedYear = parseInt(newObj.year); + this.selectedQuarter = parseInt(newObj.quarter); this.yearPicker.setValue(this.selectedYear); this.quarter.setValue(this.selectedQuarter); } this._checkQuarterStatus(this.selectedYear); } -}); -BI.StaticYearQuarterCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.static_year_quarter_card", BI.StaticYearQuarterCard); +} diff --git a/src/widget/yearquarter/combo.yearquarter.js b/src/widget/yearquarter/combo.yearquarter.js index b7f04c4bd..7ce72d6fb 100644 --- a/src/widget/yearquarter/combo.yearquarter.js +++ b/src/widget/yearquarter/combo.yearquarter.js @@ -1,72 +1,102 @@ -BI.DynamicYearQuarterCombo = BI.inherit(BI.Widget, { +import { + shortcut, + Widget, + createWidget, + toPix, + isEqual, + isNotEmptyString, + getDate, + AbsoluteLayout, + HorizontalFillLayout, + isNotNull, + isNotEmptyObject, + checkDateVoid, + getQuarter +} from "@/core"; +import { DynamicYearQuarterTrigger } from "./trigger.yearquarter"; +// TODO:需要等待yearmonth完成才能将BI.DynamicYearMonthTrigger替换 +// import { DynamicYearMonthCombo } from "../yearmonth/combo.yearmonth"; +import { DynamicYearQuarterPopup } from "./popup.yearquarter"; +import { DynamicDateCombo } from "../dynamicdate"; +import { Combo, IconButton } from "@/base"; - _consts: { - iconWidth: 24 - }, - props: { +@shortcut() +export class DynamicYearQuarterCombo extends Widget { + static xtype = "bi.dynamic_year_quarter_combo"; + + _consts = { iconWidth: 24 }; + props = { baseCls: "bi-year-quarter-combo", behaviors: {}, - minDate: "1900-01-01", // 最小日期 - maxDate: "2099-12-31", // 最大日期 + minDate: "1900-01-01", + maxDate: "2099-12-31", height: 24, supportDynamic: true, isNeedAdjustHeight: false, - isNeedAdjustWidth: false - }, + isNeedAdjustWidth: false, + }; + + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_VALID = "EVENT_VALID"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static Static = 1; + static Dynamic = 2; - _init: function () { - var self = this, o = this.options; - BI.DynamicYearQuarterCombo.superclass._init.apply(this, arguments); + _init() { + const o = this.options; + super._init(...arguments); this.storeValue = o.value; - var border = o.simple ? 1 : 2; - self.storeTriggerValue = ""; - this.trigger = BI.createWidget({ + const border = o.simple ? 1 : 2; + this.storeTriggerValue = ""; + this.trigger = createWidget({ type: "bi.dynamic_year_quarter_trigger", simple: o.simple, min: o.minDate, max: o.maxDate, - height: BI.toPix(o.height, border), + height: toPix(o.height, border), value: o.value || "", watermark: o.watermark, }); - this.trigger.on(BI.DynamicYearQuarterTrigger.EVENT_KEY_DOWN, function () { - self.combo.isViewVisible() && self.combo.hideView(); + this.trigger.on(DynamicYearQuarterTrigger.EVENT_KEY_DOWN, () => { + this.combo.isViewVisible() && this.combo.hideView(); }); - this.trigger.on(BI.DynamicYearQuarterTrigger.EVENT_START, function () { - self.combo.isViewVisible() && self.combo.hideView(); + this.trigger.on(DynamicYearQuarterTrigger.EVENT_START, () => { + this.combo.isViewVisible() && this.combo.hideView(); }); - this.trigger.on(BI.DynamicYearQuarterTrigger.EVENT_STOP, function () { - self.combo.showView(); + this.trigger.on(DynamicYearQuarterTrigger.EVENT_STOP, () => { + this.combo.showView(); }); - this.trigger.on(BI.DynamicYearQuarterTrigger.EVENT_ERROR, function () { - self.combo.isViewVisible() && self.combo.hideView(); - self.comboWrapper.element.addClass("error"); - self.fireEvent(BI.DynamicYearQuarterCombo.EVENT_ERROR); + this.trigger.on(DynamicYearQuarterTrigger.EVENT_ERROR, () => { + this.combo.isViewVisible() && this.combo.hideView(); + this.comboWrapper.element.addClass("error"); + this.fireEvent(DynamicYearQuarterCombo.EVENT_ERROR); }); - this.trigger.on(BI.DynamicYearQuarterTrigger.EVENT_VALID, function () { - self.comboWrapper.element.removeClass("error"); - self.fireEvent(BI.DynamicYearMonthCombo.EVENT_VALID); + this.trigger.on(DynamicYearQuarterTrigger.EVENT_VALID, () => { + this.comboWrapper.element.removeClass("error"); + this.fireEvent(BI.DynamicYearMonthCombo.EVENT_VALID); }); - this.trigger.on(BI.DynamicYearQuarterTrigger.EVENT_CONFIRM, function () { - var dateStore = self.storeTriggerValue; - var dateObj = self.trigger.getKey(); - if (BI.isEqual(dateObj, dateStore)) { + this.trigger.on(DynamicYearQuarterTrigger.EVENT_CONFIRM, () => { + const dateStore = this.storeTriggerValue; + const dateObj = this.trigger.getKey(); + if (isEqual(dateObj, dateStore)) { return; } - if (BI.isNotEmptyString(dateObj) && !BI.isEqual(dateObj, dateStore)) { - self.storeValue = self.trigger.getValue(); - self.setValue(self.trigger.getValue()); + if (isNotEmptyString(dateObj) && !isEqual(dateObj, dateStore)) { + this.storeValue = this.trigger.getValue(); + this.setValue(this.trigger.getValue()); } - self._checkDynamicValue(self.storeValue); - self.fireEvent(BI.DynamicYearQuarterCombo.EVENT_CONFIRM); + this._checkDynamicValue(this.storeValue); + this.fireEvent(DynamicYearQuarterCombo.EVENT_CONFIRM); }); - this.trigger.on(BI.DynamicYearQuarterTrigger.EVENT_FOCUS, function () { - self.storeTriggerValue = self.trigger.getKey(); - self.fireEvent(BI.DynamicYearQuarterCombo.EVENT_FOCUS); + this.trigger.on(DynamicYearQuarterTrigger.EVENT_FOCUS, () => { + this.storeTriggerValue = this.trigger.getKey(); + this.fireEvent(DynamicYearQuarterCombo.EVENT_FOCUS); }); - this.combo = BI.createWidget({ - type: "bi.combo", + this.combo = createWidget({ + type: Combo.xtype, container: o.container, isNeedAdjustHeight: o.isNeedAdjustHeight, isNeedAdjustWidth: o.isNeedAdjustWidth, @@ -80,172 +110,185 @@ BI.DynamicYearQuarterCombo = BI.inherit(BI.Widget, { type: "bi.dynamic_year_quarter_popup", width: o.isNeedAdjustWidth ? o.width : undefined, supportDynamic: o.supportDynamic, - ref: function () { - self.popup = this; + ref: _ref => { + this.popup = _ref; }, listeners: [ { - eventName: BI.DynamicYearQuarterPopup.EVENT_CHANGE, - action: function () { - self.setValue(self.popup.getValue()); - self.combo.hideView(); - self.fireEvent(BI.DynamicYearQuarterCombo.EVENT_CONFIRM); - } - }, { - eventName: BI.DynamicYearQuarterPopup.BUTTON_CLEAR_EVENT_CHANGE, - action: function () { - self.setValue(); - self.comboWrapper.element.removeClass("error"); - self.combo.hideView(); - self.fireEvent(BI.DynamicYearQuarterCombo.EVENT_CONFIRM); - } - }, { - eventName: BI.DynamicYearQuarterPopup.BUTTON_lABEL_EVENT_CHANGE, - action: function () { - var date = BI.getDate(); - self.setValue({ + eventName: DynamicYearQuarterPopup.EVENT_CHANGE, + action: () => { + this.setValue(this.popup.getValue()); + this.combo.hideView(); + this.fireEvent( + DynamicYearQuarterCombo.EVENT_CONFIRM + ); + }, + }, + { + eventName: + DynamicYearQuarterPopup.BUTTON_CLEAR_EVENT_CHANGE, + action: () => { + this.setValue(); + this.comboWrapper.element.removeClass("error"); + this.combo.hideView(); + this.fireEvent( + DynamicYearQuarterCombo.EVENT_CONFIRM + ); + }, + }, + { + eventName: + DynamicYearQuarterPopup.BUTTON_lABEL_EVENT_CHANGE, + action: () => { + const date = getDate(); + this.setValue({ type: BI.DynamicYearMonthCombo.Static, - value: { year: date.getFullYear(), quarter: BI.getQuarter(date) } + value: { + year: date.getFullYear(), + quarter: getQuarter(date), + }, }); - self.combo.hideView(); - self.fireEvent(BI.DynamicDateCombo.EVENT_CONFIRM); - } - }, { - eventName: BI.DynamicYearQuarterPopup.BUTTON_OK_EVENT_CHANGE, - action: function () { - var value = self.popup.getValue(); - if (self._checkValue(value)) { - self.setValue(value); + this.combo.hideView(); + this.fireEvent(DynamicDateCombo.EVENT_CONFIRM); + }, + }, + { + eventName: + DynamicYearQuarterPopup.BUTTON_OK_EVENT_CHANGE, + action: () => { + const value = this.popup.getValue(); + if (this._checkValue(value)) { + this.setValue(value); } - self.combo.hideView(); - self.fireEvent(BI.DynamicDateCombo.EVENT_CONFIRM); - } + this.combo.hideView(); + this.fireEvent(DynamicDateCombo.EVENT_CONFIRM); + }, } ], behaviors: o.behaviors, min: o.minDate, - max: o.maxDate + max: o.maxDate, }, - value: o.value || "" - } + value: o.value || "", + }, }); - this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW, function () { - self.popup.setMinDate(o.minDate); - self.popup.setMaxDate(o.maxDate); - self.popup.setValue(self.storeValue); - self.fireEvent(BI.DynamicYearQuarterCombo.EVENT_BEFORE_POPUPVIEW); + this.combo.on(Combo.EVENT_BEFORE_POPUPVIEW, () => { + this.popup.setMinDate(o.minDate); + this.popup.setMaxDate(o.maxDate); + this.popup.setValue(this.storeValue); + this.fireEvent(DynamicYearQuarterCombo.EVENT_BEFORE_POPUPVIEW); }); - BI.createWidget({ - type: "bi.absolute", + createWidget({ + type: AbsoluteLayout.xtype, element: this, items: [ { el: { - type: "bi.horizontal_fill", + type: HorizontalFillLayout.xtype, columnSize: ["", "fill"], - cls: (o.simple ? "bi-border-bottom" : "bi-border bi-border-radius") + " bi-focus-shadow", - ref: function () { - self.comboWrapper = this; + cls: + `${o.simple + ? "bi-border-bottom" + : "bi-border bi-border-radius" + } bi-focus-shadow`, + ref: _ref => { + this.comboWrapper = _ref; }, items: [ { el: { - type: "bi.icon_button", + type: IconButton.xtype, cls: "bi-trigger-icon-button date-change-h-font", width: this._consts.iconWidth, - height: BI.toPix(o.height, border), - ref: function () { - self.changeIcon = this; - } - } - }, this.combo - ] + height: toPix(o.height, border), + ref: _ref => { + this.changeIcon = _ref; + }, + }, + }, + this.combo + ], }, top: 0, left: 0, right: 0, - bottom: 0 + bottom: 0, } - ] + ], }); this._checkDynamicValue(o.value); - }, + } - _checkDynamicValue: function (v) { - var type = null; - if (BI.isNotNull(v)) { + _checkDynamicValue(v) { + let type = null; + if (isNotNull(v)) { type = v.type; } switch (type) { - case BI.DynamicYearQuarterCombo.Dynamic: - this.changeIcon.setVisible(true); - break; - default: - this.changeIcon.setVisible(false); - break; + case DynamicYearQuarterCombo.Dynamic: + this.changeIcon.setVisible(true); + break; + default: + this.changeIcon.setVisible(false); + break; } - }, + } - _checkValue: function (v) { - var o = this.options; + _checkValue(v) { + const o = this.options; + let value; switch (v.type) { - case BI.DynamicDateCombo.Dynamic: - return BI.isNotEmptyObject(v.value); - case BI.DynamicDateCombo.Static: - var value = v.value || {}; - - return !BI.checkDateVoid(value.year, (value.quarter - 1) * 3 + 1, 1, o.minDate, o.maxDate)[0]; - default: - return true; + case DynamicDateCombo.Dynamic: + return isNotEmptyObject(v.value); + case DynamicDateCombo.Static: + value = v.value || {}; + + return !checkDateVoid( + value.year, + (value.quarter - 1) * 3 + 1, + 1, + o.minDate, + o.maxDate + )[0]; + default: + return true; } - }, + } - setMinDate: function (minDate) { - var o = this.options; + setMinDate(minDate) { + const o = this.options; o.minDate = minDate; this.trigger.setMinDate(minDate); this.popup && this.popup.setMinDate(minDate); - }, + } - setMaxDate: function (maxDate) { - var o = this.options; + setMaxDate(maxDate) { + const o = this.options; o.maxDate = maxDate; this.trigger.setMaxDate(maxDate); this.popup && this.popup.setMaxDate(maxDate); - }, + } - hideView: function () { + hideView() { this.combo.hideView(); - }, + } - getKey: function () { + getKey() { return this.trigger.getKey(); - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v; this.trigger.setValue(v); this._checkDynamicValue(v); - }, + } - getValue: function () { + getValue() { return this.storeValue; - }, + } - isStateValid: function () { + isStateValid() { return this.trigger.isStateValid(); } - -}); -BI.DynamicYearQuarterCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.DynamicYearQuarterCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.DynamicYearQuarterCombo.EVENT_ERROR = "EVENT_ERROR"; -BI.DynamicYearQuarterCombo.EVENT_VALID = "EVENT_VALID"; -BI.DynamicYearQuarterCombo.EVENT_FOCUS = "EVENT_FOCUS"; -BI.shortcut("bi.dynamic_year_quarter_combo", BI.DynamicYearQuarterCombo); - -BI.extend(BI.DynamicYearQuarterCombo, { - Static: 1, - Dynamic: 2 -}); +} diff --git a/src/widget/yearquarter/index.js b/src/widget/yearquarter/index.js new file mode 100644 index 000000000..29b16b492 --- /dev/null +++ b/src/widget/yearquarter/index.js @@ -0,0 +1,6 @@ +export { DynamicYearQuarterCard } from "./card.dynamic.yearquarter"; +export { StaticYearQuarterCard } from "./card.static.yearquarter"; +export { DynamicYearQuarterCombo } from "./combo.yearquarter"; +export { DynamicYearQuarterPopup } from "./popup.yearquarter"; +export { DynamicYearQuarterTrigger } from "./trigger.yearquarter"; + diff --git a/src/widget/yearquarter/popup.yearquarter.js b/src/widget/yearquarter/popup.yearquarter.js index 6cfbc519a..f134f384e 100644 --- a/src/widget/yearquarter/popup.yearquarter.js +++ b/src/widget/yearquarter/popup.yearquarter.js @@ -1,235 +1,328 @@ -BI.DynamicYearQuarterPopup = BI.inherit(BI.Widget, { - constants: { - tabHeight: 40, - buttonHeight: 24 - }, +import { + shortcut, + Widget, + toPix, + i18nText, + VerticalLayout, + GridLayout, + print, + getDate, + checkDateVoid, + createItems, + getQuarter +} from "@/core"; +import { DynamicYearQuarterCombo } from "./combo.yearquarter"; +import { TextButton, Tab } from "@/base"; +import { DynamicDateCombo, DynamicDatePopup, DynamicDateHelper } from "../dynamicdate"; +// TODO:需要等待year完成才能将BI.DynamicYearCard替换 +// import { DynamicYearCard } from "../year/card.dynamic.year"; +import { LinearSegment } from "@/case"; +import { DynamicYearQuarterCard } from "./card.dynamic.yearquarter"; +import { StaticYearQuarterCard } from "./card.static.yearquarter"; - props: { +@shortcut() +export class DynamicYearQuarterPopup extends Widget { + static xtype = "bi.dynamic_year_quarter_popup"; + + constants = { tabHeight: 40, buttonHeight: 24 }; + props = { baseCls: "bi-year-quarter-popup", behaviors: {}, - min: "1900-01-01", // 最小日期 - max: "2099-12-31", // 最大日期, + min: "1900-01-01", + max: "2099-12-31", width: 180, supportDynamic: true, - }, + }; + + static BUTTON_CLEAR_EVENT_CHANGE = "BUTTON_CLEAR_EVENT_CHANGE"; + static BUTTON_lABEL_EVENT_CHANGE = "BUTTON_lABEL_EVENT_CHANGE"; + static BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE"; + static EVENT_CHANGE = "EVENT_CHANGE"; - render: function () { - var self = this, opts = this.options, c = this.constants; - this.storeValue = {type: BI.DynamicYearQuarterCombo.Static}; + render() { + this.storeValue = { type: DynamicYearQuarterCombo.Static }; + return { - type: "bi.vertical", - items: [{ - el: this._getTabJson() - }, { - el: { - type: "bi.grid", - items: [[{ - type: "bi.text_button", - cls: "bi-split-top bi-high-light", - shadow: true, - textHeight: BI.toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), - text: BI.i18nText("BI-Basic_Clear"), - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.DynamicYearQuarterPopup.BUTTON_CLEAR_EVENT_CHANGE); - } - }] - }, { - type: "bi.text_button", - cls: "bi-split-left bi-split-right bi-high-light bi-split-top", - textHeight: BI.toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), - shadow: true, - text: BI.i18nText("BI-Basic_Current_Quarter"), - disabled: this._checkTodayValid(), - ref: function () { - self.textButton = this; - }, - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.DynamicYearQuarterPopup.BUTTON_lABEL_EVENT_CHANGE); - } - }] - }, { - type: "bi.text_button", - cls: "bi-split-top bi-high-light", - shadow: true, - textHeight: BI.toPix(BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, 1), - text: BI.i18nText("BI-Basic_OK"), - listeners: [{ - eventName: BI.TextButton.EVENT_CHANGE, - action: function () { - var type = self.dateTab.getSelect(); - if (type === BI.DynamicDateCombo.Dynamic) { - self.dynamicPane.checkValidation(true) && self.fireEvent(BI.DynamicDatePopup.BUTTON_OK_EVENT_CHANGE); - } else { - self.fireEvent(BI.DynamicYearQuarterPopup.BUTTON_OK_EVENT_CHANGE); - } - } - }] - }]], - height: BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT + type: VerticalLayout.xtype, + items: [ + { + el: this._getTabJson(), }, - }] + { + el: { + type: GridLayout.xtype, + items: [ + [ + { + type: TextButton.xtype, + cls: "bi-split-top bi-high-light", + shadow: true, + textHeight: toPix( + BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, + 1 + ), + text: i18nText("BI-Basic_Clear"), + listeners: [ + { + eventName: TextButton.EVENT_CHANGE, + action: () => { + this.fireEvent( + DynamicYearQuarterPopup.BUTTON_CLEAR_EVENT_CHANGE + ); + }, + } + ], + }, + { + type: TextButton.xtype, + cls: "bi-split-left bi-split-right bi-high-light bi-split-top", + textHeight: toPix( + BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, + 1 + ), + shadow: true, + text: i18nText("BI-Basic_Current_Quarter"), + disabled: this._checkTodayValid(), + ref: _ref => { + this.textButton = _ref; + }, + listeners: [ + { + eventName: TextButton.EVENT_CHANGE, + action: () => { + this.fireEvent( + DynamicYearQuarterPopup.BUTTON_lABEL_EVENT_CHANGE + ); + }, + } + ], + }, + { + type: TextButton.xtype, + cls: "bi-split-top bi-high-light", + shadow: true, + textHeight: toPix( + BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, + 1 + ), + text: i18nText("BI-Basic_OK"), + listeners: [ + { + eventName: TextButton.EVENT_CHANGE, + action: () => { + const type = + this.dateTab.getSelect(); + if ( + type === + DynamicDateCombo.Dynamic + ) { + this.dynamicPane.checkValidation( + true + ) && + this.fireEvent( + DynamicDatePopup.BUTTON_OK_EVENT_CHANGE + ); + } else { + this.fireEvent(DynamicYearQuarterPopup + .BUTTON_OK_EVENT_CHANGE + ); + } + }, + } + ], + } + ] + ], + height: BI.SIZE_CONSANTS.TOOL_BAR_HEIGHT, + }, + } + ], }; - }, + } - _setInnerValue: function () { - if (this.dateTab.getSelect() === BI.DynamicYearQuarterCombo.Static) { - this.textButton.setValue(BI.i18nText("BI-Basic_Current_Quarter")); + _setInnerValue() { + if (this.dateTab.getSelect() === DynamicYearQuarterCombo.Static) { + this.textButton.setValue(i18nText("BI-Basic_Current_Quarter")); this.textButton.setEnable(!this._checkTodayValid()); } else { - var date = BI.DynamicDateHelper.getCalculation(this.dynamicPane.getInputValue()); - date = BI.print(date, "%Y-%Q"); + let date = DynamicDateHelper.getCalculation( + this.dynamicPane.getInputValue() + ); + date = print(date, "%Y-%Q"); this.textButton.setValue(date); this.textButton.setEnable(false); } - }, + } - _checkTodayValid: function () { - var o = this.options; - var today = BI.getDate(); - return !!BI.checkDateVoid(today.getFullYear(), today.getMonth() + 1, today.getDate(), o.min, o.max)[0]; - }, + _checkTodayValid() { + const o = this.options; + const today = getDate(); + + return !!checkDateVoid( + today.getFullYear(), + today.getMonth() + 1, + today.getDate(), + o.min, + o.max + )[0]; + } - _getTabJson: function () { - var self = this, o = this.options; + _getTabJson() { + const o = this.options; + return { - type: "bi.tab", + type: Tab.xtype, logic: { - dynamic: true + dynamic: true, }, - ref: function () { - self.dateTab = this; + ref: _ref => { + this.dateTab = _ref; }, tab: { - type: "bi.linear_segment", + type: LinearSegment.xtype, cls: "bi-split-bottom", invisible: !o.supportDynamic, height: this.constants.tabHeight, - items: BI.createItems([{ - text: BI.i18nText("BI-Basic_Year_Quarter"), - value: BI.DynamicYearQuarterCombo.Static - }, { - text: BI.i18nText("BI-Basic_Dynamic_Title"), - value: BI.DynamicYearQuarterCombo.Dynamic - }], { - textAlign: "center" - }) + items: createItems( + [ + { + text: i18nText("BI-Basic_Year_Quarter"), + value: DynamicYearQuarterCombo.Static, + }, + { + text: i18nText("BI-Basic_Dynamic_Title"), + value: DynamicYearQuarterCombo.Dynamic, + } + ], + { + textAlign: "center", + } + ), }, - cardCreator: function (v) { + cardCreator: v => { switch (v) { - case BI.DynamicYearQuarterCombo.Dynamic: - return { - type: "bi.dynamic_year_quarter_card", - cls: "dynamic-year-quarter-pane", - min: self.options.min, - max: self.options.max, - listeners: [{ + case DynamicYearQuarterCombo.Dynamic: + return { + type: DynamicYearQuarterCard.xtype, + cls: "dynamic-year-quarter-pane", + min: this.options.min, + max: this.options.max, + listeners: [ + { eventName: "EVENT_CHANGE", - action: function () { - self._setInnerValue(self.year, v); - } - }], - ref: function () { - self.dynamicPane = this; + action: () => { + this._setInnerValue(this.year, v); + }, } - }; - case BI.DynamicYearQuarterCombo.Static: - default: - return { - type: "bi.static_year_quarter_card", - behaviors: o.behaviors, - min: self.options.min, - max: self.options.max, - listeners: [{ + ], + ref: _ref => { + this.dynamicPane = _ref; + }, + }; + case DynamicYearQuarterCombo.Static: + default: + return { + type: StaticYearQuarterCard.xtype, + behaviors: o.behaviors, + min: this.options.min, + max: this.options.max, + listeners: [ + { eventName: BI.DynamicYearCard.EVENT_CHANGE, - action: function () { - self.fireEvent(BI.DynamicYearQuarterPopup.EVENT_CHANGE); - } - }], - ref: function () { - self.year = this; + action: () => { + this.fireEvent( + DynamicYearQuarterPopup.EVENT_CHANGE + ); + }, } - }; + ], + ref: _ref => { + this.year = _ref; + }, + }; } }, - listeners: [{ - eventName: BI.Tab.EVENT_CHANGE, - action: function () { - var v = self.dateTab.getSelect(); - switch (v) { - case BI.DynamicYearQuarterCombo.Static: - var date = BI.DynamicDateHelper.getCalculation(self.dynamicPane.getValue()); - self.year.setValue({year: date.getFullYear(), quarter: BI.getQuarter(date)}); - self._setInnerValue(); + listeners: [ + { + eventName: Tab.EVENT_CHANGE, + action: () => { + const v = this.dateTab.getSelect(); + let date; + switch (v) { + case DynamicYearQuarterCombo.Static: + date = DynamicDateHelper.getCalculation( + this.dynamicPane.getValue() + ); + this.year.setValue({ + year: date.getFullYear(), + quarter: getQuarter(date), + }); + this._setInnerValue(); break; - case BI.DynamicYearQuarterCombo.Dynamic: + case DynamicYearQuarterCombo.Dynamic: default: - if(self.storeValue && self.storeValue.type === BI.DynamicYearQuarterCombo.Dynamic) { - self.dynamicPane.setValue(self.storeValue.value); - }else{ - self.dynamicPane.setValue({ - year: 0 + if ( + this.storeValue && + this.storeValue.type === + DynamicYearQuarterCombo.Dynamic + ) { + this.dynamicPane.setValue( + this.storeValue.value + ); + } else { + this.dynamicPane.setValue({ + year: 0, }); } - self._setInnerValue(); + this._setInnerValue(); break; - } + } + }, } - }] + ], }; - }, + } - setMinDate: function (minDate) { + setMinDate(minDate) { if (this.options.min !== minDate) { this.options.min = minDate; this.year && this.year.setMinDate(minDate); this.dynamicPane && this.dynamicPane.setMinDate(minDate); } - }, + } - setMaxDate: function (maxDate) { + setMaxDate(maxDate) { if (this.options.max !== maxDate) { this.options.max = maxDate; this.year && this.year.setMaxDate(maxDate); this.dynamicPane && this.dynamicPane.setMaxDate(maxDate); } - }, + } - setValue: function (v) { + setValue(v) { this.storeValue = v; - var self = this; - var type, value; v = v || {}; - type = v.type || BI.DynamicDateCombo.Static; - value = v.value || v; + const type = v.type || DynamicDateCombo.Static; + const value = v.value || v; this.dateTab.setSelect(type); switch (type) { - case BI.DynamicDateCombo.Dynamic: - this.dynamicPane.setValue(value); - self._setInnerValue(); - break; - case BI.DynamicDateCombo.Static: - default: - this.year.setValue(value); - this.textButton.setValue(BI.i18nText("BI-Basic_Current_Quarter")); - this.textButton.setEnable(!this._checkTodayValid()); - break; + case DynamicDateCombo.Dynamic: + this.dynamicPane.setValue(value); + this._setInnerValue(); + break; + case DynamicDateCombo.Static: + default: + this.year.setValue(value); + this.textButton.setValue(i18nText("BI-Basic_Current_Quarter")); + this.textButton.setEnable(!this._checkTodayValid()); + break; } - }, + } - getValue: function () { + getValue() { return { type: this.dateTab.getSelect(), - value: this.dateTab.getValue() + value: this.dateTab.getValue(), }; } - -}); -BI.DynamicYearQuarterPopup.BUTTON_CLEAR_EVENT_CHANGE = "BUTTON_CLEAR_EVENT_CHANGE"; -BI.DynamicYearQuarterPopup.BUTTON_lABEL_EVENT_CHANGE = "BUTTON_lABEL_EVENT_CHANGE"; -BI.DynamicYearQuarterPopup.BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE"; -BI.DynamicYearQuarterPopup.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.dynamic_year_quarter_popup", BI.DynamicYearQuarterPopup); \ No newline at end of file +} diff --git a/src/widget/yearquarter/trigger.yearquarter.js b/src/widget/yearquarter/trigger.yearquarter.js index 876856379..cd31a3908 100644 --- a/src/widget/yearquarter/trigger.yearquarter.js +++ b/src/widget/yearquarter/trigger.yearquarter.js @@ -1,277 +1,374 @@ -BI.DynamicYearQuarterTrigger = BI.inherit(BI.Trigger, { - _const: { - hgap: 4, - vgap: 2, - iconWidth: 24 - }, +import { + shortcut, + i18nText, + createWidget, + HTapeLayout, + CenterLayout, + HorizontalFillLayout, + isEmptyString, + parseDateTime, + isPositiveInteger, + checkDateVoid, + isNotEmptyString, + isNotNull, + print, + checkDateLegal, + isNull, + parseInt, + getDate, + getQuarter +} from "@/core"; +import { Trigger, TextButton } from "@/base"; +import { TriggerIconButton, SignEditor } from "@/case"; +import { DynamicDateHelper } from "../dynamicdate"; +// TODO:需要等待yearmonth完成才能将BI.DynamicYearMonthTrigger替换 +// import { DynamicYearMonthTrigger } from "../yearmonth/trigger.yearmonth"; +import { DynamicYearQuarterCombo } from "./combo.yearquarter"; - props: () => ({ - extraCls: "bi-year-quarter-trigger", - min: "1900-01-01", // 最小日期 - max: "2099-12-31", // 最大日期 - height: 24, - watermark: { - year: BI.i18nText("BI-Basic_Unrestricted"), - quarter: BI.i18nText("BI-Basic_Unrestricted"), - }, - }), +@shortcut() +export class DynamicYearQuarterTrigger extends Trigger { + static xtype = "bi.dynamic_year_quarter_trigger"; - _init: function () { - BI.DynamicYearQuarterTrigger.superclass._init.apply(this, arguments); - var o = this.options; + _const = { hgap: 4, vgap: 2, iconWidth: 24 }; + + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_START = "EVENT_START"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; + static EVENT_VALID = "EVENT_VALID"; + + props() { + return { + extraCls: "bi-year-quarter-trigger", + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 + height: 24, + watermark: { + year: i18nText("BI-Basic_Unrestricted"), + quarter: i18nText("BI-Basic_Unrestricted"), + }, + }; + } + + _init() { + super._init(...arguments); + const o = this.options; this.yearEditor = this._createEditor(true); this.quarterEditor = this._createEditor(false); // 暂时的解决方法 - var height = o.height + 2; + // const height = o.height + 2; - BI.createWidget({ + createWidget({ element: this, - type: "bi.htape", - items: [{ - type: "bi.center", - items: [{ - type: "bi.horizontal_fill", - columnSize: ["fill", ""], - items: [this.yearEditor, { - el: { - type: "bi.text_button", - text: BI.i18nText("BI-Multi_Date_Year"), - }, - }] - }, { - type: "bi.horizontal_fill", - columnSize: ["fill", ""], - items: [this.quarterEditor, { - el: { - type: "bi.text_button", - text: BI.i18nText("BI-Multi_Date_Quarter"), + type: HTapeLayout.xtype, + items: [ + { + type: CenterLayout.xtype, + items: [ + { + type: HorizontalFillLayout.xtype, + columnSize: ["fill", ""], + items: [ + this.yearEditor, + { + el: { + type: TextButton.xtype, + text: i18nText("BI-Multi_Date_Year"), + }, + } + ], }, - }] - }] - }, { - el: { - type: "bi.trigger_icon_button", - width: this._const.iconWidth, + { + type: HorizontalFillLayout.xtype, + columnSize: ["fill", ""], + items: [ + this.quarterEditor, + { + el: { + type: TextButton.xtype, + text: i18nText("BI-Multi_Date_Quarter"), + }, + } + ], + } + ], }, - width: this._const.iconWidth, - }] + { + el: { + type: TriggerIconButton.xtype, + width: this._const.iconWidth, + }, + width: this._const.iconWidth, + } + ], }); this.setValue(o.value); - }, + } - _createEditor: function (isYear) { - var self = this, o = this.options, c = this._const; - var editor = BI.createWidget({ - type: "bi.sign_editor", + _createEditor(isYear) { + const o = this.options, + c = this._const; + const editor = createWidget({ + type: SignEditor.xtype, simple: o.simple, height: o.height, - validationChecker: function (v) { - if(isYear) { - var month = self.quarterEditor.getValue(); - if(BI.isEmptyString(month)) { - month = parseInt(v, 10) === BI.parseDateTime(o.min, "%Y-%X-%d").getFullYear() ? BI.parseDateTime(o.min, "%Y-%X-%d").getMonth() + 1 : 1; + validationChecker: v => { + if (isYear) { + let month = this.quarterEditor.getValue(); + if (isEmptyString(month)) { + month = + parseInt(v, 10) === + parseDateTime(o.min, "%Y-%X-%d").getFullYear() + ? parseDateTime(o.min, "%Y-%X-%d").getMonth() + + 1 + : 1; } else { month = (parseInt(month, 10) - 1) * 3 + 1; } - return v === "" || (BI.isPositiveInteger(v) && !BI.checkDateVoid(v, month, 1, o.min, o.max)[0]); + + return ( + v === "" || + (isPositiveInteger(v) && + !checkDateVoid(v, month, 1, o.min, o.max)[0]) + ); } - var year = self.yearEditor.getValue(); + const year = this.yearEditor.getValue(); - return v === "" || ((BI.isPositiveInteger(v) && v >= 1 && v <= 4) && (BI.isEmptyString(year) ? true : !BI.checkDateVoid(self.yearEditor.getValue(), (v - 1) * 3 + 1, 1, o.min, o.max)[0])); - }, - quitChecker: function () { - return false; + return ( + v === "" || + (isPositiveInteger(v) && + v >= 1 && + v <= 4 && + (isEmptyString(year) + ? true + : !checkDateVoid( + this.yearEditor.getValue(), + (v - 1) * 3 + 1, + 1, + o.min, + o.max + )[0])) + ); }, - errorText: function (v) { - var year = isYear ? v : self.yearEditor.getValue(); - var quarter = isYear ? self.quarterEditor.getValue() : v; - if (!BI.isPositiveInteger(year) || !BI.isPositiveInteger(quarter) || quarter > 4) { - return BI.i18nText("BI-Year_Trigger_Invalid_Text"); + quitChecker: () => false, + errorText: v => { + const year = isYear ? v : this.yearEditor.getValue(); + const quarter = isYear ? this.quarterEditor.getValue() : v; + if ( + !isPositiveInteger(year) || + !isPositiveInteger(quarter) || + quarter > 4 + ) { + return i18nText("BI-Year_Trigger_Invalid_Text"); } - var start = BI.parseDateTime(o.min, "%Y-%X-%d"); - var end = BI.parseDateTime(o.max, "%Y-%X-%d"); + const start = parseDateTime(o.min, "%Y-%X-%d"); + const end = parseDateTime(o.max, "%Y-%X-%d"); - return BI.i18nText("BI-Basic_Year_Quarter_Range_Error", + return i18nText( + "BI-Basic_Year_Quarter_Range_Error", start.getFullYear(), - BI.getQuarter(start), + getQuarter(start), end.getFullYear(), - BI.getQuarter(end) + getQuarter(end) ); }, watermark: isYear ? o.watermark?.year : o.watermark?.quarter, hgap: c.hgap, vgap: c.vgap, - allowBlank: true + allowBlank: true, }); - editor.on(BI.SignEditor.EVENT_KEY_DOWN, function () { - self.fireEvent(BI.DynamicYearQuarterTrigger.EVENT_KEY_DOWN); + editor.on(SignEditor.EVENT_KEY_DOWN, () => { + this.fireEvent(DynamicYearQuarterTrigger.EVENT_KEY_DOWN); }); - editor.on(BI.SignEditor.EVENT_FOCUS, function () { - self.fireEvent(BI.DynamicYearQuarterTrigger.EVENT_FOCUS); + editor.on(SignEditor.EVENT_FOCUS, () => { + this.fireEvent(DynamicYearQuarterTrigger.EVENT_FOCUS); }); - editor.on(BI.SignEditor.EVENT_STOP, function () { - self.fireEvent(BI.DynamicYearQuarterTrigger.EVENT_STOP); + editor.on(SignEditor.EVENT_STOP, () => { + this.fireEvent(DynamicYearQuarterTrigger.EVENT_STOP); }); - editor.on(BI.SignEditor.EVENT_CONFIRM, function () { - self._doEditorConfirm(editor); - self.fireEvent(BI.DynamicYearQuarterTrigger.EVENT_CONFIRM); + editor.on(SignEditor.EVENT_CONFIRM, () => { + this._doEditorConfirm(editor); + this.fireEvent(DynamicYearQuarterTrigger.EVENT_CONFIRM); }); - editor.on(BI.SignEditor.EVENT_SPACE, function () { + editor.on(SignEditor.EVENT_SPACE, () => { if (editor.isValid()) { editor.blur(); } }); - editor.on(BI.SignEditor.EVENT_START, function () { - self.fireEvent(BI.DynamicYearQuarterTrigger.EVENT_START); + editor.on(SignEditor.EVENT_START, () => { + this.fireEvent(DynamicYearQuarterTrigger.EVENT_START); }); - editor.on(BI.SignEditor.EVENT_ERROR, function () { - self.fireEvent(BI.DynamicYearQuarterTrigger.EVENT_ERROR); + editor.on(SignEditor.EVENT_ERROR, () => { + this.fireEvent(DynamicYearQuarterTrigger.EVENT_ERROR); }); - editor.on(BI.SignEditor.EVENT_VALID, function () { - var year = self.yearEditor.getValue(); - var quarter = self.quarterEditor.getValue(); - if(BI.isNotEmptyString(year) && BI.isNotEmptyString(quarter)) { - if(BI.isPositiveInteger(year) && quarter >= 1 && quarter <= 4 && !BI.checkDateVoid(year, (quarter - 1) * 3 + 1, 1, o.min, o.max)[0]) { - self.fireEvent(BI.DynamicYearMonthTrigger.EVENT_VALID); + editor.on(SignEditor.EVENT_VALID, () => { + const year = this.yearEditor.getValue(); + const quarter = this.quarterEditor.getValue(); + if (isNotEmptyString(year) && isNotEmptyString(quarter)) { + if ( + isPositiveInteger(year) && + quarter >= 1 && + quarter <= 4 && + !checkDateVoid( + year, + (quarter - 1) * 3 + 1, + 1, + o.min, + o.max + )[0] + ) { + this.fireEvent(BI.DynamicYearMonthTrigger.EVENT_VALID); } } }); - editor.on(BI.SignEditor.EVENT_CHANGE, function () { - if(isYear) { - self._autoSwitch(editor); + editor.on(SignEditor.EVENT_CHANGE, () => { + if (isYear) { + this._autoSwitch(editor); } }); return editor; - }, + } - _doEditorConfirm: function (editor) { - var value = editor.getValue(); - if (BI.isNotNull(value)) { + _doEditorConfirm(editor) { + const value = editor.getValue(); + if (isNotNull(value)) { editor.setValue(value); } - var quarterValue = this.quarterEditor.getValue(); + const quarterValue = this.quarterEditor.getValue(); this.storeValue = { - type: BI.DynamicYearQuarterCombo.Static, + type: DynamicYearQuarterCombo.Static, value: { year: this.yearEditor.getValue(), - quarter: BI.isEmptyString(this.quarterEditor.getValue()) ? "" : quarterValue - } + quarter: isEmptyString(this.quarterEditor.getValue()) + ? "" + : quarterValue, + }, }; this.setTitle(this._getStaticTitle(this.storeValue.value)); - }, + } - _yearCheck: function (v) { - var date = BI.print(BI.parseDateTime(v, "%Y-%X-%d"), "%Y-%X-%d"); - return BI.print(BI.parseDateTime(v, "%Y"), "%Y") === v && date >= this.options.min && date <= this.options.max; - }, + _yearCheck(v) { + const date = print(parseDateTime(v, "%Y-%X-%d"), "%Y-%X-%d"); + + return ( + print(parseDateTime(v, "%Y"), "%Y") === v && + date >= this.options.min && + date <= this.options.max + ); + } - _autoSwitch: function (editor) { - var v = editor.getValue(); - if (BI.isNotEmptyString(v) && BI.checkDateLegal(v)) { + _autoSwitch(editor) { + const v = editor.getValue(); + if (isNotEmptyString(v) && checkDateLegal(v)) { if (v.length === 4 && this._yearCheck(v)) { this._doEditorConfirm(editor); - this.fireEvent(BI.DynamicYearQuarterTrigger.EVENT_CONFIRM); + this.fireEvent(DynamicYearQuarterTrigger.EVENT_CONFIRM); this.quarterEditor.focus(); } } - }, + } - _getStaticTitle: function (value) { + _getStaticTitle(value) { value = value || {}; - var hasYear = !(BI.isNull(value.year) || BI.isEmptyString(value.year)); - var hasMonth = !(BI.isNull(value.quarter) || BI.isEmptyString(value.quarter)); + const hasYear = !(isNull(value.year) || isEmptyString(value.year)); + const hasMonth = !(isNull(value.quarter) || isEmptyString(value.quarter)); switch ((hasYear << 1) | hasMonth) { - // !hasYear && !hasMonth - case 0: - return ""; + // !hasYear && !hasMonth + case 0: + return ""; // !hasYear && hasMonth - case 1: - return value.quarter; + case 1: + return value.quarter; // hasYear && !hasMonth - case 2: - return value.year; + case 2: + return value.year; // hasYear && hasMonth - case 3: - default: - return value.year + "-" + value.quarter; + case 3: + default: + return `${value.year}-${value.quarter}`; } - }, + } - _getText: function (obj) { - var value = ""; - if(BI.isNotNull(obj.year) && BI.parseInt(obj.year) !== 0) { - value += Math.abs(obj.year) + BI.i18nText("BI-Basic_Year") + (obj.year < 0 ? BI.i18nText("BI-Basic_Front") : BI.i18nText("BI-Basic_Behind")); + _getText(obj) { + let value = ""; + if (isNotNull(obj.year) && parseInt(obj.year) !== 0) { + value += + Math.abs(obj.year) + + i18nText("BI-Basic_Year") + + (obj.year < 0 + ? i18nText("BI-Basic_Front") + : i18nText("BI-Basic_Behind")); } - if(BI.isNotNull(obj.quarter) && BI.parseInt(obj.quarter) !== 0) { - value += Math.abs(obj.quarter) + BI.i18nText("BI-Basic_Single_Quarter") + (obj.quarter < 0 ? BI.i18nText("BI-Basic_Front") : BI.i18nText("BI-Basic_Behind")); + if (isNotNull(obj.quarter) && parseInt(obj.quarter) !== 0) { + value += + Math.abs(obj.quarter) + + i18nText("BI-Basic_Single_Quarter") + + (obj.quarter < 0 + ? i18nText("BI-Basic_Front") + : i18nText("BI-Basic_Behind")); } + return value; - }, + } - _setInnerValue: function (date, text) { - var dateStr = BI.print(date, "%Y-%Q"); + _setInnerValue(date, text) { + const dateStr = print(date, "%Y-%Q"); this.yearEditor.setValue(date.getFullYear()); - this.quarterEditor.setValue(BI.getQuarter(date)); - this.setTitle(BI.isEmptyString(text) ? dateStr : (text + ":" + dateStr)); - }, + this.quarterEditor.setValue(getQuarter(date)); + this.setTitle(isEmptyString(text) ? dateStr : `${text}:${dateStr}`); + } - setMinDate: function (minDate) { - if (BI.isNotEmptyString(this.options.min)) { + setMinDate(minDate) { + if (isNotEmptyString(this.options.min)) { this.options.min = minDate; } - }, + } - setMaxDate: function (maxDate) { - if (BI.isNotEmptyString(this.options.max)) { + setMaxDate(maxDate) { + if (isNotEmptyString(this.options.max)) { this.options.max = maxDate; } - }, + } - setValue: function (v) { - var type, value; - var date = BI.getDate(); + setValue(v) { + let type, value, text, quarter; + let date = getDate(); this.storeValue = v; - if (BI.isNotNull(v)) { - type = v.type || BI.DynamicYearQuarterCombo.Static; + if (isNotNull(v)) { + type = v.type || DynamicYearQuarterCombo.Static; value = v.value || v; } switch (type) { - case BI.DynamicYearQuarterCombo.Dynamic: - var text = this._getText(value); - date = BI.DynamicDateHelper.getCalculation(value); - this._setInnerValue(date, text); - break; - case BI.DynamicYearQuarterCombo.Static: - default: - value = value || {}; - var quarter = BI.isNull(value.quarter) ? null : value.quarter; - this.yearEditor.setValue(value.year); - this.quarterEditor.setValue(quarter); - this.setTitle(this._getStaticTitle(value)); - break; + case DynamicYearQuarterCombo.Dynamic: + text = this._getText(value); + date = DynamicDateHelper.getCalculation(value); + this._setInnerValue(date, text); + break; + case DynamicYearQuarterCombo.Static: + default: + value = value || {}; + quarter = isNull(value.quarter) ? null : value.quarter; + this.yearEditor.setValue(value.year); + this.quarterEditor.setValue(quarter); + this.setTitle(this._getStaticTitle(value)); + break; } - }, + } - getValue: function () { + getValue() { return this.storeValue; - }, + } - getKey: function () { - return this.yearEditor.getValue() + "-" + this.quarterEditor.getValue(); - }, + getKey() { + return `${this.yearEditor.getValue()}-${this.quarterEditor.getValue()}`; + } - isStateValid: function () { + isStateValid() { return this.yearEditor.isValid() && this.quarterEditor.isValid(); } -}); -BI.DynamicYearQuarterTrigger.EVENT_FOCUS = "EVENT_FOCUS"; -BI.DynamicYearQuarterTrigger.EVENT_ERROR = "EVENT_ERROR"; -BI.DynamicYearQuarterTrigger.EVENT_START = "EVENT_START"; -BI.DynamicYearQuarterTrigger.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.DynamicYearQuarterTrigger.EVENT_STOP = "EVENT_STOP"; -BI.DynamicYearQuarterTrigger.EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; -BI.DynamicYearQuarterTrigger.EVENT_VALID = "EVENT_VALID"; -BI.shortcut("bi.dynamic_year_quarter_trigger", BI.DynamicYearQuarterTrigger); +} diff --git a/src/widget/yearquarterinterval/yearquarterinterval.js b/src/widget/yearquarterinterval/yearquarterinterval.js index 02a0c67d7..16fa9f4a5 100644 --- a/src/widget/yearquarterinterval/yearquarterinterval.js +++ b/src/widget/yearquarterinterval/yearquarterinterval.js @@ -1,193 +1,248 @@ -/** - * @author windy - * @version 2.0 - * Created by windy on 2021/1/25 - */ -BI.YearQuarterInterval = BI.inherit(BI.Single, { - constants: { +import { + shortcut, + HorizontalFillLayout, + createWidget, + i18nText, + print, + parseDateTime, + checkDateVoid, + isNotNull, + checkDateLegal +} from "@/core"; +import { Single, Label, Bubbles } from "@/base"; +import { DynamicYearQuarterCombo } from "../yearquarter"; + +@shortcut() +export class YearQuarterInterval extends Single { + static xtype = "bi.year_quarter_interval"; + + constants = { height: 24, width: 25, lgap: 15, offset: -15, - timeErrorCls: "time-error" - }, - - props: { + timeErrorCls: "time-error", + }; + props = { extraCls: "bi-year-quarter-interval", minDate: "1900-01-01", maxDate: "2099-12-31", supportDynamic: true, - }, + }; + + static EVENT_VALID = "EVENT_VALID"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; - render: function () { - var self = this, o = this.options; + render() { + const o = this.options; o.value = o.value || {}; this.left = this._createCombo(o.value.start, o.watermark?.start); this.right = this._createCombo(o.value.end, o.watermark?.end); - return { - type: "bi.horizontal_fill", + type: HorizontalFillLayout.xtype, columnSize: ["fill", "", "fill"], - items: [{ - el: self.left - }, { - el: { - type: "bi.label", - height: o.height, - hgap: 5, - text: "-", - ref: function (_ref) { - self.label = _ref; - } + items: [ + { + el: this.left, + }, + { + el: { + type: Label.xtype, + height: o.height, + hgap: 5, + text: "-", + ref: _ref => { + this.label = _ref; + }, + }, + }, + { + el: this.right, } - }, { - el: self.right - }] + ], }; - }, + } - _createCombo: function (v, watermark) { - var self = this, o = this.options; - var combo = BI.createWidget({ - type: "bi.dynamic_year_quarter_combo", + _createCombo(v, watermark) { + const o = this.options; + const combo = createWidget({ + type: DynamicYearQuarterCombo.xtype, supportDynamic: o.supportDynamic, minDate: o.minDate, maxDate: o.maxDate, behaviors: o.behaviors, value: v, height: o.height, - watermark: watermark, - listeners: [{ - eventName: BI.DynamicYearQuarterCombo.EVENT_BEFORE_POPUPVIEW, - action: function () { - self.fireEvent(BI.YearQuarterInterval.EVENT_BEFORE_POPUPVIEW); + watermark, + listeners: [ + { + eventName: DynamicYearQuarterCombo.EVENT_BEFORE_POPUPVIEW, + action: () => { + this.fireEvent( + YearQuarterInterval.EVENT_BEFORE_POPUPVIEW + ); + }, } - }] + ], }); - combo.on(BI.DynamicYearQuarterCombo.EVENT_ERROR, function () { - self._clearTitle(); - BI.Bubbles.hide("error"); - self.element.removeClass(self.constants.timeErrorCls); - self.fireEvent(BI.YearQuarterInterval.EVENT_ERROR); + combo.on(DynamicYearQuarterCombo.EVENT_ERROR, () => { + this._clearTitle(); + Bubbles.hide("error"); + this.element.removeClass(this.constants.timeErrorCls); + this.fireEvent(YearQuarterInterval.EVENT_ERROR); }); - combo.on(BI.DynamicYearQuarterCombo.EVENT_VALID, function () { - self._checkValid(); + combo.on(DynamicYearQuarterCombo.EVENT_VALID, () => { + this._checkValid(); }); - combo.on(BI.DynamicYearQuarterCombo.EVENT_FOCUS, function () { - self._checkValid(); + combo.on(DynamicYearQuarterCombo.EVENT_FOCUS, () => { + this._checkValid(); }); - combo.on(BI.DynamicYearQuarterCombo.EVENT_CONFIRM, function () { - BI.Bubbles.hide("error"); - var smallDate = self.left.getKey(), bigDate = self.right.getKey(); - if (self.left.isStateValid() && self.right.isStateValid() && self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { - self._setTitle(BI.i18nText("BI-Time_Interval_Error_Text")); - self.element.addClass(self.constants.timeErrorCls); - self.fireEvent(BI.YearQuarterInterval.EVENT_ERROR); - }else{ - self._clearTitle(); - self.element.removeClass(self.constants.timeErrorCls); - self.fireEvent(BI.YearQuarterInterval.EVENT_CHANGE); + combo.on(DynamicYearQuarterCombo.EVENT_CONFIRM, () => { + Bubbles.hide("error"); + const smallDate = this.left.getKey(), + bigDate = this.right.getKey(); + if ( + this.left.isStateValid() && + this.right.isStateValid() && + this._check(smallDate, bigDate) && + this._compare(smallDate, bigDate) + ) { + this._setTitle(i18nText("BI-Time_Interval_Error_Text")); + this.element.addClass(this.constants.timeErrorCls); + this.fireEvent(YearQuarterInterval.EVENT_ERROR); + } else { + this._clearTitle(); + this.element.removeClass(this.constants.timeErrorCls); + this.fireEvent(YearQuarterInterval.EVENT_CHANGE); } }); + return combo; - }, - - - _dateCheck: function (date) { - return BI.print(BI.parseDateTime(date, "%Y-%Q"), "%Y-%Q") === date || BI.print(BI.parseDateTime(date, "%Y-%q"), "%Y-%q") === date; - }, + } + _dateCheck(date) { + return ( + print(parseDateTime(date, "%Y-%Q"), "%Y-%Q") === date || + print(parseDateTime(date, "%Y-%q"), "%Y-%q") === date + ); + } - // 判是否在最大最小之间 - _checkVoid: function (obj) { - var o = this.options; - return !BI.checkDateVoid(obj.year, (obj.quarter - 1) * 3 + 1, 1, o.minDate, o.maxDate)[0]; - }, + _checkVoid(obj) { + const o = this.options; + + return !checkDateVoid( + obj.year, + (obj.quarter - 1) * 3 + 1, + 1, + o.minDate, + o.maxDate + )[0]; + } - // 判格式合法 - _check: function (smallDate, bigDate) { - var smallObj = smallDate.match(/\d+/g), bigObj = bigDate.match(/\d+/g); + _check(smallDate, bigDate) { + const smallObj = smallDate.match(/\d+/g), + bigObj = bigDate.match(/\d+/g); - var smallDate4Check = ""; - if (BI.isNotNull(smallObj)) { - smallDate4Check = (smallObj[0] || "") + "-" + (smallObj[1] || 1); + let smallDate4Check = ""; + if (isNotNull(smallObj)) { + smallDate4Check = `${smallObj[0] || ""}-${smallObj[1] || 1}`; } - var bigDate4Check = ""; - if (BI.isNotNull(bigObj)) { - bigDate4Check = (bigObj[0] || "") + "-" + (bigObj[1] || 1); + let bigDate4Check = ""; + if (isNotNull(bigObj)) { + bigDate4Check = `${bigObj[0] || ""}-${bigObj[1] || 1}`; } - return this._dateCheck(smallDate4Check) && BI.checkDateLegal(smallDate4Check) && this._checkVoid({ - year: smallObj[0], - quarter: smallObj[1] || 1 - }) && this._dateCheck(bigDate4Check) && BI.checkDateLegal(bigDate4Check) && this._checkVoid({ - year: bigObj[0], - quarter: bigObj[1] || 1 - }); - }, - - _compare: function (smallDate, bigDate) { - smallDate = BI.print(BI.parseDateTime(smallDate, "%Y-%Q"), "%Y-%Q"); - bigDate = BI.print(BI.parseDateTime(bigDate, "%Y-%Q"), "%Y-%Q"); - return BI.isNotNull(smallDate) && BI.isNotNull(bigDate) && smallDate > bigDate; - }, - _setTitle: function (v) { + return ( + this._dateCheck(smallDate4Check) && + checkDateLegal(smallDate4Check) && + this._checkVoid({ + year: smallObj[0], + quarter: smallObj[1] || 1, + }) && + this._dateCheck(bigDate4Check) && + checkDateLegal(bigDate4Check) && + this._checkVoid({ + year: bigObj[0], + quarter: bigObj[1] || 1, + }) + ); + } + + _compare(smallDate, bigDate) { + smallDate = print(parseDateTime(smallDate, "%Y-%Q"), "%Y-%Q"); + bigDate = print(parseDateTime(bigDate, "%Y-%Q"), "%Y-%Q"); + + return ( + isNotNull(smallDate) && isNotNull(bigDate) && smallDate > bigDate + ); + } + + _setTitle(v) { this.setTitle(v); - }, - _clearTitle: function () { + } + + _clearTitle() { this.setTitle(""); - }, - _checkValid: function () { - var self = this; - - BI.Bubbles.hide("error"); - var smallDate = self.left.getKey(), bigDate = self.right.getKey(); - if (self.left.isValid() && self.right.isValid() && self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { - self._setTitle(BI.i18nText("BI-Time_Interval_Error_Text")); - self.element.addClass(self.constants.timeErrorCls); - BI.Bubbles.show("error", BI.i18nText("BI-Time_Interval_Error_Text"), self, { - offsetStyle: "center" - }); - self.fireEvent(BI.YearQuarterInterval.EVENT_ERROR); + } + + _checkValid() { + Bubbles.hide("error"); + const smallDate = this.left.getKey(), + bigDate = this.right.getKey(); + if ( + this.left.isValid() && + this.right.isValid() && + this._check(smallDate, bigDate) && + this._compare(smallDate, bigDate) + ) { + this._setTitle(i18nText("BI-Time_Interval_Error_Text")); + this.element.addClass(this.constants.timeErrorCls); + Bubbles.show( + "error", + i18nText("BI-Time_Interval_Error_Text"), + this, + { + offsetStyle: "center", + } + ); + this.fireEvent(YearQuarterInterval.EVENT_ERROR); } else { - self._clearTitle(); - self.element.removeClass(self.constants.timeErrorCls); + this._clearTitle(); + this.element.removeClass(this.constants.timeErrorCls); } - }, + } - setMinDate: function (minDate) { - var o = this.options; + setMinDate(minDate) { + const o = this.options; o.minDate = minDate; this.left.setMinDate(minDate); this.right.setMinDate(minDate); - }, + } - setMaxDate: function (maxDate) { - var o = this.options; + setMaxDate(maxDate) { + const o = this.options; o.maxDate = maxDate; this.left.setMaxDate(maxDate); this.right.setMaxDate(maxDate); - }, + } - setValue: function (date) { + setValue(date) { date = date || {}; this.left.setValue(date.start); this.right.setValue(date.end); this._checkValid(); - }, - getValue: function () { - return {start: this.left.getValue(), end: this.right.getValue()}; } -}); -BI.YearQuarterInterval.EVENT_VALID = "EVENT_VALID"; -BI.YearQuarterInterval.EVENT_ERROR = "EVENT_ERROR"; -BI.YearQuarterInterval.EVENT_CHANGE = "EVENT_CHANGE"; -BI.YearQuarterInterval.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut("bi.year_quarter_interval", BI.YearQuarterInterval); + + getValue() { + return { start: this.left.getValue(), end: this.right.getValue() }; + } +} From 137d8b14315d2fa61a52260f55ef7d4d89a35bd6 Mon Sep 17 00:00:00 2001 From: Treecat Date: Fri, 13 Jan 2023 17:31:34 +0800 Subject: [PATCH 117/300] =?UTF-8?q?KERNEL-14076=20feat:=20=E5=BE=AA?= =?UTF-8?q?=E7=8E=AF=E4=BE=9D=E8=B5=96=E4=BF=AE=E5=A4=8D=20&&=20=E6=97=A0j?= =?UTF-8?q?ira=20=E6=9B=BF=E6=8D=A2=20case=20=E5=85=A8=E9=83=A8=20xtype?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- es6.js | 195 +-- es6.xtype.js | 59 +- src/case/button/icon/icon.change.js | 18 +- src/case/button/icon/icon.trigger.js | 8 +- .../button/icon/iconhalf/icon.half.image.js | 10 +- src/case/button/icon/iconhalf/icon.half.js | 24 +- src/case/button/index.js | 59 +- src/case/button/item.multiselect.js | 59 +- src/case/button/item.singleselect.icontext.js | 8 +- src/case/button/item.singleselect.js | 11 +- src/case/button/item.singleselect.radio.js | 66 +- src/case/button/node/node.arrow.js | 53 +- src/case/button/node/node.first.plus.js | 45 +- src/case/button/node/node.icon.arrow.js | 56 +- src/case/button/node/node.last.plus.js | 43 +- src/case/button/node/node.mid.plus.js | 46 +- .../button/node/node.multilayer.icon.arrow.js | 13 +- src/case/button/node/node.plus.js | 54 +- src/case/button/node/siwtcher.tree.node.js | 24 +- src/case/button/node/treenode.js | 7 +- src/case/button/switch.js | 25 +- .../button/treeitem/item.icon.treeleaf.js | 56 +- .../treeitem/item.multilayer.icon.treeleaf.js | 32 +- src/case/button/treeitem/treeitem.js | 57 +- src/case/calendar/calendar.date.item.js | 50 +- src/case/calendar/calendar.js | 197 ++- src/case/calendar/calendar.year.js | 154 +- src/case/calendar/index.js | 6 +- src/case/checkbox/check.arrownode.js | 5 +- src/case/checkbox/check.checkingmarknode.js | 5 +- src/case/checkbox/check.first.treenode.js | 10 +- src/case/checkbox/check.last.treenode.js | 10 +- src/case/checkbox/check.mid.treenode.js | 10 +- src/case/checkbox/check.treenode.js | 12 +- src/case/colorchooser/colorchooser.custom.js | 57 +- src/case/colorchooser/colorchooser.js | 74 +- .../colorchooser/colorchooser.popup.hex.js | 428 +++--- .../colorchooser.popup.hex.simple.js | 28 +- src/case/colorchooser/colorchooser.popup.js | 191 ++- src/case/colorchooser/colorchooser.simple.js | 5 +- src/case/colorchooser/colorchooser.trigger.js | 64 +- .../colorchooser/colorchooser.trigger.long.js | 89 +- .../colorpicker/button/button.colorpicker.js | 26 +- .../colorpicker/button/button.colorshow.js | 17 +- .../colorchooser/colorpicker/button/index.js | 4 +- .../colorpicker/colorpicker.hex.js | 28 +- .../colorchooser/colorpicker/colorpicker.js | 351 +++-- .../colorpicker/editor.colorpicker.hex.js | 125 +- .../editor.colorpicker.hex.simple.js | 108 +- .../colorpicker/editor.colorpicker.js | 125 +- .../colorpicker/editor.colorpicker.simple.js | 72 +- src/case/colorchooser/colorpicker/index.js | 14 +- .../colorchooser/farbtastic/farbtastic.js | 164 ++- src/case/colorchooser/index.js | 22 +- src/case/combo/bubblecombo/combo.bubble.js | 18 +- src/case/combo/bubblecombo/popup.bubble.js | 6 +- .../combo.editiconcheck.js | 15 +- src/case/combo/iconcombo/combo.icon.js | 16 +- src/case/combo/iconcombo/popup.iconcombo.js | 10 +- src/case/combo/iconcombo/trigger.iconcombo.js | 15 +- .../icontextvaluecombo/combo.icontextvalue.js | 20 +- .../icontextvaluecombo/popup.icontextvalue.js | 12 +- .../combo.searchtextvalue.js | 46 +- .../popup.searchtextvalue.js | 45 +- .../trigger.searchtextvalue.js | 49 +- .../combo.textvaluecheck.js | 28 +- .../popup.textvaluecheck.js | 32 +- .../combo/textvaluecombo/combo.textvalue.js | 62 +- .../textvaluecombo/combo.textvaluesmall.js | 21 +- .../combo/textvaluecombo/popup.textvalue.js | 61 +- src/case/editor/editor.clear.js | 85 +- src/case/editor/editor.defaulttext.js | 88 +- src/case/editor/editor.shelter.js | 153 +- src/case/editor/editor.sign.js | 109 +- src/case/editor/editor.state.js | 168 ++- src/case/editor/editor.state.simple.js | 83 +- src/case/layer/index.js | 8 +- src/case/layer/layer.multipopup.js | 27 +- src/case/layer/layer.panel.js | 44 +- src/case/layer/pane.list.js | 60 +- src/case/layer/panel.js | 40 +- .../linearsegment/button.linear.segment.js | 78 +- src/case/linearsegment/index.js | 4 +- src/case/linearsegment/linear.segment.js | 78 +- src/case/list/list.select.js | 35 +- src/case/loader/loader.lazy.js | 10 +- src/case/loader/loader.list.js | 110 +- src/case/loader/sort.list.js | 34 +- src/case/pager/index.js | 6 +- src/case/pager/pager.all.count.js | 159 +- src/case/pager/pager.detail.js | 158 +- src/case/pager/pager.direction.js | 121 +- src/case/segment/button.segment.js | 8 +- src/case/segment/segment.js | 53 +- src/case/toolbar/toolbar.multiselect.js | 47 +- src/case/tree/tree.level.js | 50 +- .../tree/treeexpander/tree.expander.popup.js | 17 +- src/case/trigger/trigger.editor.js | 20 +- src/case/trigger/trigger.icon.js | 5 +- src/case/trigger/trigger.icon.text.js | 57 +- src/case/trigger/trigger.icon.text.select.js | 7 +- src/case/trigger/trigger.text.js | 91 +- src/case/trigger/trigger.text.select.js | 24 +- src/case/trigger/trigger.text.select.small.js | 5 +- src/case/trigger/trigger.text.small.js | 32 +- src/case/ztree/asynctree.js | 22 +- src/case/ztree/jquery.ztree.core-3.5.js | 541 ++++--- src/case/ztree/jquery.ztree.excheck-3.5.js | 1312 +++++++++-------- src/case/ztree/list/listasynctree.js | 12 +- src/case/ztree/list/listparttree.js | 21 +- src/case/ztree/list/listtreeview.js | 6 +- src/case/ztree/parttree.js | 60 +- src/case/ztree/tree.display.js | 10 +- src/case/ztree/tree.list.display.js | 9 +- src/case/ztree/tree.simple.js | 32 +- src/case/ztree/treerender.page.service.js | 6 +- src/case/ztree/treerender.scroll.service.js | 16 +- src/case/ztree/treeview.js | 75 +- 118 files changed, 4624 insertions(+), 3507 deletions(-) diff --git a/es6.js b/es6.js index afc7ff8e1..357bb92cc 100644 --- a/es6.js +++ b/es6.js @@ -3,7 +3,8 @@ const path = require("path"); const prettier = require("prettier"); const { exec } = require("child_process"); const { search, initDepts, depts } = require("./es6.xtype"); -const _ = require("lodash"); +const lodash = require("lodash"); +const DEPTS = depts; // const XTYPE_ONLY = false; // const THIS_REPLACE = false; @@ -32,10 +33,11 @@ function parserImport(code) { while (regResult) { importMap[regResult[2]] = regResult[1] .split(",") - .map(el => el.trim()).filter(el => el); + .map(el => el.trim()) + .filter(el => el); regResult = reg.exec(code); } - + return importMap; } @@ -46,7 +48,7 @@ async function saveAndFixCode(path, code) { } const prettierCode = prettier.format(_code, { tabWidth: 4, - parser: 'babel', + parser: "babel", printWidth: 120, }); fs.writeFileSync(path, prettierCode); @@ -58,56 +60,18 @@ async function saveAndFixCode(path, code) { }); } -const target = [ - "isNull", - "toPix", - "isKey", - "isObject", - "map", - "extend", - "isFunction", - "isEmptyArray", - "isArray", - "Controller", - "createWidget", - "Events", - "emptyFn", - "nextTick", - "bind", - "i18nText", - "isNotNull", - "isString", - "isNumber", - "isEmpty", - "isEmptyString", - "any", - "deepContains", - "isNotEmptyString", - "each", - "contains", - "remove", - "createItems", - "makeArrayByArray", - "VerticalAlign", - "pushDistinct", - "endWith", - "transformItems", - "print", - "Tree", - "Func", - "Selection", -]; +// const target = []; // 加载模块 const loader = { // G: { "@/core": { shortcut: true } }, load(srcName, module) { const G = loader.G; - if (target.indexOf(module) >= 0) { - G["@/core"][module] = true; + // if (target.indexOf(module) >= 0) { + // G["@/core"][module] = true; - return true; - } + // return true; + // } if (module.startsWith('"bi.')) { const key = search(srcName, module); if (key) { @@ -136,15 +100,15 @@ const loader = { async function handleFile(srcName) { await saveAndFixCode(srcName); // 全局状态回归 - let G = loader.G = { }; - + let G = (loader.G = {}); + const sourceCode = fs.readFileSync(srcName).toString(); const result = /BI\.(.*?)\s=\sBI\.inherit\(/.exec(sourceCode); if (!result) { // console.log(`已经es6过,替换 xtype => ${srcName}`); if (!/export class/.test(sourceCode)) { - console.log("忽略文件", srcName); + // console.log("忽略文件", srcName); return; } @@ -165,9 +129,9 @@ async function handleFile(srcName) { }); // 识别 import const importMap = parserImport(noXtypeCode); - + // 合并原来的 import 到 G - _.forEach(importMap, (depts, module) => { + lodash.forEach(importMap, (depts, module) => { depts.forEach(dept => { if (!G[module]) { G[module] = {}; @@ -176,56 +140,110 @@ async function handleFile(srcName) { G[module][dept] = true; }); }); + - // 合并 core - const crossPackages = fs.readdirSync("src"); - _.forEach(G, (depts, module) => { + // 合并包 + const crossPackages = fs.readdirSync("src").map(el => `@/${el}`); + lodash.forEach(G, (depts, module) => { crossPackages.forEach(crosspackage => { - if (module.indexOf(crosspackage) >= 0) { - if (!G[`@/${crosspackage}`]) { - G[`@/${crosspackage}`] = {}; + if (module.indexOf(crosspackage.replace(/^@\//, "")) >= 0) { + if (!G[crosspackage]) { + G[crosspackage] = {}; } - Object.assign(G[`@/${crosspackage}`], depts); + Object.assign(G[crosspackage], depts); } }); }); - const tmpG = {}; - _.forEach(G, (depts, module) => { - const flag = _.some(crossPackages, crosspackage => module.indexOf(crosspackage) >= 0 && !module.startsWith("@")); + lodash.forEach(G, (depts, module) => { + const flag = lodash.some( + crossPackages, + crosspackage => + module.indexOf(crosspackage) >= 0 && !module.startsWith("@"), + ); if (!flag) { tmpG[module] = depts; } }); + + let circle = false; + // 处理循环依赖 + const forbiddenCrossRules = { + base: ["@/case", "@/base", "@/widget"], + "case": ["@/case", "@/widget"], + widget: ["@/widget"], + }; + + const forbiddenKeys = []; + const circleG = {}; + + lodash.forEach(G, (depts, module) => { + // 找出 rule + const packages = Object.keys(forbiddenCrossRules); + let key = packages.filter( + _package => srcName.indexOf(_package) >= 0, + ); + if (key.length !== 1) { + throw new Error( + "理论不可能出现这个问题,需要 treecat 优化下找包逻辑1", + ); + } + key = key[0]; + const rule = forbiddenCrossRules[key]; + + if (lodash.includes(rule, module)) { + circle = true; + + const deptsArr = Object.keys(depts); + if (deptsArr.filter(dept => !DEPTS[dept]).length > 0) { + throw new Error( + "理论不可能出现这个问题,需要 treecat 优化下找包逻辑2", + ); + } + deptsArr + .filter(dept => DEPTS[dept]) + .forEach(dept => { + const value = `@${DEPTS[dept].replace(path.resolve("src"), "").replace(/\\/g, "/").replace(/\.js$/, "")}`; + if (!tmpG[value]) { + tmpG[value] = {}; + } + tmpG[value][dept] = true; + }); + forbiddenKeys.push(module); + } + }); + Object.assign(tmpG, circleG); + forbiddenKeys.forEach(key => { + delete tmpG[key]; + }); // 较验手工 import 错误 const map = {}; let conflict = false; - let circle = false; - _.forEach(tmpG, (imports, fromStr) => { - if (srcName.indexOf("base") >= 0) { - if (fromStr === "@/case" || fromStr === "@/base") { - circle = true; - } - } - _.forEach(imports, (bools, _import) => { - if (map[_import] && map[_import] !== fromStr) { + lodash.forEach(tmpG, (depts, module) => { + lodash.forEach(depts, (_, _import) => { + if (map[_import] && map[_import] !== module) { conflict = true; } - - map[_import] = fromStr; + + map[_import] = module; }); }); conflict && ConflictImport.push(srcName); circle && CircularDependency.push(srcName); + + G = tmpG; - - const noImportCode = noXtypeCode.replace(/import {([\s\S]*?)} from "(.*?)";/g, ""); - + + const noImportCode = noXtypeCode.replace( + /import {([\s\S]*?)} from "(.*?)";/g, + "", + ); + let I = ""; Object.keys(G).forEach(key => { let moduleKey = key; @@ -236,14 +254,13 @@ async function handleFile(srcName) { Object.keys(G[moduleKey]).forEach(key => { i += `${key}, `; }); - + // 必须以 . 开头 const moduleInValid = /^[^@.]/.test(moduleKey); if (moduleInValid) { moduleKey = `./${moduleKey}`; } - - + I += `import {${i}} from '${moduleKey}'\n`; }); const code = `${I}\n${noImportCode}`; @@ -255,17 +272,16 @@ async function handleFile(srcName) { G["@/core"] = { shortcut: true }; - const clzName = result[1]; if (!clzName) { console.log(`${srcName} 不需要 es6 化`); - + return; } const superName = /inherit\(BI\.(.*?),/.exec(sourceCode)[1]; - + // const xtype = /BI.shortcut\(\"(.*?)\"/.exec(sourceCode)[1]; const collection = { @@ -463,19 +479,6 @@ async function traverse(srcName) { const srcName = process.argv[2]; initDepts().then(async () => { - const content = fs.readFileSync("src/core/2.base.js").toString(); - - let result = content.match(/export function (.*?)\(/g); - target.push( - ...result.map(el => - el.replace("export function ", "").replace("(", ""), - ), - ); - result = content.match(/export const (.*?) =/g); - target.push( - ...result.map(el => el.replace("export const ", "").replace(" =", "")), - ); - await traverse(srcName); // 对数据处理 @@ -483,6 +486,6 @@ initDepts().then(async () => { console.log(`导入冲突 ${el}`); }); CircularDependency.forEach(el => { - console.log(`出现循环依赖 ${el}`); + console.log(`出现循环依赖(已经fixed) ${el}`); }); }); diff --git a/es6.xtype.js b/es6.xtype.js index 351134bf3..db1babcbb 100644 --- a/es6.xtype.js +++ b/es6.xtype.js @@ -1,35 +1,49 @@ const fs = require("fs"); const path = require("path"); +const lodash = require("lodash"); const depts = {}; async function handle(filename) { - // 找clzName - const code = fs.readFileSync(filename); + if (path.extname(filename) !== ".js") { + return; + } + const code = fs.readFileSync(filename).toString(); + const inheritRegResult = /BI\.(.*?)\s=\sBI\.inherit\(/.exec(code); - let clzName; if (inheritRegResult) { - clzName = inheritRegResult[1]; + const clzName = inheritRegResult[1]; + depts[clzName] = filename; } else { - const clzRegResult = /export\s+class\s+(.*?)\s+/.exec(code); - - if (clzRegResult) { - clzName = clzRegResult[1]; - } else { - return; - } - const xtypeResult = /static xtype = (.*?)(;|\s)/.exec(code); - // 找一下 xtype - if (xtypeResult) { - depts[xtypeResult[1]] = { - clzName, + // 一个文件夹里面可能有多个 xtype + const reg = /export\s+class\s+(.*?)([\s|{])([\w\W]*?)static xtype\s?=\s?((["|'])(.*?)(\5))/g; + Array.from(code.matchAll(reg)).forEach(res => { + const xtype = res[4]; + depts[xtype] = { + clzName: res[1], clzPath: filename, }; - } else { - // console.log(`${filename} 没有 xtype`); + }); + // 同时找一下 export + if (path.basename(filename) !== "index.js") { + const regs = [ + /export function (.*?)\(/g, + /export const (.*?) =/g, + /export class (.*?) /g, + /export \{([\w\W]*?)\}/g, + ]; + regs.forEach((reg, index) => { + Array.from(code.matchAll(reg)).forEach(el => { + depts[el[1]] = filename; + if (index === 3) { + el[1].split(",").map(el => el.trim()).forEach(key => { + depts[key] = filename; + }); + } + }); + }); } } - depts[clzName] = filename; } function isExist(filePath) { @@ -53,6 +67,13 @@ async function bfs(filename) { async function initDepts() { // dfs 构建依赖关系 await bfs(path.resolve("src")); + const m = {}; + lodash.forEach(depts, value => { + if (typeof value === "object") { + m[value.clzName] = value.clzPath; + } + }); + Object.assign(depts, m); } diff --git a/src/case/button/icon/icon.change.js b/src/case/button/icon/icon.change.js index 16ebd501d..b56d7c696 100644 --- a/src/case/button/icon/icon.change.js +++ b/src/case/button/icon/icon.change.js @@ -1,6 +1,5 @@ -import { Single } from "../../../base/single/0.single"; -import { IconButton } from "../../../base/single/button/buttons/button.icon"; -import { shortcut, extend, emptyFn, isFunction, createWidget, Controller } from "../../../core"; +import { IconButton, Single } from "@/base"; +import { shortcut, extend, emptyFn, isFunction, createWidget, Controller } from "@/core"; /** * 可以改变图标的button @@ -15,10 +14,9 @@ export class IconChangeButton extends Single { static xtype = "bi.icon_change_button"; static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: "bi-icon-change-button", iconCls: "", @@ -42,12 +40,14 @@ export class IconChangeButton extends Single { _init() { const o = this.options; - o.iconCls = isFunction(o.iconCls) ? this.__watch(o.iconCls, (context, newValue) => { - this.setIcon(newValue); - }) : o.iconCls; + o.iconCls = isFunction(o.iconCls) + ? this.__watch(o.iconCls, (context, newValue) => { + this.setIcon(newValue); + }) + : o.iconCls; super._init(...arguments); this.button = createWidget({ - type: "bi.icon_button", + type: IconButton.xtype, element: this, cls: o.iconCls, height: o.height, diff --git a/src/case/button/icon/icon.trigger.js b/src/case/button/icon/icon.trigger.js index a7606d59b..b22c54cec 100644 --- a/src/case/button/icon/icon.trigger.js +++ b/src/case/button/icon/icon.trigger.js @@ -1,5 +1,5 @@ -import { IconButton } from "../../../base/single/button/buttons/button.icon"; -import { shortcut, extend } from "../../../core"; +import { IconButton } from "@/base"; +import { shortcut, extend } from "@/core"; /** * 统一的trigger图标按钮 @@ -12,10 +12,10 @@ import { shortcut, extend } from "../../../core"; export class TriggerIconButton extends IconButton { static xtype = "bi.trigger_icon_button"; static EVENT_CHANGE = IconButton.EVENT_CHANGE; - + _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-trigger-icon-button overflow-hidden`, extraCls: "pull-down-font", diff --git a/src/case/button/icon/iconhalf/icon.half.image.js b/src/case/button/icon/iconhalf/icon.half.image.js index 24d2d0cea..ca51f65f4 100644 --- a/src/case/button/icon/iconhalf/icon.half.image.js +++ b/src/case/button/icon/iconhalf/icon.half.image.js @@ -1,6 +1,5 @@ -import { IconButton } from "../../../../base/single/button/buttons/button.icon"; -import { shortcut, extend } from "../../../../core"; - +import { IconButton } from "@/base"; +import { shortcut, extend } from "@/core"; /** * guy @@ -10,11 +9,11 @@ import { shortcut, extend } from "../../../../core"; @shortcut() export class HalfIconButton extends IconButton { static xtype = "bi.half_icon_button"; - static EVENT_CHANGE = IconButton.EVENT_CHANGE + static EVENT_CHANGE = IconButton.EVENT_CHANGE; _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { extraCls: "bi-half-icon-button check-half-select-icon", height: 16, @@ -25,4 +24,3 @@ export class HalfIconButton extends IconButton { }); } } - diff --git a/src/case/button/icon/iconhalf/icon.half.js b/src/case/button/icon/iconhalf/icon.half.js index a0db816ed..0e84aedae 100644 --- a/src/case/button/icon/iconhalf/icon.half.js +++ b/src/case/button/icon/iconhalf/icon.half.js @@ -1,5 +1,5 @@ -import { BasicButton } from "../../../../base/single/button/button.basic"; -import { shortcut, extend } from "../../../../core"; +import { CenterAdaptLayout, DefaultLayout, shortcut, extend } from "@/core"; +import { BasicButton } from "@/base"; /** * guy @@ -13,7 +13,7 @@ export class HalfButton extends BasicButton { _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { selected: false, width: 14, @@ -25,15 +25,17 @@ export class HalfButton extends BasicButton { render() { const o = this.options; - + return { - type: "bi.center_adapt", - items: [{ - type: "bi.default", - cls: "bi-half-button bi-high-light-border", - width: o.iconWidth, - height: o.iconHeight, - }], + type: CenterAdaptLayout.xtype, + items: [ + { + type: DefaultLayout.xtype, + cls: "bi-half-button bi-high-light-border", + width: o.iconWidth, + height: o.iconHeight, + }, + ], }; } diff --git a/src/case/button/index.js b/src/case/button/index.js index 8f366680c..6f4a1b209 100644 --- a/src/case/button/index.js +++ b/src/case/button/index.js @@ -1,28 +1,31 @@ -export { MultiSelectItem } from "./item.multiselect"; -export { SingleSelectIconTextItem } from "./item.singleselect.icontext"; -export { SingleSelectItem } from "./item.singleselect"; -export { SingleSelectRadioItem } from "./item.singleselect.radio"; -export { Switch } from "./switch"; - -export { IconChangeButton } from "./icon/icon.change"; -export { TriggerIconButton } from "./icon/icon.trigger"; -export { HalfIconButton } from "./icon/iconhalf/icon.half.image"; -export { HalfButton } from "./icon/iconhalf/icon.half"; - -export { ArrowNode } from "./node/node.arrow"; -export { FirstPlusGroupNode } from "./node/node.first.plus"; -export { IconArrowNode } from "./node/node.icon.arrow"; -export { LastPlusGroupNode } from "./node/node.last.plus"; -export { MidPlusGroupNode } from "./node/node.mid.plus"; -export { MultiLayerIconArrowNode } from "./node/node.multilayer.icon.arrow"; -export { PlusGroupNode } from "./node/node.plus"; -export { TreeNodeSwitcher } from "./node/siwtcher.tree.node"; -export { BasicTreeNode } from "./node/treenode"; - -export { IconTreeLeafItem } from "./treeitem/item.icon.treeleaf"; -export { MultiLayerIconTreeLeafItem } from "./treeitem/item.multilayer.icon.treeleaf"; - - -export { - BasicTreeItem, FirstTreeLeafItem, MidTreeLeafItem, LastTreeLeafItem, RootTreeLeafItem -} from "./treeitem/treeitem"; +export { MultiSelectItem } from "./item.multiselect"; +export { SingleSelectIconTextItem } from "./item.singleselect.icontext"; +export { SingleSelectItem } from "./item.singleselect"; +export { SingleSelectRadioItem } from "./item.singleselect.radio"; +export { Switch } from "./switch"; + +export { IconChangeButton } from "./icon/icon.change"; +export { TriggerIconButton } from "./icon/icon.trigger"; +export { HalfIconButton } from "./icon/iconhalf/icon.half.image"; +export { HalfButton } from "./icon/iconhalf/icon.half"; + +export { ArrowNode } from "./node/node.arrow"; +export { FirstPlusGroupNode } from "./node/node.first.plus"; +export { IconArrowNode } from "./node/node.icon.arrow"; +export { LastPlusGroupNode } from "./node/node.last.plus"; +export { MidPlusGroupNode } from "./node/node.mid.plus"; +export { MultiLayerIconArrowNode } from "./node/node.multilayer.icon.arrow"; +export { PlusGroupNode } from "./node/node.plus"; +export { TreeNodeSwitcher } from "./node/siwtcher.tree.node"; +export { BasicTreeNode } from "./node/treenode"; + +export { IconTreeLeafItem } from "./treeitem/item.icon.treeleaf"; +export { MultiLayerIconTreeLeafItem } from "./treeitem/item.multilayer.icon.treeleaf"; + +export { + BasicTreeItem, + FirstTreeLeafItem, + MidTreeLeafItem, + LastTreeLeafItem, + RootTreeLeafItem +} from "./treeitem/treeitem"; diff --git a/src/case/button/item.multiselect.js b/src/case/button/item.multiselect.js index bd82f2dcc..d39bb97fc 100644 --- a/src/case/button/item.multiselect.js +++ b/src/case/button/item.multiselect.js @@ -1,5 +1,5 @@ -import { BasicButton } from "../../base/single/button/button.basic"; -import { shortcut, extend, createWidget } from "../../core"; +import { Checkbox, Label, BasicButton } from "@/base"; +import { VerticalAdaptLayout, CenterAdaptLayout, shortcut, extend, createWidget } from "@/core"; /** * guy @@ -10,7 +10,6 @@ import { shortcut, extend, createWidget } from "../../core"; export class MultiSelectItem extends BasicButton { static xtype = "bi.multi_select_item"; static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig() { return extend(super._defaultConfig(...arguments), { @@ -26,36 +25,39 @@ export class MultiSelectItem extends BasicButton { render() { const o = this.options; this.checkbox = createWidget({ - type: "bi.checkbox", + type: Checkbox.xtype, }); - + return { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, columnSize: [o.iconWrapperWidth || o.height, "fill"], - items: [{ - type: "bi.center_adapt", - items: [this.checkbox], - }, { - el: { - type: "bi.label", - ref: _ref => { - this.text = _ref; + items: [ + { + type: CenterAdaptLayout.xtype, + items: [this.checkbox], + }, + { + el: { + type: Label.xtype, + ref: (_ref) => { + this.text = _ref; + }, + cls: "list-item-text", + textAlign: "left", + whiteSpace: "nowrap", + textHeight: o.height, + height: o.height, + hgap: o.textHgap, + rgap: o.textRgap, + lgap: o.textLgap, + vgap: o.textVgap, + text: o.text, + keyword: o.keyword, + value: o.value, + py: o.py, }, - cls: "list-item-text", - textAlign: "left", - whiteSpace: "nowrap", - textHeight: o.height, - height: o.height, - hgap: o.textHgap, - rgap: o.textRgap, - lgap: o.textLgap, - vgap: o.textVgap, - text: o.text, - keyword: o.keyword, - value: o.value, - py: o.py, }, - }], + ], }; } @@ -88,4 +90,3 @@ export class MultiSelectItem extends BasicButton { this.checkbox.setSelected(v); } } - diff --git a/src/case/button/item.singleselect.icontext.js b/src/case/button/item.singleselect.icontext.js index 58e329ff4..c55de1e17 100644 --- a/src/case/button/item.singleselect.icontext.js +++ b/src/case/button/item.singleselect.icontext.js @@ -1,5 +1,5 @@ -import { Single } from "../../base/single/0.single"; -import { shortcut, extend, createWidget, Controller } from "../../core"; +import { IconTextItem, Single } from "@/base"; +import { shortcut, extend, createWidget, Controller } from "@/core"; /** * Created by GUY on 2016/2/2. @@ -25,7 +25,7 @@ export class SingleSelectIconTextItem extends Single { render() { const o = this.options; this.text = createWidget({ - type: "bi.icon_text_item", + type: IconTextItem.xtype, element: this, cls: o.iconCls, once: o.once, @@ -73,5 +73,3 @@ export class SingleSelectIconTextItem extends Single { this.text.unRedMark(...arguments); } } - - diff --git a/src/case/button/item.singleselect.js b/src/case/button/item.singleselect.js index a3fd34b01..9a66ef5f3 100644 --- a/src/case/button/item.singleselect.js +++ b/src/case/button/item.singleselect.js @@ -1,6 +1,6 @@ -import { BasicButton } from "../../base/single/button/button.basic"; -import { shortcut, extend, createWidget } from "../../core"; - +import { Label, BasicButton } from "@/base"; +import { shortcut, extend, createWidget } from "@/core"; + @shortcut() export class SingleSelectItem extends BasicButton { static xtype = "bi.single_select_item"; @@ -21,7 +21,7 @@ export class SingleSelectItem extends BasicButton { render() { const o = this.options; this.text = createWidget({ - type: "bi.label", + type: Label.xtype, element: this, textAlign: o.textAlign, whiteSpace: "nowrap", @@ -66,6 +66,3 @@ export class SingleSelectItem extends BasicButton { super.setSelected(...arguments); } } - - - diff --git a/src/case/button/item.singleselect.radio.js b/src/case/button/item.singleselect.radio.js index 0fd83a4b6..cdee75636 100644 --- a/src/case/button/item.singleselect.radio.js +++ b/src/case/button/item.singleselect.radio.js @@ -1,5 +1,5 @@ -import { BasicButton } from "../../base/single/button/button.basic"; -import { shortcut, extend } from "../../core"; +import { VerticalAdaptLayout, CenterAdaptLayout, shortcut, extend } from "@/core"; +import { Radio, Label, BasicButton } from "@/base"; /** * guy @@ -27,37 +27,42 @@ export class SingleSelectRadioItem extends BasicButton { const o = this.options; return { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, columnSize: [o.iconWrapperWidth || o.height, "fill"], - items: [{ - type: "bi.center_adapt", - items: [{ - type: "bi.radio", - ref: _ref => { - this.radio = _ref; - }, - }], - }, { - el: { - type: "bi.label", - ref: _ref => { - this.text = _ref; + items: [ + { + type: CenterAdaptLayout.xtype, + items: [ + { + type: Radio.xtype, + ref: (_ref) => { + this.radio = _ref; + }, + }, + ], + }, + { + el: { + type: Label.xtype, + ref: (_ref) => { + this.text = _ref; + }, + cls: "list-item-text", + textAlign: "left", + whiteSpace: "nowrap", + textHeight: o.height, + height: o.height, + hgap: o.hgap || o.textHgap, + vgap: o.textVgap, + lgap: o.textLgap, + rgap: o.textRgap, + text: o.text, + keyword: o.keyword, + value: o.value, + py: o.py, }, - cls: "list-item-text", - textAlign: "left", - whiteSpace: "nowrap", - textHeight: o.height, - height: o.height, - hgap: o.hgap || o.textHgap, - vgap: o.textVgap, - lgap: o.textLgap, - rgap: o.textRgap, - text: o.text, - keyword: o.keyword, - value: o.value, - py: o.py, }, - }], + ], }; } @@ -90,4 +95,3 @@ export class SingleSelectRadioItem extends BasicButton { this.radio.setSelected(v); } } - diff --git a/src/case/button/node/node.arrow.js b/src/case/button/node/node.arrow.js index dc1834c88..7d1d0118b 100644 --- a/src/case/button/node/node.arrow.js +++ b/src/case/button/node/node.arrow.js @@ -1,5 +1,6 @@ -import { NodeButton } from "../../../base/single/button/button.node"; -import { shortcut, extend, createWidget } from "../../../core"; +import { ArrowTreeGroupNodeCheckbox } from "../../checkbox"; +import { VerticalAdaptLayout, shortcut, extend, createWidget } from "@/core"; +import { Label, NodeButton } from "@/base"; /** * Created by roy on 15/10/16. @@ -10,7 +11,7 @@ export class ArrowNode extends NodeButton { _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-arrow-group-node bi-list-item`, id: "", @@ -24,34 +25,37 @@ export class ArrowNode extends NodeButton { render() { const o = this.options; this.checkbox = createWidget({ - type: "bi.arrow_group_node_checkbox", + type: ArrowTreeGroupNodeCheckbox.xtype, expandIcon: o.expandIcon, collapseIcon: o.collapseIcon, }); - + return { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, columnSize: [o.iconWrapperWidth || o.height, "fill"], - items: [this.checkbox, { - el: { - type: "bi.label", - ref: _ref => { - this.text = _ref; + items: [ + this.checkbox, + { + el: { + type: Label.xtype, + ref: (_ref) => { + this.text = _ref; + }, + textAlign: "left", + whiteSpace: "nowrap", + textHeight: o.height, + height: o.height, + hgap: o.hgap || o.textHgap, + vgap: o.textVgap, + lgap: o.textLgap, + rgap: o.textRgap, + text: o.text, + value: o.value, + py: o.py, + keyword: o.keyword, }, - textAlign: "left", - whiteSpace: "nowrap", - textHeight: o.height, - height: o.height, - hgap: o.hgap || o.textHgap, - vgap: o.textVgap, - lgap: o.textLgap, - rgap: o.textRgap, - text: o.text, - value: o.value, - py: o.py, - keyword: o.keyword, }, - }], + ], }; } @@ -78,4 +82,3 @@ export class ArrowNode extends NodeButton { this.checkbox.setSelected(v); } } - diff --git a/src/case/button/node/node.first.plus.js b/src/case/button/node/node.first.plus.js index 8e895f801..288b70aea 100644 --- a/src/case/button/node/node.first.plus.js +++ b/src/case/button/node/node.first.plus.js @@ -1,6 +1,6 @@ -import { NodeButton } from "../../../base/single/button/button.node"; -import { shortcut, extend, createWidget, Controller } from "../../../core"; - +import { FirstTreeNodeCheckbox } from "../../checkbox"; +import { Label, NodeButton } from "@/base"; +import { shortcut, extend, createWidget, Controller } from "@/core"; /** * 加号表示的组节点 @@ -11,10 +11,10 @@ import { shortcut, extend, createWidget, Controller } from "../../../core"; @shortcut() export class FirstPlusGroupNode extends NodeButton { static xtype = "bi.first_plus_group_node"; - + _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-first-plus-group-node bi-list-item`, logic: { @@ -31,13 +31,13 @@ export class FirstPlusGroupNode extends NodeButton { super._init.apply(this, arguments); const o = this.options; this.checkbox = createWidget({ - type: "bi.first_tree_node_checkbox", + type: FirstTreeNodeCheckbox.xtype, stopPropagation: true, iconHeight: o.height, iconWidth: o.height, }); this.text = createWidget({ - type: "bi.label", + type: Label.xtype, textAlign: "left", whiteSpace: "nowrap", textHeight: o.height, @@ -58,15 +58,27 @@ export class FirstPlusGroupNode extends NodeButton { } }); const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: this.checkbox, - }, this.text); - BI.createWidget(BI.extend({ - element: this, - }, BI.LogicFactory.createLogic(type, BI.extend(o.logic, { - items, - })))); + const items = BI.LogicFactory.createLogicItemsByDirection( + BI.Direction.Left, + { + width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, + el: this.checkbox, + }, + this.text + ); + BI.createWidget( + BI.extend( + { + element: this, + }, + BI.LogicFactory.createLogic( + type, + BI.extend(o.logic, { + items, + }) + ) + ) + ); } doRedMark() { @@ -89,4 +101,3 @@ export class FirstPlusGroupNode extends NodeButton { } } } - diff --git a/src/case/button/node/node.icon.arrow.js b/src/case/button/node/node.icon.arrow.js index 866568b95..575a8c1c0 100644 --- a/src/case/button/node/node.icon.arrow.js +++ b/src/case/button/node/node.icon.arrow.js @@ -1,5 +1,6 @@ -import { NodeButton } from "../../../base/single/button/button.node"; -import { shortcut, extend, createWidget, Controller, isNotNull } from "../../../core"; +import { ArrowTreeGroupNodeCheckbox } from "../../checkbox"; +import { IconLabel, Label, NodeButton } from "@/base"; +import { shortcut, extend, createWidget, Controller, isNotNull } from "@/core"; /** * Created by User on 2016/3/31. @@ -14,7 +15,7 @@ export class IconArrowNode extends NodeButton { _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-icon-arrow-node bi-list-item`, logic: { @@ -35,7 +36,7 @@ export class IconArrowNode extends NodeButton { super._init.apply(this, arguments); const o = this.options; this.checkbox = createWidget({ - type: "bi.arrow_group_node_checkbox", + type: ArrowTreeGroupNodeCheckbox.xtype, expandIcon: o.expandIcon, collapseIcon: o.collapseIcon, width: 24, @@ -43,7 +44,7 @@ export class IconArrowNode extends NodeButton { }); const icon = createWidget({ - type: "bi.icon_label", + type: IconLabel.xtype, width: 24, cls: o.iconCls, iconWidth: o.iconWidth, @@ -51,7 +52,7 @@ export class IconArrowNode extends NodeButton { }); createWidget({ - type: "bi.label", + type: Label.xtype, textAlign: "left", whiteSpace: "nowrap", textHeight: o.height, @@ -62,7 +63,7 @@ export class IconArrowNode extends NodeButton { py: o.py, keyword: o.keyword, }); - this.checkbox.on(Controller.EVENT_CHANGE, type => { + this.checkbox.on(Controller.EVENT_CHANGE, (type) => { if (type === BI.Events.CLICK) { if (this.checkbox.isSelected()) { this.triggerExpand(); @@ -72,22 +73,35 @@ export class IconArrowNode extends NodeButton { } }); const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { - width: o.iconWrapperWidth, - el: this.checkbox, - }, { - width: 16, - el: icon, - }, this.text); - createWidget(extend({ - element: this, - }, BI.LogicFactory.createLogic(type, extend(o.logic, { - items, - rgap: 5, - })))); + const items = BI.LogicFactory.createLogicItemsByDirection( + BI.Direction.Left, + { + width: o.iconWrapperWidth, + el: this.checkbox, + }, + { + width: 16, + el: icon, + }, + this.text + ); + createWidget( + extend( + { + element: this, + }, + BI.LogicFactory.createLogic( + type, + extend(o.logic, { + items, + rgap: 5, + }) + ) + ) + ); } - doRedMark () { + doRedMark() { this.text.doRedMark(...arguments); } diff --git a/src/case/button/node/node.last.plus.js b/src/case/button/node/node.last.plus.js index 95e745f4e..628197cb0 100644 --- a/src/case/button/node/node.last.plus.js +++ b/src/case/button/node/node.last.plus.js @@ -1,5 +1,6 @@ -import { NodeButton } from "../../../base/single/button/button.node"; -import { shortcut, extend, createWidget, isNotNull, Controller } from "../../../core"; +import { LastTreeNodeCheckbox } from "../../checkbox"; +import { Label, NodeButton } from "@/base"; +import { shortcut, extend, createWidget, isNotNull, Controller } from "@/core"; /** * 加号表示的组节点 @@ -13,7 +14,7 @@ export class LastPlusGroupNode extends NodeButton { _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-last-plus-group-node bi-list-item`, logic: { @@ -29,13 +30,13 @@ export class LastPlusGroupNode extends NodeButton { BI.LastPlusGroupNode.superclass._init.apply(this, arguments); const o = this.options; this.checkbox = createWidget({ - type: "bi.last_tree_node_checkbox", + type: LastTreeNodeCheckbox.xtype, stopPropagation: true, iconHeight: o.height, iconWidth: o.height, }); this.text = createWidget({ - type: "bi.label", + type: Label.xtype, textAlign: "left", whiteSpace: "nowrap", textHeight: o.height, @@ -46,7 +47,7 @@ export class LastPlusGroupNode extends NodeButton { py: o.py, keyword: o.keyword, }); - this.checkbox.on(Controller.EVENT_CHANGE, type => { + this.checkbox.on(Controller.EVENT_CHANGE, (type) => { if (type === BI.Events.CLICK) { if (this.checkbox.isSelected()) { this.triggerExpand(); @@ -56,15 +57,27 @@ export class LastPlusGroupNode extends NodeButton { } }); const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: this.checkbox, - }, this.text); - createWidget(extend({ - element: this, - }, BI.LogicFactory.createLogic(type, extend(o.logic, { - items, - })))); + const items = BI.LogicFactory.createLogicItemsByDirection( + BI.Direction.Left, + { + width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, + el: this.checkbox, + }, + this.text + ); + createWidget( + extend( + { + element: this, + }, + BI.LogicFactory.createLogic( + type, + extend(o.logic, { + items, + }) + ) + ) + ); } doRedMark() { diff --git a/src/case/button/node/node.mid.plus.js b/src/case/button/node/node.mid.plus.js index e1276d6ab..ba3d38ea2 100644 --- a/src/case/button/node/node.mid.plus.js +++ b/src/case/button/node/node.mid.plus.js @@ -1,5 +1,6 @@ -import { NodeButton } from "../../../base/single/button/button.node"; -import { shortcut, extend, createWidget, Controller } from "../../../core"; +import { MidTreeNodeCheckbox } from "../../checkbox"; +import { Label, NodeButton } from "@/base"; +import { shortcut, extend, createWidget, Controller } from "@/core"; /** * 加号表示的组节点 @@ -10,10 +11,10 @@ import { shortcut, extend, createWidget, Controller } from "../../../core"; @shortcut export class MidPlusGroupNode extends NodeButton { static xtype = "bi.mid_plus_group_node"; - + _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-mid-plus-group-node bi-list-item`, logic: { @@ -30,13 +31,13 @@ export class MidPlusGroupNode extends NodeButton { super._init(...arguments); const o = this.options; this.checkbox = createWidget({ - type: "bi.mid_tree_node_checkbox", + type: MidTreeNodeCheckbox.xtype, stopPropagation: true, iconHeight: o.height, iconWidth: o.height, }); this.text = createWidget({ - type: "bi.label", + type: Label.xtype, textAlign: "left", whiteSpace: "nowrap", textHeight: o.height, @@ -47,7 +48,7 @@ export class MidPlusGroupNode extends NodeButton { py: o.py, keyword: o.keyword, }); - this.checkbox.on(Controller.EVENT_CHANGE, type => { + this.checkbox.on(Controller.EVENT_CHANGE, (type) => { if (type === BI.Events.CLICK) { if (this.checkbox.isSelected()) { this.triggerExpand(); @@ -57,15 +58,27 @@ export class MidPlusGroupNode extends NodeButton { } }); const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { - width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - el: this.checkbox, - }, this.text); - createWidget(extend({ - element: this, - }, BI.LogicFactory.createLogic(type, extend(o.logic, { - items, - })))); + const items = BI.LogicFactory.createLogicItemsByDirection( + BI.Direction.Left, + { + width: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, + el: this.checkbox, + }, + this.text + ); + createWidget( + extend( + { + element: this, + }, + BI.LogicFactory.createLogic( + type, + extend(o.logic, { + items, + }) + ) + ) + ); } doRedMark() { @@ -88,4 +101,3 @@ export class MidPlusGroupNode extends NodeButton { } } } - diff --git a/src/case/button/node/node.multilayer.icon.arrow.js b/src/case/button/node/node.multilayer.icon.arrow.js index 995bc0327..fb4554741 100644 --- a/src/case/button/node/node.multilayer.icon.arrow.js +++ b/src/case/button/node/node.multilayer.icon.arrow.js @@ -1,5 +1,6 @@ -import { NodeButton } from "../../../base/single/button/button.node"; -import { shortcut, extend, createWidget, Controller, count, makeArray } from "../../../core"; +import { IconArrowNode } from "./node.icon.arrow"; +import { Layout, HorizontalAdaptLayout, shortcut, extend, createWidget, Controller, count, makeArray } from "@/core"; +import { NodeButton } from "@/base"; @shortcut() export class MultiLayerIconArrowNode extends NodeButton { @@ -7,7 +8,7 @@ export class MultiLayerIconArrowNode extends NodeButton { _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { extraCls: "bi-multilayer-icon-arrow-node bi-list-item", layer: 0, // 第几层级 @@ -25,7 +26,7 @@ export class MultiLayerIconArrowNode extends NodeButton { super._init(...arguments); const o = this.options; this.node = createWidget({ - type: "bi.icon_arrow_node", + type: IconArrowNode.xtype, iconCls: o.iconCls, cls: "bi-list-item-none", id: o.id, @@ -48,14 +49,14 @@ export class MultiLayerIconArrowNode extends NodeButton { const items = []; count(0, o.layer, () => { items.push({ - type: "bi.layout", + type: Layout.xtype, width: 15, height: o.height, }); }); items.push(this.node); createWidget({ - type: "bi.horizontal_adapt", + type: HorizontalAdaptLayout.xtype, element: this, columnSize: makeArray(o.layer, 15), items, diff --git a/src/case/button/node/node.plus.js b/src/case/button/node/node.plus.js index 4a4e1b042..d8c632fce 100644 --- a/src/case/button/node/node.plus.js +++ b/src/case/button/node/node.plus.js @@ -1,5 +1,6 @@ -import { NodeButton } from "../../../base/single/button/button.node"; -import { shortcut, extend, createWidget, Controller } from "../../../core"; +import { TreeNodeCheckbox } from "../../checkbox"; +import { VerticalAdaptLayout, shortcut, extend, createWidget, Controller } from "@/core"; +import { Label, NodeButton } from "@/base"; /** * 加号表示的组节点 @@ -10,10 +11,10 @@ import { shortcut, extend, createWidget, Controller } from "../../../core"; @shortcut() export class PlusGroupNode extends NodeButton { static xtype = "bi.plus_group_node"; - + _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-plus-group-node bi-list-item`, id: "", @@ -26,7 +27,7 @@ export class PlusGroupNode extends NodeButton { render() { const o = this.options; this.checkbox = createWidget({ - type: "bi.tree_node_checkbox", + type: TreeNodeCheckbox.xtype, iconHeight: o.height, iconWidth: o.iconWrapperWidth || o.height, }); @@ -37,30 +38,33 @@ export class PlusGroupNode extends NodeButton { } this.fireEvent(Controller.EVENT_CHANGE, args); }); - + return { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, columnSize: [o.iconWrapperWidth || o.height, "fill"], - items: [this.checkbox, { - el: { - type: "bi.label", - ref: _ref => { - this.text = _ref; + items: [ + this.checkbox, + { + el: { + type: Label.xtype, + ref: (_ref) => { + this.text = _ref; + }, + textAlign: "left", + whiteSpace: "nowrap", + textHeight: o.height, + height: o.height, + hgap: o.hgap || o.textHgap, + vgap: o.textVgap, + lgap: o.textLgap, + rgap: o.textRgap, + text: o.text, + value: o.value, + keyword: o.keyword, + py: o.py, }, - textAlign: "left", - whiteSpace: "nowrap", - textHeight: o.height, - height: o.height, - hgap: o.hgap || o.textHgap, - vgap: o.textVgap, - lgap: o.textLgap, - rgap: o.textRgap, - text: o.text, - value: o.value, - keyword: o.keyword, - py: o.py, }, - }], + ], }; } diff --git a/src/case/button/node/siwtcher.tree.node.js b/src/case/button/node/siwtcher.tree.node.js index 502deb48f..316340039 100644 --- a/src/case/button/node/siwtcher.tree.node.js +++ b/src/case/button/node/siwtcher.tree.node.js @@ -1,11 +1,11 @@ -import { NodeButton } from "../../../base/single/button/button.node"; -import { shortcut, extend } from "../../../core"; +import { IconLabel, NodeButton } from "@/base"; +import { shortcut, extend } from "@/core"; @shortcut() export class TreeNodeSwitcher extends NodeButton { static xtype = "bi.tree_node_switcher"; static EVENT_CHANGE = "EVENT_CHANGE"; - + _defaultConfig() { return extend(super._defaultConfig(...arguments), { baseCls: "bi-tree-node-switcher", @@ -21,7 +21,7 @@ export class TreeNodeSwitcher extends NodeButton { const [collapse, expand] = this.getIconCls(); return { - type: "bi.icon_label", + type: IconLabel.xtype, iconWidth: this.options.iconWidth, iconHeight: this.options.iconHeight, cls: this.options.open ? expand : collapse, @@ -32,16 +32,24 @@ export class TreeNodeSwitcher extends NodeButton { const options = this.options; if (options.layer === 0 && options.isFirstNode && options.isLastNode) { // 只有一层,并且是第一个节点,并且是最后一个节点 - return BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? ["tree-solid-collapse-icon-type1", "tree-solid-expand-icon-type1"] : ["tree-collapse-icon-type1", "tree-expand-icon-type1"]; + return BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" + ? ["tree-solid-collapse-icon-type1", "tree-solid-expand-icon-type1"] + : ["tree-collapse-icon-type1", "tree-expand-icon-type1"]; } else if (options.layer === 0 && options.isFirstNode) { // 第一层,并且是第一个节点 - return BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? ["tree-solid-collapse-icon-type1", "tree-solid-expand-icon-type1"] : ["tree-collapse-icon-type2", "tree-expand-icon-type2"]; + return BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" + ? ["tree-solid-collapse-icon-type1", "tree-solid-expand-icon-type1"] + : ["tree-collapse-icon-type2", "tree-expand-icon-type2"]; } else if (options.isLastNode) { // 最后一个节点 - return BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? ["tree-solid-collapse-icon-type1", "tree-solid-expand-icon-type1"] : ["tree-collapse-icon-type4", "tree-expand-icon-type4"]; + return BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" + ? ["tree-solid-collapse-icon-type1", "tree-solid-expand-icon-type1"] + : ["tree-collapse-icon-type4", "tree-expand-icon-type4"]; } else { // 其他情况 - return BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? ["tree-solid-collapse-icon-type1", "tree-solid-expand-icon-type1"] : ["tree-collapse-icon-type3", "tree-expand-icon-type3"]; + return BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" + ? ["tree-solid-collapse-icon-type1", "tree-solid-expand-icon-type1"] + : ["tree-collapse-icon-type3", "tree-expand-icon-type3"]; } } diff --git a/src/case/button/node/treenode.js b/src/case/button/node/treenode.js index f6ef4c5bc..9610cd7a1 100644 --- a/src/case/button/node/treenode.js +++ b/src/case/button/node/treenode.js @@ -61,8 +61,9 @@ export class BasicTreeNode extends NodeButton { items: [ { el: checkbox, - lgap: o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, // 偏移公式为每一层的偏移量为节点高度的一半 - }, { + lgap: (o.layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT) / 2, // 偏移公式为每一层的偏移量为节点高度的一半 + }, + { el: { type: Label.xtype, ref: _ref => { @@ -110,5 +111,3 @@ export class BasicTreeNode extends NodeButton { super.setValue(...arguments); } } - - diff --git a/src/case/button/switch.js b/src/case/button/switch.js index f40cf3cf4..f51939219 100644 --- a/src/case/button/switch.js +++ b/src/case/button/switch.js @@ -1,10 +1,11 @@ +import { AbsoluteLayout, shortcut } from "@/core"; +import { TextButton, Label, BasicButton } from "@/base"; + + /** * Created by Windy on 2018/2/1. */ -import { BasicButton } from "../../base/single/button/button.basic"; -import { shortcut } from "../../core"; - @shortcut() export class Switch extends BasicButton { static xtype = "bi.switch"; @@ -28,16 +29,16 @@ export class Switch extends BasicButton { const o = this.options, c = this.constants; const tgap = (o.height - c.CIRCLE_SIZE) / 2; - + return { - type: "bi.absolute", - ref: _ref => { + type: AbsoluteLayout.xtype, + ref: (_ref) => { this.layout = _ref; }, items: [ { el: { - type: "bi.text_button", + type: TextButton.xtype, cls: "circle-button", }, width: 12, @@ -46,27 +47,27 @@ export class Switch extends BasicButton { left: o.selected ? 28 : 4, }, { - type: "bi.label", + type: Label.xtype, text: BI.i18nText("BI-Basic_Simple_Open"), cls: "content-tip", left: 8, top: tgap - 2, invisible: !(o.showTip && o.selected), - ref: _ref => { + ref: (_ref) => { this.openTip = _ref; }, }, { - type: "bi.label", + type: Label.xtype, text: BI.i18nText("BI-Basic_Simple_Close"), cls: "content-tip", right: 8, top: tgap - 2, invisible: !(o.showTip && !o.selected), - ref: _ref => { + ref: (_ref) => { this.closeTip = _ref; }, - } + }, ], }; } diff --git a/src/case/button/treeitem/item.icon.treeleaf.js b/src/case/button/treeitem/item.icon.treeleaf.js index dee13e086..a4dd0d3b8 100644 --- a/src/case/button/treeitem/item.icon.treeleaf.js +++ b/src/case/button/treeitem/item.icon.treeleaf.js @@ -1,5 +1,5 @@ -import { BasicButton } from "../../../base/single/button/button.basic"; -import { shortcut, extend, createWidget } from "../../../core"; +import { CenterAdaptLayout, shortcut, extend, createWidget } from "@/core"; +import { Icon, Label, BasicButton } from "@/base"; @shortcut() export class IconTreeLeafItem extends BasicButton { @@ -23,18 +23,20 @@ export class IconTreeLeafItem extends BasicButton { const o = this.options; const icon = createWidget({ - type: "bi.center_adapt", + type: CenterAdaptLayout.xtype, width: 24, cls: o.iconCls, - items: [{ - type: "bi.icon", - width: o.iconWidth, - height: o.iconHeight, - }], + items: [ + { + type: Icon.xtype, + width: o.iconWidth, + height: o.iconHeight, + }, + ], }); this.text = createWidget({ - type: "bi.label", + type: Label.xtype, textAlign: "left", whiteSpace: "nowrap", textHeight: o.height, @@ -46,18 +48,30 @@ export class IconTreeLeafItem extends BasicButton { keyword: o.keyword, }); const type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left); - const items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, { - width: 16, - el: icon, - }, { - el: this.text, - }); - createWidget(extend({ - element: this, - }, BI.LogicFactory.createLogic(type, extend(o.logic, { - items, - hgap: 5, - })))); + const items = BI.LogicFactory.createLogicItemsByDirection( + BI.Direction.Left, + { + width: 16, + el: icon, + }, + { + el: this.text, + } + ); + createWidget( + extend( + { + element: this, + }, + BI.LogicFactory.createLogic( + type, + extend(o.logic, { + items, + hgap: 5, + }) + ) + ) + ); } doRedMark() { diff --git a/src/case/button/treeitem/item.multilayer.icon.treeleaf.js b/src/case/button/treeitem/item.multilayer.icon.treeleaf.js index 75d67b090..e9fac6ea5 100644 --- a/src/case/button/treeitem/item.multilayer.icon.treeleaf.js +++ b/src/case/button/treeitem/item.multilayer.icon.treeleaf.js @@ -1,5 +1,6 @@ -import { BasicButton } from "../../../base/single/button/button.basic"; -import { shortcut, extend, createWidget, Controller, makeArray, count } from "../../../core"; +import { IconTreeLeafItem } from "./item.icon.treeleaf"; +import { Layout, HorizontalAdaptLayout, shortcut, extend, createWidget, Controller, makeArray, count } from "@/core"; +import { BasicButton } from "@/base"; /** * @class BI.MultiLayerIconTreeLeafItem @@ -8,7 +9,7 @@ import { shortcut, extend, createWidget, Controller, makeArray, count } from ".. @shortcut() export class MultiLayerIconTreeLeafItem extends BasicButton { static xtype = "bi.multilayer_icon_tree_leaf_item"; - + _defaultConfig() { return extend(super._defaultConfig(...arguments), { extraCls: "bi-multilayer-icon-tree-leaf-item bi-list-item-active", @@ -24,7 +25,7 @@ export class MultiLayerIconTreeLeafItem extends BasicButton { super._init(...arguments); const o = this.options; this.item = createWidget({ - type: "bi.icon_tree_leaf_item", + type: IconTreeLeafItem.xtype, cls: "bi-list-item-none", iconCls: o.iconCls, id: o.id, @@ -41,7 +42,8 @@ export class MultiLayerIconTreeLeafItem extends BasicButton { }); this.item.on(Controller.EVENT_CHANGE, (...args) => { const [type] = args; - if (type === BI.Events.CLICK) {// 本身实现click功能 + if (type === BI.Events.CLICK) { + // 本身实现click功能 return; } this.fireEvent(Controller.EVENT_CHANGE, ...args); @@ -50,45 +52,45 @@ export class MultiLayerIconTreeLeafItem extends BasicButton { const items = []; count(0, o.layer, () => { items.push({ - type: "bi.layout", + type: Layout.xtype, width: 15, height: o.height, }); }); items.push(this.item); createWidget({ - type: "bi.horizontal_adapt", + type: HorizontalAdaptLayout.xtype, element: this, columnSize: makeArray(o.layer, 15), items, }); } - doRedMark () { + doRedMark() { this.item.doRedMark(...arguments); } - unRedMark () { + unRedMark() { this.item.unRedMark(...arguments); } - + doHighLight() { this.item.doHighLight(...arguments); } - unHighLight () { + unHighLight() { this.item.unHighLight(...arguments); } - getId () { + getId() { return this.options.id; } - getPId () { + getPId() { return this.options.pId; } - doClick () { + doClick() { super.doClick(...arguments); this.item.setSelected(this.isSelected()); } @@ -102,5 +104,3 @@ export class MultiLayerIconTreeLeafItem extends BasicButton { return this.options.value; } } - - diff --git a/src/case/button/treeitem/treeitem.js b/src/case/button/treeitem/treeitem.js index 189573c33..39277dfa3 100644 --- a/src/case/button/treeitem/treeitem.js +++ b/src/case/button/treeitem/treeitem.js @@ -41,26 +41,31 @@ export class BasicTreeItem extends NodeButton { iconCls, } = this.options; - const icon = isKey(iconCls) ? { - el: { - type: IconLabel.xtype, - iconWidth, - iconHeight, - cls: iconCls, - }, - width: 24, - } : null; - - const indent = layer === 0 ? null : { - el: { - type: Layout.xtype, - height, - width: height, - cls: this.getLineCls(), - }, - lgap: layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2, // 偏移公式为每一层的偏移量为节点高度的一半 - width: "", - }; + const icon = isKey(iconCls) + ? { + el: { + type: IconLabel.xtype, + iconWidth, + iconHeight, + cls: iconCls, + }, + width: 24, + } + : null; + + const indent = + layer === 0 + ? null + : { + el: { + type: Layout.xtype, + height, + width: height, + cls: this.getLineCls(), + }, + lgap: (layer * BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT) / 2, // 偏移公式为每一层的偏移量为节点高度的一半 + width: "", + }; return { type: VerticalAdaptLayout.xtype, @@ -97,11 +102,17 @@ export class BasicTreeItem extends NodeButton { if (options.layer === 0 && options.isFirstNode && options.isLastNode) { return ""; } else if (options.layer === 0 && options.isFirstNode) { - return BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? "tree-first-solid-line-conn-background" : "first-line-conn-background"; + return BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" + ? "tree-first-solid-line-conn-background" + : "first-line-conn-background"; } else if (options.isLastNode) { - return BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? "tree-last-solid-line-conn-background" : "last-line-conn-background"; + return BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" + ? "tree-last-solid-line-conn-background" + : "last-line-conn-background"; } else { - return BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? "tree-mid-solid-line-conn-background" : "mid-line-conn-background"; + return BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" + ? "tree-mid-solid-line-conn-background" + : "mid-line-conn-background"; } } diff --git a/src/case/calendar/calendar.date.item.js b/src/case/calendar/calendar.date.item.js index b1b4ef5c5..f5ea79b1d 100644 --- a/src/case/calendar/calendar.date.item.js +++ b/src/case/calendar/calendar.date.item.js @@ -1,5 +1,5 @@ -import { shortcut } from "@/core"; -import { BasicButton } from "@/base"; +import { AbsoluteLayout, shortcut } from "@/core"; +import { TextItem, BasicButton } from "@/base"; /** * 专门为calendar的视觉加的button,作为私有button,不能配置任何属性,也不要用这个玩意 @@ -15,50 +15,52 @@ export class CalendarDateItem extends BasicButton { static xtype = "bi.calendar_date_item"; - render () { + render() { const { text, value, lgap, rgap, tgap, bgap } = this.options; return { - type: "bi.absolute", - items: [{ - el: { - type: "bi.text_item", - cls: "bi-border-radius bi-list-item-select", - textAlign: "center", - text, - value, - ref: _ref => { - this.text = _ref; + type: AbsoluteLayout.xtype, + items: [ + { + el: { + type: TextItem.xtype, + cls: "bi-border-radius bi-list-item-select", + textAlign: "center", + text, + value, + ref: _ref => { + this.text = _ref; + }, }, - }, - left: lgap, - right: rgap, - top: tgap, - bottom: bgap, - }], + left: lgap, + right: rgap, + top: tgap, + bottom: bgap, + } + ], }; } - doHighLight () { + doHighLight() { this.text.doHighLight(...arguments); } - unHighLight () { + unHighLight() { this.text.unHighLight(...arguments); } - setValue () { + setValue() { if (!this.isReadOnly()) { this.text.setValue(...arguments); } } - setSelected (b) { + setSelected(b) { super.setSelected(...arguments); this.text.setSelected(b); } - getValue () { + getValue() { return this.text.getValue(); } } diff --git a/src/case/calendar/calendar.js b/src/case/calendar/calendar.js index b049e18b4..82d97b039 100644 --- a/src/case/calendar/calendar.js +++ b/src/case/calendar/calendar.js @@ -1,4 +1,27 @@ -import { shortcut, Widget, getDate, each, range, extend, isLeapYear, Date, StartOfWeek, checkDateVoid, map, createWidget, createItems, LogicFactory, Controller, getShortDayName, getOffsetDate, isNotEmptyString, parseInt } from "@/core"; +import { Label, ButtonGroup } from "@/base"; +import { + CenterLayout, + shortcut, + Widget, + getDate, + each, + range, + extend, + isLeapYear, + Date, + StartOfWeek, + checkDateVoid, + map, + createWidget, + createItems, + LogicFactory, + Controller, + getShortDayName, + getOffsetDate, + isNotEmptyString, + parseInt +} from "@/core"; +import { CalendarDateItem } from "./calendar.date.item"; /** * Created by GUY on 2015/8/28. @@ -8,17 +31,17 @@ import { shortcut, Widget, getDate, each, range, extend, isLeapYear, Date, Start @shortcut() export class Calendar extends Widget { static xtype = "bi.calendar"; - - static getPageByDateJSON (json) { + + static getPageByDateJSON(json) { const year = getDate().getFullYear(); const month = getDate().getMonth(); let page = (json.year - year) * 12; page += json.month - 1 - month; - + return page; } - static getDateJSONByPage (v) { + static getDateJSONByPage(v) { const months = getDate().getMonth(); let page = v; @@ -29,17 +52,17 @@ export class Calendar extends Widget { if (page < 0 && page % 12 !== 0) { year--; } - const month = page >= 0 ? (page % 12) : ((12 + page % 12) % 12); - + const month = page >= 0 ? page % 12 : (12 + (page % 12)) % 12; + return { year: getDate().getFullYear() + year, month: month + 1, }; } - _defaultConfig () { + _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: "bi-calendar", logic: { @@ -52,8 +75,10 @@ export class Calendar extends Widget { day: 25, }); } - _dateCreator (Y, M, D) { - const { min, max } = this.options, log = {}, De = getDate(); + _dateCreator(Y, M, D) { + const { min, max } = this.options, + log = {}, + De = getDate(); const mins = min.match(/\d+/g); const maxs = max.match(/\d+/g); @@ -78,7 +103,9 @@ export class Calendar extends Widget { const items = []; each(range(42), i => { const td = {}; - let YY = log.ymd[0], MM = log.ymd[1] + 1, DD; + let YY = log.ymd[0], + MM = log.ymd[1] + 1, + DD; // 上个月的日期 if (i < offSetFDay) { td.lastMonth = true; @@ -103,83 +130,101 @@ export class Calendar extends Widget { td.text = DD; items.push(td); }); - + return items; } - _init () { + _init() { super._init(...arguments); const { year, month, day, logic } = this.options; const items = map(this._getWeekLabel(), (i, value) => { return { - type: "bi.label", + type: Label.xtype, height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, text: value, }; }); const title = createWidget({ - type: "bi.button_group", + type: ButtonGroup.xtype, height: 44, items, - layouts: [{ - type: "bi.center", - hgap: 5, - vgap: 10, - }], + layouts: [ + { + type: CenterLayout.xtype, + hgap: 5, + vgap: 10, + } + ], }); this.days = createWidget({ - type: "bi.button_group", + type: ButtonGroup.xtype, items: createItems(this._getItems(), {}), value: `${year}-${month}-${day}`, - layouts: [LogicFactory.createLogic("table", extend({}, logic, { - columns: 7, - rows: 6, - columnSize: [1 / 7, 1 / 7, 1 / 7, 1 / 7, 1 / 7, 1 / 7, 1 / 7], - rowSize: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + 8, - }))], + layouts: [ + LogicFactory.createLogic( + "table", + extend({}, logic, { + columns: 7, + rows: 6, + columnSize: [1 / 7, 1 / 7, 1 / 7, 1 / 7, 1 / 7, 1 / 7, 1 / 7], + rowSize: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT + 8, + }) + ) + ], }); this.days.on(Controller.EVENT_CHANGE, (...args) => { this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - createWidget(extend({ - element: this, - - }, LogicFactory.createLogic("vertical", extend({}, logic, { - items: LogicFactory.createLogicItemsByDirection("top", title, { - el: this.days, - tgap: -5, - }), - })))); + createWidget( + extend( + { + element: this, + }, + LogicFactory.createLogic( + "vertical", + extend({}, logic, { + items: LogicFactory.createLogicItemsByDirection("top", title, { + el: this.days, + tgap: -5, + }), + }) + ) + ) + ); } - _getWeekLabel () { + _getWeekLabel() { return map(range(0, 7), (idx, v) => getShortDayName((v + StartOfWeek) % 7)); } - isFrontDate () { + isFrontDate() { const { year, month, min, max } = this.options; let Y = year; - const M = month, De = getDate(), day = De.getDay(); + const M = month, + De = getDate(), + day = De.getDay(); Y = Y | 0; De.setFullYear(Y, M, 1); const newDate = getOffsetDate(De, -1 * (day + 1)); - + return !!checkDateVoid(newDate.getFullYear(), newDate.getMonth(), newDate.getDate(), min, max)[0]; } - isFinalDate () { + isFinalDate() { const { year, month, min, max } = this.options; let Y = year; - const M = month, De = getDate(), day = De.getDay(); + const M = month, + De = getDate(), + day = De.getDay(); Y = Y | 0; De.setFullYear(Y, M, 1); const newDate = getOffsetDate(De, 42 - day); - + return !!checkDateVoid(newDate.getFullYear(), newDate.getMonth(), newDate.getDate(), min, max)[0]; } - _getItems () { + _getItems() { const o = this.options; const days = this._dateCreator(o.year, o.month - 1, o.day); const items = []; @@ -190,38 +235,40 @@ export class Calendar extends Widget { items.push(days.slice(28, 35)); items.push(days.slice(35, 42)); - return map(items, (i, item) => map(item, (j, td) => { - let month = td.lastMonth ? o.month - 1 : (td.nextMonth ? o.month + 1 : o.month); - let year = o.year; - if (month > 12) { - month = 1; - year++; - } else if (month < 1) { - month = 12; - year--; - } - - return extend(td, { - type: "bi.calendar_date_item", - once: false, - forceSelected: true, - value: `${year}-${month}-${td.text}`, - disabled: td.disabled, - cls: td.lastMonth || td.nextMonth ? "bi-tips" : "", - lgap: 2, - rgap: 2, - tgap: 4, - bgap: 4, - // selected: td.currentDay - }); - })); + return map(items, (i, item) => + map(item, (j, td) => { + let month = td.lastMonth ? o.month - 1 : td.nextMonth ? o.month + 1 : o.month; + let year = o.year; + if (month > 12) { + month = 1; + year++; + } else if (month < 1) { + month = 12; + year--; + } + + return extend(td, { + type: CalendarDateItem.xtype, + once: false, + forceSelected: true, + value: `${year}-${month}-${td.text}`, + disabled: td.disabled, + cls: td.lastMonth || td.nextMonth ? "bi-tips" : "", + lgap: 2, + rgap: 2, + tgap: 4, + bgap: 4, + // selected: td.currentDay + }); + }) + ); } _populate() { this.days.populate(this._getItems()); } - setMinDate (minDate) { + setMinDate(minDate) { const o = this.options; if (isNotEmptyString(o.min)) { o.min = minDate; @@ -229,7 +276,7 @@ export class Calendar extends Widget { } } - setMaxDate (maxDate) { + setMaxDate(maxDate) { const o = this.options; if (isNotEmptyString(o.max)) { o.max = maxDate; @@ -237,13 +284,13 @@ export class Calendar extends Widget { } } - setValue (ob) { + setValue(ob) { this.days.setValue([`${ob.year}-${ob.month}-${ob.day}`]); } - getValue () { + getValue() { const date = this.days.getValue()[0].match(/\d+/g); - + return { year: date[0] | 0, month: date[1] | 0, diff --git a/src/case/calendar/calendar.year.js b/src/case/calendar/calendar.year.js index c8ebc58b0..85321b145 100644 --- a/src/case/calendar/calendar.year.js +++ b/src/case/calendar/calendar.year.js @@ -1,4 +1,23 @@ -import { shortcut, Widget, extend, parseDateTime, range, checkDateVoid, print, getDate, each, createWidget, createItems, LogicFactory, Controller, makeArray, map, isNotEmptyString } from "@/core"; +import { ButtonGroup, TextItem } from "@/base"; +import { + CenterAdaptLayout, + shortcut, + Widget, + extend, + parseDateTime, + range, + checkDateVoid, + print, + getDate, + each, + createWidget, + createItems, + LogicFactory, + Controller, + makeArray, + map, + isNotEmptyString +} from "@/core"; /** * Created by GUY on 2015/8/28. @@ -11,26 +30,26 @@ export class YearCalendar extends Widget { static INTERVAL = 12; // 获取显示的第一年 - static getStartYear (year) { + static getStartYear(year) { const cur = getDate().getFullYear(); - - return year - ((year - cur + 3) % YearCalendar.INTERVAL + 12) % YearCalendar.INTERVAL; + + return year - ((((year - cur + 3) % YearCalendar.INTERVAL) + 12) % YearCalendar.INTERVAL); } - static getEndYear (year) { + static getEndYear(year) { return YearCalendar.getStartYear(year) + YearCalendar.INTERVAL - 1; } - static getPageByYear (year) { + static getPageByYear(year) { const cur = getDate().getFullYear(); year = YearCalendar.getStartYear(year); - + return (year - cur + 3) / YearCalendar.INTERVAL; } - _defaultConfig () { + _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: "bi-year-calendar", behaviors: {}, @@ -43,7 +62,7 @@ export class YearCalendar extends Widget { }); } - _yearCreator (Y) { + _yearCreator(Y) { const { min, max } = this.options; Y = Y | 0; const start = YearCalendar.getStartYear(Y); @@ -53,69 +72,92 @@ export class YearCalendar extends Widget { const endDate = parseDateTime(max, "%Y-%X-%d"); each(range(YearCalendar.INTERVAL), i => { const td = {}; - if (checkDateVoid(start + i, 1, 1, print(getDate(startDate.getFullYear(), 0, 1), "%Y-%X-%d"), print(getDate(endDate.getFullYear(), 0, 1), "%Y-%X-%d"))[0]) { + if ( + checkDateVoid( + start + i, + 1, + 1, + print(getDate(startDate.getFullYear(), 0, 1), "%Y-%X-%d"), + print(getDate(endDate.getFullYear(), 0, 1), "%Y-%X-%d") + )[0] + ) { td.disabled = true; } td.text = start + i; items.push(td); }); - + return items; } - _init () { + _init() { super._init(...arguments); const { behaviors, logic } = this.options; this.currentYear = getDate().getFullYear(); this.years = createWidget({ - type: "bi.button_group", + type: ButtonGroup.xtype, behaviors, items: createItems(this._getItems(), {}), - layouts: [LogicFactory.createLogic("table", extend({}, logic, { - columns: 2, - rows: 6, - columnSize: [1 / 2, 1 / 2], - rowSize: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - })), { - type: "bi.center_adapt", - vgap: 2, - }], + layouts: [ + LogicFactory.createLogic( + "table", + extend({}, logic, { + columns: 2, + rows: 6, + columnSize: [1 / 2, 1 / 2], + rowSize: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, + }) + ), + { + type: CenterAdaptLayout.xtype, + vgap: 2, + } + ], }); this.years.on(Controller.EVENT_CHANGE, (...args) => { this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - createWidget(extend({ - element: this, - }, LogicFactory.createLogic("vertical", extend({}, logic, { - scrolly: true, - vgap: 5, - hgap: 6, - items: LogicFactory.createLogicItemsByDirection("top", this.years), - })))); + createWidget( + extend( + { + element: this, + }, + LogicFactory.createLogic( + "vertical", + extend({}, logic, { + scrolly: true, + vgap: 5, + hgap: 6, + items: LogicFactory.createLogicItemsByDirection("top", this.years), + }) + ) + ) + ); } - isFrontYear () { + isFrontYear() { const { min, max } = this.options; let Y = this.options.year; Y = Y | 0; - + return !!checkDateVoid(YearCalendar.getStartYear(Y) - 1, 1, 1, min, max)[0]; } - isFinalYear () { + isFinalYear() { const { min, max } = this.options; let Y = this.options.year; Y = Y | 0; - + return !!checkDateVoid(YearCalendar.getEndYear(Y) + 1, 1, 1, min, max)[0]; } - _getItems () { + _getItems() { const { year } = this.options; const years = this._yearCreator(year || this.currentYear); // 纵向排列年 - const len = years.length, tyears = makeArray(len, ""); + const len = years.length, + tyears = makeArray(len, ""); const mapArr = [0, 6, 1, 7, 2, 8, 3, 9, 4, 10, 5, 11]; each(years, (i, y) => { tyears[i] = years[mapArr[i]]; @@ -129,25 +171,29 @@ export class YearCalendar extends Widget { items.push(tyears.slice(8, 10)); items.push(tyears.slice(10, 12)); - return map(items, (i, item) => map(item, (j, td) => extend(td, { - type: "bi.text_item", - cls: "bi-list-item-select bi-border-radius", - textAlign: "center", - whiteSpace: "normal", - once: false, - forceSelected: true, - height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, - width: 45, - value: td.text, - disabled: td.disabled, - }))); + return map(items, (i, item) => + map(item, (j, td) => + extend(td, { + type: TextItem.xtype, + cls: "bi-list-item-select bi-border-radius", + textAlign: "center", + whiteSpace: "normal", + once: false, + forceSelected: true, + height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, + width: 45, + value: td.text, + disabled: td.disabled, + }) + ) + ); } - _populate () { + _populate() { this.years.populate(this._getItems()); } - setMinDate (minDate) { + setMinDate(minDate) { const o = this.options; if (isNotEmptyString(o.min)) { o.min = minDate; @@ -155,7 +201,7 @@ export class YearCalendar extends Widget { } } - setMaxDate (maxDate) { + setMaxDate(maxDate) { const o = this.options; if (isNotEmptyString(this.options.max)) { o.max = maxDate; @@ -163,11 +209,11 @@ export class YearCalendar extends Widget { } } - setValue (val) { + setValue(val) { this.years.setValue([val]); } - getValue () { + getValue() { return this.years.getValue()[0]; } } diff --git a/src/case/calendar/index.js b/src/case/calendar/index.js index 17c7f5fac..d07f7b8ef 100644 --- a/src/case/calendar/index.js +++ b/src/case/calendar/index.js @@ -1,3 +1,3 @@ -export { CalendarDateItem } from "./calendar.date.item"; -export { Calendar } from "./calendar"; -export { YearCalendar } from "./calendar.year"; +export { CalendarDateItem } from "./calendar.date.item"; +export { Calendar } from "./calendar"; +export { YearCalendar } from "./calendar.year"; diff --git a/src/case/checkbox/check.arrownode.js b/src/case/checkbox/check.arrownode.js index 625e7a6e4..b34751edc 100644 --- a/src/case/checkbox/check.arrownode.js +++ b/src/case/checkbox/check.arrownode.js @@ -1,9 +1,10 @@ +import { shortcut } from "@/core"; +import { IconButton } from "@/base"; + /** * Created by roy on 15/10/16. * 右与下箭头切换的树节点 */ -import { shortcut } from "@/core"; -import { IconButton } from "@/base"; @shortcut() export class ArrowTreeGroupNodeCheckbox extends IconButton { diff --git a/src/case/checkbox/check.checkingmarknode.js b/src/case/checkbox/check.checkingmarknode.js index 4f51a02c1..159988ed0 100644 --- a/src/case/checkbox/check.checkingmarknode.js +++ b/src/case/checkbox/check.checkingmarknode.js @@ -1,10 +1,11 @@ +import { extend, shortcut } from "@/core"; +import { IconButton } from "@/base"; + /** * 十字型的树节点 * @class BI.CheckingMarkNode * @extends BI.IconButton */ -import { extend, shortcut } from "@/core"; -import { IconButton } from "@/base"; @shortcut() export class CheckingMarkNode extends IconButton { diff --git a/src/case/checkbox/check.first.treenode.js b/src/case/checkbox/check.first.treenode.js index bade32c4d..0f7342a25 100644 --- a/src/case/checkbox/check.first.treenode.js +++ b/src/case/checkbox/check.first.treenode.js @@ -1,10 +1,11 @@ +import { extend, shortcut } from "@/core"; +import { IconButton } from "@/base"; + /** * 十字型的树节点 * @class BI.FirstTreeNodeCheckbox * @extends BI.IconButton */ -import { extend, shortcut } from "@/core"; -import { IconButton } from "@/base"; @shortcut() export class FirstTreeNodeCheckbox extends IconButton { @@ -12,7 +13,10 @@ export class FirstTreeNodeCheckbox extends IconButton { _defaultConfig() { return extend(super._defaultConfig(...arguments), { - extraCls: BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? "tree-solid-collapse-icon-type2" : "tree-collapse-icon-type2", + extraCls: + BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" + ? "tree-solid-collapse-icon-type2" + : "tree-collapse-icon-type2", iconWidth: 24, iconHeight: 24, }); diff --git a/src/case/checkbox/check.last.treenode.js b/src/case/checkbox/check.last.treenode.js index 93ebc9c66..14875f550 100644 --- a/src/case/checkbox/check.last.treenode.js +++ b/src/case/checkbox/check.last.treenode.js @@ -1,10 +1,11 @@ +import { extend, shortcut } from "@/core"; +import { IconButton } from "@/base"; + /** * 十字型的树节点 * @class BI.LastTreeNodeCheckbox * @extends BI.IconButton */ -import { extend, shortcut } from "@/core"; -import { IconButton } from "@/base"; @shortcut() export class LastTreeNodeCheckbox extends IconButton { @@ -12,7 +13,10 @@ export class LastTreeNodeCheckbox extends IconButton { _defaultConfig() { return extend(super._defaultConfig(...arguments), { - extraCls: BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? "tree-solid-collapse-icon-type4" : "tree-collapse-icon-type4", + extraCls: + BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" + ? "tree-solid-collapse-icon-type4" + : "tree-collapse-icon-type4", iconWidth: 24, iconHeight: 24, }); diff --git a/src/case/checkbox/check.mid.treenode.js b/src/case/checkbox/check.mid.treenode.js index a9d44de0e..e670d87e0 100644 --- a/src/case/checkbox/check.mid.treenode.js +++ b/src/case/checkbox/check.mid.treenode.js @@ -1,10 +1,11 @@ +import { extend, shortcut } from "@/core"; +import { IconButton } from "@/base"; + /** * 十字型的树节点 * @class BI.MidTreeNodeCheckbox * @extends BI.IconButton */ -import { extend, shortcut } from "@/core"; -import { IconButton } from "@/base"; @shortcut() export class MidTreeNodeCheckbox extends IconButton { @@ -12,7 +13,10 @@ export class MidTreeNodeCheckbox extends IconButton { _defaultConfig() { return extend(super._defaultConfig(...arguments), { - extraCls: BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? "tree-solid-collapse-icon-type3" : "tree-collapse-icon-type3", + extraCls: + BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" + ? "tree-solid-collapse-icon-type3" + : "tree-collapse-icon-type3", iconWidth: 24, iconHeight: 24, }); diff --git a/src/case/checkbox/check.treenode.js b/src/case/checkbox/check.treenode.js index fa1b54404..6dec8d452 100644 --- a/src/case/checkbox/check.treenode.js +++ b/src/case/checkbox/check.treenode.js @@ -1,18 +1,22 @@ +import { extend, shortcut } from "@/core"; +import { IconButton } from "@/base"; + /** * 十字型的树节点 * @class BI.TreeNodeCheckbox * @extends BI.IconButton */ -import { extend, shortcut } from "@/core"; -import { IconButton } from "@/base"; @shortcut() export class TreeNodeCheckbox extends IconButton { static xtype = "bi.tree_node_checkbox"; - + _defaultConfig() { return extend(super._defaultConfig(...arguments), { - extraCls: BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? "tree-solid-collapse-icon-type1" : "tree-collapse-icon-type1", + extraCls: + BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" + ? "tree-solid-collapse-icon-type1" + : "tree-collapse-icon-type1", iconWidth: 24, iconHeight: 24, }); diff --git a/src/case/colorchooser/colorchooser.custom.js b/src/case/colorchooser/colorchooser.custom.js index dd8bf8350..3b260d339 100644 --- a/src/case/colorchooser/colorchooser.custom.js +++ b/src/case/colorchooser/colorchooser.custom.js @@ -1,6 +1,7 @@ -import { shortcut, Widget, extend, createWidget } from "@/core"; -import { ColorPickerEditor } from "./colorpicker"; +import { SimpleHexColorPickerEditor, ColorPickerEditor } from "./colorpicker"; import { Farbtastic } from "./farbtastic/farbtastic"; +import { VTapeLayout, AbsoluteLayout, shortcut, Widget, extend, createWidget } from "@/core"; + /** * 自定义选色 @@ -27,14 +28,14 @@ export class CustomColorChooser extends Widget { super._init(...arguments); const o = this.options; this.editor = createWidget(o.editor, { - type: "bi.simple_hex_color_picker_editor", + type: SimpleHexColorPickerEditor.xtype, value: o.value, }); this.editor.on(ColorPickerEditor.EVENT_CHANGE, () => { this.setValue(this.editor.getValue()); }); this.farbtastic = createWidget({ - type: "bi.farbtastic", + type: Farbtastic.xtype, value: o.value, }); this.farbtastic.on(Farbtastic.EVENT_CHANGE, () => { @@ -42,27 +43,34 @@ export class CustomColorChooser extends Widget { }); createWidget({ - type: "bi.vtape", + type: VTapeLayout.xtype, element: this, - items: [{ - type: "bi.absolute", - items: [{ - el: this.editor, - left: 10, - top: 0, - right: 10, - }], - height: 50, - }, { - type: "bi.absolute", - items: [{ - el: this.farbtastic, - left: 46, - right: 46, - top: 7, - }], - height: 215, - }], + items: [ + { + type: AbsoluteLayout.xtype, + items: [ + { + el: this.editor, + left: 10, + top: 0, + right: 10, + }, + ], + height: 50, + }, + { + type: AbsoluteLayout.xtype, + items: [ + { + el: this.farbtastic, + left: 46, + right: 46, + top: 7, + }, + ], + height: 215, + }, + ], }); } @@ -75,4 +83,3 @@ export class CustomColorChooser extends Widget { return this.editor.getValue(); } } - diff --git a/src/case/colorchooser/colorchooser.js b/src/case/colorchooser/colorchooser.js index 20b410a68..7b075eae0 100644 --- a/src/case/colorchooser/colorchooser.js +++ b/src/case/colorchooser/colorchooser.js @@ -1,5 +1,6 @@ -import { shortcut, Widget, extend, createWidget, toPix, isNotEmptyString } from "@/core"; import { Combo } from "@/base"; +import { HexColorChooserPopup } from "./colorchooser.popup.hex"; +import { shortcut, Widget, extend, createWidget, toPix, isNotEmptyString } from "@/core"; import { ColorChooserPopup } from "./colorchooser.popup"; /** @@ -36,47 +37,56 @@ export class ColorChooser extends Widget { super._init(...arguments); o.value = (o.value || "").toLowerCase(); this.combo = createWidget({ - type: "bi.combo", + type: Combo.xtype, element: this, container: o.container, adjustLength: 1, destroyWhenHide: o.destroyWhenHide, isNeedAdjustWidth: false, isNeedAdjustHeight: false, - el: extend({ - type: o.width <= 24 ? "bi.color_chooser_trigger" : "bi.long_color_chooser_trigger", - simple: o.simple, - ref: _ref => { - this.trigger = _ref; + el: extend( + { + type: o.width <= 24 ? "bi.color_chooser_trigger" : "bi.long_color_chooser_trigger", + simple: o.simple, + ref: _ref => { + this.trigger = _ref; + }, + value: o.value, + width: o.el.type ? o.width : toPix(o.width, 2), + height: o.el.type ? o.height : toPix(o.height, 2), }, - value: o.value, - width: o.el.type ? o.width : toPix(o.width, 2), - height: o.el.type ? o.height : toPix(o.height, 2), - }, o.el), + o.el + ), popup: () => { return { - el: extend({ - type: "bi.hex_color_chooser_popup", - recommendColorsGetter: o.recommendColorsGetter, - ref: _ref => { - this.colorPicker = _ref; - }, - listeners: [{ - eventName: ColorChooserPopup.EVENT_VALUE_CHANGE, - action: () => { - fn(); - if (!this._isRGBColor(this.colorPicker.getValue())) { - this.combo.hideView(); - } - }, - }, { - eventName: ColorChooserPopup.EVENT_CHANGE, - action: () => { - fn(); - this.combo.hideView(); + el: extend( + { + type: HexColorChooserPopup.xtype, + recommendColorsGetter: o.recommendColorsGetter, + ref: _ref => { + this.colorPicker = _ref; }, - }], - }, o.popup), + listeners: [ + { + eventName: ColorChooserPopup.EVENT_VALUE_CHANGE, + action: () => { + fn(); + if (!this._isRGBColor(this.colorPicker.getValue())) { + this.combo.hideView(); + } + }, + }, + { + eventName: ColorChooserPopup.EVENT_CHANGE, + action: () => { + fn(); + this.combo.hideView(); + }, + } + ], + }, + o.popup + ), value: o.value, width: 300, }; diff --git a/src/case/colorchooser/colorchooser.popup.hex.js b/src/case/colorchooser/colorchooser.popup.hex.js index ce0506e95..7d0f5b02a 100644 --- a/src/case/colorchooser/colorchooser.popup.hex.js +++ b/src/case/colorchooser/colorchooser.popup.hex.js @@ -1,7 +1,26 @@ -import { shortcut, Widget, isNotNull, extend, isNotEmptyString, array2String, map, count, string2Array, filter, isArray, Cache, Queue } from "@/core"; -import { Combo } from "@/base"; +import { + VerticalLayout, + Layout, + AbsoluteLayout, + shortcut, + Widget, + isNotNull, + extend, + isNotEmptyString, + array2String, + map, + count, + string2Array, + filter, + isArray, + Cache, + Queue +} from "@/core"; +import { Label, Combo, TextItem } from "@/base"; +import { PopupPanel } from "../layer"; +import { CustomColorChooser } from "./colorchooser.custom"; import { ColorChooserPopup } from "./colorchooser.popup"; -import { ColorPickerEditor, ColorPicker } from "./colorpicker"; +import { ColorPickerEditor, ColorPicker, HexColorPicker } from "./colorpicker"; /** * @author windy @@ -20,203 +39,244 @@ export class HexColorChooserPopup extends Widget { width: 300, recommendColorsGetter: BI.emptyFn, // 推荐色获取接口 simple: false, // 简单模式, popup中没有自动和透明 - } + }; render() { const o = this.options; const hasRecommendColors = isNotNull(o.recommendColorsGetter()); - - return [{ - type: "bi.vertical", - items: [{ - el: { - type: "bi.vertical", - hgap: 15, - items: [extend({ - type: o.simple ? "bi.simple_hex_color_picker_editor" : "bi.hex_color_picker_editor", - value: o.value, - height: o.simple ? 36 : 70, - listeners: [{ - eventName: ColorPickerEditor.EVENT_CHANGE, - action: (...args) => { - this.setValue(this.colorEditor.getValue()); - this._dealStoreColors(); - this.fireEvent(ColorChooserPopup.EVENT_VALUE_CHANGE, ...args); - }, - }], - ref: _ref => { - this.colorEditor = _ref; - }, - }, o.editor), { + + return [ + { + type: VerticalLayout.xtype, + items: [ + { el: { - type: "bi.hex_color_picker", - cls: "bi-border-bottom bi-border-right", - items: [this._digestStoreColors(this._getStoreColors())], - height: 22, - value: o.value, - listeners: [{ - eventName: ColorPicker.EVENT_CHANGE, - action: (...args) => { - this.setValue(this.storeColors.getValue()[0]); - this._dealStoreColors(); - this.fireEvent(ColorChooserPopup.EVENT_CHANGE, ...args); + type: VerticalLayout.xtype, + hgap: 15, + items: [ + extend( + { + type: o.simple + ? "bi.simple_hex_color_picker_editor" + : "bi.hex_color_picker_editor", + value: o.value, + height: o.simple ? 36 : 70, + listeners: [ + { + eventName: ColorPickerEditor.EVENT_CHANGE, + action: (...args) => { + this.setValue(this.colorEditor.getValue()); + this._dealStoreColors(); + this.fireEvent(ColorChooserPopup.EVENT_VALUE_CHANGE, ...args); + }, + } + ], + ref: _ref => { + this.colorEditor = _ref; + }, + }, + o.editor + ), + { + el: { + type: HexColorPicker.xtype, + cls: "bi-border-bottom bi-border-right", + items: [this._digestStoreColors(this._getStoreColors())], + height: 22, + value: o.value, + listeners: [ + { + eventName: ColorPicker.EVENT_CHANGE, + action: (...args) => { + this.setValue(this.storeColors.getValue()[0]); + this._dealStoreColors(); + this.fireEvent(ColorChooserPopup.EVENT_CHANGE, ...args); + }, + } + ], + ref: _ref => { + this.storeColors = _ref; + }, + }, + tgap: 10, + height: 22, }, - }], - ref: _ref => { - this.storeColors = _ref; - }, - }, - tgap: 10, - height: 22, - }, { - el: hasRecommendColors ? { - type: "bi.vertical", - items: [{ - type: "bi.label", - text: BI.i18nText("BI-Basic_Recommend_Color"), - textAlign: "left", - height: 24, - }, { - type: "bi.hex_color_picker", - cls: "bi-border-bottom bi-border-right", - items: [this._digestStoreColors(o.recommendColorsGetter())], - height: 22, - value: o.value, - listeners: [{ - eventName: ColorPicker.EVENT_CHANGE, - action: (...args) => { - this.setValue(this.recommendColors.getValue()[0]); - this._dealStoreColors(); - this.fireEvent(ColorChooserPopup.EVENT_CHANGE, ...args); + { + el: hasRecommendColors + ? { + type: VerticalLayout.xtype, + items: [ + { + type: Label.xtype, + text: BI.i18nText("BI-Basic_Recommend_Color"), + textAlign: "left", + height: 24, + }, + { + type: HexColorPicker.xtype, + cls: "bi-border-bottom bi-border-right", + items: [this._digestStoreColors(o.recommendColorsGetter())], + height: 22, + value: o.value, + listeners: [ + { + eventName: ColorPicker.EVENT_CHANGE, + action: (...args) => { + this.setValue(this.recommendColors.getValue()[0]); + this._dealStoreColors(); + this.fireEvent( + ColorChooserPopup.EVENT_CHANGE, + ...args + ); + }, + } + ], + ref: _ref => { + this.recommendColors = _ref; + }, + } + ], + } + : { type: Layout.xtype }, + tgap: hasRecommendColors ? 10 : 0, + height: hasRecommendColors ? 47 : 0, + }, + { + el: { + type: Layout.xtype, + cls: "bi-border-top", }, - }], - ref: _ref => { - this.recommendColors = _ref; + vgap: 10, + height: 1, }, - }], - } : { type: "bi.layout" }, - tgap: hasRecommendColors ? 10 : 0, - height: hasRecommendColors ? 47 : 0, - }, { + { + type: AbsoluteLayout.xtype, + items: [ + { + el: { + type: HexColorPicker.xtype, + space: true, + value: o.value, + listeners: [ + { + eventName: ColorPicker.EVENT_CHANGE, + action: (...args) => { + this.setValue(this.colorPicker.getValue()[0]); + this._dealStoreColors(); + this.fireEvent(ColorChooserPopup.EVENT_CHANGE, ...args); + }, + } + ], + ref: _ref => { + this.colorPicker = _ref; + }, + }, + top: 0, + left: 0, + right: 0, + bottom: 1, + } + ], + height: 80, + } + ], + }, + }, + { el: { - type: "bi.layout", + type: Combo.xtype, cls: "bi-border-top", - }, - vgap: 10, - height: 1, - }, { - type: "bi.absolute", - items: [{ + container: null, + direction: "right,top", + isNeedAdjustHeight: false, el: { - type: "bi.hex_color_picker", - space: true, - value: o.value, - listeners: [{ - eventName: ColorPicker.EVENT_CHANGE, - action: (...args) => { - this.setValue(this.colorPicker.getValue()[0]); - this._dealStoreColors(); - this.fireEvent(ColorChooserPopup.EVENT_CHANGE, ...args); + type: TextItem.xtype, + cls: "color-chooser-popup-more bi-list-item", + textAlign: "center", + height: 24, + textLgap: 10, + text: `${BI.i18nText("BI-Basic_More")}...`, + }, + popup: { + type: PopupPanel.xtype, + buttons: [BI.i18nText("BI-Basic_Cancel"), BI.i18nText("BI-Basic_Save")], + title: BI.i18nText("BI-Custom_Color"), + el: { + type: CustomColorChooser.xtype, + value: o.value, + editor: o.editor, + ref: _ref => { + this.customColorChooser = _ref; }, - }], - ref: _ref => { - this.colorPicker = _ref; }, + stopPropagation: false, + bgap: -1, + rgap: 1, + lgap: 1, + minWidth: 227, + listeners: [ + { + eventName: BI.PopupPanel.EVENT_CLICK_TOOLBAR_BUTTON, + action: (index, ...args) => { + switch (index) { + case 0: + this.more.hideView(); + break; + case 1: { + const color = this.customColorChooser.getValue(); + // farbtastic选择器没有透明和自动选项,点击保存不应该设置透明 + if (isNotEmptyString(color)) { + this.setValue(color); + this._dealStoreColors(); + } + this.more.hideView(); + this.fireEvent(ColorChooserPopup.EVENT_CHANGE, index, ...args); + break; + } + default: + break; + } + }, + } + ], }, - top: 0, - left: 0, - right: 0, - bottom: 1, - }], - height: 80, - }], - }, - }, { - el: { - type: "bi.combo", - cls: "bi-border-top", - container: null, - direction: "right,top", - isNeedAdjustHeight: false, - el: { - type: "bi.text_item", - cls: "color-chooser-popup-more bi-list-item", - textAlign: "center", - height: 24, - textLgap: 10, - text: `${BI.i18nText("BI-Basic_More")}...`, - }, - popup: { - type: "bi.popup_panel", - buttons: [BI.i18nText("BI-Basic_Cancel"), BI.i18nText("BI-Basic_Save")], - title: BI.i18nText("BI-Custom_Color"), - el: { - type: "bi.custom_color_chooser", - value: o.value, - editor: o.editor, + listeners: [ + { + eventName: Combo.EVENT_AFTER_POPUPVIEW, + action: () => { + this.customColorChooser.setValue(this.getValue()); + }, + } + ], ref: _ref => { - this.customColorChooser = _ref; + this.more = _ref; }, }, - stopPropagation: false, - bgap: -1, - rgap: 1, - lgap: 1, - minWidth: 227, - listeners: [{ - eventName: BI.PopupPanel.EVENT_CLICK_TOOLBAR_BUTTON, - action: (index, ...args) => { - switch (index) { - case 0: - this.more.hideView(); - break; - case 1: { - const color = this.customColorChooser.getValue(); - // farbtastic选择器没有透明和自动选项,点击保存不应该设置透明 - if (isNotEmptyString(color)) { - this.setValue(color); - this._dealStoreColors(); - } - this.more.hideView(); - this.fireEvent(ColorChooserPopup.EVENT_CHANGE, index, ...args); - break; - } - default: - break; - } + tgap: 10, + height: 24, + } + ], + }, + { + type: AbsoluteLayout.xtype, + items: [ + { + el: { + type: Layout.xtype, + cls: "disable-mask", + invisible: !o.disabled, + ref: () => { + this.mask = this; }, - }], - }, - listeners: [{ - eventName: Combo.EVENT_AFTER_POPUPVIEW, - action: () => { - this.customColorChooser.setValue(this.getValue()); }, - }], - ref: _ref => { - this.more = _ref; - }, - }, - tgap: 10, - height: 24, - }], - }, { - type: "bi.absolute", - items: [{ - el: { - type: "bi.layout", - cls: "disable-mask", - invisible: !o.disabled, - ref: () => { - this.mask = this; - }, - }, - left: 0, - right: 0, - top: 0, - bottom: 0, - }], - }]; + left: 0, + right: 0, + top: 0, + bottom: 0, + } + ], + } + ]; } // 这里就实现的不好了,setValue里面有个editor,editor的setValue会检测错误然后出bubble提示 @@ -256,15 +316,15 @@ export class HexColorChooserPopup extends Widget { disabled: true, }); }); - + return items; } _getStoreColors() { const o = this.options; const colorsArray = string2Array(Cache.getItem("colors") || ""); - - return filter(colorsArray, (idx, color) => o.simple ? this._isRGBColor(color) : true); + + return filter(colorsArray, (idx, color) => (o.simple ? this._isRGBColor(color) : true)); } _isRGBColor(color) { diff --git a/src/case/colorchooser/colorchooser.popup.hex.simple.js b/src/case/colorchooser/colorchooser.popup.hex.simple.js index 608017de2..7ccaa9558 100644 --- a/src/case/colorchooser/colorchooser.popup.hex.simple.js +++ b/src/case/colorchooser/colorchooser.popup.hex.simple.js @@ -1,3 +1,4 @@ +import { HexColorChooserPopup } from "./colorchooser.popup.hex"; import { shortcut, Widget } from "@/core"; import { ColorChooserPopup } from "./colorchooser.popup"; import { SimpleColorChooserPopup } from "./colorchooser.popup.simple"; @@ -16,27 +17,30 @@ export class SimpleHexColorChooserPopup extends Widget { props = { baseCls: "bi-color-chooser-popup", - } + }; render() { const o = this.options; return { - type: "bi.hex_color_chooser_popup", + type: HexColorChooserPopup.xtype, recommendColorsGetter: o.recommendColorsGetter, value: o.value, simple: true, // 是否有自动 - listeners: [{ - eventName: ColorChooserPopup.EVENT_CHANGE, - action: (...args) => { - this.fireEvent(SimpleColorChooserPopup.EVENT_CHANGE, ...args); - }, - }, { - eventName: ColorChooserPopup.EVENT_VALUE_CHANGE, - action: (...args) => { - this.fireEvent(SimpleColorChooserPopup.EVENT_VALUE_CHANGE, ...args); + listeners: [ + { + eventName: ColorChooserPopup.EVENT_CHANGE, + action: (...args) => { + this.fireEvent(SimpleColorChooserPopup.EVENT_CHANGE, ...args); + }, }, - }], + { + eventName: ColorChooserPopup.EVENT_VALUE_CHANGE, + action: (...args) => { + this.fireEvent(SimpleColorChooserPopup.EVENT_VALUE_CHANGE, ...args); + }, + } + ], ref: _ref => { this.popup = _ref; }, diff --git a/src/case/colorchooser/colorchooser.popup.js b/src/case/colorchooser/colorchooser.popup.js index 7580e7a52..30ffe11fc 100644 --- a/src/case/colorchooser/colorchooser.popup.js +++ b/src/case/colorchooser/colorchooser.popup.js @@ -1,5 +1,24 @@ -import { shortcut, Widget, createWidget, Cache, string2Array, isNotNull, Queue, array2String, map, count, filter, isNotEmptyString, isArray } from "@/core"; -import { Combo } from "@/base"; +import { CustomColorChooser } from "./colorchooser.custom"; +import { PopupPanel } from "../layer"; +import { Combo, TextItem } from "@/base"; +import { + AbsoluteLayout, + VTapeLayout, + Layout, + shortcut, + Widget, + createWidget, + Cache, + string2Array, + isNotNull, + Queue, + array2String, + map, + count, + filter, + isNotEmptyString, + isArray +} from "@/core"; import { ColorPickerEditor, ColorPicker } from "./colorpicker"; /** @@ -21,9 +40,9 @@ export class ColorChooserPopup extends Widget { width: 230, height: 145, simple: false, // 简单模式, popup中没有自动和透明 - } + }; - render () { + render() { const o = this.options; this.colorEditor = createWidget(o.editor, { type: o.simple ? "bi.simple_color_picker_editor" : "bi.color_picker_editor", @@ -39,7 +58,7 @@ export class ColorChooserPopup extends Widget { }); this.storeColors = createWidget({ - type: "bi.color_picker", + type: ColorPicker.xtype, cls: "bi-border-bottom bi-border-right", items: [this._digestStoreColors(this._getStoreColors())], width: 210, @@ -53,7 +72,7 @@ export class ColorChooserPopup extends Widget { }); this.colorPicker = createWidget({ - type: "bi.color_picker", + type: ColorPicker.xtype, width: 210, height: 50, value: o.value, @@ -66,12 +85,12 @@ export class ColorChooserPopup extends Widget { }); this.customColorChooser = createWidget({ - type: "bi.custom_color_chooser", + type: CustomColorChooser.xtype, editor: o.editor, }); const panel = createWidget({ - type: "bi.popup_panel", + type: PopupPanel.xtype, buttons: [BI.i18nText("BI-Basic_Cancel"), BI.i18nText("BI-Basic_Save")], title: BI.i18nText("BI-Custom_Color"), el: this.customColorChooser, @@ -83,13 +102,13 @@ export class ColorChooserPopup extends Widget { }); this.more = createWidget({ - type: "bi.combo", + type: Combo.xtype, cls: "bi-border-top", container: null, direction: "right,top", isNeedAdjustHeight: false, el: { - type: "bi.text_item", + type: TextItem.xtype, cls: "color-chooser-popup-more bi-list-item", textAlign: "center", height: 24, @@ -104,88 +123,100 @@ export class ColorChooserPopup extends Widget { }); panel.on(BI.PopupPanel.EVENT_CLICK_TOOLBAR_BUTTON, (index, ...args) => { switch (index) { - case 0: - this.more.hideView(); - break; - case 1: - this.setValue(this.customColorChooser.getValue()); - this._dealStoreColors(); - this.more.hideView(); - this.fireEvent(ColorChooserPopup.EVENT_CHANGE, index, ...args); - break; - default: - break; + case 0: + this.more.hideView(); + break; + case 1: + this.setValue(this.customColorChooser.getValue()); + this._dealStoreColors(); + this.more.hideView(); + this.fireEvent(ColorChooserPopup.EVENT_CHANGE, index, ...args); + break; + default: + break; } }); return { - type: "bi.absolute", - items: [{ - el: { - type: "bi.vtape", - items: [this.colorEditor, { - el: { - type: "bi.absolute", - items: [{ - el: this.storeColors, - left: 10, - right: 10, - top: 5, - }], - }, - height: 29, - }, { - el: { - type: "bi.absolute", - items: [{ - el: this.colorPicker, - left: 10, - right: 10, - top: 5, - bottom: 5, - }], - }, - height: 60, - }, { - el: this.more, - height: 24, - }], + type: AbsoluteLayout.xtype, + items: [ + { + el: { + type: VTapeLayout.xtype, + items: [ + this.colorEditor, + { + el: { + type: AbsoluteLayout.xtype, + items: [ + { + el: this.storeColors, + left: 10, + right: 10, + top: 5, + }, + ], + }, + height: 29, + }, + { + el: { + type: AbsoluteLayout.xtype, + items: [ + { + el: this.colorPicker, + left: 10, + right: 10, + top: 5, + bottom: 5, + }, + ], + }, + height: 60, + }, + { + el: this.more, + height: 24, + }, + ], + }, + left: 0, + right: 0, + top: 0, + bottom: 0, }, - left: 0, - right: 0, - top: 0, - bottom: 0, - }, { - el: { - type: "bi.layout", - cls: "disable-mask", - invisible: !o.disabled, - ref: () => { - this.mask = this; + { + el: { + type: Layout.xtype, + cls: "disable-mask", + invisible: !o.disabled, + ref: () => { + this.mask = this; + }, }, + left: 0, + right: 0, + top: 0, + bottom: 0, }, - left: 0, - right: 0, - top: 0, - bottom: 0, - }], + ], }; } // 这里就实现的不好了,setValue里面有个editor,editor的setValue会检测错误然后出bubble提示 - mounted () { + mounted() { const o = this.options; if (isNotNull(o.value)) { this.setValue(o.value); } } - _setEnable (enable) { + _setEnable(enable) { super._setEnable(...arguments); this.mask.setVisible(!enable); } - _dealStoreColors () { + _dealStoreColors() { const color = this.getValue(); const colors = this._getStoreColors(); const que = new Queue(8); @@ -197,34 +228,34 @@ export class ColorChooserPopup extends Widget { this.setStoreColors(array); } - _digestStoreColors (colors) { + _digestStoreColors(colors) { const items = map(colors, (i, color) => { return { value: color, }; }); - count(colors.length, 8, i => { + count(colors.length, 8, (i) => { items.push({ value: "", disabled: true, }); }); - + return items; } _getStoreColors() { const o = this.options; const colorsArray = string2Array(Cache.getItem("colors") || ""); - - return filter(colorsArray, (idx, color) => o.simple ? this._isRGBColor(color) : true); + + return filter(colorsArray, (idx, color) => (o.simple ? this._isRGBColor(color) : true)); } - _isRGBColor (color) { + _isRGBColor(color) { return isNotEmptyString(color) && color !== "transparent"; } - setStoreColors (colors) { + setStoreColors(colors) { if (isArray(colors)) { this.storeColors.populate([this._digestStoreColors(colors)]); // BI-66973 选中颜色的同时选中历史 @@ -232,13 +263,13 @@ export class ColorChooserPopup extends Widget { } } - setValue (color) { + setValue(color) { this.colorEditor.setValue(color); this.colorPicker.setValue(color); this.storeColors.setValue(color); } - getValue () { + getValue() { return this.colorEditor.getValue(); } } diff --git a/src/case/colorchooser/colorchooser.simple.js b/src/case/colorchooser/colorchooser.simple.js index 6cf9d9ded..f6eaf762d 100644 --- a/src/case/colorchooser/colorchooser.simple.js +++ b/src/case/colorchooser/colorchooser.simple.js @@ -1,3 +1,4 @@ +import { SimpleHexColorChooserPopup } from "./colorchooser.popup.hex.simple"; import { shortcut, Widget, extend, createWidget } from "@/core"; import { ColorChooser } from "./colorchooser"; @@ -27,7 +28,7 @@ export class SimpleColorChooser extends Widget { const o = this.options; this.combo = createWidget({ - type: "bi.color_chooser", + type: ColorChooser.xtype, simple: o.simple, element: this, container: o.container, @@ -36,7 +37,7 @@ export class SimpleColorChooser extends Widget { height: o.height, destroyWhenHide: o.destroyWhenHide, popup: { - type: "bi.simple_hex_color_chooser_popup", + type: SimpleHexColorChooserPopup.xtype, recommendColorsGetter: o.recommendColorsGetter, }, }); diff --git a/src/case/colorchooser/colorchooser.trigger.js b/src/case/colorchooser/colorchooser.trigger.js index 1187a8460..8412362d0 100644 --- a/src/case/colorchooser/colorchooser.trigger.js +++ b/src/case/colorchooser/colorchooser.trigger.js @@ -1,5 +1,5 @@ -import { shortcut, extend, createWidget, isNotNull } from "@/core"; -import { Trigger } from "@/base"; +import { Layout, AbsoluteLayout, shortcut, extend, createWidget, isNotNull } from "@/core"; +import { IconButton, Trigger } from "@/base"; /** * 选色控件 @@ -14,24 +14,26 @@ export class ColorChooserTrigger extends Trigger { static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig (config) { + _defaultConfig(config) { const conf = super._defaultConfig(...arguments); - + return extend(conf, { - baseCls: `${conf.baseCls || ""} bi-color-chooser-trigger bi-focus-shadow ${config.simple ? "bi-border-bottom" : "bi-border bi-border-radius"}`, + baseCls: `${conf.baseCls || ""} bi-color-chooser-trigger bi-focus-shadow ${ + config.simple ? "bi-border-bottom" : "bi-border bi-border-radius" + }`, height: 22, }); } - _init () { + _init() { super._init(...arguments); this.colorContainer = createWidget({ - type: "bi.layout", - cls: "color-chooser-trigger-content" + (BI.isIE9Below && BI.isIE9Below() ? " hack" : "") + type: Layout.xtype, + cls: `color-chooser-trigger-content${BI.isIE9Below && BI.isIE9Below() ? " hack" : ""}`, }); const down = createWidget({ - type: "bi.icon_button", + type: IconButton.xtype, disableSelected: true, cls: "icon-combo-down-icon trigger-triangle-font icon-size-12", width: 12, @@ -39,33 +41,45 @@ export class ColorChooserTrigger extends Trigger { }); createWidget({ - type: "bi.absolute", + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.colorContainer, - left: 2, - right: 2, - top: 2, - bottom: 2, - }, { - el: down, - right: -1, - bottom: 1, - }], + items: [ + { + el: this.colorContainer, + left: 2, + right: 2, + top: 2, + bottom: 2, + }, + { + el: down, + right: -1, + bottom: 1, + } + ], }); if (isNotNull(this.options.value)) { this.setValue(this.options.value); } } - setValue (color) { + setValue(color) { super.setValue(...arguments); if (color === "") { - this.colorContainer.element.css("background-color", "").removeClass("trans-color-background").addClass("auto-color-background"); + this.colorContainer.element + .css("background-color", "") + .removeClass("trans-color-background") + .addClass("auto-color-background"); } else if (color === "transparent") { - this.colorContainer.element.css("background-color", "").removeClass("auto-color-background").addClass("trans-color-background"); + this.colorContainer.element + .css("background-color", "") + .removeClass("auto-color-background") + .addClass("trans-color-background"); } else { - this.colorContainer.element.css({ "background-color": color }).removeClass("auto-color-background").removeClass("trans-color-background"); + this.colorContainer.element + .css({ "background-color": color }) + .removeClass("auto-color-background") + .removeClass("trans-color-background"); } } } diff --git a/src/case/colorchooser/colorchooser.trigger.long.js b/src/case/colorchooser/colorchooser.trigger.long.js index 8210e111e..5f80f9979 100644 --- a/src/case/colorchooser/colorchooser.trigger.long.js +++ b/src/case/colorchooser/colorchooser.trigger.long.js @@ -1,5 +1,6 @@ -import { shortcut, extend, createWidget } from "@/core"; -import { Trigger } from "@/base"; +import { HTapeLayout, AbsoluteLayout, shortcut, extend, createWidget } from "@/core"; +import { IconChangeButton } from "../button"; +import { Label, IconButton, Trigger } from "@/base"; /** * 选色控件 @@ -14,46 +15,51 @@ export class LongColorChooserTrigger extends Trigger { static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig (config) { + _defaultConfig(config) { const conf = super._defaultConfig(...arguments); - + return extend(conf, { - baseCls: `${conf.baseCls || ""} bi-color-chooser-trigger bi-focus-shadow ${config.simple ? "bi-border-bottom" : "bi-border bi-border-radius"}`, + baseCls: `${conf.baseCls || ""} bi-color-chooser-trigger bi-focus-shadow ${ + config.simple ? "bi-border-bottom" : "bi-border bi-border-radius" + }`, height: 24, }); } - _init () { + _init() { super._init(...arguments); this.colorContainer = createWidget({ - type: "bi.htape", + type: HTapeLayout.xtype, cls: "color-chooser-trigger-content", - items: [{ - type: "bi.icon_change_button", - ref: _ref => { - this.changeIcon = _ref; - }, - disableSelected: true, - iconCls: "auto-color-icon", - width: 24, - iconWidth: 16, - iconHeight: 16, - }, { - el: { - type: "bi.label", + items: [ + { + type: IconChangeButton.xtype, ref: _ref => { - this.label = _ref; + this.changeIcon = _ref; }, - textAlign: "left", - hgap: 5, - height: 18, - text: BI.i18nText("BI-Basic_Auto"), + disableSelected: true, + iconCls: "auto-color-icon", + width: 24, + iconWidth: 16, + iconHeight: 16, }, - }], + { + el: { + type: Label.xtype, + ref: _ref => { + this.label = _ref; + }, + textAlign: "left", + hgap: 5, + height: 18, + text: BI.i18nText("BI-Basic_Auto"), + }, + } + ], }); const down = createWidget({ - type: "bi.icon_button", + type: IconButton.xtype, disableSelected: true, cls: "icon-combo-down-icon trigger-triangle-font icon-size-12", width: 12, @@ -61,26 +67,29 @@ export class LongColorChooserTrigger extends Trigger { }); createWidget({ - type: "bi.absolute", + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.colorContainer, - left: 2, - right: 2, - top: 2, - bottom: 2, - }, { - el: down, - right: 3, - bottom: 3, - }], + items: [ + { + el: this.colorContainer, + left: 2, + right: 2, + top: 2, + bottom: 2, + }, + { + el: down, + right: 3, + bottom: 3, + } + ], }); if (this.options.value) { this.setValue(this.options.value); } } - setValue (color) { + setValue(color) { super.setValue(...arguments); if (color === "") { this.colorContainer.element.css("background-color", ""); diff --git a/src/case/colorchooser/colorpicker/button/button.colorpicker.js b/src/case/colorchooser/colorpicker/button/button.colorpicker.js index e690eb1f3..8b8702bbc 100644 --- a/src/case/colorchooser/colorpicker/button/button.colorpicker.js +++ b/src/case/colorchooser/colorpicker/button/button.colorpicker.js @@ -16,7 +16,7 @@ export class ColorPickerButton extends BasicButton { _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-color-picker-button bi-background bi-border-top bi-border-left`, }); @@ -34,21 +34,25 @@ export class ColorPickerButton extends BasicButton { this.element.css("background-color", o.value); } const name = this.getName(); - this.element.hover(() => { - this._createMask(); - if (this.isEnabled()) { - Maskers.show(name); - } - }, () => { - if (!this.isSelected()) { - Maskers.hide(name); + this.element.hover( + () => { + this._createMask(); + if (this.isEnabled()) { + Maskers.show(name); + } + }, + () => { + if (!this.isSelected()) { + Maskers.hide(name); + } } - }); + ); } } _createMask() { - const o = this.options, name = this.getName(); + const o = this.options, + name = this.getName(); if (this.isEnabled() && !Maskers.has(name)) { const w = Maskers.make(name, this, { offset: { diff --git a/src/case/colorchooser/colorpicker/button/button.colorshow.js b/src/case/colorchooser/colorpicker/button/button.colorshow.js index 104dfabf2..dd82301c0 100644 --- a/src/case/colorchooser/colorpicker/button/button.colorshow.js +++ b/src/case/colorchooser/colorpicker/button/button.colorshow.js @@ -1,5 +1,5 @@ -import { shortcut } from "@/core"; -import { BasicButton } from "@/base"; +import { HTapeLayout, shortcut } from "@/core"; +import { IconLabel, Label, BasicButton } from "@/base"; /** * @author windy @@ -14,17 +14,17 @@ export class ColorChooserShowButton extends BasicButton { props = { baseCls: "bi-color-chooser-show-button bi-border bi-list-item-effect bi-border-radius", - } + }; render() { const o = this.options; - + return { - type: "bi.htape", + type: HTapeLayout.xtype, items: [ { el: { - type: "bi.icon_label", + type: IconLabel.xtype, ref: _ref => { this.icon = _ref; }, @@ -33,8 +33,9 @@ export class ColorChooserShowButton extends BasicButton { }, hgap: 20, width: 16, - }, { - type: "bi.label", + }, + { + type: Label.xtype, textAlign: "left", text: o.text, } diff --git a/src/case/colorchooser/colorpicker/button/index.js b/src/case/colorchooser/colorpicker/button/index.js index 59b5c9378..68da81f74 100644 --- a/src/case/colorchooser/colorpicker/button/index.js +++ b/src/case/colorchooser/colorpicker/button/index.js @@ -1,2 +1,2 @@ -export { ColorPickerButton } from "./button.colorpicker"; -export { ColorChooserShowButton } from "./button.colorshow"; \ No newline at end of file +export { ColorPickerButton } from "./button.colorpicker"; +export { ColorChooserShowButton } from "./button.colorshow"; diff --git a/src/case/colorchooser/colorpicker/colorpicker.hex.js b/src/case/colorchooser/colorpicker/colorpicker.hex.js index 5a1b4162b..ef57023df 100644 --- a/src/case/colorchooser/colorpicker/colorpicker.hex.js +++ b/src/case/colorchooser/colorpicker/colorpicker.hex.js @@ -1,5 +1,6 @@ -import { shortcut, Widget, extend, each } from "@/core"; import { ButtonGroup } from "@/base"; +import { GridLayout, Layout, shortcut, Widget, extend, each } from "@/core"; +import { ColorPickerButton } from "./button"; /** * @author windy @@ -15,7 +16,7 @@ export class HexColorPicker extends Widget { props = { baseCls: "bi-hex-color-picker", items: null, - } + }; _items = [ [ @@ -163,17 +164,17 @@ export class HexColorPicker extends Widget { value: "#B30072", } ] - ] + ]; render() { const o = this.options; return { - type: "bi.button_group", + type: ButtonGroup.xtype, items: this._digest(o.items || this._items), layouts: [ { - type: "bi.grid", + type: GridLayout.xtype, } ], value: o.value, @@ -197,13 +198,18 @@ export class HexColorPicker extends Widget { each(items, (idx, row) => { const bRow = []; each(row, (idx, item) => { - bRow.push(extend({ - type: "bi.color_picker_button", - once: false, - cls: o.space ? "bi-border-right" : "", - }, item)); + bRow.push( + extend( + { + type: ColorPickerButton.xtype, + once: false, + cls: o.space ? "bi-border-right" : "", + }, + item + ) + ); if (o.space && idx < row.length - 1) { - bRow.push({ type: "bi.layout" }); + bRow.push({ type: Layout.xtype }); } }); blocks.push(bRow); diff --git a/src/case/colorchooser/colorpicker/colorpicker.js b/src/case/colorchooser/colorpicker/colorpicker.js index fa4bd5c9d..f645ec6f6 100644 --- a/src/case/colorchooser/colorpicker/colorpicker.js +++ b/src/case/colorchooser/colorpicker/colorpicker.js @@ -1,5 +1,6 @@ -import { shortcut, Widget, extend, createItems, createWidget } from "@/core"; import { ButtonGroup } from "@/base"; +import { ColorPickerButton } from "./button"; +import { GridLayout, shortcut, Widget, extend, createItems, createWidget } from "@/core"; /** * 简单选色控件 @@ -22,153 +23,223 @@ export class ColorPicker extends Widget { } _items = [ - [{ - value: "#ffffff", - }, { - value: "#f2f2f2", - }, { - value: "#e5e5e5", - }, { - value: "#d9d9d9", - }, { - value: "#cccccc", - }, { - value: "#bfbfbf", - }, { - value: "#b2b2b2", - }, { - value: "#a6a6a6", - }, { - value: "#999999", - }, { - value: "#8c8c8c", - }, { - value: "#808080", - }, { - value: "#737373", - }, { - value: "#666666", - }, { - value: "#4d4d4d", - }, { - value: "#333333", - }, { - value: "#000000", - }], - [{ - value: "#d8b5a6", - }, { - value: "#ff9e9a", - }, { - value: "#ffc17d", - }, { - value: "#f5e56b", - }, { - value: "#d8e698", - }, { - value: "#e0ebaf", - }, { - value: "#c3d825", - }, { - value: "#bbe2e7", - }, { - value: "#85d3cd", - }, { - value: "#bde1e6", - }, { - value: "#a0d8ef", - }, { - value: "#89c3eb", - }, { - value: "#bbc8e6", - }, { - value: "#bbbcde", - }, { - value: "#d6b4cc", - }, { - value: "#fbc0d3", - }], - [{ - value: "#bb9581", - }, { - value: "#f37d79", - }, { - value: "#fba74f", - }, { - value: "#ffdb4f", - }, { - value: "#c7dc68", - }, { - value: "#b0ca71", - }, { - value: "#99ab4e", - }, { - value: "#84b9cb", - }, { - value: "#00a3af", - }, { - value: "#2ca9e1", - }, { - value: "#0095d9", - }, { - value: "#4c6cb3", - }, { - value: "#8491c3", - }, { - value: "#a59aca", - }, { - value: "#cc7eb1", - }, { - value: "#e89bb4", - }], - [{ - value: "#9d775f", - }, { - value: "#dd4b4b", - }, { - value: "#ef8b07", - }, { - value: "#fcc800", - }, { - value: "#aacf53", - }, { - value: "#82ae46", - }, { - value: "#69821b", - }, { - value: "#59b9c6", - }, { - value: "#2a83a2", - }, { - value: "#007bbb", - }, { - value: "#19448e", - }, { - value: "#274a78", - }, { - value: "#4a488e", - }, { - value: "#7058a3", - }, { - value: "#884898", - }, { - value: "#d47596", - }] - ] + [ + { + value: "#ffffff", + }, + { + value: "#f2f2f2", + }, + { + value: "#e5e5e5", + }, + { + value: "#d9d9d9", + }, + { + value: "#cccccc", + }, + { + value: "#bfbfbf", + }, + { + value: "#b2b2b2", + }, + { + value: "#a6a6a6", + }, + { + value: "#999999", + }, + { + value: "#8c8c8c", + }, + { + value: "#808080", + }, + { + value: "#737373", + }, + { + value: "#666666", + }, + { + value: "#4d4d4d", + }, + { + value: "#333333", + }, + { + value: "#000000", + } + ], + [ + { + value: "#d8b5a6", + }, + { + value: "#ff9e9a", + }, + { + value: "#ffc17d", + }, + { + value: "#f5e56b", + }, + { + value: "#d8e698", + }, + { + value: "#e0ebaf", + }, + { + value: "#c3d825", + }, + { + value: "#bbe2e7", + }, + { + value: "#85d3cd", + }, + { + value: "#bde1e6", + }, + { + value: "#a0d8ef", + }, + { + value: "#89c3eb", + }, + { + value: "#bbc8e6", + }, + { + value: "#bbbcde", + }, + { + value: "#d6b4cc", + }, + { + value: "#fbc0d3", + } + ], + [ + { + value: "#bb9581", + }, + { + value: "#f37d79", + }, + { + value: "#fba74f", + }, + { + value: "#ffdb4f", + }, + { + value: "#c7dc68", + }, + { + value: "#b0ca71", + }, + { + value: "#99ab4e", + }, + { + value: "#84b9cb", + }, + { + value: "#00a3af", + }, + { + value: "#2ca9e1", + }, + { + value: "#0095d9", + }, + { + value: "#4c6cb3", + }, + { + value: "#8491c3", + }, + { + value: "#a59aca", + }, + { + value: "#cc7eb1", + }, + { + value: "#e89bb4", + } + ], + [ + { + value: "#9d775f", + }, + { + value: "#dd4b4b", + }, + { + value: "#ef8b07", + }, + { + value: "#fcc800", + }, + { + value: "#aacf53", + }, + { + value: "#82ae46", + }, + { + value: "#69821b", + }, + { + value: "#59b9c6", + }, + { + value: "#2a83a2", + }, + { + value: "#007bbb", + }, + { + value: "#19448e", + }, + { + value: "#274a78", + }, + { + value: "#4a488e", + }, + { + value: "#7058a3", + }, + { + value: "#884898", + }, + { + value: "#d47596", + } + ] + ]; _init() { super._init(...arguments); const o = this.options; this.colors = createWidget({ - type: "bi.button_group", + type: ButtonGroup.xtype, element: this, items: createItems(o.items || this._items, { - type: "bi.color_picker_button", + type: ColorPickerButton.xtype, once: false, }), - layouts: [{ - type: "bi.grid", - }], + layouts: [ + { + type: GridLayout.xtype, + } + ], value: o.value, }); this.colors.on(ButtonGroup.EVENT_CHANGE, (...args) => { @@ -179,7 +250,7 @@ export class ColorPicker extends Widget { populate(items) { const args = [].slice.call(arguments); args[0] = createItems(items, { - type: "bi.color_picker_button", + type: ColorPickerButton.xtype, once: false, }); this.colors.populate.apply(this.colors, args); diff --git a/src/case/colorchooser/colorpicker/editor.colorpicker.hex.js b/src/case/colorchooser/colorpicker/editor.colorpicker.hex.js index 7b626a37c..8e8a480ec 100644 --- a/src/case/colorchooser/colorpicker/editor.colorpicker.hex.js +++ b/src/case/colorchooser/colorpicker/editor.colorpicker.hex.js @@ -1,8 +1,27 @@ -import { shortcut, Widget, createItems, map, isNumeric, range, extend, isEmptyString, isNull, DOM } from "@/core"; -import { ColorPickerEditor } from "./editor.colorpicker"; +import { Label } from "@/base"; +import { + AbsoluteLayout, + VerticalLayout, + VerticalAdaptLayout, + Layout, + shortcut, + Widget, + createItems, + map, + isNumeric, + range, + extend, + isEmptyString, + isNull, + DOM +} from "@/core"; import { ColorChooserShowButton } from "./button"; +import { ColorPickerEditor } from "./editor.colorpicker"; +import { SmallTextEditor } from "@/widget/editor/editor.text.small.js"; -const RGB_WIDTH = 32, HEX_WIDTH = 70, HEX_PREFIX_POSITION = 1; +const RGB_WIDTH = 32, + HEX_WIDTH = 70, + HEX_PREFIX_POSITION = 1; /** * 简单选色控件 @@ -14,18 +33,18 @@ const RGB_WIDTH = 32, HEX_WIDTH = 70, HEX_PREFIX_POSITION = 1; @shortcut() export class HexColorPickerEditor extends Widget { static xtype = "bi.hex_color_picker_editor"; - + static EVENT_CHANGE = "EVENT_CHANGE"; - + props = { baseCls: "bi-color-picker-editor", height: 30, - } + }; render() { this.storeValue = {}; const RGB = createItems([{ text: "R" }, { text: "G" }, { text: "B" }], { - type: "bi.label", + type: Label.xtype, cls: "color-picker-editor-label", height: 20, }); @@ -33,7 +52,7 @@ export class HexColorPickerEditor extends Widget { const checker = v => isNumeric(v) && (v | 0) >= 0 && (v | 0) <= 255; const Ws = map(range(0, 3), () => { return { - type: "bi.small_text_editor", + type: SmallTextEditor.xtype, cls: "color-picker-editor-input bi-border-radius", validationChecker: checker, errorText: BI.i18nText("BI-Color_Picker_Error_Text"), @@ -46,7 +65,11 @@ export class HexColorPickerEditor extends Widget { eventName: BI.TextEditor.EVENT_CHANGE, action: () => { this._checkEditors(); - if (checker(this.storeValue.r) && checker(this.storeValue.g) && checker(this.storeValue.b)) { + if ( + checker(this.storeValue.r) && + checker(this.storeValue.g) && + checker(this.storeValue.b) + ) { this.colorShow.element.css("background-color", this.getValue()); this.fireEvent(ColorPickerEditor.EVENT_CHANGE); } @@ -57,20 +80,20 @@ export class HexColorPickerEditor extends Widget { }); return { - type: "bi.absolute", + type: AbsoluteLayout.xtype, items: [ { el: { - type: "bi.vertical", + type: VerticalLayout.xtype, tgap: 10, items: [ { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, columnSize: ["fill", "fill"], height: 24, items: [ { - type: "bi.color_picker_show_button", + type: ColorChooserShowButton.xtype, cls: "trans-color-icon", height: 22, title: BI.i18nText("BI-Transparent_Color"), @@ -87,9 +110,10 @@ export class HexColorPickerEditor extends Widget { ref: _ref => { this.transparent = _ref; }, - }, { + }, + { el: { - type: "bi.color_picker_show_button", + type: ColorChooserShowButton.xtype, cls: "auto-color-icon", height: 22, title: BI.i18nText("BI-Basic_Auto"), @@ -110,16 +134,17 @@ export class HexColorPickerEditor extends Widget { lgap: 10, } ], - }, { + }, + { el: { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, columnSize: [22, 10, "fill", 12, RGB_WIDTH, 12, RGB_WIDTH, 12, RGB_WIDTH], rgap: 5, items: [ { el: { - type: "bi.layout", + type: Layout.xtype, cls: "color-picker-editor-display bi-card bi-border", height: 22, width: 22, @@ -128,12 +153,14 @@ export class HexColorPickerEditor extends Widget { }, }, width: 18, - }, { - type: "bi.label", + }, + { + type: Label.xtype, text: "#", width: 10, - }, { - type: "bi.small_text_editor", + }, + { + type: SmallTextEditor.xtype, ref: _ref => { this.hexEditor = _ref; }, @@ -148,28 +175,41 @@ export class HexColorPickerEditor extends Widget { eventName: "EVENT_CHANGE", action: () => { this._checkHexEditor(); - if (checker(this.storeValue.r) && checker(this.storeValue.g) && checker(this.storeValue.b)) { - this.colorShow.element.css("background-color", this.getValue()); + if ( + checker(this.storeValue.r) && + checker(this.storeValue.g) && + checker(this.storeValue.b) + ) { + this.colorShow.element.css( + "background-color", + this.getValue() + ); this.fireEvent(ColorPickerEditor.EVENT_CHANGE); } }, } ], - }, RGB[0], { + }, + RGB[0], + { el: extend(Ws[0], { ref: _ref => { this.R = _ref; }, }), width: RGB_WIDTH, - }, RGB[1], { + }, + RGB[1], + { el: extend(Ws[1], { ref: _ref => { this.G = _ref; }, }), width: RGB_WIDTH, - }, RGB[2], { + }, + RGB[2], + { el: extend(Ws[2], { ref: _ref => { this.B = _ref; @@ -235,11 +275,20 @@ export class HexColorPickerEditor extends Widget { _showPreColor(color) { if (color === "") { - this.colorShow.element.css("background-color", "").removeClass("trans-color-background").addClass("auto-color-square-normal-background"); + this.colorShow.element + .css("background-color", "") + .removeClass("trans-color-background") + .addClass("auto-color-square-normal-background"); } else if (color === "transparent") { - this.colorShow.element.css("background-color", "").removeClass("auto-color-square-normal-background").addClass("trans-color-background"); + this.colorShow.element + .css("background-color", "") + .removeClass("auto-color-square-normal-background") + .addClass("trans-color-background"); } else { - this.colorShow.element.css({ "background-color": color }).removeClass("auto-color-square-normal-background").removeClass("trans-color-background"); + this.colorShow.element + .css({ "background-color": color }) + .removeClass("auto-color-square-normal-background") + .removeClass("trans-color-background"); } } @@ -266,7 +315,7 @@ export class HexColorPickerEditor extends Widget { g: "", b: "", }; - + return; } if (!color) { @@ -293,11 +342,13 @@ export class HexColorPickerEditor extends Widget { if (this._isEmptyRGB() && this.transparent.isSelected()) { return "transparent"; } - - return DOM.rgb2hex(DOM.json2rgb({ - r: this.storeValue.r, - g: this.storeValue.g, - b: this.storeValue.b, - })); + + return DOM.rgb2hex( + DOM.json2rgb({ + r: this.storeValue.r, + g: this.storeValue.g, + b: this.storeValue.b, + }) + ); } } diff --git a/src/case/colorchooser/colorpicker/editor.colorpicker.hex.simple.js b/src/case/colorchooser/colorpicker/editor.colorpicker.hex.simple.js index f055be894..8f12b325e 100644 --- a/src/case/colorchooser/colorpicker/editor.colorpicker.hex.simple.js +++ b/src/case/colorchooser/colorpicker/editor.colorpicker.hex.simple.js @@ -1,8 +1,27 @@ -import { shortcut, Widget, extend, isEmptyObject, createItems, isNull, isNumeric, map, isEmptyString, range, DOM } from "@/core"; +import { Label } from "@/base"; +import { + VerticalLayout, + VerticalAdaptLayout, + Layout, + shortcut, + Widget, + extend, + isEmptyObject, + createItems, + isNull, + isNumeric, + map, + isEmptyString, + range, + DOM +} from "@/core"; import { SimpleColorPickerEditor } from "./editor.colorpicker.simple"; import { ColorPickerEditor } from "./editor.colorpicker"; +import { SmallTextEditor } from "@/widget/editor/editor.text.small.js"; -const RGB_WIDTH = 32, HEX_WIDTH = 70, HEX_PREFIX_POSITION = 1; +const RGB_WIDTH = 32, + HEX_WIDTH = 70, + HEX_PREFIX_POSITION = 1; /** * @author windy @@ -18,19 +37,19 @@ export class SimpleHexColorPickerEditor extends Widget { props = { baseCls: "bi-color-picker-editor", height: 36, - } + }; - render () { + render() { const RGB = createItems([{ text: "R" }, { text: "G" }, { text: "B" }], { - type: "bi.label", + type: Label.xtype, cls: "color-picker-editor-label", height: 20, }); - const checker = v => isNumeric(v) && (v | 0) >= 0 && (v | 0) <= 255; + const checker = (v) => isNumeric(v) && (v | 0) >= 0 && (v | 0) <= 255; const Ws = map(range(0, 3), () => { return { - type: "bi.small_text_editor", + type: SmallTextEditor.xtype, cls: "color-picker-editor-input bi-border-radius", validationChecker: checker, errorText: BI.i18nText("BI-Color_Picker_Error_Text"), @@ -48,39 +67,41 @@ export class SimpleHexColorPickerEditor extends Widget { this.fireEvent(SimpleColorPickerEditor.EVENT_CHANGE); } }, - } + }, ], }; }); return { - type: "bi.vertical", + type: VerticalLayout.xtype, tgap: 10, items: [ { el: { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, rgap: 5, columnSize: [22, 10, "fill", 12, RGB_WIDTH, 12, RGB_WIDTH, 12, RGB_WIDTH], items: [ { el: { - type: "bi.layout", + type: Layout.xtype, cls: "color-picker-editor-display bi-card bi-border", height: 22, width: 22, - ref: _ref => { + ref: (_ref) => { this.colorShow = _ref; }, }, width: 18, - }, { - type: "bi.label", + }, + { + type: Label.xtype, text: "#", width: 10, - }, { - type: "bi.small_text_editor", - ref: _ref => { + }, + { + type: SmallTextEditor.xtype, + ref: (_ref) => { this.hexEditor = _ref; }, cls: "color-picker-editor-input bi-border-radius", @@ -94,49 +115,58 @@ export class SimpleHexColorPickerEditor extends Widget { eventName: "EVENT_CHANGE", action: () => { this._checkHexEditor(); - if (checker(this.storeValue.r) && checker(this.storeValue.g) && checker(this.storeValue.b)) { + if ( + checker(this.storeValue.r) && + checker(this.storeValue.g) && + checker(this.storeValue.b) + ) { this.colorShow.element.css("background-color", this.getValue()); this.fireEvent(ColorPickerEditor.EVENT_CHANGE); } }, - } + }, ], - }, RGB[0], { + }, + RGB[0], + { el: extend(Ws[0], { - ref: _ref => { + ref: (_ref) => { this.R = _ref; }, }), width: RGB_WIDTH, - }, RGB[1], { + }, + RGB[1], + { el: extend(Ws[1], { - ref: _ref => { + ref: (_ref) => { this.G = _ref; }, }), width: RGB_WIDTH, - }, RGB[2], { + }, + RGB[2], + { el: extend(Ws[2], { - ref: _ref => { + ref: (_ref) => { this.B = _ref; }, }), rgap: -5, width: RGB_WIDTH, - } + }, ], }, - } + }, ], - }; } - _hexChecker (v) { + _hexChecker(v) { return /^[0-9a-fA-F]{6}$/.test(v); } - _checkEditors () { + _checkEditors() { if (isEmptyString(this.R.getValue())) { this.R.setValue(0); } @@ -149,7 +179,7 @@ export class SimpleHexColorPickerEditor extends Widget { this.hexEditor.setValue(this.getValue().slice(HEX_PREFIX_POSITION)); } - _checkHexEditor () { + _checkHexEditor() { if (isEmptyString(this.hexEditor.getValue())) { this.hexEditor.setValue("000000"); } @@ -164,7 +194,7 @@ export class SimpleHexColorPickerEditor extends Widget { this.B.setValue(this.storeValue.b); } - setValue (color) { + setValue(color) { this.colorShow.element.css({ "background-color": color }); const json = DOM.rgb2json(DOM.hex2rgb(color)); this.R.setValue(isNull(json.r) ? "" : json.r); @@ -173,11 +203,13 @@ export class SimpleHexColorPickerEditor extends Widget { this.hexEditor.setValue(isEmptyObject(json) ? "" : color.slice(HEX_PREFIX_POSITION)); } - getValue () { - return DOM.rgb2hex(DOM.json2rgb({ - r: this.R.getValue(), - g: this.G.getValue(), - b: this.B.getValue(), - })); + getValue() { + return DOM.rgb2hex( + DOM.json2rgb({ + r: this.R.getValue(), + g: this.G.getValue(), + b: this.B.getValue(), + }) + ); } } diff --git a/src/case/colorchooser/colorpicker/editor.colorpicker.js b/src/case/colorchooser/colorpicker/editor.colorpicker.js index f413ff94d..9f05660f3 100644 --- a/src/case/colorchooser/colorpicker/editor.colorpicker.js +++ b/src/case/colorchooser/colorpicker/editor.colorpicker.js @@ -1,5 +1,21 @@ -import { shortcut, Widget, extend, createWidgets, createItems, createWidget, each, isEmptyString, isNumeric, isNull, DOM } from "@/core"; -import { IconButton } from "@/base"; +import { + Layout, + AbsoluteLayout, + VerticalAdaptLayout, + shortcut, + Widget, + extend, + createWidgets, + createItems, + createWidget, + each, + isEmptyString, + isNumeric, + isNull, + DOM +} from "@/core"; +import { Label, IconButton } from "@/base"; +import { SmallTextEditor } from "@/widget/editor/editor.text.small.js"; const RGB_WIDTH = 32; @@ -16,7 +32,7 @@ export class ColorPickerEditor extends Widget { static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig () { + _defaultConfig() { return extend(super._defaultConfig(...arguments), { baseCls: "bi-color-picker-editor", // width: 200, @@ -24,25 +40,27 @@ export class ColorPickerEditor extends Widget { }); } - _init () { + _init() { super._init(...arguments); this.storeValue = {}; this.colorShow = createWidget({ - type: "bi.layout", + type: Layout.xtype, cls: "color-picker-editor-display bi-card bi-border", height: 16, width: 16, }); - const RGB = createWidgets(createItems([{ text: "R" }, { text: "G" }, { text: "B" }], { - type: "bi.label", - cls: "color-picker-editor-label", - width: 20, - height: 20, - })); + const RGB = createWidgets( + createItems([{ text: "R" }, { text: "G" }, { text: "B" }], { + type: Label.xtype, + cls: "color-picker-editor-label", + width: 20, + height: 20, + }) + ); - const checker = v => isNumeric(v) && (v | 0) >= 0 && (v | 0) <= 255; + const checker = (v) => isNumeric(v) && (v | 0) >= 0 && (v | 0) <= 255; const Ws = createWidgets([{}, {}, {}], { - type: "bi.small_text_editor", + type: SmallTextEditor.xtype, cls: "color-picker-editor-input bi-border-radius", validationChecker: checker, errorText: BI.i18nText("BI-Color_Picker_Error_Text"), @@ -65,7 +83,7 @@ export class ColorPickerEditor extends Widget { this.B = Ws[2]; this.none = createWidget({ - type: "bi.icon_button", + type: IconButton.xtype, cls: "auto-color-icon", width: 16, height: 16, @@ -76,11 +94,11 @@ export class ColorPickerEditor extends Widget { this.none.on(IconButton.EVENT_CHANGE, () => { const value = this.getValue(); this.setValue(""); - (value !== "") && this.fireEvent(ColorPickerEditor.EVENT_CHANGE); + value !== "" && this.fireEvent(ColorPickerEditor.EVENT_CHANGE); }); this.transparent = createWidget({ - type: "bi.icon_button", + type: IconButton.xtype, cls: "trans-color-icon", width: 16, height: 16, @@ -91,59 +109,67 @@ export class ColorPickerEditor extends Widget { this.transparent.on(IconButton.EVENT_CHANGE, () => { const value = this.getValue(); this.setValue("transparent"); - (value !== "transparent") && this.fireEvent(ColorPickerEditor.EVENT_CHANGE); + value !== "transparent" && this.fireEvent(ColorPickerEditor.EVENT_CHANGE); }); createWidget({ - type: "bi.absolute", + type: AbsoluteLayout.xtype, element: this, items: [ { el: { - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, items: [ { el: this.colorShow, width: 16, - }, { + }, + { el: RGB[0], width: 20, - }, { + }, + { el: this.R, width: RGB_WIDTH, - }, { + }, + { el: RGB[1], width: 20, - }, { + }, + { el: this.G, width: RGB_WIDTH, - }, { + }, + { el: RGB[2], width: 20, - }, { + }, + { el: this.B, width: RGB_WIDTH, - }, { + }, + { el: this.transparent, width: 16, lgap: 5, - }, { + }, + { el: this.none, width: 16, lgap: 5, - } + }, ], }, left: 10, right: 10, top: 0, bottom: 0, - } + }, ], }); } - _checkEditors () { + _checkEditors() { if (isEmptyString(this.R.getValue())) { this.R.setValue(0); } @@ -160,21 +186,30 @@ export class ColorPickerEditor extends Widget { }; } - _isEmptyRGB () { + _isEmptyRGB() { return isEmptyString(this.storeValue.r) && isEmptyString(this.storeValue.g) && isEmptyString(this.storeValue.b); } - _showPreColor (color) { + _showPreColor(color) { if (color === "") { - this.colorShow.element.css("background-color", "").removeClass("trans-color-background").addClass("auto-color-normal-background"); + this.colorShow.element + .css("background-color", "") + .removeClass("trans-color-background") + .addClass("auto-color-normal-background"); } else if (color === "transparent") { - this.colorShow.element.css("background-color", "").removeClass("auto-color-normal-background").addClass("trans-color-background"); + this.colorShow.element + .css("background-color", "") + .removeClass("auto-color-normal-background") + .addClass("trans-color-background"); } else { - this.colorShow.element.css({ "background-color": color }).removeClass("auto-color-normal-background").removeClass("trans-color-background"); + this.colorShow.element + .css({ "background-color": color }) + .removeClass("auto-color-normal-background") + .removeClass("trans-color-background"); } } - _setEnable (enable) { + _setEnable(enable) { super._setEnable(...arguments); if (enable === true) { this.element.removeClass("base-disabled disabled"); @@ -183,7 +218,7 @@ export class ColorPickerEditor extends Widget { } } - setValue (color) { + setValue(color) { if (color === "transparent") { this.transparent.setSelected(true); this.none.setSelected(false); @@ -196,7 +231,7 @@ export class ColorPickerEditor extends Widget { g: "", b: "", }; - + return; } if (!color) { @@ -222,11 +257,13 @@ export class ColorPickerEditor extends Widget { if (this._isEmptyRGB() && this.transparent.isSelected()) { return "transparent"; } - - return DOM.rgb2hex(DOM.json2rgb({ - r: this.storeValue.r, - g: this.storeValue.g, - b: this.storeValue.b, - })); + + return DOM.rgb2hex( + DOM.json2rgb({ + r: this.storeValue.r, + g: this.storeValue.g, + b: this.storeValue.b, + }) + ); } } diff --git a/src/case/colorchooser/colorpicker/editor.colorpicker.simple.js b/src/case/colorchooser/colorpicker/editor.colorpicker.simple.js index 590cd1c37..d64c771bc 100644 --- a/src/case/colorchooser/colorpicker/editor.colorpicker.simple.js +++ b/src/case/colorchooser/colorpicker/editor.colorpicker.simple.js @@ -1,4 +1,20 @@ -import { shortcut, Widget, extend, isNull, createWidget, isNumeric, createItems, createWidgets, each, isEmptyString, DOM } from "@/core"; +import { + Layout, + VerticalAdaptLayout, + shortcut, + Widget, + extend, + isNull, + createWidget, + isNumeric, + createItems, + createWidgets, + each, + isEmptyString, + DOM +} from "@/core"; +import { Label } from "@/base"; +import { SmallTextEditor } from "@/widget/editor/editor.text.small.js"; const RGB_WIDTH = 32; @@ -26,21 +42,23 @@ export class SimpleColorPickerEditor extends Widget { _init() { super._init(...arguments); this.colorShow = createWidget({ - type: "bi.layout", + type: Layout.xtype, cls: "color-picker-editor-display bi-card bi-border", height: 16, width: 16, }); - const RGB = createWidgets(createItems([{ text: "R" }, { text: "G" }, { text: "B" }], { - type: "bi.label", - cls: "color-picker-editor-label", - width: 20, - height: 20, - })); + const RGB = createWidgets( + createItems([{ text: "R" }, { text: "G" }, { text: "B" }], { + type: Label.xtype, + cls: "color-picker-editor-label", + width: 20, + height: 20, + }) + ); - const checker = v => isNumeric(v) && (v | 0) >= 0 && (v | 0) <= 255; + const checker = (v) => isNumeric(v) && (v | 0) >= 0 && (v | 0) <= 255; const Ws = createWidgets([{}, {}, {}], { - type: "bi.small_text_editor", + type: SmallTextEditor.xtype, cls: "color-picker-editor-input bi-border-radius", validationChecker: checker, errorText: BI.i18nText("BI-Color_Picker_Error_Text"), @@ -63,7 +81,7 @@ export class SimpleColorPickerEditor extends Widget { this.B = Ws[2]; createWidget({ - type: "bi.vertical_adapt", + type: VerticalAdaptLayout.xtype, element: this, items: [ { @@ -71,25 +89,31 @@ export class SimpleColorPickerEditor extends Widget { width: 16, lgap: 20, rgap: 15, - }, { + }, + { el: RGB[0], width: 20, - }, { + }, + { el: this.R, width: RGB_WIDTH, - }, { + }, + { el: RGB[1], width: 20, - }, { + }, + { el: this.G, width: RGB_WIDTH, - }, { + }, + { el: RGB[2], width: 20, - }, { + }, + { el: this.B, width: RGB_WIDTH, - } + }, ], }); } @@ -115,10 +139,12 @@ export class SimpleColorPickerEditor extends Widget { } getValue() { - return DOM.rgb2hex(DOM.json2rgb({ - r: this.R.getValue(), - g: this.G.getValue(), - b: this.B.getValue(), - })); + return DOM.rgb2hex( + DOM.json2rgb({ + r: this.R.getValue(), + g: this.G.getValue(), + b: this.B.getValue(), + }) + ); } } diff --git a/src/case/colorchooser/colorpicker/index.js b/src/case/colorchooser/colorpicker/index.js index 73724cae8..dc05c0270 100644 --- a/src/case/colorchooser/colorpicker/index.js +++ b/src/case/colorchooser/colorpicker/index.js @@ -1,7 +1,7 @@ -export { ColorPicker } from "./colorpicker"; -export { HexColorPicker } from "./colorpicker.hex"; -export { ColorPickerEditor } from "./editor.colorpicker"; -export { HexColorPickerEditor } from "./editor.colorpicker.hex"; -export { SimpleHexColorPickerEditor } from "./editor.colorpicker.hex.simple"; -export { SimpleColorPickerEditor } from "./editor.colorpicker.simple"; -export * from "./button"; +export { ColorPicker } from "./colorpicker"; +export { HexColorPicker } from "./colorpicker.hex"; +export { ColorPickerEditor } from "./editor.colorpicker"; +export { HexColorPickerEditor } from "./editor.colorpicker.hex"; +export { SimpleHexColorPickerEditor } from "./editor.colorpicker.hex.simple"; +export { SimpleColorPickerEditor } from "./editor.colorpicker.simple"; +export * from "./button"; diff --git a/src/case/colorchooser/farbtastic/farbtastic.js b/src/case/colorchooser/farbtastic/farbtastic.js index 9a57fbaf8..527d5529b 100644 --- a/src/case/colorchooser/farbtastic/farbtastic.js +++ b/src/case/colorchooser/farbtastic/farbtastic.js @@ -1,7 +1,9 @@ -import { shortcut, isKey, DOM } from "@/core"; +import { AbsoluteLayout, Layout, shortcut, isKey, DOM } from "@/core"; import { BasicButton } from "@/base"; -const RADIUS = 84, SQUARE = 100, WIDTH = 194; +const RADIUS = 84, + SQUARE = 100, + WIDTH = 194; @shortcut() export class Farbtastic extends BasicButton { @@ -15,72 +17,78 @@ export class Farbtastic extends BasicButton { height: 195, stopPropagation: true, value: "#000000", - } + }; render() { this._defaultState(); - + return { - type: "bi.absolute", - items: [{ - el: { - type: "bi.layout", - cls: "", - ref: _ref => { - this.colorWrapper = _ref; + type: AbsoluteLayout.xtype, + items: [ + { + el: { + type: Layout.xtype, + cls: "", + ref: _ref => { + this.colorWrapper = _ref; + }, }, + top: 47, + left: 47, + width: 101, + height: 101, }, - top: 47, - left: 47, - width: 101, - height: 101, - }, { - el: { - type: "bi.layout", - cls: "wheel", - ref: _ref => { - this.wheel = _ref; + { + el: { + type: Layout.xtype, + cls: "wheel", + ref: _ref => { + this.wheel = _ref; + }, }, + left: 0, + right: 0, + top: 0, + bottom: 0, }, - left: 0, - right: 0, - top: 0, - bottom: 0, - }, { - el: { - type: "bi.layout", - cls: "overlay", - ref: _ref => { - this.overlay = _ref; + { + el: { + type: Layout.xtype, + cls: "overlay", + ref: _ref => { + this.overlay = _ref; + }, }, + top: 47, + left: 47, + width: 101, + height: 101, }, - top: 47, - left: 47, - width: 101, - height: 101, - }, { - el: { - type: "bi.layout", - cls: "marker", - ref: _ref => { - this.hMarker = _ref; + { + el: { + type: Layout.xtype, + cls: "marker", + ref: _ref => { + this.hMarker = _ref; + }, + scrollable: false, + width: 17, + height: 17, }, - scrollable: false, - width: 17, - height: 17, }, - }, { - el: { - type: "bi.layout", - cls: "marker", - ref: _ref => { - this.slMarker = _ref; + { + el: { + type: Layout.xtype, + cls: "marker", + ref: _ref => { + this.slMarker = _ref; + }, + scrollable: false, + width: 17, + height: 17, }, - scrollable: false, - width: 17, - height: 17, - }, - }], + } + ], }; } @@ -97,13 +105,17 @@ export class Farbtastic extends BasicButton { _unpack(color) { if (color.length === 7) { - return [parseInt("0x" + color.substring(1, 3)) / 255, - parseInt("0x" + color.substring(3, 5)) / 255, - parseInt("0x" + color.substring(5, 7)) / 255]; + return [ + parseInt(`0x${color.substring(1, 3)}`) / 255, + parseInt(`0x${color.substring(3, 5)}`) / 255, + parseInt(`0x${color.substring(5, 7)}`) / 255 + ]; } else if (color.length === 4) { - return [parseInt("0x" + color.substring(1, 2)) / 15, - parseInt("0x" + color.substring(2, 3)) / 15, - parseInt("0x" + color.substring(3, 4)) / 15]; + return [ + parseInt(`0x${color.substring(1, 2)}`) / 15, + parseInt(`0x${color.substring(2, 3)}`) / 15, + parseInt(`0x${color.substring(3, 4)}`) / 15 + ]; } } @@ -111,10 +123,16 @@ export class Farbtastic extends BasicButton { const r = Math.round(rgb[0] * 255); const g = Math.round(rgb[1] * 255); const b = Math.round(rgb[2] * 255); - - return "#" + (r < 16 ? "0" : "") + r.toString(16) + - (g < 16 ? "0" : "") + g.toString(16) + - (b < 16 ? "0" : "") + b.toString(16); + + return ( + `#${ + r < 16 ? "0" : "" + }${r.toString(16) + }${g < 16 ? "0" : "" + }${g.toString(16) + }${b < 16 ? "0" : "" + }${b.toString(16)}` + ); } _setColor(color) { @@ -132,7 +150,7 @@ export class Farbtastic extends BasicButton { this.rgb = this._HSLToRGB(hsl); this.value = this._pack(this.rgb); this._updateDisplay(); - + return this; } @@ -152,8 +170,8 @@ export class Farbtastic extends BasicButton { }); this.slMarker.element.css({ - left: `${Math.round(SQUARE * (.5 - this.hsl[1]) + WIDTH / 2)}px`, - top: `${Math.round(SQUARE * (.5 - this.hsl[2]) + WIDTH / 2)}px`, + left: `${Math.round(SQUARE * (0.5 - this.hsl[1]) + WIDTH / 2)}px`, + top: `${Math.round(SQUARE * (0.5 - this.hsl[2]) + WIDTH / 2)}px`, }); // Saturation/Luminance gradient @@ -168,7 +186,7 @@ export class Farbtastic extends BasicButton { r.x += tmp.x; r.y += tmp.y; } - + return r; } @@ -218,7 +236,7 @@ export class Farbtastic extends BasicButton { x = (event.pageX || 0) - pos.x; y = (event.pageY || 0) - pos.y; } - + // Subtract distance to middle return { x: x - WIDTH / 2, y: y - WIDTH / 2 }; } @@ -232,8 +250,8 @@ export class Farbtastic extends BasicButton { if (hue < 0) hue += 1; this._setHSL([hue, this.hsl[1], this.hsl[2]]); } else { - const sat = Math.max(0, Math.min(1, -(pos.x / SQUARE) + .5)); - const lum = Math.max(0, Math.min(1, -(pos.y / SQUARE) + .5)); + const sat = Math.max(0, Math.min(1, -(pos.x / SQUARE) + 0.5)); + const lum = Math.max(0, Math.min(1, -(pos.y / SQUARE) + 0.5)); this._setHSL([this.hsl[0], sat, lum]); } this.fireEvent(Farbtastic.EVENT_CHANGE, this.getValue(), this); @@ -245,7 +263,7 @@ export class Farbtastic extends BasicButton { // Process this._doMouseMove(event); - + return false; } diff --git a/src/case/colorchooser/index.js b/src/case/colorchooser/index.js index 582eac086..24d8bc806 100644 --- a/src/case/colorchooser/index.js +++ b/src/case/colorchooser/index.js @@ -1,11 +1,11 @@ -export { ColorChooser } from "./colorchooser"; -export { CustomColorChooser } from "./colorchooser.custom"; -export { ColorChooserPopup } from "./colorchooser.popup"; -export { HexColorChooserPopup } from "./colorchooser.popup.hex"; -export { SimpleHexColorChooserPopup } from "./colorchooser.popup.hex.simple"; -export { SimpleColorChooserPopup } from "./colorchooser.popup.simple"; -export { SimpleColorChooser } from "./colorchooser.simple"; -export { ColorChooserTrigger } from "./colorchooser.trigger"; -export { LongColorChooserTrigger } from "./colorchooser.trigger.long"; -export { Farbtastic } from "./farbtastic/farbtastic"; -export * from "./colorpicker"; +export { ColorChooser } from "./colorchooser"; +export { CustomColorChooser } from "./colorchooser.custom"; +export { ColorChooserPopup } from "./colorchooser.popup"; +export { HexColorChooserPopup } from "./colorchooser.popup.hex"; +export { SimpleHexColorChooserPopup } from "./colorchooser.popup.hex.simple"; +export { SimpleColorChooserPopup } from "./colorchooser.popup.simple"; +export { SimpleColorChooser } from "./colorchooser.simple"; +export { ColorChooserTrigger } from "./colorchooser.trigger"; +export { LongColorChooserTrigger } from "./colorchooser.trigger.long"; +export { Farbtastic } from "./farbtastic/farbtastic"; +export * from "./colorpicker"; diff --git a/src/case/combo/bubblecombo/combo.bubble.js b/src/case/combo/bubblecombo/combo.bubble.js index f7e79c93d..df03267e4 100644 --- a/src/case/combo/bubblecombo/combo.bubble.js +++ b/src/case/combo/bubblecombo/combo.bubble.js @@ -1,11 +1,5 @@ -import { - shortcut, - Widget, - extend, - emptyFn, - createWidget, - isFunction -} from "@/core"; +import { BubblePopupView } from "./popup.bubble"; +import { shortcut, Widget, extend, emptyFn, createWidget, isFunction } from "@/core"; import { Combo } from "@/base"; @shortcut() @@ -76,14 +70,12 @@ export class BubbleCombo extends Widget { popup: () => extend( { - type: "bi.bubble_popup_view", + type: BubblePopupView.xtype, animation: "bi-zoom-big", animationDuring: 200, primary: o.primary, }, - isFunction(this.options.popup) - ? this.options.popup() - : this.options.popup + isFunction(this.options.popup) ? this.options.popup() : this.options.popup ), }); this.combo.on(Combo.EVENT_TRIGGER_CHANGE, (...args) => { @@ -135,5 +127,3 @@ export class BubbleCombo extends Widget { this.combo.adjustHeight(); } } - - diff --git a/src/case/combo/bubblecombo/popup.bubble.js b/src/case/combo/bubblecombo/popup.bubble.js index 2a6050af0..0f7782160 100644 --- a/src/case/combo/bubblecombo/popup.bubble.js +++ b/src/case/combo/bubblecombo/popup.bubble.js @@ -11,7 +11,7 @@ export class BubblePopupView extends PopupView { _defaultConfig() { const config = super._defaultConfig(...arguments); - + return extend(config, { baseCls: `${config.baseCls} bi-text-bubble-bar-popup-view`, text: "", @@ -20,13 +20,13 @@ export class BubblePopupView extends PopupView { _createContent() { const o = this.options; - + return { type: Label.xtype, text: o.text, whiteSpace: "normal", textAlign: "left", - ref: _ref => { + ref: (_ref) => { this.text = _ref; }, }; diff --git a/src/case/combo/editoriconcheckcombo/combo.editiconcheck.js b/src/case/combo/editoriconcheckcombo/combo.editiconcheck.js index b3bb8e29f..4d06ab584 100644 --- a/src/case/combo/editoriconcheckcombo/combo.editiconcheck.js +++ b/src/case/combo/editoriconcheckcombo/combo.editiconcheck.js @@ -1,14 +1,7 @@ -import { - shortcut, - Widget, - extend, - emptyFn, - createWidget, - Controller -} from "@/core"; +import { TextValueCheckComboPopup } from "../textvaluecheckcombo/popup.textvaluecheck"; +import { shortcut, Widget, extend, emptyFn, createWidget, Controller } from "@/core"; import { ButtonGroup, Combo } from "@/base"; import { EditorTrigger } from "../../trigger"; -import { TextValueCheckComboPopup } from "../textvaluecheckcombo/popup.textvaluecheck"; @shortcut() export class EditorIconCheckCombo extends Widget { @@ -66,7 +59,7 @@ export class EditorIconCheckCombo extends Widget { }); this.popup = createWidget({ - type: "bi.text_value_check_combo_popup", + type: TextValueCheckComboPopup.xtype, chooseType: o.chooseType, items: o.items, value: o.value, @@ -105,4 +98,4 @@ export class EditorIconCheckCombo extends Widget { this.options.items = items; this.editorIconCheckCombo.populate(items); } -} \ No newline at end of file +} diff --git a/src/case/combo/iconcombo/combo.icon.js b/src/case/combo/iconcombo/combo.icon.js index 338e10183..d7aaf3f63 100644 --- a/src/case/combo/iconcombo/combo.icon.js +++ b/src/case/combo/iconcombo/combo.icon.js @@ -1,13 +1,5 @@ -import { - shortcut, - Widget, - extend, - isFunction, - createWidget, - Controller, - isNull, - isArray -} from "@/core"; +import { IconComboTrigger } from "./trigger.iconcombo"; +import { shortcut, Widget, extend, isFunction, createWidget, Controller, isNull, isArray } from "@/core"; import { ButtonGroup, Combo } from "@/base"; import { IconComboPopup } from "./popup.iconcombo"; @@ -52,7 +44,7 @@ export class IconCombo extends Widget { : o.items; super._init(...arguments); this.trigger = createWidget(o.el, { - type: "bi.icon_combo_trigger", + type: IconComboTrigger.xtype, iconCls: o.iconCls, title: o.title, items: o.items, @@ -113,7 +105,7 @@ export class IconCombo extends Widget { getValue() { const value = this.popup.getValue(); - + return isNull(value) ? [] : isArray(value) ? value : [value]; } diff --git a/src/case/combo/iconcombo/popup.iconcombo.js b/src/case/combo/iconcombo/popup.iconcombo.js index a503dd427..6b28bdd81 100644 --- a/src/case/combo/iconcombo/popup.iconcombo.js +++ b/src/case/combo/iconcombo/popup.iconcombo.js @@ -1,12 +1,4 @@ -import { - shortcut, - extend, - createWidget, - createItems, - Controller, - Events, - VerticalLayout -} from "@/core"; +import { shortcut, extend, createWidget, createItems, Controller, Events, VerticalLayout } from "@/core"; import { Pane, ButtonGroup } from "@/base"; import { SingleSelectIconTextItem } from "../../button"; diff --git a/src/case/combo/iconcombo/trigger.iconcombo.js b/src/case/combo/iconcombo/trigger.iconcombo.js index 67293f2fc..4a94241e5 100644 --- a/src/case/combo/iconcombo/trigger.iconcombo.js +++ b/src/case/combo/iconcombo/trigger.iconcombo.js @@ -1,13 +1,4 @@ -import { - shortcut, - extend, - isKey, - createWidget, - isNotEmptyString, - AbsoluteLayout, - isArray, - any -} from "@/core"; +import { shortcut, extend, isKey, createWidget, isNotEmptyString, AbsoluteLayout, isArray, any } from "@/core"; import { Trigger, IconButton } from "@/base"; import { IconChangeButton } from "../../button"; @@ -83,11 +74,11 @@ export class IconComboTrigger extends Trigger { any(items, (i, item) => { if (v === item.value) { iconCls = item.iconCls; - + return true; } }); - + return iconCls; } diff --git a/src/case/combo/icontextvaluecombo/combo.icontextvalue.js b/src/case/combo/icontextvaluecombo/combo.icontextvalue.js index 85004eb22..6080de4ea 100644 --- a/src/case/combo/icontextvaluecombo/combo.icontextvalue.js +++ b/src/case/combo/icontextvaluecombo/combo.icontextvalue.js @@ -1,3 +1,4 @@ +import { IconTextValueComboPopup } from "./popup.icontextvalue"; import { shortcut, Widget, @@ -14,7 +15,6 @@ import { find, contains } from "@/core"; -import { IconTextValueComboPopup } from "./popup.icontextvalue"; import { SelectIconTextTrigger } from "../../trigger"; import { Combo } from "@/base"; @@ -26,11 +26,7 @@ export class IconTextValueCombo extends Widget { _defaultConfig(config) { return extend(super._defaultConfig(...arguments), { - baseCls: - `bi-icon-text-value-combo ${ - config.simple - ? "bi-border-bottom" - : "bi-border bi-border-radius"}`, + baseCls: `bi-icon-text-value-combo ${config.simple ? "bi-border-bottom" : "bi-border bi-border-radius"}`, height: 24, iconHeight: null, iconWidth: null, @@ -42,13 +38,13 @@ export class IconTextValueCombo extends Widget { const o = this.options; o.value = isFunction(o.value) ? this.__watch(o.value, (context, newValue) => { - this.setValue(newValue); - }) + this.setValue(newValue); + }) : o.value; o.items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { - this.populate(newValue); - }) + this.populate(newValue); + }) : o.items; super._init(...arguments); this.trigger = createWidget({ @@ -66,7 +62,7 @@ export class IconTextValueCombo extends Widget { warningTitle: o.warningTitle, }); this.popup = createWidget({ - type: "bi.icon_text_value_combo_popup", + type: IconTextValueComboPopup.xtype, items: o.items, value: o.value, iconHeight: o.iconHeight, @@ -126,7 +122,7 @@ export class IconTextValueCombo extends Widget { getValue() { const value = this.popup.getValue(); - + return isNull(value) ? [] : isArray(value) ? value : [value]; } diff --git a/src/case/combo/icontextvaluecombo/popup.icontextvalue.js b/src/case/combo/icontextvaluecombo/popup.icontextvalue.js index 02edd74f3..98dd00b1a 100644 --- a/src/case/combo/icontextvaluecombo/popup.icontextvalue.js +++ b/src/case/combo/icontextvaluecombo/popup.icontextvalue.js @@ -1,12 +1,4 @@ -import { - shortcut, - extend, - createWidget, - createItems, - Controller, - Events, - VerticalLayout -} from "@/core"; +import { shortcut, extend, createWidget, createItems, Controller, Events, VerticalLayout } from "@/core"; import { Pane, ButtonGroup } from "@/base"; import { SingleSelectIconTextItem } from "../../button"; @@ -20,7 +12,7 @@ export class IconTextValueComboPopup extends Pane { return extend(super._defaultConfig(...arguments), { baseCls: "bi-icon-text-icon-popup", behaviors: { - redmark () { + redmark() { return true; }, }, diff --git a/src/case/combo/searchtextvaluecombo/combo.searchtextvalue.js b/src/case/combo/searchtextvaluecombo/combo.searchtextvalue.js index a5c586773..1db1dec92 100644 --- a/src/case/combo/searchtextvaluecombo/combo.searchtextvalue.js +++ b/src/case/combo/searchtextvaluecombo/combo.searchtextvalue.js @@ -1,3 +1,5 @@ +import { SearchTextValueTrigger } from "./trigger.searchtextvalue"; +import { TextValueComboPopup } from "../textvaluecombo/popup.textvalue"; import { shortcut, Widget, @@ -11,9 +13,7 @@ import { find, contains } from "@/core"; -import { SearchTextValueTrigger } from "./trigger.searchtextvalue"; import { ButtonGroup, Combo } from "@/base"; -import { TextValueComboPopup } from "../textvaluecombo/popup.textvalue"; @shortcut() export class SearchTextValueCombo extends Widget { @@ -38,32 +38,30 @@ export class SearchTextValueCombo extends Widget { const o = this.options; o.value = isFunction(o.value) ? this.__watch(o.value, (context, newValue) => { - this.setValue(newValue); - }) + this.setValue(newValue); + }) : o.value; o.items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { - this.populate(newValue); - }) + this.populate(newValue); + }) : o.items; return { type: Combo.xtype, - cls: - `${o.simple ? "bi-border-bottom" : "bi-border bi-border-radius" - } bi-focus-shadow`, + cls: `${o.simple ? "bi-border-bottom" : "bi-border bi-border-radius"} bi-focus-shadow`, container: o.container, adjustLength: 2, height: toPix(o.height, o.simple ? 1 : 2), width: toPix(o.width, 2), - ref: _ref => { + ref: (_ref) => { this.combo = _ref; }, el: { - type: "bi.search_text_value_trigger", + type: SearchTextValueTrigger.xtype, cls: "search-text-value-trigger", watermark: o.watermark, - ref: _ref => { + ref: (_ref) => { this.trigger = _ref; }, items: o.items, @@ -90,16 +88,16 @@ export class SearchTextValueCombo extends Widget { this._clear(); this.fireEvent(SearchTextValueCombo.EVENT_CHANGE); }, - } + }, ], }, popup: { el: { - type: "bi.text_value_combo_popup", + type: TextValueComboPopup.xtype, chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, value: o.value, items: o.items, - ref: _ref => { + ref: (_ref) => { this.popup = _ref; this.trigger.getSearcher().setAdapter(this.popup); }, @@ -109,11 +107,9 @@ export class SearchTextValueCombo extends Widget { action: () => { this.setValue(this.getValue()[0]); this.combo.hideView(); - this.fireEvent( - SearchTextValueCombo.EVENT_CHANGE - ); + this.fireEvent(SearchTextValueCombo.EVENT_CHANGE); }, - } + }, ], }, value: o.value, @@ -125,19 +121,15 @@ export class SearchTextValueCombo extends Widget { eventName: Combo.EVENT_AFTER_HIDEVIEW, action: () => { this.trigger.stopEditing(); - this.fireEvent( - SearchTextValueCombo.EVENT_AFTER_HIDEVIEW - ); + this.fireEvent(SearchTextValueCombo.EVENT_AFTER_HIDEVIEW); }, }, { eventName: Combo.EVENT_BEFORE_POPUPVIEW, action: () => { - this.fireEvent( - SearchTextValueCombo.EVENT_BEFORE_POPUPVIEW - ); + this.fireEvent(SearchTextValueCombo.EVENT_BEFORE_POPUPVIEW); }, - } + }, ], }; } @@ -182,7 +174,7 @@ export class SearchTextValueCombo extends Widget { getValue() { const value = this.combo.getValue(); - + return isNull(value) ? [] : isArray(value) ? value : [value]; } } diff --git a/src/case/combo/searchtextvaluecombo/popup.searchtextvalue.js b/src/case/combo/searchtextvaluecombo/popup.searchtextvalue.js index 36975c1d7..64baf06d7 100644 --- a/src/case/combo/searchtextvaluecombo/popup.searchtextvalue.js +++ b/src/case/combo/searchtextvaluecombo/popup.searchtextvalue.js @@ -1,12 +1,4 @@ -import { - shortcut, - Controller, - Events, - VerticalLayout, - map, - extend, - concat -} from "@/core"; +import { shortcut, Controller, Events, VerticalLayout, map, extend, concat } from "@/core"; import { ButtonGroup, Pane } from "@/base"; import { SingleSelectItem } from "../../button"; @@ -20,7 +12,7 @@ export class SearchTextValueComboPopup extends Pane { render() { const o = this.options; - + return { type: VerticalLayout.xtype, vgap: 5, @@ -38,7 +30,7 @@ export class SearchTextValueComboPopup extends Pane { } ], behaviors: { - redmark () { + redmark() { return true; }, }, @@ -48,16 +40,9 @@ export class SearchTextValueComboPopup extends Pane { eventName: Controller.EVENT_CHANGE, action: (...args) => { const [type, val, obj] = args; - this.fireEvent( - Controller.EVENT_CHANGE, - ...args - ); + this.fireEvent(Controller.EVENT_CHANGE, ...args); if (type === Events.CLICK) { - this.fireEvent( - SearchTextValueComboPopup.EVENT_CHANGE, - val, - obj - ); + this.fireEvent(SearchTextValueComboPopup.EVENT_CHANGE, val, obj); } }, } @@ -69,15 +54,17 @@ export class SearchTextValueComboPopup extends Pane { _formatItems(items) { const o = this.options; - - return map(items, (i, item) => extend( - { - type: SingleSelectItem.xtype, - textAlign: o.textAlign, - title: item.title || item.text, - }, - item - )); + + return map(items, (i, item) => + extend( + { + type: SingleSelectItem.xtype, + textAlign: o.textAlign, + title: item.title || item.text, + }, + item + ) + ); } mounted() { diff --git a/src/case/combo/searchtextvaluecombo/trigger.searchtextvalue.js b/src/case/combo/searchtextvaluecombo/trigger.searchtextvalue.js index a090b4c66..96dfd15ec 100644 --- a/src/case/combo/searchtextvaluecombo/trigger.searchtextvalue.js +++ b/src/case/combo/searchtextvaluecombo/trigger.searchtextvalue.js @@ -1,16 +1,6 @@ -import { - shortcut, - find, - i18nText, - isNotEmptyString, - VerticalAdaptLayout -} from "@/core"; -import { - ButtonGroup, - Trigger, - Searcher, - IconButton -} from "@/base"; +import { HorizontalFillLayout, shortcut, find, i18nText, isNotEmptyString, VerticalAdaptLayout } from "@/core"; +import { SearchTextValueComboPopup } from "./popup.searchtextvalue"; +import { ButtonGroup, Trigger, Searcher, IconButton } from "@/base"; import { TriggerIconButton } from "../../button"; import { DefaultTextEditor } from "../../editor"; @@ -50,7 +40,7 @@ export class SearchTextValueTrigger extends Trigger { const stateText = this._digest(o.value, o.items) || o.text; return { - type: "bi.horizontal_fill", + type: HorizontalFillLayout.xtype, columnSize: ["fill", 24], items: [ { @@ -72,17 +62,14 @@ export class SearchTextValueTrigger extends Trigger { height: o.height, }, popup: { - type: "bi.search_text_value_combo_popup", + type: SearchTextValueComboPopup.xtype, cls: "bi-card", chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, tipText: i18nText("BI-No_Select"), }, - onSearch (obj, callback) { + onSearch(obj, callback) { const keyword = obj.keyword; - const finding = BI.Func.getSearchResult( - o.items, - keyword - ); + const finding = BI.Func.getSearchResult(o.items, keyword); const matched = finding.match, find = finding.find; callback(matched, find); @@ -91,9 +78,7 @@ export class SearchTextValueTrigger extends Trigger { { eventName: Searcher.EVENT_CHANGE, action: () => { - this.fireEvent( - SearchTextValueTrigger.EVENT_CHANGE - ); + this.fireEvent(SearchTextValueTrigger.EVENT_CHANGE); }, } ], @@ -112,20 +97,13 @@ export class SearchTextValueTrigger extends Trigger { ref: _ref => { this.clearBtn = _ref; }, - cls: - `close-h-font ${ - o.allowClear - ? "clear-button" - : ""}`, + cls: `close-h-font ${o.allowClear ? "clear-button" : ""}`, stopPropagation: true, - invisible: - !isNotEmptyString(stateText), + invisible: !isNotEmptyString(stateText), width: o.height, height: o.height, handler: () => { - this.fireEvent( - SearchTextValueTrigger.EVENT_CLEAR - ); + this.fireEvent(SearchTextValueTrigger.EVENT_CLEAR); }, }, }, @@ -147,7 +125,7 @@ export class SearchTextValueTrigger extends Trigger { _digest(value, items) { const result = find(items, (i, item) => item.value === value); - + return result?.text; } @@ -166,8 +144,7 @@ export class SearchTextValueTrigger extends Trigger { setValue(vals) { const digestText = this._digest(vals, this.options.items); this._setState(digestText); - this.options.allowClear && - this.clearBtn.setVisible(isNotEmptyString(digestText)); + this.options.allowClear && this.clearBtn.setVisible(isNotEmptyString(digestText)); } getValue() { diff --git a/src/case/combo/textvaluecheckcombo/combo.textvaluecheck.js b/src/case/combo/textvaluecheckcombo/combo.textvaluecheck.js index c2fcfe901..cd8079878 100644 --- a/src/case/combo/textvaluecheckcombo/combo.textvaluecheck.js +++ b/src/case/combo/textvaluecheckcombo/combo.textvaluecheck.js @@ -1,15 +1,4 @@ -import { - shortcut, - Widget, - extend, - isFunction, - createWidget, - toPix, - Controller, - isKey, - isNull, - isArray -} from "@/core"; +import { shortcut, Widget, extend, isFunction, createWidget, toPix, Controller, isKey, isNull, isArray } from "@/core"; import { ButtonGroup, Combo } from "@/base"; import { TextValueCheckComboPopup } from "./popup.textvaluecheck"; import { SelectTextTrigger } from "../../trigger"; @@ -22,9 +11,7 @@ export class TextValueCheckCombo extends Widget { _defaultConfig(config) { return extend(super._defaultConfig(...arguments), { - baseCls: - `bi-text-value-check-combo ${ - config.simple ? "bi-border-bottom" : "bi-border"}`, + baseCls: `bi-text-value-check-combo ${config.simple ? "bi-border-bottom" : "bi-border"}`, width: 100, height: 24, chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, @@ -64,9 +51,12 @@ export class TextValueCheckCombo extends Widget { this.textIconCheckCombo.hideView(); this.fireEvent(TextValueCheckCombo.EVENT_CHANGE); }); - this.popup.on(Controller.EVENT_CHANGE, ...args => { - this.fireEvent(Controller.EVENT_CHANGE, ...args); - }); + this.popup.on( + Controller.EVENT_CHANGE, + ...args => { + this.fireEvent(Controller.EVENT_CHANGE, ...args); + } + ); this.textIconCheckCombo = createWidget({ type: Combo.xtype, container: o.container, @@ -102,7 +92,7 @@ export class TextValueCheckCombo extends Widget { getValue() { const value = this.popup.getValue(); - + return isNull(value) ? [] : isArray(value) ? value : [value]; } diff --git a/src/case/combo/textvaluecheckcombo/popup.textvaluecheck.js b/src/case/combo/textvaluecheckcombo/popup.textvaluecheck.js index 9c32c2b68..6520d1099 100644 --- a/src/case/combo/textvaluecheckcombo/popup.textvaluecheck.js +++ b/src/case/combo/textvaluecheckcombo/popup.textvaluecheck.js @@ -1,12 +1,4 @@ -import { - shortcut, - extend, - createWidget, - Controller, - Events, - VerticalLayout, - map -} from "@/core"; +import { shortcut, extend, createWidget, Controller, Events, VerticalLayout, map } from "@/core"; import { Pane, ButtonGroup } from "@/base"; import { SingleSelectItem } from "../../button"; @@ -56,16 +48,18 @@ export class TextValueCheckComboPopup extends Pane { _formatItems(items) { const o = this.options; - - return map(items, (i, item) => extend( - { - type: SingleSelectItem.xtype, - cls: "bi-list-item", - textAlign: o.textAlign, - title: item.title || item.text, - }, - item - )); + + return map(items, (i, item) => + extend( + { + type: SingleSelectItem.xtype, + cls: "bi-list-item", + textAlign: o.textAlign, + title: item.title || item.text, + }, + item + ) + ); } populate(items) { diff --git a/src/case/combo/textvaluecombo/combo.textvalue.js b/src/case/combo/textvaluecombo/combo.textvalue.js index a9bf892b5..d6b307026 100644 --- a/src/case/combo/textvaluecombo/combo.textvalue.js +++ b/src/case/combo/textvaluecombo/combo.textvalue.js @@ -1,3 +1,4 @@ +import { TextValueComboPopup } from "./popup.textvalue"; import { shortcut, Widget, @@ -15,7 +16,6 @@ import { } from "@/core"; import { ButtonGroup, Combo } from "@/base"; import { SelectTextTrigger } from "../../trigger"; -import { TextValueComboPopup } from "./popup.textvalue"; @shortcut() export class TextValueCombo extends Widget { @@ -25,11 +25,7 @@ export class TextValueCombo extends Widget { _defaultConfig(config) { return extend(super._defaultConfig(...arguments), { - baseCls: - `bi-text-value-combo ${ - config.simple - ? "bi-border-bottom" - : "bi-border bi-border-radius"}`, + baseCls: `bi-text-value-combo ${config.simple ? "bi-border-bottom" : "bi-border bi-border-radius"}`, height: 24, chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE, text: "", @@ -47,13 +43,13 @@ export class TextValueCombo extends Widget { const o = this.options; o.value = isFunction(o.value) ? this.__watch(o.value, (context, newValue) => { - this.setValue(newValue); - }) + this.setValue(newValue); + }) : o.value; o.items = isFunction(o.items) ? this.__watch(o.items, (context, newValue) => { - this.populate(newValue); - }) + this.populate(newValue); + }) : o.items; super._init(...arguments); } @@ -71,7 +67,7 @@ export class TextValueCombo extends Widget { text: o.warningTitle, }; } - + return { level: "success", }; @@ -79,7 +75,7 @@ export class TextValueCombo extends Widget { const trigger = { type: SelectTextTrigger.xtype, - ref: ref => (this.trigger = ref), + ref: (ref) => (this.trigger = ref), cls: "text-value-trigger", items: o.items, height: toPix(o.height, o.simple ? 1 : 2), @@ -95,14 +91,14 @@ export class TextValueCombo extends Widget { this._clear(); this.fireEvent(TextValueCombo.EVENT_CHANGE); }, - } + }, ], ...o.el, }; let changeTag = false; const popup = { - type: "bi.text_value_combo_popup", - ref: ref => (this.popup = ref), + type: TextValueComboPopup.xtype, + ref: (ref) => (this.popup = ref), chooseType: o.chooseType, items: o.items, allowSelectAll: o.allowSelectAll, @@ -115,15 +111,9 @@ export class TextValueCombo extends Widget { this.setValue(value); if (o.chooseType === ButtonGroup.CHOOSE_TYPE_SINGLE) { this.combo.hideView(...args); - this.fireEvent( - TextValueCombo.EVENT_CHANGE, - ...args - ); + this.fireEvent(TextValueCombo.EVENT_CHANGE, ...args); } - if ( - o.chooseType === ButtonGroup.CHOOSE_TYPE_MULTI && - isEmptyArray(value) - ) { + if (o.chooseType === ButtonGroup.CHOOSE_TYPE_MULTI && isEmptyArray(value)) { this._clear(); } }, @@ -147,7 +137,7 @@ export class TextValueCombo extends Widget { action: (...args) => { this.combo.hideView(); }, - } + }, ], }; @@ -155,7 +145,7 @@ export class TextValueCombo extends Widget { type: Combo.xtype, height: toPix(o.height, 2), width: toPix(o.width, 2), - ref: ref => (this.combo = ref), + ref: (ref) => (this.combo = ref), container: o.container, direction: o.direction, adjustLength: 2, @@ -170,27 +160,17 @@ export class TextValueCombo extends Widget { { eventName: Combo.EVENT_AFTER_HIDEVIEW, action: (...args) => { - if ( - o.chooseType !== ButtonGroup.CHOOSE_TYPE_SINGLE && - changeTag - ) { - this.fireEvent( - TextValueCombo.EVENT_CHANGE, - ...args - ); + if (o.chooseType !== ButtonGroup.CHOOSE_TYPE_SINGLE && changeTag) { + this.fireEvent(TextValueCombo.EVENT_CHANGE, ...args); } }, - } + }, ], popup: { el: popup, value: o.value, maxHeight: 240, - minHeight: - o.chooseType === ButtonGroup.CHOOSE_TYPE_MULTI && - o.allowSelectAll - ? 55 - : 25, + minHeight: o.chooseType === ButtonGroup.CHOOSE_TYPE_MULTI && o.allowSelectAll ? 55 : 25, }, }; } @@ -211,7 +191,7 @@ export class TextValueCombo extends Widget { _checkError(v) { if (isNull(v)) { this.setStatus("success"); - + return; } @@ -247,7 +227,7 @@ export class TextValueCombo extends Widget { getValue() { const value = this.combo.getValue(); - + return isNull(value) ? [] : isArray(value) ? value : [value]; } diff --git a/src/case/combo/textvaluecombo/combo.textvaluesmall.js b/src/case/combo/textvaluecombo/combo.textvaluesmall.js index d531e1885..c6bfe6180 100644 --- a/src/case/combo/textvaluecombo/combo.textvaluesmall.js +++ b/src/case/combo/textvaluecombo/combo.textvaluesmall.js @@ -1,11 +1,7 @@ -import { - shortcut, - Widget, - extend -} from "@/core"; +import { TextValueCombo } from "./combo.textvalue"; +import { shortcut, Widget, extend } from "@/core"; import { ButtonGroup } from "@/base"; import { SmallSelectTextTrigger } from "../../trigger"; -import { TextValueCombo } from "./combo.textvalue"; @shortcut() export class SmallTextValueCombo extends Widget { @@ -25,10 +21,10 @@ export class SmallTextValueCombo extends Widget { render() { const o = this.options; - + return { - type: "bi.text_value_combo", - ref: _ref => { + type: TextValueCombo.xtype, + ref: (_ref) => { this.combo = _ref; }, height: o.height, @@ -47,12 +43,9 @@ export class SmallTextValueCombo extends Widget { { eventName: TextValueCombo.EVENT_CHANGE, action: (...args) => { - this.fireEvent( - SmallTextValueCombo.EVENT_CHANGE, - ...args - ); + this.fireEvent(SmallTextValueCombo.EVENT_CHANGE, ...args); }, - } + }, ], }; } diff --git a/src/case/combo/textvaluecombo/popup.textvalue.js b/src/case/combo/textvaluecombo/popup.textvalue.js index a9fa0caaf..b0b22a048 100644 --- a/src/case/combo/textvaluecombo/popup.textvalue.js +++ b/src/case/combo/textvaluecombo/popup.textvalue.js @@ -55,16 +55,9 @@ export class TextValueComboPopup extends Pane { { eventName: Controller.EVENT_CHANGE, action: (type, val, obj) => { - this.fireEvent( - Controller.EVENT_CHANGE, - arguments - ); + this.fireEvent(Controller.EVENT_CHANGE, arguments); if (type === Events.CLICK) { - this.fireEvent( - TextValueComboPopup.EVENT_CHANGE, - val, - obj - ); + this.fireEvent(TextValueComboPopup.EVENT_CHANGE, val, obj); } }, } @@ -73,7 +66,7 @@ export class TextValueComboPopup extends Pane { ], }; } - + return { type: VerticalLayout.xtype, verticalAlign: VerticalAlign.Stretch, @@ -104,11 +97,8 @@ export class TextValueComboPopup extends Pane { listeners: [ { eventName: SelectList.EVENT_CHANGE, - action (val) { - this.fireEvent( - TextValueComboPopup.EVENT_CHANGE, - val - ); + action(val) { + this.fireEvent(TextValueComboPopup.EVENT_CHANGE, val); }, } ], @@ -123,18 +113,14 @@ export class TextValueComboPopup extends Pane { type: TextButton.xtype, text: i18nText("BI-Basic_Clears"), handler: () => { - this.fireEvent( - TextValueComboPopup.EVENT_CLEAR - ); + this.fireEvent(TextValueComboPopup.EVENT_CLEAR); }, }, { type: TextButton.xtype, text: i18nText("BI-Basic_OK"), handler: () => { - this.fireEvent( - TextValueComboPopup.EVENT_CONFIRM - ); + this.fireEvent(TextValueComboPopup.EVENT_CONFIRM); }, } ], @@ -168,10 +154,7 @@ export class TextValueComboPopup extends Pane { { eventName: ListPane.EVENT_CHANGE, action: val => { - this.fireEvent( - TextValueComboPopup.EVENT_CHANGE, - val - ); + this.fireEvent(TextValueComboPopup.EVENT_CHANGE, val); }, } ], @@ -188,19 +171,19 @@ export class TextValueComboPopup extends Pane { _formatItems(items) { const o = this.options; - - return map(items, (i, item) => extend( - { - type: - o.chooseType !== ButtonGroup.CHOOSE_TYPE_MULTI - ? SingleSelectItem.xtype - : MultiSelectItem.xtype, - iconWrapperWidth: 36, - textAlign: o.textAlign, - title: item.title || item.text, - }, - item - )); + + return map(items, (i, item) => + extend( + { + type: + o.chooseType !== ButtonGroup.CHOOSE_TYPE_MULTI ? SingleSelectItem.xtype : MultiSelectItem.xtype, + iconWrapperWidth: 36, + textAlign: o.textAlign, + title: item.title || item.text, + }, + item + ) + ); } populate(items) { @@ -229,7 +212,7 @@ export class TextValueComboPopup extends Pane { } if (!this.options.allowSelectAll) { this.popup.setValue(v); - + return; } this.popup.setValue({ diff --git a/src/case/editor/editor.clear.js b/src/case/editor/editor.clear.js index c536e3ec1..a35a4302e 100644 --- a/src/case/editor/editor.clear.js +++ b/src/case/editor/editor.clear.js @@ -1,5 +1,16 @@ -import { shortcut, Widget, extend, emptyFn, isKey, isFunction, createWidget, Controller, Events } from "@/core"; import { Editor, IconButton } from "@/base"; +import { + HTapeLayout, + shortcut, + Widget, + extend, + emptyFn, + isKey, + isFunction, + createWidget, + Controller, + Events +} from "@/core"; /** * 有清除按钮的文本框 @@ -9,31 +20,31 @@ import { Editor, IconButton } from "@/base"; */ @shortcut() export class ClearEditor extends Widget { - static xtype = "bi.clear_editor" + static xtype = "bi.clear_editor"; - static EVENT_CHANGE = "EVENT_CHANGE" - static EVENT_FOCUS = "EVENT_FOCUS" - static EVENT_BLUR = "EVENT_BLUR" - static EVENT_CLICK = "EVENT_CLICK" - static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" - static EVENT_SPACE = "EVENT_SPACE" - static EVENT_BACKSPACE = "EVENT_BACKSPACE" - static EVENT_CLEAR = "EVENT_CLEAR" - static EVENT_START = "EVENT_START" - static EVENT_PAUSE = "EVENT_PAUSE" - static EVENT_STOP = "EVENT_STOP" - static EVENT_CONFIRM = "EVENT_CONFIRM" - static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM" - static EVENT_VALID = "EVENT_VALID" - static EVENT_ERROR = "EVENT_ERROR" - static EVENT_ENTER = "EVENT_ENTER" - static EVENT_RESTRICT = "EVENT_RESTRICT" - static EVENT_REMOVE = "EVENT_REMOVE" - static EVENT_EMPTY = "EVENT_EMPTY" + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_CLICK = "EVENT_CLICK"; + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; + static EVENT_SPACE = "EVENT_SPACE"; + static EVENT_BACKSPACE = "EVENT_BACKSPACE"; + static EVENT_CLEAR = "EVENT_CLEAR"; + static EVENT_START = "EVENT_START"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; + static EVENT_VALID = "EVENT_VALID"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_ENTER = "EVENT_ENTER"; + static EVENT_RESTRICT = "EVENT_RESTRICT"; + static EVENT_REMOVE = "EVENT_REMOVE"; + static EVENT_EMPTY = "EVENT_EMPTY"; _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: "bi-clear-editor", height: 24, @@ -46,12 +57,14 @@ export class ClearEditor extends Widget { _init() { const o = this.options; - o.value = isFunction(o.value) ? this.__watch(o.value, (context, newValue) => { - this.setValue(newValue); - }) : o.value; + o.value = isFunction(o.value) + ? this.__watch(o.value, (context, newValue) => { + this.setValue(newValue); + }) + : o.value; super._init(...arguments); this.editor = createWidget({ - type: "bi.editor", + type: Editor.xtype, simple: o.simple, height: o.height, watermark: o.watermark, @@ -63,7 +76,7 @@ export class ClearEditor extends Widget { autoTrim: o.autoTrim, }); this.clear = createWidget({ - type: "bi.icon_button", + type: IconButton.xtype, stopEvent: true, invisible: !isKey(o.value), cls: "search-close-h-font", @@ -75,14 +88,15 @@ export class ClearEditor extends Widget { }); createWidget({ element: this, - type: "bi.htape", - items: [{ - el: this.editor, - }, - { - el: this.clear, - width: 24, - } + type: HTapeLayout.xtype, + items: [ + { + el: this.editor, + }, + { + el: this.clear, + width: 24, + } ], }); this.editor.on(Controller.EVENT_CHANGE, (...args) => { @@ -112,7 +126,6 @@ export class ClearEditor extends Widget { this.fireEvent(ClearEditor.EVENT_BACKSPACE); }); - this.editor.on(Editor.EVENT_VALID, () => { this.fireEvent(ClearEditor.EVENT_VALID); }); diff --git a/src/case/editor/editor.defaulttext.js b/src/case/editor/editor.defaulttext.js index 7597347d7..d8db6f2da 100644 --- a/src/case/editor/editor.defaulttext.js +++ b/src/case/editor/editor.defaulttext.js @@ -1,6 +1,15 @@ - -import { shortcut, Widget, emptyFn, isKey, isFunction, createWidget, nextTick, Controller } from "@/core"; import { Editor, TextButton } from "@/base"; +import { + AbsoluteLayout, + shortcut, + Widget, + emptyFn, + isKey, + isFunction, + createWidget, + nextTick, + Controller +} from "@/core"; /** * dailer @@ -10,25 +19,25 @@ import { Editor, TextButton } from "@/base"; */ @shortcut() export class DefaultTextEditor extends Widget { - static xtype = "bi.default_text_editor" - - static EVENT_CHANGE = "EVENT_CHANGE" - static EVENT_FOCUS = "EVENT_FOCUS" - static EVENT_BLUR = "EVENT_BLUR" - static EVENT_CLICK = "EVENT_CLICK" - static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" - static EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL" - static EVENT_START = "EVENT_START" - static EVENT_PAUSE = "EVENT_PAUSE" - static EVENT_STOP = "EVENT_STOP" - static EVENT_CONFIRM = "EVENT_CONFIRM" - static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM" - static EVENT_VALID = "EVENT_VALID" - static EVENT_ERROR = "EVENT_ERROR" - static EVENT_ENTER = "EVENT_ENTER" - static EVENT_RESTRICT = "EVENT_RESTRICT" - static EVENT_SPACE = "EVENT_SPACE" - static EVENT_EMPTY = "EVENT_EMPTY" + static xtype = "bi.default_text_editor"; + + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_CLICK = "EVENT_CLICK"; + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; + static EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL"; + static EVENT_START = "EVENT_START"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; + static EVENT_VALID = "EVENT_VALID"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_ENTER = "EVENT_ENTER"; + static EVENT_RESTRICT = "EVENT_RESTRICT"; + static EVENT_SPACE = "EVENT_SPACE"; + static EVENT_EMPTY = "EVENT_EMPTY"; props() { return { @@ -54,7 +63,7 @@ export class DefaultTextEditor extends Widget { render() { const o = this.options; this.editor = createWidget(o.el, { - type: "bi.editor", + type: Editor.xtype, simple: o.simple, height: o.height, hgap: o.hgap, @@ -76,7 +85,7 @@ export class DefaultTextEditor extends Widget { const showText = isFunction(o.text) ? o.text() : o.text; this.text = createWidget({ - type: "bi.text_button", + type: TextButton.xtype, cls: isKey(showText) ? "tip-text-style" : "bi-water-mark tip-text-style", textAlign: "left", height: o.height, @@ -153,20 +162,23 @@ export class DefaultTextEditor extends Widget { }); return { - type: "bi.absolute", - items: [{ - el: this.editor, - left: 0, - right: 0, - top: 0, - bottom: 0, - }, { - el: this.text, - left: 0, - right: 0, - top: 0, - bottom: 0, - }], + type: AbsoluteLayout.xtype, + items: [ + { + el: this.editor, + left: 0, + right: 0, + top: 0, + bottom: 0, + }, + { + el: this.text, + left: 0, + right: 0, + top: 0, + bottom: 0, + } + ], }; } @@ -273,7 +285,7 @@ export class DefaultTextEditor extends Widget { if (isKey(v)) { this.text.setText(v); this.text.element.removeClass("bi-water-mark"); - + return; } this.text.setText(o.defaultText); diff --git a/src/case/editor/editor.shelter.js b/src/case/editor/editor.shelter.js index 7517c6320..054bb37b6 100644 --- a/src/case/editor/editor.shelter.js +++ b/src/case/editor/editor.shelter.js @@ -1,5 +1,17 @@ -import { shortcut, Widget, extend, emptyFn, isFunction, createWidget, Controller, isKey, nextTick, bind } from "@/core"; import { Editor, TextButton } from "@/base"; +import { + AbsoluteLayout, + shortcut, + Widget, + extend, + emptyFn, + isFunction, + createWidget, + Controller, + isKey, + nextTick, + bind +} from "@/core"; /** * 带标记的文本框 @@ -9,29 +21,29 @@ import { Editor, TextButton } from "@/base"; */ @shortcut() export class ShelterEditor extends Widget { - static xtype = "bi.shelter_editor" + static xtype = "bi.shelter_editor"; - static EVENT_CHANGE = "EVENT_CHANGE" - static EVENT_FOCUS = "EVENT_FOCUS" - static EVENT_BLUR = "EVENT_BLUR" - static EVENT_CLICK = "EVENT_CLICK" - static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" - static EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL" - static EVENT_START = "EVENT_START" - static EVENT_PAUSE = "EVENT_PAUSE" - static EVENT_STOP = "EVENT_STOP" - static EVENT_CONFIRM = "EVENT_CONFIRM" - static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM" - static EVENT_VALID = "EVENT_VALID" - static EVENT_ERROR = "EVENT_ERROR" - static EVENT_ENTER = "EVENT_ENTER" - static EVENT_RESTRICT = "EVENT_RESTRICT" - static EVENT_SPACE = "EVENT_SPACE" - static EVENT_EMPTY = "EVENT_EMPTY" + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_CLICK = "EVENT_CLICK"; + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; + static EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL"; + static EVENT_START = "EVENT_START"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; + static EVENT_VALID = "EVENT_VALID"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_ENTER = "EVENT_ENTER"; + static EVENT_RESTRICT = "EVENT_RESTRICT"; + static EVENT_SPACE = "EVENT_SPACE"; + static EVENT_EMPTY = "EVENT_EMPTY"; _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-shelter-editor`, hgap: 4, @@ -49,15 +61,17 @@ export class ShelterEditor extends Widget { textAlign: "left", }); } - + _init() { const o = this.options; - o.value = isFunction(o.value) ? this.__watch(o.value, (context, newValue) => { - this.setValue(newValue); - }) : o.value; + o.value = isFunction(o.value) + ? this.__watch(o.value, (context, newValue) => { + this.setValue(newValue); + }) + : o.value; super._init(...arguments); this.editor = createWidget({ - type: "bi.editor", + type: Editor.xtype, simple: o.simple, height: o.height, hgap: o.hgap, @@ -75,7 +89,7 @@ export class ShelterEditor extends Widget { autoTrim: o.autoTrim, }); this.text = createWidget({ - type: "bi.text_button", + type: TextButton.xtype, cls: "shelter-editor-text", title: o.title, warningTitle: o.warningTitle, @@ -149,131 +163,136 @@ export class ShelterEditor extends Widget { this.fireEvent(ShelterEditor.EVENT_EMPTY, ...args); }); createWidget({ - type: "bi.absolute", + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.text, - inset: 0, - }, { - el: this.editor, - inset: 0, - }], + items: [ + { + el: this.text, + inset: 0, + }, + { + el: this.editor, + inset: 0, + } + ], }); this._showHint(); this._checkText(); } - + _checkText() { const o = this.options; - nextTick(bind(function () { - if (this.editor.getValue() === "") { - this.text.setValue(o.watermark || ""); - this.text.element.addClass("bi-water-mark"); - } else { - this.text.setValue(this.editor.getValue()); - this.text.element.removeClass("bi-water-mark"); - } - isKey(o.keyword) && this.text.doRedMark(o.keyword); - }, this)); + nextTick( + bind(function () { + if (this.editor.getValue() === "") { + this.text.setValue(o.watermark || ""); + this.text.element.addClass("bi-water-mark"); + } else { + this.text.setValue(this.editor.getValue()); + this.text.element.removeClass("bi-water-mark"); + } + isKey(o.keyword) && this.text.doRedMark(o.keyword); + }, this) + ); } - + _showInput() { this.editor.visible(); this.text.invisible(); } - + _showHint() { this.editor.invisible(); this.text.visible(); } - + setWaterMark(v) { this.options.watermark = v; this.editor.setWaterMark(v); } - + setTitle(title) { this.text.setTitle(title); } - + setWarningTitle(title) { this.text.setWarningTitle(title); } - + focus() { this._showInput(); this.editor.focus(); } - + blur() { this.editor.blur(); this._showHint(); this._checkText(); } - + doRedMark() { if (this.editor.getValue() === "" && isKey(this.options.watermark)) { return; } this.text.doRedMark(...arguments); } - + unRedMark() { this.text.unRedMark(...arguments); } - + doHighLight() { if (this.editor.getValue() === "" && isKey(this.options.watermark)) { return; } this.text.doHighLight(...arguments); } - + unHighLight() { this.text.unHighLight(...arguments); } - + isValid() { return this.editor.isValid(); } - + setErrorText(text) { this.editor.setErrorText(text); } - + getErrorText() { return this.editor.getErrorText(); } - + isEditing() { return this.editor.isEditing(); } - + getLastValidValue() { return this.editor.getLastValidValue(); } - + getLastChangedValue() { return this.editor.getLastChangedValue(); } - + setTextStyle(style) { this.text.setStyle(style); } - + setValue(k) { this.editor.setValue(k); this._checkText(); } - + getValue() { return this.editor.getValue(); } - + getState() { return this.text.getValue(); } - + setState(v) { this._showHint(); this.text.setValue(v); diff --git a/src/case/editor/editor.sign.js b/src/case/editor/editor.sign.js index 08feca088..f5b4712b4 100644 --- a/src/case/editor/editor.sign.js +++ b/src/case/editor/editor.sign.js @@ -1,5 +1,17 @@ -import { shortcut, Widget, extend, emptyFn, isFunction, createWidget, nextTick, isKey, bind, Controller } from "@/core"; import { Editor, TextButton } from "@/base"; +import { + AbsoluteLayout, + shortcut, + Widget, + extend, + emptyFn, + isFunction, + createWidget, + nextTick, + isKey, + bind, + Controller +} from "@/core"; /** * 带标记的文本框 @@ -9,30 +21,30 @@ import { Editor, TextButton } from "@/base"; */ @shortcut() export class SignEditor extends Widget { - static xtype = "bi.sign_editor" + static xtype = "bi.sign_editor"; - static EVENT_CHANGE = "EVENT_CHANGE" - static EVENT_FOCUS = "EVENT_FOCUS" - static EVENT_BLUR = "EVENT_BLUR" - static EVENT_CLICK = "EVENT_CLICK" - static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" - static EVENT_QUICK_DOWN = "EVENT_QUICK_DOWN" - static EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL" - static EVENT_START = "EVENT_START" - static EVENT_PAUSE = "EVENT_PAUSE" - static EVENT_STOP = "EVENT_STOP" - static EVENT_CONFIRM = "EVENT_CONFIRM" - static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM" - static EVENT_VALID = "EVENT_VALID" - static EVENT_ERROR = "EVENT_ERROR" - static EVENT_ENTER = "EVENT_ENTER" - static EVENT_RESTRICT = "EVENT_RESTRICT" - static EVENT_SPACE = "EVENT_SPACE" - static EVENT_EMPTY = "EVENT_EMPTY" + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_CLICK = "EVENT_CLICK"; + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; + static EVENT_QUICK_DOWN = "EVENT_QUICK_DOWN"; + static EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL"; + static EVENT_START = "EVENT_START"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; + static EVENT_VALID = "EVENT_VALID"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_ENTER = "EVENT_ENTER"; + static EVENT_RESTRICT = "EVENT_RESTRICT"; + static EVENT_SPACE = "EVENT_SPACE"; + static EVENT_EMPTY = "EVENT_EMPTY"; _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-sign-editor`, hgap: 4, @@ -53,12 +65,14 @@ export class SignEditor extends Widget { _init() { const o = this.options; - o.value = isFunction(o.value) ? this.__watch(o.value, (context, newValue) => { - this.setValue(newValue); - }) : o.value; + o.value = isFunction(o.value) + ? this.__watch(o.value, (context, newValue) => { + this.setValue(newValue); + }) + : o.value; super._init(...arguments); this.editor = createWidget({ - type: "bi.editor", + type: Editor.xtype, simple: o.simple, height: o.height, hgap: o.hgap, @@ -76,7 +90,7 @@ export class SignEditor extends Widget { autoTrim: o.autoTrim, }); this.text = createWidget({ - type: "bi.text_button", + type: TextButton.xtype, cls: "sign-editor-text", title: o.title, warningTitle: o.warningTitle, @@ -156,15 +170,18 @@ export class SignEditor extends Widget { this.fireEvent(SignEditor.EVENT_EMPTY, ...args); }); createWidget({ - type: "bi.absolute", + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.text, - inset: 0, - }, { - el: this.editor, - inset: 0, - }], + items: [ + { + el: this.text, + inset: 0, + }, + { + el: this.editor, + inset: 0, + } + ], }); this._showHint(); this._checkText(); @@ -172,16 +189,18 @@ export class SignEditor extends Widget { _checkText() { const o = this.options; - nextTick(bind(function () { - if (this.editor.getValue() === "") { - this.text.setValue(o.watermark || ""); - this.text.element.addClass("bi-water-mark"); - } else { - this.text.setValue(this.editor.getValue()); - this.text.element.removeClass("bi-water-mark"); - isKey(o.keyword) && this.text.doRedMark(o.keyword); - } - }, this)); + nextTick( + bind(function () { + if (this.editor.getValue() === "") { + this.text.setValue(o.watermark || ""); + this.text.element.addClass("bi-water-mark"); + } else { + this.text.setValue(this.editor.getValue()); + this.text.element.removeClass("bi-water-mark"); + isKey(o.keyword) && this.text.doRedMark(o.keyword); + } + }, this) + ); } _showInput() { @@ -256,7 +275,7 @@ export class SignEditor extends Widget { getErrorText() { return this.editor.getErrorText(); } - + isEditing() { return this.editor.isEditing(); } diff --git a/src/case/editor/editor.state.js b/src/case/editor/editor.state.js index d11dc059d..09625729c 100644 --- a/src/case/editor/editor.state.js +++ b/src/case/editor/editor.state.js @@ -1,5 +1,22 @@ -import { shortcut, Widget, extend, emptyFn, i18nText, isArray, createWidget, nextTick, Controller, isNotNull, isString, isKey, isFunction, isNumber, isEmpty } from "@/core"; -import { TextButton, Editor } from "@/base"; +import { Editor, TextButton } from "@/base"; +import { + AbsoluteLayout, + shortcut, + Widget, + extend, + emptyFn, + i18nText, + isArray, + createWidget, + nextTick, + Controller, + isNotNull, + isString, + isKey, + isFunction, + isNumber, + isEmpty +} from "@/core"; /** * guy @@ -9,29 +26,29 @@ import { TextButton, Editor } from "@/base"; */ @shortcut() export class StateEditor extends Widget { - static xtype = "bi.state_editor" + static xtype = "bi.state_editor"; - static EVENT_CHANGE = "EVENT_CHANGE" - static EVENT_FOCUS = "EVENT_FOCUS" - static EVENT_BLUR = "EVENT_BLUR" - static EVENT_CLICK = "EVENT_CLICK" - static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" - static EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL" - static EVENT_START = "EVENT_START" - static EVENT_PAUSE = "EVENT_PAUSE" - static EVENT_STOP = "EVENT_STOP" - static EVENT_CONFIRM = "EVENT_CONFIRM" - static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM" - static EVENT_VALID = "EVENT_VALID" - static EVENT_ERROR = "EVENT_ERROR" - static EVENT_ENTER = "EVENT_ENTER" - static EVENT_RESTRICT = "EVENT_RESTRICT" - static EVENT_SPACE = "EVENT_SPACE" - static EVENT_EMPTY = "EVENT_EMPTY" + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_CLICK = "EVENT_CLICK"; + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; + static EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL"; + static EVENT_START = "EVENT_START"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; + static EVENT_VALID = "EVENT_VALID"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_ENTER = "EVENT_ENTER"; + static EVENT_RESTRICT = "EVENT_RESTRICT"; + static EVENT_SPACE = "EVENT_SPACE"; + static EVENT_EMPTY = "EVENT_EMPTY"; _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-state-editor`, hgap: 4, @@ -51,12 +68,12 @@ export class StateEditor extends Widget { el: {}, }); } - + _init() { super._init(...arguments); const o = this.options; this.editor = createWidget(o.el, { - type: "bi.editor", + type: Editor.xtype, simple: o.simple, height: o.height, hgap: o.hgap, @@ -74,7 +91,7 @@ export class StateEditor extends Widget { autoTrim: o.autoTrim, }); this.text = createWidget({ - type: "bi.text_button", + type: TextButton.xtype, cls: "bi-water-mark tip-text-style", textAlign: "left", height: o.height, @@ -85,17 +102,19 @@ export class StateEditor extends Widget { this.editor.focus(); this.editor.setValue(""); }, - title: isNotNull(o.tipText) ? o.tipText : () => { - let title = ""; - if (isString(this.stateValue)) { - title = this.stateValue; - } - if (isArray(this.stateValue) && this.stateValue.length === 1) { - title = this.stateValue[0]; - } - - return title; - }, + title: isNotNull(o.tipText) + ? o.tipText + : () => { + let title = ""; + if (isString(this.stateValue)) { + title = this.stateValue; + } + if (isArray(this.stateValue) && this.stateValue.length === 1) { + title = this.stateValue[0]; + } + + return title; + }, warningTitle: o.warningTitle, tipType: o.tipType, }); @@ -159,112 +178,115 @@ export class StateEditor extends Widget { this.fireEvent(StateEditor.EVENT_EMPTY, ...args); }); createWidget({ - type: "bi.absolute", + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.text, - inset: 0, - }, { - el: this.editor, - inset: 0, - }], + items: [ + { + el: this.text, + inset: 0, + }, + { + el: this.editor, + inset: 0, + } + ], }); this._showHint(); if (isNotNull(o.text)) { this.setState(o.text); } } - + setWaterMark(v) { this.options.watermark = v; this.editor.setWaterMark(v); } - + doRedMark() { if (this.editor.getValue() === "" && isKey(this.options.watermark)) { return; } this.text.doRedMark(...arguments); } - + unRedMark() { this.text.unRedMark(...arguments); } - + doHighLight() { if (this.editor.getValue() === "" && isKey(this.options.watermark)) { return; } this.text.doHighLight(...arguments); } - + unHighLight() { this.text.unHighLight(...arguments); } - + focus() { if (this.options.disabled === false) { this._showInput(); this.editor.focus(); } } - + blur() { this.editor.blur(); this._showHint(); } - + _showInput() { this.editor.visible(); this.text.invisible(); } - + _showHint() { this.editor.invisible(); this.text.visible(); } - + _setText(v) { this.text.setText(v); this.text.setTitle(v); } - + isValid() { return this.editor.isValid(); } - + setErrorText(text) { this.editor.setErrorText(text); } - + getErrorText() { return this.editor.getErrorText(); } - + isEditing() { return this.editor.isEditing(); } - + getLastValidValue() { return this.editor.getLastValidValue(); } - + getLastChangedValue() { return this.editor.getLastChangedValue(); } - + setValue(k) { this.editor.setValue(k); } - + getValue() { return this.editor.getValue(); } - + getState() { return this.editor.getValue().match(/[^\s]+/g); } - + setState(v) { const o = this.options; const defaultText = isFunction(o.defaultText) ? o.defaultText() : o.defaultText; @@ -279,22 +301,28 @@ export class StateEditor extends Widget { this.text.element.removeClass("bi-water-mark"); } else { this._setText(isKey(defaultText) ? defaultText : o.text); - isKey(defaultText) ? this.text.element.addClass("bi-water-mark") : this.text.element.removeClass("bi-water-mark"); + isKey(defaultText) + ? this.text.element.addClass("bi-water-mark") + : this.text.element.removeClass("bi-water-mark"); } - + return; } if (isString(v)) { this._setText(v); // 配置了defaultText才判断标灰,其他情况不标灰 - (isKey(defaultText) && defaultText === v) ? this.text.element.addClass("bi-water-mark") : this.text.element.removeClass("bi-water-mark"); - + isKey(defaultText) && defaultText === v + ? this.text.element.addClass("bi-water-mark") + : this.text.element.removeClass("bi-water-mark"); + return; } if (isArray(v)) { if (isEmpty(v)) { this._setText(isKey(defaultText) ? defaultText : o.text); - isKey(defaultText) ? this.text.element.addClass("bi-water-mark") : this.text.element.removeClass("bi-water-mark"); + isKey(defaultText) + ? this.text.element.addClass("bi-water-mark") + : this.text.element.removeClass("bi-water-mark"); } else if (v.length === 1) { this._setText(v[0]); this.text.element.removeClass("bi-water-mark"); @@ -304,11 +332,11 @@ export class StateEditor extends Widget { } } } - + setTipType(v) { this.text.options.tipType = v; } - + getText() { return this.text.getText(); } diff --git a/src/case/editor/editor.state.simple.js b/src/case/editor/editor.state.simple.js index 807a8c158..8175c5083 100644 --- a/src/case/editor/editor.state.simple.js +++ b/src/case/editor/editor.state.simple.js @@ -1,5 +1,22 @@ -import { shortcut, Widget, extend, emptyFn, i18nText, Controller, createWidget, nextTick, isNotNull, isKey, isFunction, isArray, isNumber, isEmpty } from "@/core"; import { Editor, TextButton } from "@/base"; +import { + AbsoluteLayout, + VerticalLayout, + shortcut, + Widget, + extend, + emptyFn, + i18nText, + Controller, + createWidget, + nextTick, + isNotNull, + isKey, + isFunction, + isArray, + isNumber, + isEmpty +} from "@/core"; /** * 无限制-已选择状态输入框 @@ -9,29 +26,29 @@ import { Editor, TextButton } from "@/base"; */ @shortcut() export class SimpleStateEditor extends Widget { - static xtype = "bi.simple_state_editor" + static xtype = "bi.simple_state_editor"; - static EVENT_CHANGE = "EVENT_CHANGE" - static EVENT_FOCUS = "EVENT_FOCUS" - static EVENT_BLUR = "EVENT_BLUR" - static EVENT_CLICK = "EVENT_CLICK" - static EVENT_KEY_DOWN = "EVENT_KEY_DOWN" - static EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL" - static EVENT_START = "EVENT_START" - static EVENT_PAUSE = "EVENT_PAUSE" - static EVENT_STOP = "EVENT_STOP" - static EVENT_CONFIRM = "EVENT_CONFIRM" - static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM" - static EVENT_VALID = "EVENT_VALID" - static EVENT_ERROR = "EVENT_ERROR" - static EVENT_ENTER = "EVENT_ENTER" - static EVENT_RESTRICT = "EVENT_RESTRICT" - static EVENT_SPACE = "EVENT_SPACE" - static EVENT_EMPTY = "EVENT_EMPTY" + static EVENT_CHANGE = "EVENT_CHANGE"; + static EVENT_FOCUS = "EVENT_FOCUS"; + static EVENT_BLUR = "EVENT_BLUR"; + static EVENT_CLICK = "EVENT_CLICK"; + static EVENT_KEY_DOWN = "EVENT_KEY_DOWN"; + static EVENT_CLICK_LABEL = "EVENT_CLICK_LABEL"; + static EVENT_START = "EVENT_START"; + static EVENT_PAUSE = "EVENT_PAUSE"; + static EVENT_STOP = "EVENT_STOP"; + static EVENT_CONFIRM = "EVENT_CONFIRM"; + static EVENT_CHANGE_CONFIRM = "EVENT_CHANGE_CONFIRM"; + static EVENT_VALID = "EVENT_VALID"; + static EVENT_ERROR = "EVENT_ERROR"; + static EVENT_ENTER = "EVENT_ENTER"; + static EVENT_RESTRICT = "EVENT_RESTRICT"; + static EVENT_SPACE = "EVENT_SPACE"; + static EVENT_EMPTY = "EVENT_EMPTY"; _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-simple-state-editor`, hgap: 4, @@ -56,7 +73,7 @@ export class SimpleStateEditor extends Widget { super._init(...arguments); const o = this.options; this.editor = createWidget({ - type: "bi.editor", + type: Editor.xtype, simple: o.simple, height: o.height, hgap: o.hgap, @@ -74,7 +91,7 @@ export class SimpleStateEditor extends Widget { autoTrim: o.autoTrim, }); this.text = createWidget({ - type: "bi.text_button", + type: TextButton.xtype, cls: "bi-water-mark", textAlign: "left", text: o.text, @@ -92,15 +109,17 @@ export class SimpleStateEditor extends Widget { }); }); createWidget({ - type: "bi.absolute", + type: AbsoluteLayout.xtype, element: this, - items: [{ - el: this.text, - left: 0, - right: 0, - top: 0, - bottom: 0, - }], + items: [ + { + el: this.text, + left: 0, + right: 0, + top: 0, + bottom: 0, + } + ], }); this.editor.on(Controller.EVENT_CHANGE, (...args) => { this.fireEvent(Controller.EVENT_CHANGE, ...args); @@ -157,7 +176,7 @@ export class SimpleStateEditor extends Widget { this.fireEvent(SimpleStateEditor.EVENT_EMPTY, ...args); }); createWidget({ - type: "bi.vertical", + type: VerticalLayout.xtype, scrolly: false, element: this, items: [this.editor], @@ -271,7 +290,7 @@ export class SimpleStateEditor extends Widget { this._setText(isKey(defaultText) ? defaultText : o.text); this.text.element.addClass("bi-water-mark"); } - + return; } if (!isArray(v) || v.length === 1) { diff --git a/src/case/layer/index.js b/src/case/layer/index.js index 73a7ea575..2737f6b07 100644 --- a/src/case/layer/index.js +++ b/src/case/layer/index.js @@ -1,4 +1,4 @@ -export { MultiPopupView } from "./layer.multipopup"; -export { PopupPanel } from "./layer.panel"; -export { ListPane } from "./pane.list"; -export { Panel } from "./panel"; +export { MultiPopupView } from "./layer.multipopup"; +export { PopupPanel } from "./layer.panel"; +export { ListPane } from "./pane.list"; +export { Panel } from "./panel"; diff --git a/src/case/layer/layer.multipopup.js b/src/case/layer/layer.multipopup.js index d531f57c7..cf0e2a5a5 100644 --- a/src/case/layer/layer.multipopup.js +++ b/src/case/layer/layer.multipopup.js @@ -1,26 +1,27 @@ +import { ButtonGroup, TextButton, PopupView } from "@/base"; +import { CenterLayout, shortcut, extend, i18nText, each, createWidget, createItems } from "@/core"; + /** * 下拉框弹出层的多选版本,toolbar带有若干按钮, zIndex在1000w * @class BI.MultiPopupView * @extends BI.Widget */ -import { shortcut, extend, i18nText, each, createWidget, createItems } from "@/core"; -import { PopupView, ButtonGroup } from "@/base"; @shortcut() export class MultiPopupView extends PopupView { static xtype = "bi.multi_popup_view"; static EVENT_CHANGE = "EVENT_CHANGE"; static EVENT_CLICK_TOOLBAR_BUTTON = "EVENT_CLICK_TOOLBAR_BUTTON"; - _defaultConfig () { + _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { _baseCls: `${conf._baseCls || ""} bi-multi-list-view`, buttons: [i18nText("BI-Basic_OK")], }); } - _createToolBar () { + _createToolBar() { const o = this.options; if (o.buttons.length === 0) { return; @@ -35,20 +36,22 @@ export class MultiPopupView extends PopupView { }); this.buttongroup = createWidget({ - type: "bi.button_group", + type: ButtonGroup.xtype, cls: "list-view-toolbar bi-high-light bi-split-top", height: BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT, items: createItems(text, { - type: "bi.text_button", + type: TextButton.xtype, once: false, shadow: true, isShadowShowingOnSelected: true, }), - layouts: [{ - type: "bi.center", - hgap: 0, - vgap: 0, - }], + layouts: [ + { + type: CenterLayout.xtype, + hgap: 0, + vgap: 0, + } + ], }); this.buttongroup.on(ButtonGroup.EVENT_CHANGE, (value, obj) => { diff --git a/src/case/layer/layer.panel.js b/src/case/layer/layer.panel.js index cc5701e61..386186025 100644 --- a/src/case/layer/layer.panel.js +++ b/src/case/layer/layer.panel.js @@ -1,31 +1,32 @@ +import { IconButton, Label } from "@/base"; +import { HTapeLayout, shortcut, extend, createWidget } from "@/core"; +import { MultiPopupView } from "./layer.multipopup"; + /** * 可以理解为MultiPopupView和Panel两个面板的结合体 * @class BI.PopupPanel * @extends BI.MultiPopupView */ -import { shortcut, extend, createWidget } from "@/core"; -import { IconButton } from "@/base"; -import { MultiPopupView } from "./layer.multipopup"; @shortcut() export class PopupPanel extends MultiPopupView { static xtype = "bi.popup_panel"; static EVENT_CHANGE = "EVENT_CHANGE"; static EVENT_CLOSE = "EVENT_CLOSE"; static EVENT_CLICK_TOOLBAR_BUTTON = "EVENT_CLICK_TOOLBAR_BUTTON"; - _defaultConfig () { + _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-popup-panel`, title: "", }); } - _createTool () { + _createTool() { const o = this.options; const close = createWidget({ - type: "bi.icon_button", + type: IconButton.xtype, cls: "close-h-font", width: 25, height: 25, @@ -34,23 +35,26 @@ export class PopupPanel extends MultiPopupView { this.setVisible(false); this.fireEvent(PopupPanel.EVENT_CLOSE); }); - + return createWidget({ - type: "bi.htape", + type: HTapeLayout.xtype, cls: "popup-panel-title bi-header-background", height: 25, - items: [{ - el: { - type: "bi.label", - textAlign: "left", - text: o.title, - height: 25, - lgap: 10, + items: [ + { + el: { + type: Label.xtype, + textAlign: "left", + text: o.title, + height: 25, + lgap: 10, + }, }, - }, { - el: close, - width: 25, - }], + { + el: close, + width: 25, + } + ], }); } } diff --git a/src/case/layer/pane.list.js b/src/case/layer/pane.list.js index 70d79c4f0..d70eaebc3 100644 --- a/src/case/layer/pane.list.js +++ b/src/case/layer/pane.list.js @@ -1,10 +1,3 @@ -/** - * list面板 - * - * Created by GUY on 2015/10/30. - * @class BI.ListPane - * @extends BI.Pane - */ import { shortcut, extend, @@ -27,6 +20,14 @@ import { } from "@/core"; import { Pane, ButtonGroup } from "@/base"; +/** + * list面板 + * + * Created by GUY on 2015/10/30. + * @class BI.ListPane + * @extends BI.Pane + */ + @shortcut() export class ListPane extends Pane { static xtype = "bi.list_pane"; @@ -102,19 +103,31 @@ export class ListPane extends Pane { }); this.check(); - createWidget(extend({ - element: this, - }, LogicFactory.createLogic(LogicFactory.createLogicTypeByDirection(Direction.Top), extend({ - scrolly: true, - lgap: o.lgap, - rgap: o.rgap, - tgap: o.tgap, - bgap: o.bgap, - vgap: o.vgap, - hgap: o.hgap, - }, o.logic, { - items: LogicFactory.createLogicItemsByDirection(Direction.Top, this.button_group), - })))); + createWidget( + extend( + { + element: this, + }, + LogicFactory.createLogic( + LogicFactory.createLogicTypeByDirection(Direction.Top), + extend( + { + scrolly: true, + lgap: o.lgap, + rgap: o.rgap, + tgap: o.tgap, + bgap: o.bgap, + vgap: o.vgap, + hgap: o.hgap, + }, + o.logic, + { + items: LogicFactory.createLogicItemsByDirection(Direction.Top, this.button_group), + } + ) + ) + ) + ); } hasPrev() { @@ -146,9 +159,11 @@ export class ListPane extends Pane { populate(items) { const o = this.options; - if (arguments.length === 0 && (isFunction(this.button_group.attr("itemsCreator")))) {// 接管loader的populate方法 + if (arguments.length === 0 && isFunction(this.button_group.attr("itemsCreator"))) { + // 接管loader的populate方法 this.button_group.attr("itemsCreator").apply(this, [ - { times: 1 }, (...args) => { + { times: 1 }, + (...args) => { if (args.length === 0) { throw new Error("参数不能为空"); } @@ -229,4 +244,3 @@ export class ListPane extends Pane { return this.button_group.getNodeByValue(value); } } - diff --git a/src/case/layer/panel.js b/src/case/layer/panel.js index de18dc35f..2ce1be1ac 100644 --- a/src/case/layer/panel.js +++ b/src/case/layer/panel.js @@ -1,15 +1,21 @@ - -import { shortcut, Widget, extend, toPix, Controller, createWidget } from "@/core"; -import { ButtonGroup } from "@/base"; +import { + VerticalFillLayout, + CenterAdaptLayout, + LeftRightVerticalAdaptLayout, + shortcut, + Widget, + extend, + toPix, + Controller, + createWidget +} from "@/core"; +import { Label, ButtonGroup } from "@/base"; @shortcut() export class Panel extends Widget { - static xtype = "bi.panel" - - - - static EVENT_CHANGE = "EVENT_CHANGE" + static xtype = "bi.panel"; + static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { return extend(super._defaultConfig(...arguments), { @@ -26,7 +32,7 @@ export class Panel extends Widget { render() { return { - type: "bi.vertical_fill", + type: VerticalFillLayout.xtype, rowSize: ["", "fill"], items: [this._createTitle(), this.options.el], }; @@ -35,19 +41,21 @@ export class Panel extends Widget { _createTitle() { const o = this.options; this.text = createWidget({ - type: "bi.label", + type: Label.xtype, cls: "panel-title-text", text: o.title, height: o.titleHeight, }); this.button_group = createWidget({ - type: "bi.button_group", + type: ButtonGroup.xtype, items: o.titleButtons, - layouts: [{ - type: "bi.center_adapt", - lgap: 10, - }], + layouts: [ + { + type: CenterAdaptLayout.xtype, + lgap: 10, + } + ], }); this.button_group.on(Controller.EVENT_CHANGE, (...args) => { @@ -60,7 +68,7 @@ export class Panel extends Widget { return { // el: { - type: "bi.left_right_vertical_adapt", + type: LeftRightVerticalAdaptLayout.xtype, cls: "panel-title bi-header-background bi-border-bottom", height: toPix(o.titleHeight, 1), items: { diff --git a/src/case/linearsegment/button.linear.segment.js b/src/case/linearsegment/button.linear.segment.js index 11c2b20b5..44316cb76 100644 --- a/src/case/linearsegment/button.linear.segment.js +++ b/src/case/linearsegment/button.linear.segment.js @@ -1,47 +1,55 @@ - -import { shortcut, toPix } from "@/core"; -import { BasicButton } from "@/base"; +import { Label, BasicButton } from "@/base"; +import { AbsoluteLayout, Layout, shortcut, toPix } from "@/core"; @shortcut() export class LinearSegmentButton extends BasicButton { - static xtype = "bi.linear_segment_button" - - props = { extraCls:"bi-line-segment-button bi-list-item-effect", once:true, readonly:true, hgap:10, height:24 }; - + static xtype = "bi.linear_segment_button"; + props = { + extraCls: "bi-line-segment-button bi-list-item-effect", + once: true, + readonly: true, + hgap: 10, + height: 24, + }; - render () { + render() { const o = this.options; - return [{ - type: "bi.label", - text: o.text, - height: o.height, - textHeight: toPix(o.height, 2), - value: o.value, - hgap: o.hgap, - ref : _ref => { - this.text = _ref; - }, - }, { - type: "bi.absolute", - items: [{ - el: { - type: "bi.layout", - cls: "line-segment-button-line", - height: 2, - ref : _ref => { - this.line = _ref; - }, + return [ + { + type: Label.xtype, + text: o.text, + height: o.height, + textHeight: toPix(o.height, 2), + value: o.value, + hgap: o.hgap, + ref: _ref => { + this.text = _ref; }, - left: 0, - right: 0, - bottom: 0, - }], - }]; + }, + { + type: AbsoluteLayout.xtype, + items: [ + { + el: { + type: Layout.xtype, + cls: "line-segment-button-line", + height: 2, + ref: _ref => { + this.line = _ref; + }, + }, + left: 0, + right: 0, + bottom: 0, + } + ], + } + ]; } - setSelected (v) { + setSelected(v) { super.setSelected(...arguments); if (v) { this.line.element.addClass("bi-high-light-background"); @@ -50,7 +58,7 @@ export class LinearSegmentButton extends BasicButton { } } - setText (text) { + setText(text) { this.text.setText(text); } } diff --git a/src/case/linearsegment/index.js b/src/case/linearsegment/index.js index bf437ca2b..339335d84 100644 --- a/src/case/linearsegment/index.js +++ b/src/case/linearsegment/index.js @@ -1,2 +1,2 @@ -export { LinearSegmentButton } from "./button.linear.segment"; -export { LinearSegment } from "./linear.segment"; +export { LinearSegmentButton } from "./button.linear.segment"; +export { LinearSegment } from "./linear.segment"; diff --git a/src/case/linearsegment/linear.segment.js b/src/case/linearsegment/linear.segment.js index c44265704..98c5a5bb8 100644 --- a/src/case/linearsegment/linear.segment.js +++ b/src/case/linearsegment/linear.segment.js @@ -1,62 +1,70 @@ - -import { shortcut, Widget, createItems, makeArrayByArray } from "@/core"; +import { ButtonGroup } from "@/base"; +import { LinearSegmentButton } from "./button.linear.segment"; +import { TableLayout, shortcut, Widget, createItems, makeArrayByArray } from "@/core"; @shortcut() export class LinearSegment extends Widget { - static xtype = "bi.linear_segment" - - props = { baseCls:"bi-linear-segment", items:[], height:30 }; + static xtype = "bi.linear_segment"; + props = { baseCls: "bi-linear-segment", items: [], height: 30 }; - - render () { + render() { const o = this.options; - + return { - type: "bi.button_group", - items: [createItems(o.items, { - type: "bi.linear_segment_button", - height: o.height, - })], - layouts: [{ - type: "bi.table", - columnSize: makeArrayByArray(o.items, "fill"), - }], + type: ButtonGroup.xtype, + items: [ + createItems(o.items, { + type: LinearSegmentButton.xtype, + height: o.height, + }) + ], + layouts: [ + { + type: TableLayout.xtype, + columnSize: makeArrayByArray(o.items, "fill"), + } + ], value: o.value, - listeners: [{ - eventName: "__EVENT_CHANGE__", - action: (...args) => { - this.fireEvent("__EVENT_CHANGE__", ...args); - }, - }, { - eventName: "EVENT_CHANGE", - action: () => { - this.fireEvent("EVENT_CHANGE"); + listeners: [ + { + eventName: "__EVENT_CHANGE__", + action: (...args) => { + this.fireEvent("__EVENT_CHANGE__", ...args); + }, }, - }], + { + eventName: "EVENT_CHANGE", + action: () => { + this.fireEvent("EVENT_CHANGE"); + }, + } + ], ref: _ref => { this.buttonGroup = _ref; }, }; } - setValue (v) { + setValue(v) { this.buttonGroup.setValue(v); } - setEnabledValue (v) { + setEnabledValue(v) { this.buttonGroup.setEnabledValue(v); } - getValue () { + getValue() { return this.buttonGroup.getValue(); } - populate (buttons) { + populate(buttons) { const o = this.options; - this.buttonGroup.populate([createItems(buttons, { - type: "bi.linear_segment_button", - height: o.height, - })]); + this.buttonGroup.populate([ + createItems(buttons, { + type: LinearSegmentButton.xtype, + height: o.height, + }) + ]); } } diff --git a/src/case/list/list.select.js b/src/case/list/list.select.js index 9c5896a30..4301aff57 100644 --- a/src/case/list/list.select.js +++ b/src/case/list/list.select.js @@ -1,5 +1,3 @@ -/* eslint-disable no-mixed-spaces-and-tabs */ - import { shortcut, Widget, @@ -21,6 +19,8 @@ import { ButtonGroup } from "@/base"; import { MultiSelectBar } from "../toolbar/toolbar.multiselect"; import { ListPane } from "../layer/pane.list"; +/* eslint-disable no-mixed-spaces-and-tabs */ + @shortcut() export class SelectList extends Widget { static xtype = "bi.select_list"; @@ -94,13 +94,25 @@ export class SelectList extends Widget { this.fireEvent(Controller.EVENT_CHANGE, ...args); }); - createWidget(extend({ - element: this, - }, LogicFactory.createLogic(LogicFactory.createLogicTypeByDirection(o.direction), extend({ - scrolly: true, - }, o.logic, { - items: LogicFactory.createLogicItemsByDirection(o.direction, this.toolbar, this.list), - })))); + createWidget( + extend( + { + element: this, + }, + LogicFactory.createLogic( + LogicFactory.createLogicTypeByDirection(o.direction), + extend( + { + scrolly: true, + }, + o.logic, + { + items: LogicFactory.createLogicItemsByDirection(o.direction, this.toolbar, this.list), + } + ) + ) + ) + ); if (o.items.length <= 0) { this.toolbar.setVisible(false); @@ -214,8 +226,9 @@ export class SelectList extends Widget { resetHeight(h) { const toolHeight = (this.toolbar.element.outerHeight() || 25) * (this.toolbar.isVisible() ? 1 : 0); - this.list.resetHeight ? this.list.resetHeight(h - toolHeight) : - this.list.element.css({ "max-height": pixFormat(h - toolHeight) }); + this.list.resetHeight + ? this.list.resetHeight(h - toolHeight) + : this.list.element.css({ "max-height": pixFormat(h - toolHeight) }); } setNotSelectedValue() { diff --git a/src/case/loader/loader.lazy.js b/src/case/loader/loader.lazy.js index 54f983ee6..eddfa82c6 100644 --- a/src/case/loader/loader.lazy.js +++ b/src/case/loader/loader.lazy.js @@ -1,15 +1,15 @@ -import { shortcut, Widget, extend, createWidget, takeRight, take } from "@/core"; import { Loader } from "@/base"; +import { shortcut, Widget, extend, createWidget, takeRight, take } from "@/core"; @shortcut() export class LazyLoader extends Widget { - static xtype = "bi.lazy_loader" + static xtype = "bi.lazy_loader"; _const = { PAGE: 100, }; - static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { return extend(super._defaultConfig(...arguments), { @@ -24,7 +24,7 @@ export class LazyLoader extends Widget { super._init(...arguments); const all = o.items.length; this.loader = createWidget({ - type: "bi.loader", + type: Loader.xtype, element: this, // 下面是button_group的属性 el: o.el, @@ -44,7 +44,7 @@ export class LazyLoader extends Widget { const lastNum = o.items.length - this._const.PAGE * (options.times - 1); const lastItems = takeRight(o.items, lastNum); const nextItems = take(lastItems, this._const.PAGE); - + return nextItems; } diff --git a/src/case/loader/loader.list.js b/src/case/loader/loader.list.js index a8aa011e3..3bb61f829 100644 --- a/src/case/loader/loader.list.js +++ b/src/case/loader/loader.list.js @@ -1,4 +1,23 @@ -import { shortcut, Widget, extend, emptyFn, Controller, createWidget, Events, nextTick, bind, isEmpty, isNumber, isObject, isFunction, each, isNotEmptyArray, DOM } from "@/core"; +import { ButtonGroup, LoadingBar } from "@/base"; +import { + VerticalLayout, + shortcut, + Widget, + extend, + emptyFn, + Controller, + createWidget, + Events, + nextTick, + bind, + isEmpty, + isNumber, + isObject, + isFunction, + each, + isNotEmptyArray, + DOM +} from "@/core"; /** * 恶心的加载控件, 为解决排序问题引入的控件 @@ -9,9 +28,9 @@ import { shortcut, Widget, extend, emptyFn, Controller, createWidget, Events, ne */ @shortcut() export class ListLoader extends Widget { - static xtype = "bi.list_loader" + static xtype = "bi.list_loader"; - static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { return extend(super._defaultConfig(...arguments), { @@ -19,7 +38,7 @@ export class ListLoader extends Widget { isDefaultInit: true, // 是否默认初始化数据 // 下面是button_group的属性 el: { - type: "bi.button_group", + type: ButtonGroup.xtype, }, items: [], itemsCreator: emptyFn, @@ -34,12 +53,15 @@ export class ListLoader extends Widget { _nextLoad() { const o = this.options; this.next.setLoading(); - o.itemsCreator.apply(this, [{ - times: ++this.times, - }, (...args) => { - this.next.setLoaded(); - this.addItems(...args); - }]); + o.itemsCreator.apply(this, [ + { + times: ++this.times, + }, + (...args) => { + this.next.setLoaded(); + this.addItems(...args); + } + ]); } _init() { @@ -50,14 +72,16 @@ export class ListLoader extends Widget { } this.button_group = createWidget(o.el, { - type: "bi.button_group", + type: ButtonGroup.xtype, element: this, chooseType: 0, items: o.items, behaviors: {}, - layouts: [{ - type: "bi.vertical", - }], + layouts: [ + { + type: VerticalLayout.xtype, + } + ], }); this.button_group.on(Controller.EVENT_CHANGE, (...args) => { const [type, , obj] = args; @@ -68,9 +92,14 @@ export class ListLoader extends Widget { }); if (o.next !== false) { - this.next = createWidget(extend({ - type: "bi.loading_bar", - }, o.next)); + this.next = createWidget( + extend( + { + type: LoadingBar.xtype, + }, + o.next + ) + ); this.next.on(Controller.EVENT_CHANGE, type => { if (type === Events.CLICK) { this._nextLoad(); @@ -79,14 +108,18 @@ export class ListLoader extends Widget { } createWidget({ - type: "bi.vertical", + type: VerticalLayout.xtype, element: this, items: [this.next], }); - o.isDefaultInit && isEmpty(o.items) && nextTick(bind(function () { - this.populate(); - }, this)); + o.isDefaultInit && + isEmpty(o.items) && + nextTick( + bind(function () { + this.populate(); + }, this) + ); if (isNotEmptyArray(o.items)) { this.populate(o.items); } @@ -97,11 +130,13 @@ export class ListLoader extends Widget { if (isNumber(o.count)) { return this.count < o.count; } - - return !!o.hasNext.apply(this, [{ - times: this.times, - count: this.count, - }]); + + return !!o.hasNext.apply(this, [ + { + times: this.times, + count: this.count, + } + ]); } addItems(items) { @@ -120,17 +155,20 @@ export class ListLoader extends Widget { populate(items) { const o = this.options; - if (arguments.length === 0 && (isFunction(o.itemsCreator))) { - o.itemsCreator.apply(this, [{ - times: 1, - }, (...args) => { - if (args.length === 0) { - throw new Error("参数不能为空"); + if (arguments.length === 0 && isFunction(o.itemsCreator)) { + o.itemsCreator.apply(this, [ + { + times: 1, + }, + (...args) => { + if (args.length === 0) { + throw new Error("参数不能为空"); + } + this.populate(...args); + o.onLoaded(); } - this.populate(...args); - o.onLoaded(); - }]); - + ]); + return; } this.options.items = items; diff --git a/src/case/loader/sort.list.js b/src/case/loader/sort.list.js index b3d147fe3..617aac682 100644 --- a/src/case/loader/sort.list.js +++ b/src/case/loader/sort.list.js @@ -1,4 +1,6 @@ -import { shortcut, Widget, extend, emptyFn, Controller, createWidget, Events, each, stripEL } from "@/core"; +import { ButtonGroup } from "@/base"; +import { ListLoader } from "./loader.list"; +import { Layout, shortcut, Widget, extend, emptyFn, Controller, createWidget, Events, each, stripEL } from "@/core"; /** * Created by GUY on 2016/4/29. @@ -8,9 +10,9 @@ import { shortcut, Widget, extend, emptyFn, Controller, createWidget, Events, ea */ @shortcut() export class SortList extends Widget { - static xtype = "bi.sort_list" + static xtype = "bi.sort_list"; - static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { return extend(super._defaultConfig(...arguments), { @@ -18,7 +20,7 @@ export class SortList extends Widget { isDefaultInit: true, // 是否默认初始化数据 // 下面是button_group的属性 el: { - type: "bi.button_group", + type: ButtonGroup.xtype, }, items: [], itemsCreator: emptyFn, @@ -36,12 +38,12 @@ export class SortList extends Widget { super._init(...arguments); const o = this.options; this.loader = createWidget({ - type: "bi.list_loader", + type: ListLoader.xtype, element: this, isDefaultInit: o.isDefaultInit, el: o.el, items: this._formatItems(o.items), - itemsCreator (op, callback) { + itemsCreator(op, callback) { o.itemsCreator(op, items => { callback(this._formatItems(items)); }); @@ -66,9 +68,9 @@ export class SortList extends Widget { cursor: o.cursor || "drag", tolerance: o.tolerance || "intersect", placeholder: { - element ($currentItem) { + element($currentItem) { const holder = createWidget({ - type: "bi.layout", + type: Layout.xtype, cls: "bi-sortable-holder", height: $currentItem.outerHeight(), }); @@ -79,22 +81,16 @@ export class SortList extends Widget { "margin-bottom": $currentItem.css("margin-bottom"), margin: $currentItem.css("margin"), }); - - return holder.element; - }, - update () { + return holder.element; }, + update() {}, }, - start (event, ui) { - - }, + start(event, ui) {}, stop: (event, ui) => { this.fireEvent(SortList.EVENT_CHANGE); }, - over (event, ui) { - - }, + over(event, ui) {}, }); } @@ -106,7 +102,7 @@ export class SortList extends Widget { sorted: item.value, }; }); - + return items; } diff --git a/src/case/pager/index.js b/src/case/pager/index.js index ec62a806d..222ce3940 100644 --- a/src/case/pager/index.js +++ b/src/case/pager/index.js @@ -1,3 +1,3 @@ -export { AllCountPager } from "./pager.all.count"; -export { DetailPager } from "./pager.detail"; -export { DirectionPager } from "./pager.direction"; +export { AllCountPager } from "./pager.all.count"; +export { DetailPager } from "./pager.detail"; +export { DirectionPager } from "./pager.direction"; diff --git a/src/case/pager/pager.all.count.js b/src/case/pager/pager.all.count.js index 2dfdc0c3c..dcfa40002 100644 --- a/src/case/pager/pager.all.count.js +++ b/src/case/pager/pager.all.count.js @@ -1,15 +1,31 @@ +import { Pager, IconButton, Label } from "@/base"; +import { + HorizontalLayout, + VerticalAdaptLayout, + FloatLeftLayout, + shortcut, + Widget, + extend, + isPositiveInteger, + createWidget, + parseInt, + HorizontalAlign, + isNotEmptyObject +} from "@/core"; +import { SmallTextEditor } from "@/widget/editor/editor.text.small"; + /** * 有总页数和总行数的分页控件 * Created by Young's on 2016/10/13. */ -import { shortcut, Widget, extend, isPositiveInteger, createWidget, parseInt, HorizontalAlign, isNotEmptyObject } from "@/core"; -// import { TextEditor } from "@/widget/editor/editor.text"; -import { Pager } from "@/base"; + +// + @shortcut() export class AllCountPager extends Widget { static xtype = "bi.all_count_pager"; static EVENT_CHANGE = "EVENT_CHANGE"; - _defaultConfig () { + _defaultConfig() { return extend(super._defaultConfig(...arguments), { extraCls: "bi-all-count-pager", pagerDirection: "vertical", // 翻页按钮方向,可选值:vertical/horizontal @@ -22,13 +38,14 @@ export class AllCountPager extends Widget { showRowInfo: true, }); } - _init () { + _init() { super._init(...arguments); - const { pages, curr, hasPrev, hasNext, firstPage, lastPage, height, showRowCount } = this.options, pagerIconCls = this._getPagerIconCls(); + const { pages, curr, hasPrev, hasNext, firstPage, lastPage, height, showRowCount } = this.options, + pagerIconCls = this._getPagerIconCls(); this.editor = createWidget({ - type: "bi.small_text_editor", + type: SmallTextEditor.xtype, cls: "pager-editor bi-border-radius", - validationChecker (v) { + validationChecker(v) { return (pages === 0 && v === "0") || isPositiveInteger(v); }, hgap: 4, @@ -41,12 +58,14 @@ export class AllCountPager extends Widget { }); this.pager = createWidget({ - type: "bi.pager", + type: Pager.xtype, width: 58, - layouts: [{ - type: "bi.horizontal", - lgap: 5, - }], + layouts: [ + { + type: HorizontalLayout.xtype, + lgap: 5, + } + ], dynamicShow: false, pages, @@ -56,7 +75,7 @@ export class AllCountPager extends Widget { first: false, last: false, prev: { - type: "bi.icon_button", + type: IconButton.xtype, value: "prev", title: BI.i18nText("BI-Previous_Page"), warningTitle: BI.i18nText("BI-Current_Is_First_Page"), @@ -65,7 +84,7 @@ export class AllCountPager extends Widget { cls: `bi-border bi-border-radius all-pager-prev bi-list-item-select2 ${pagerIconCls.preCls}`, }, next: { - type: "bi.icon_button", + type: IconButton.xtype, value: "next", title: BI.i18nText("BI-Next_Page"), warningTitle: BI.i18nText("BI-Current_Is_Last_Page"), @@ -94,7 +113,7 @@ export class AllCountPager extends Widget { }); this.allPages = createWidget({ - type: "bi.label", + type: Label.xtype, title: pages, height, text: `/${pages}`, @@ -102,24 +121,25 @@ export class AllCountPager extends Widget { invisible: pages <= 1, }); - createWidget(showRowCount ? { - type: "bi.vertical_adapt", - element: this, - scrollx: false, - columnSize: ["fill", ""], - horizontalAlign: HorizontalAlign.Right, - items: [ - this._getRowCountObject(), - this.editor, this.allPages, this.pager - ], - } : { - type: "bi.vertical_adapt", - element: this, - items: [this.editor, this.allPages, this.pager], - }); + createWidget( + showRowCount + ? { + type: VerticalAdaptLayout.xtype, + element: this, + scrollx: false, + columnSize: ["fill", ""], + horizontalAlign: HorizontalAlign.Right, + items: [this._getRowCountObject(), this.editor, this.allPages, this.pager], + } + : { + type: VerticalAdaptLayout.xtype, + element: this, + items: [this.editor, this.allPages, this.pager], + } + ); } - _getPagerIconCls () { + _getPagerIconCls() { const { pagerDirection } = this.options; switch (pagerDirection) { case "horizontal": @@ -140,41 +160,46 @@ export class AllCountPager extends Widget { const { height, count, rowInfoObject } = this.options; return { - type: "bi.left", + type: FloatLeftLayout.xtype, height, scrollable: false, - ref: _ref => { + ref: _ref => { this.rowCountObject = _ref; }, - items: [{ - type: "bi.label", - height, - text: BI.i18nText("BI-Basic_Total"), - ref: _ref => { - this.prevText = _ref; - }, - }, { - el: { - type: "bi.label", + items: [ + { + type: Label.xtype, + height, + text: BI.i18nText("BI-Basic_Total"), ref: _ref => { - this.rowCount = _ref; + this.prevText = _ref; }, - cls: "row-count", + }, + { + el: { + type: Label.xtype, + ref: _ref => { + this.rowCount = _ref; + }, + cls: "row-count", + height, + text: count, + title: count, + }, + hgap: 5, + }, + { + type: Label.xtype, height, - text: count, - title: count, + text: BI.i18nText("BI-Tiao_Data"), + textAlign: "left", }, - hgap: 5, - }, { - type: "bi.label", - height, - text: BI.i18nText("BI-Tiao_Data"), - textAlign: "left", - }, isNotEmptyObject(rowInfoObject) ? rowInfoObject : null], + isNotEmptyObject(rowInfoObject) ? rowInfoObject : null + ], }; } - setAllPages (v) { + setAllPages(v) { this.allPages.setText(`/${v}`); this.allPages.setTitle(v); this.options.pages = v; @@ -183,55 +208,55 @@ export class AllCountPager extends Widget { this.setPagerVisible(v > 1); } - setShowRowInfo (b) { + setShowRowInfo(b) { this.options.showRowInfo = b; this.rowCountObject.setVisible(b); } - setValue (v) { + setValue(v) { this.pager.setValue(v); } - setVPage (v) { + setVPage(v) { this.pager.setValue(v); } - setCount (count) { + setCount(count) { if (this.options.showRowCount) { this.rowCount.setText(count); this.rowCount.setTitle(count); } } - setCountPrevText (text) { + setCountPrevText(text) { if (this.options.showRowCount) { this.prevText.setText(text); } } - getCurrentPage () { + getCurrentPage() { return this.pager.getCurrentPage(); } - hasPrev () { + hasPrev() { return this.pager.hasPrev(); } - hasNext () { + hasNext() { return this.pager.hasNext(); } - isShowPager () { + isShowPager() { return this.options.showRowInfo || this.options.pages > 1; } - setPagerVisible (b) { + setPagerVisible(b) { this.editor.setVisible(b); this.allPages.setVisible(b); this.pager.setVisible(b); } - populate () { + populate() { this.pager.populate(); this.setPagerVisible(this.options.pages > 1); } diff --git a/src/case/pager/pager.detail.js b/src/case/pager/pager.detail.js index 37e56edc5..72ca03d49 100644 --- a/src/case/pager/pager.detail.js +++ b/src/case/pager/pager.detail.js @@ -1,3 +1,21 @@ +import { + HorizontalLayout, + shortcut, + Widget, + extend, + emptyFn, + result, + debounce, + isKey, + createWidget, + createItems, + Controller, + Events, + MIN, + MAX +} from "@/core"; +import { Label, ButtonGroup } from "@/base"; + /** * 分页控件 * @@ -6,26 +24,27 @@ * @extends BI.Widget */ -import { shortcut, Widget, extend, emptyFn, result, debounce, isKey, createWidget, createItems, Controller, Events, MIN, MAX } from "@/core"; @shortcut() export class DetailPager extends Widget { static xtype = "bi.detail_pager"; static EVENT_CHANGE = "EVENT_CHANGE"; static EVENT_AFTER_POPULATE = "EVENT_AFTER_POPULATE"; - _defaultConfig () { + _defaultConfig() { return extend(super._defaultConfig(...arguments), { baseCls: "bi-detail-pager", behaviors: {}, - layouts: [{ - type: "bi.horizontal", - }], + layouts: [ + { + type: HorizontalLayout.xtype, + } + ], dynamicShow: true, // 是否动态显示上一页、下一页、首页、尾页, 若为false,则指对其设置使能状态 // dynamicShow为false时以下两个有用 dynamicShowFirstLast: false, // 是否动态显示首页、尾页 dynamicShowPrevNext: false, // 是否动态显示上一页、下一页 pages: false, // 总页数 - curr () { + curr() { return 1; }, // 初始化当前页 groups: 0, // 连续显示分页数 @@ -37,14 +56,15 @@ export class DetailPager extends Widget { next: "下一页", firstPage: 1, - lastPage () { // 在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 + lastPage() { + // 在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 return 1; }, hasPrev: emptyFn, // pages不可用时有效 hasNext: emptyFn, // pages不可用时有效 }); } - _init () { + _init() { super._init(...arguments); this.currPage = result(this.options, "curr"); // 翻页太灵敏 @@ -54,9 +74,12 @@ export class DetailPager extends Widget { }, 300); this._populate(); } - _populate () { - const o = this.options, view = [], dict = {}; - const { dynamicShow, dynamicShowPrevNext, hasPrev, dynamicShowFirstLast, hasNext, behaviors, layouts, jump } = this.options; + _populate() { + const o = this.options, + view = [], + dict = {}; + const { dynamicShow, dynamicShowPrevNext, hasPrev, dynamicShowFirstLast, hasNext, behaviors, layouts, jump } = + this.options; this.empty(); const pages = result(o, "pages"); const curr = result(this, "currPage"); @@ -75,7 +98,7 @@ export class DetailPager extends Widget { } // 计算当前组 - dict.index = Math.ceil((curr + ((groups > 1 && groups !== pages) ? 1 : 0)) / (groups === 0 ? 1 : groups)); + dict.index = Math.ceil((curr + (groups > 1 && groups !== pages ? 1 : 0)) / (groups === 0 ? 1 : groups)); // 当前页非首页,则输出上一页 if (((!dynamicShow && !dynamicShowPrevNext) || curr > 1) && prev !== false) { @@ -86,9 +109,14 @@ export class DetailPager extends Widget { disabled: pages === false ? hasPrev(curr) === false : !(curr > 1 && prev !== false), }); } else { - view.push(extend({ - disabled: pages === false ? hasPrev(curr) === false : !(curr > 1 && prev !== false), - }, prev)); + view.push( + extend( + { + disabled: pages === false ? hasPrev(curr) === false : !(curr > 1 && prev !== false), + }, + prev + ) + ); } } @@ -101,7 +129,7 @@ export class DetailPager extends Widget { }); if (dict.index > 1 && groups !== 0) { view.push({ - type: "bi.label", + type: Label.xtype, cls: "page-ellipsis", text: "\u2026", }); @@ -111,16 +139,21 @@ export class DetailPager extends Widget { // 输出当前页组 dict.poor = Math.floor((groups - 1) / 2); dict.start = dict.index > 1 ? curr - dict.poor : 1; - dict.end = dict.index > 1 ? (function () { - const max = curr + (groups - dict.poor - 1); - - return max > pages ? pages : max; - }()) : groups; - if (dict.end - dict.start < groups - 1) { // 最后一组状态 + dict.end = + dict.index > 1 + ? (function () { + const max = curr + (groups - dict.poor - 1); + + return max > pages ? pages : max; + }()) + : groups; + if (dict.end - dict.start < groups - 1) { + // 最后一组状态 dict.start = dict.end - groups + 1; } - let s = dict.start, e = dict.end; - if (first && last && (dict.index > 1 && groups !== 0) && (pages > groups && dict.end < pages && groups !== 0)) { + let s = dict.start, + e = dict.end; + if (first && last && dict.index > 1 && groups !== 0 && pages > groups && dict.end < pages && groups !== 0) { s++; e--; } @@ -143,7 +176,7 @@ export class DetailPager extends Widget { if (((!dynamicShow && !dynamicShowFirstLast) || (pages > groups && dict.end < pages && groups !== 0)) && last) { if (pages > groups && dict.end < pages && groups !== 0) { view.push({ - type: "bi.label", + type: Label.xtype, cls: "page-ellipsis", text: "\u2026", }); @@ -157,28 +190,32 @@ export class DetailPager extends Widget { // 当前页不为尾页时,输出下一页 dict.flow = !prev && groups === 0; - if (((!dynamicShow && !dynamicShowPrevNext) && next) || (curr !== pages && next || dict.flow)) { - view.push((function () { - if (isKey(next)) { - if (pages === false) { - return { text: next, value: "next", disabled: hasNext(curr) === false }; + if ((!dynamicShow && !dynamicShowPrevNext && next) || (curr !== pages && next) || dict.flow) { + view.push( + (function () { + if (isKey(next)) { + if (pages === false) { + return { text: next, value: "next", disabled: hasNext(curr) === false }; + } + + return dict.flow && curr === pages + ? { text: next, value: "next", disabled: true } + : { text: next, value: "next", disabled: !((curr !== pages && next) || dict.flow) }; } - - return (dict.flow && curr === pages) - ? - { text: next, value: "next", disabled: true } - : - { text: next, value: "next", disabled: !(curr !== pages && next || dict.flow) }; - } - - return extend({ - disabled: pages === false ? hasNext(curr) === false : !(curr !== pages && next || dict.flow), - }, next); - }())); + + return extend( + { + disabled: + pages === false ? hasNext(curr) === false : !((curr !== pages && next) || dict.flow), + }, + next + ); + })() + ); } this.button_group = createWidget({ - type: "bi.button_group", + type: ButtonGroup.xtype, element: this, items: createItems(view, { cls: "page-item bi-border bi-list-item-active", @@ -212,10 +249,12 @@ export class DetailPager extends Widget { this.currPage = v; break; } - jump.apply(this, [{ - pages, - curr: this.currPage, - }]); + jump.apply(this, [ + { + pages, + curr: this.currPage, + } + ]); this._populate(); this.fireEvent(DetailPager.EVENT_CHANGE, obj); } @@ -224,32 +263,32 @@ export class DetailPager extends Widget { this.fireEvent(DetailPager.EVENT_AFTER_POPULATE); } - getCurrentPage () { + getCurrentPage() { return this.currPage; } - setAllPages (pages) { + setAllPages(pages) { this.options.pages = pages; this._populate(); } - hasPrev (v) { + hasPrev(v) { v || (v = 1); const { hasPrev } = this.options; const pages = this.options.pages; - + return pages === false ? hasPrev(v) : v > 1; } - hasNext (v) { + hasNext(v) { v || (v = 1); const { hasNext } = this.options; const pages = this.options.pages; - + return pages === false ? hasNext(v) : v < pages; } - setValue (v) { + setValue(v) { const o = this.options; const { pages } = this.options; v = v || 0; @@ -257,7 +296,8 @@ export class DetailPager extends Widget { if (pages === false) { const lastPage = result(o, "lastPage"); let firstPage = 1; - this.currPage = v > lastPage ? lastPage : ((firstPage = result(o, "firstPage")), (v < firstPage ? firstPage : v)); + this.currPage = + v > lastPage ? lastPage : ((firstPage = result(o, "firstPage")), v < firstPage ? firstPage : v); } else { v = v > pages ? pages : v; this.currPage = v; @@ -265,7 +305,7 @@ export class DetailPager extends Widget { this._populate(); } - getValue () { + getValue() { const val = this.button_group.getValue()[0]; switch (val) { case "prev": @@ -276,19 +316,19 @@ export class DetailPager extends Widget { return MIN; case "last": return MAX; - default : + default: return val; } } - attr (key, value) { + attr(key, value) { super.attr(...arguments); if (key === "curr") { this.currPage = result(this.options, "curr"); } } - populate () { + populate() { this._populate(); } } diff --git a/src/case/pager/pager.direction.js b/src/case/pager/pager.direction.js index 512b2cc20..b114beb4b 100644 --- a/src/case/pager/pager.direction.js +++ b/src/case/pager/pager.direction.js @@ -1,3 +1,6 @@ +import { AbsoluteLayout, HorizontalLayout, shortcut, Widget, extend, emptyFn, createWidget } from "@/core"; +import { Label, Pager, IconButton } from "@/base"; + /** * 显示页码的分页控件 * @@ -6,14 +9,12 @@ * @extends BI.Widget */ -import { shortcut, Widget, extend, emptyFn, createWidget } from "@/core"; -import { Pager } from "@/base"; @shortcut() export class DirectionPager extends Widget { static EVENT_CHANGE = "EVENT_CHANGE"; static xtype = "bi.direction_pager"; - _defaultConfig () { + _defaultConfig() { return extend(super._defaultConfig(...arguments), { baseCls: "bi-direction-pager", height: 24, @@ -37,38 +38,43 @@ export class DirectionPager extends Widget { }, }); } - _init () { + _init() { super._init(...arguments); this._createVPager(); this._createHPager(); this.layout = createWidget({ - type: "bi.absolute", + type: AbsoluteLayout.xtype, scrollable: false, element: this, - items: [{ - el: this.vpager, - top: 0, - right: 86, - }, { - el: this.vlabel, - top: 0, - right: 110, - }, { - el: this.hpager, - top: 0, - right: 0, - }, { - el: this.hlabel, - top: 0, - right: 24, - }], + items: [ + { + el: this.vpager, + top: 0, + right: 86, + }, + { + el: this.vlabel, + top: 0, + right: 110, + }, + { + el: this.hpager, + top: 0, + right: 0, + }, + { + el: this.hlabel, + top: 0, + right: 24, + } + ], }); } - _createVPager () { + _createVPager() { const v = this.options.vertical; this.vlabel = createWidget({ - type: "bi.label", + type: Label.xtype, width: 24, height: 24, value: v.curr, @@ -76,13 +82,15 @@ export class DirectionPager extends Widget { invisible: true, }); this.vpager = createWidget({ - type: "bi.pager", + type: Pager.xtype, width: 72, - layouts: [{ - type: "bi.horizontal", - scrollx: false, - rgap: 24, - }], + layouts: [ + { + type: HorizontalLayout.xtype, + scrollx: false, + rgap: 24, + } + ], invisible: true, dynamicShow: false, @@ -93,7 +101,7 @@ export class DirectionPager extends Widget { first: false, last: false, prev: { - type: "bi.icon_button", + type: IconButton.xtype, value: "prev", title: BI.i18nText("BI-Up_Page"), warningTitle: BI.i18nText("BI-Current_Is_First_Page"), @@ -102,7 +110,7 @@ export class DirectionPager extends Widget { cls: "bi-border bi-border-radius direction-pager-prev column-pre-page-h-font bi-list-item-select2", }, next: { - type: "bi.icon_button", + type: IconButton.xtype, value: "next", title: BI.i18nText("BI-Down_Page"), warningTitle: BI.i18nText("BI-Current_Is_Last_Page"), @@ -125,10 +133,10 @@ export class DirectionPager extends Widget { this.vlabel.setTitle(this.vpager.getCurrentPage()); }); } - _createHPager () { + _createHPager() { const h = this.options.horizontal; this.hlabel = createWidget({ - type: "bi.label", + type: Label.xtype, width: 24, height: 24, value: h.curr, @@ -136,13 +144,15 @@ export class DirectionPager extends Widget { invisible: true, }); this.hpager = createWidget({ - type: "bi.pager", + type: Pager.xtype, width: 72, - layouts: [{ - type: "bi.horizontal", - scrollx: false, - rgap: 24, - }], + layouts: [ + { + type: HorizontalLayout.xtype, + scrollx: false, + rgap: 24, + } + ], invisible: true, dynamicShow: false, @@ -153,7 +163,7 @@ export class DirectionPager extends Widget { first: false, last: false, prev: { - type: "bi.icon_button", + type: IconButton.xtype, value: "prev", title: BI.i18nText("BI-Left_Page"), warningTitle: BI.i18nText("BI-Current_Is_First_Page"), @@ -162,7 +172,7 @@ export class DirectionPager extends Widget { cls: "bi-border bi-border-radius direction-pager-prev row-pre-page-h-font bi-list-item-select2", }, next: { - type: "bi.icon_button", + type: IconButton.xtype, value: "next", title: BI.i18nText("BI-Right_Page"), warningTitle: BI.i18nText("BI-Current_Is_Last_Page"), @@ -186,56 +196,57 @@ export class DirectionPager extends Widget { }); } - getVPage () { + getVPage() { return this.vpager.getCurrentPage(); } - getHPage () { + getHPage() { return this.hpager.getCurrentPage(); } - setVPage (v) { + setVPage(v) { this.vpager.setValue(v); this.vlabel.setValue(v); this.vlabel.setTitle(v); } - setHPage (v) { + setHPage(v) { this.hpager.setValue(v); this.hlabel.setValue(v); this.hlabel.setTitle(v); } - hasVNext () { + hasVNext() { return this.vpager.hasNext(); } - hasHNext () { + hasHNext() { return this.hpager.hasNext(); } - hasVPrev () { + hasVPrev() { return this.vpager.hasPrev(); } - hasHPrev () { + hasHPrev() { return this.hpager.hasPrev(); } - setHPagerVisible (b) { + setHPagerVisible(b) { this.hpager.setVisible(b); this.hlabel.setVisible(b); } - setVPagerVisible (b) { + setVPagerVisible(b) { this.vpager.setVisible(b); this.vlabel.setVisible(b); } - populate () { + populate() { this.vpager.populate(); this.hpager.populate(); - let vShow = false, hShow = false; + let vShow = false, + hShow = false; if (!this.hasHNext() && !this.hasHPrev()) { this.setHPagerVisible(false); } else { @@ -268,7 +279,7 @@ export class DirectionPager extends Widget { this.layout.resize(); } - clear () { + clear() { this.vpager.attr("curr", 1); this.hpager.attr("curr", 1); } diff --git a/src/case/segment/button.segment.js b/src/case/segment/button.segment.js index 9508a686c..160fb645d 100644 --- a/src/case/segment/button.segment.js +++ b/src/case/segment/button.segment.js @@ -1,5 +1,5 @@ +import { Label, BasicButton } from "@/base"; import { shortcut, extend, createWidget } from "@/core"; -import { BasicButton } from "@/base"; /** * 分段控件使用的button @@ -10,11 +10,11 @@ import { BasicButton } from "@/base"; */ @shortcut() export class SegmentButton extends BasicButton { - static xtype = "bi.segment_button" + static xtype = "bi.segment_button"; _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-segment-button bi-list-item-select bi-card`, shadow: true, @@ -27,7 +27,7 @@ export class SegmentButton extends BasicButton { super._init(...arguments); const opts = this.options; this.text = createWidget({ - type: "bi.label", + type: Label.xtype, element: this, textHeight: opts.height, whiteSpace: opts.whiteSpace, diff --git a/src/case/segment/segment.js b/src/case/segment/segment.js index ac16eba20..0adc0866a 100644 --- a/src/case/segment/segment.js +++ b/src/case/segment/segment.js @@ -1,5 +1,16 @@ -import { shortcut, Widget, extend, toPix, Controller, createWidget, createItems, makeArrayByArray } from "@/core"; import { ButtonGroup } from "@/base"; +import { SegmentButton } from "./button.segment"; +import { + TableLayout, + shortcut, + Widget, + extend, + toPix, + Controller, + createWidget, + createItems, + makeArrayByArray +} from "@/core"; /** * 单选按钮组 @@ -10,9 +21,9 @@ import { ButtonGroup } from "@/base"; */ @shortcut() export class Segment extends Widget { - static xtype = "bi.segment" + static xtype = "bi.segment"; - static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { return extend(super._defaultConfig(...arguments), { @@ -27,17 +38,21 @@ export class Segment extends Widget { const o = this.options; this.buttonGroup = createWidget({ element: this, - type: "bi.button_group", + type: ButtonGroup.xtype, value: o.value, - items: [createItems(o.items, { - type: "bi.segment_button", - height: toPix(o.height, 2), - whiteSpace: o.whiteSpace, - })], - layouts: [{ - type: "bi.table", - columnSize: makeArrayByArray(o.items, "fill"), - }], + items: [ + createItems(o.items, { + type: SegmentButton.xtype, + height: toPix(o.height, 2), + whiteSpace: o.whiteSpace, + }) + ], + layouts: [ + { + type: TableLayout.xtype, + columnSize: makeArrayByArray(o.items, "fill"), + } + ], }); this.buttonGroup.on(Controller.EVENT_CHANGE, (...args) => { this.fireEvent(Controller.EVENT_CHANGE, ...args); @@ -70,10 +85,12 @@ export class Segment extends Widget { populate(buttons) { const o = this.options; - this.buttonGroup.populate([createItems(buttons, { - type: "bi.segment_button", - height: toPix(o.height, 2), - whiteSpace: o.whiteSpace, - })]); + this.buttonGroup.populate([ + createItems(buttons, { + type: SegmentButton.xtype, + height: toPix(o.height, 2), + whiteSpace: o.whiteSpace, + }) + ]); } } diff --git a/src/case/toolbar/toolbar.multiselect.js b/src/case/toolbar/toolbar.multiselect.js index f5fb1bf45..f0df9ce78 100644 --- a/src/case/toolbar/toolbar.multiselect.js +++ b/src/case/toolbar/toolbar.multiselect.js @@ -1,6 +1,16 @@ -import { shortcut, extend, emptyFn, i18nText, Controller, createWidget, Events } from "@/core"; -import { BasicButton, Checkbox } from "@/base"; +import { Checkbox, Label, BasicButton } from "@/base"; import { HalfIconButton } from "../button"; +import { + HTapeLayout, + CenterAdaptLayout, + shortcut, + extend, + emptyFn, + i18nText, + Controller, + createWidget, + Events +} from "@/core"; /** * guy @@ -11,9 +21,9 @@ import { HalfIconButton } from "../button"; */ @shortcut() export class MultiSelectBar extends BasicButton { - static xtype = "bi.multi_select_bar" + static xtype = "bi.multi_select_bar"; - static EVENT_CHANGE = "EVENT_CHANGE" + static EVENT_CHANGE = "EVENT_CHANGE"; _defaultConfig() { return extend(super._defaultConfig(...arguments), { @@ -23,7 +33,7 @@ export class MultiSelectBar extends BasicButton { isAllCheckedBySelectedValue: emptyFn, // 手动控制选中 disableSelected: true, - isHalfCheckedBySelectedValue (selectedValues) { + isHalfCheckedBySelectedValue(selectedValues) { return selectedValues.length > 0; }, halfSelected: false, @@ -39,7 +49,7 @@ export class MultiSelectBar extends BasicButton { const isSelect = o.selected === true; const isHalfSelect = !o.selected && o.halfSelected; this.checkbox = createWidget({ - type: "bi.checkbox", + type: Checkbox.xtype, stopPropagation: true, handler: () => { this.setSelected(this.isSelected()); @@ -50,7 +60,7 @@ export class MultiSelectBar extends BasicButton { iconHeight: o.iconHeight, }); this.half = createWidget({ - type: "bi.half_icon_button", + type: HalfIconButton.xtype, stopPropagation: true, handler: () => { this.setSelected(true); @@ -72,7 +82,7 @@ export class MultiSelectBar extends BasicButton { this.fireEvent(MultiSelectBar.EVENT_CHANGE, this.isSelected(), this); }); this.text = createWidget({ - type: "bi.label", + type: Label.xtype, textAlign: "left", whiteSpace: "nowrap", textHeight: o.height, @@ -84,17 +94,20 @@ export class MultiSelectBar extends BasicButton { py: o.py, }); createWidget({ - type: "bi.htape", + type: HTapeLayout.xtype, element: this, - items: [{ - width: o.iconWrapperWidth, - el: { - type: "bi.center_adapt", - items: [this.checkbox, this.half], + items: [ + { + width: o.iconWrapperWidth, + el: { + type: CenterAdaptLayout.xtype, + items: [this.checkbox, this.half], + }, }, - }, { - el: this.text, - }], + { + el: this.text, + } + ], }); } diff --git a/src/case/tree/tree.level.js b/src/case/tree/tree.level.js index 426175b54..7f49ece0f 100644 --- a/src/case/tree/tree.level.js +++ b/src/case/tree/tree.level.js @@ -9,11 +9,14 @@ import { isNotEmptyArray, Tree, createWidget, - VerticalLayout, Controller, Events + VerticalLayout, + Controller, + Events } from "@/core"; import { ButtonTree, CustomTree } from "@/base"; import { TreeExpander } from "./treeexpander/tree.expander"; -import { BasicTreeItem, BasicTreeNode } from "@/case"; +import { BasicTreeItem } from "@/case/button/treeitem/treeitem"; +import { BasicTreeNode } from "@/case/button/node/treenode"; @shortcut() export class LevelTree extends Widget { @@ -74,33 +77,40 @@ export class LevelTree extends Widget { } initTree(nodes) { - const self = this, o = this.options; + const self = this, + o = this.options; this.empty(); this._assertId(nodes); this.tree = createWidget({ type: CustomTree.xtype, element: this, - expander: extend({ - type: TreeExpander.xtype, - el: {}, - isDefaultInit: false, - selectable: false, - popup: { - type: CustomTree.xtype, + expander: extend( + { + type: TreeExpander.xtype, + el: {}, + isDefaultInit: false, + selectable: false, + popup: { + type: CustomTree.xtype, + }, }, - }, o.expander), + o.expander + ), items: this._formatItems(Tree.transformToTreeFormat(nodes), 0), value: o.value, - el: extend({ - type: ButtonTree.xtype, - chooseType: 0, - layouts: [ - { - type: VerticalLayout.xtype, - } - ], - }, o.el), + el: extend( + { + type: ButtonTree.xtype, + chooseType: 0, + layouts: [ + { + type: VerticalLayout.xtype, + } + ], + }, + o.el + ), }); this.tree.on(Controller.EVENT_CHANGE, function (type, value, ob) { self.fireEvent(Controller.EVENT_CHANGE, arguments); diff --git a/src/case/tree/treeexpander/tree.expander.popup.js b/src/case/tree/treeexpander/tree.expander.popup.js index d00c790f7..a07829d3b 100644 --- a/src/case/tree/treeexpander/tree.expander.popup.js +++ b/src/case/tree/treeexpander/tree.expander.popup.js @@ -19,10 +19,13 @@ export class TreeExpanderPopup extends Widget { const { el, value, layer, showLine, isLastNode } = this.options; const offset = BI.SIZE_CONSANTS.LIST_ITEM_HEIGHT / 2; - this.popupView = createWidget({ - ...el, - value, - }, this); + this.popupView = createWidget( + { + ...el, + value, + }, + this + ); this.popupView.on(Controller.EVENT_CHANGE, function () { self.fireEvent(Controller.EVENT_CHANGE, arguments); @@ -35,11 +38,9 @@ export class TreeExpanderPopup extends Widget { return { type: VerticalLayout.xtype, - cls: (showLine && !isLastNode) ? (BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? "line solid" : "line") : "", + cls: showLine && !isLastNode ? (BI.STYLE_CONSTANTS.LINK_LINE_TYPE === "solid" ? "line solid" : "line") : "", scrolly: null, - items: [ - this.popupView - ], + items: [this.popupView], }; } diff --git a/src/case/trigger/trigger.editor.js b/src/case/trigger/trigger.editor.js index 3bb8439ac..2ea76e859 100644 --- a/src/case/trigger/trigger.editor.js +++ b/src/case/trigger/trigger.editor.js @@ -1,6 +1,7 @@ -import { shortcut, extend, emptyFn, createWidget, toPix, Controller } from "@/core"; -import { Trigger } from "@/base"; import { SignEditor } from "../editor"; +import { HorizontalFillLayout, shortcut, extend, emptyFn, createWidget, toPix, Controller } from "@/core"; +import { TriggerIconButton } from "../button"; +import { Trigger } from "@/base"; /** * 文本输入框trigger @@ -20,9 +21,11 @@ export class EditorTrigger extends Trigger { _defaultConfig(config) { const conf = super._defaultConfig(...arguments); - + return extend(conf, { - baseCls: `${conf.baseCls || ""} bi-editor-trigger bi-border-radius ${config.simple ? "bi-border-bottom" : "bi-border"}`, + baseCls: `${conf.baseCls || ""} bi-editor-trigger bi-border-radius ${ + config.simple ? "bi-border-bottom" : "bi-border" + }`, height: 24, validationChecker: emptyFn, quitChecker: emptyFn, @@ -36,7 +39,7 @@ export class EditorTrigger extends Trigger { super._init(...arguments); const o = this.options; this.editor = createWidget({ - type: "bi.sign_editor", + type: SignEditor.xtype, height: toPix(o.height, 2), value: o.value, validationChecker: o.validationChecker, @@ -67,15 +70,16 @@ export class EditorTrigger extends Trigger { createWidget({ element: this, - type: "bi.horizontal_fill", + type: HorizontalFillLayout.xtype, height: toPix(o.height, 2), items: [ { el: this.editor, width: "fill", - }, { + }, + { el: { - type: "bi.trigger_icon_button", + type: TriggerIconButton.xtype, width: o.triggerWidth || toPix(o.height, 2), }, width: "", diff --git a/src/case/trigger/trigger.icon.js b/src/case/trigger/trigger.icon.js index 3368dd070..c1f3b1ffe 100644 --- a/src/case/trigger/trigger.icon.js +++ b/src/case/trigger/trigger.icon.js @@ -1,3 +1,4 @@ +import { TriggerIconButton } from "../button"; import { shortcut, extend, createWidget } from "@/core"; import { Trigger } from "@/base"; @@ -10,7 +11,7 @@ import { Trigger } from "@/base"; */ @shortcut() export class IconTrigger extends Trigger { - static xtype = "bi.icon_trigger" + static xtype = "bi.icon_trigger"; _defaultConfig() { return extend(super._defaultConfig(...arguments), { @@ -25,7 +26,7 @@ export class IconTrigger extends Trigger { const o = this.options; super._init(...arguments); this.iconButton = createWidget(o.el, { - type: "bi.trigger_icon_button", + type: TriggerIconButton.xtype, element: this, width: o.width, height: o.height, diff --git a/src/case/trigger/trigger.icon.text.js b/src/case/trigger/trigger.icon.text.js index b93c3181b..658a8ccf3 100644 --- a/src/case/trigger/trigger.icon.text.js +++ b/src/case/trigger/trigger.icon.text.js @@ -1,5 +1,6 @@ -import { shortcut, extend, isKey, createWidget, isEmptyString } from "@/core"; -import { Trigger } from "@/base"; +import { Label, Trigger } from "@/base"; +import { TriggerIconButton, IconChangeButton } from "../button"; +import { HorizontalFillLayout, shortcut, extend, isKey, createWidget, isEmptyString } from "@/core"; /** * 文字trigger @@ -10,11 +11,11 @@ import { Trigger } from "@/base"; */ @shortcut() export class IconTextTrigger extends Trigger { - static xtype = "bi.icon_text_trigger" + static xtype = "bi.icon_text_trigger"; _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-text-trigger`, height: 24, @@ -28,8 +29,8 @@ export class IconTextTrigger extends Trigger { super._init(...arguments); const o = this.options; this.text = createWidget({ - type: "bi.label", - cls: `select-text-label${isKey(o.textCls) ? (` ${o.textCls}`) : ""}`, + type: Label.xtype, + cls: `select-text-label${isKey(o.textCls) ? ` ${o.textCls}` : ""}`, textAlign: "left", height: o.height, hgap: o.textHgap, @@ -41,37 +42,41 @@ export class IconTextTrigger extends Trigger { text: o.text, }); this.trigerButton = createWidget({ - type: "bi.trigger_icon_button", + type: TriggerIconButton.xtype, width: o.triggerWidth || o.height, }); createWidget({ element: this, - type: "bi.horizontal_fill", + type: HorizontalFillLayout.xtype, columnSize: ["", "fill", ""], ref: _ref => { this.wrapper = _ref; }, - items: [{ - el: { - type: "bi.icon_change_button", - cls: "icon-combo-trigger-icon", - width: o.triggerWidth || o.height, - iconCls: o.iconCls, - invisible: !o.iconCls, - ref: _ref => { - this.icon = _ref; + items: [ + { + el: { + type: IconChangeButton.xtype, + cls: "icon-combo-trigger-icon", + width: o.triggerWidth || o.height, + iconCls: o.iconCls, + invisible: !o.iconCls, + ref: _ref => { + this.icon = _ref; + }, + iconHeight: o.iconHeight, + iconWidth: o.iconWidth, + disableSelected: true, }, - iconHeight: o.iconHeight, - iconWidth: o.iconWidth, - disableSelected: true, }, - }, { - el: this.text, - lgap: isEmptyString(o.iconCls) ? 5 : 0, - }, { - el: this.trigerButton, - }], + { + el: this.text, + lgap: isEmptyString(o.iconCls) ? 5 : 0, + }, + { + el: this.trigerButton, + } + ], }); } diff --git a/src/case/trigger/trigger.icon.text.select.js b/src/case/trigger/trigger.icon.text.select.js index 0045972a4..76c02d519 100644 --- a/src/case/trigger/trigger.icon.text.select.js +++ b/src/case/trigger/trigger.icon.text.select.js @@ -1,3 +1,4 @@ +import { IconTextTrigger } from "./trigger.icon.text"; import { shortcut, extend, createWidget, isFunction, isArray, isNotNull, any, deepContains, Tree } from "@/core"; import { Trigger } from "@/base"; @@ -6,7 +7,7 @@ import { Trigger } from "@/base"; */ @shortcut() export class SelectIconTextTrigger extends Trigger { - static xtype = "bi.select_icon_text_trigger" + static xtype = "bi.select_icon_text_trigger"; _defaultConfig() { return extend(super._defaultConfig(...arguments), { @@ -23,7 +24,7 @@ export class SelectIconTextTrigger extends Trigger { const o = this.options; const obj = this._digist(o.value, o.items); this.trigger = createWidget({ - type: "bi.icon_text_trigger", + type: IconTextTrigger.xtype, element: this, text: obj.text, textCls: obj.textCls, @@ -52,7 +53,7 @@ export class SelectIconTextTrigger extends Trigger { text: item.text || item.value, iconCls: item.iconCls, }; - + return true; } }); diff --git a/src/case/trigger/trigger.text.js b/src/case/trigger/trigger.text.js index f4e15110d..dfe9cef1b 100644 --- a/src/case/trigger/trigger.text.js +++ b/src/case/trigger/trigger.text.js @@ -1,5 +1,6 @@ -import { shortcut, isFunction, isKey, isNotEmptyString } from "@/core"; -import { Trigger } from "@/base"; +import { Label, IconButton, Trigger } from "@/base"; +import { TriggerIconButton } from "../button"; +import { HorizontalFillLayout, VerticalAdaptLayout, shortcut, isFunction, isKey, isNotEmptyString } from "@/core"; /** * 文字trigger @@ -10,9 +11,9 @@ import { Trigger } from "@/base"; */ @shortcut() export class TextTrigger extends Trigger { - static xtype = "bi.text_trigger" + static xtype = "bi.text_trigger"; - static EVENT_CLEAR = "EVENT_CLEAR" + static EVENT_CLEAR = "EVENT_CLEAR"; props() { return { @@ -35,11 +36,13 @@ export class TextTrigger extends Trigger { const defaultText = this.getDefaultText(); const label = { - type: "bi.label", + type: Label.xtype, ref: _ref => { this.text = _ref; }, - cls: `select-text-label ${o.textCls} ${!isNotEmptyString(text) && isNotEmptyString(defaultText) ? "bi-tips" : ""}`, + cls: `select-text-label ${o.textCls} ${ + !isNotEmptyString(text) && isNotEmptyString(defaultText) ? "bi-tips" : "" + }`, textAlign: "left", height: o.height, text: text || o.defaultText, @@ -55,57 +58,65 @@ export class TextTrigger extends Trigger { }; const triggerButton = { - type: "bi.trigger_icon_button", + type: TriggerIconButton.xtype, ref: _ref => { this.triggerButton = _ref; }, width: o.triggerWidth || o.height, }; - return ({ - type: "bi.horizontal_fill", + return { + type: HorizontalFillLayout.xtype, columnSize: ["fill", ""], - items: [{ - el: label, - width: "fill", - }, { - el: o.allowClear ? { - type: "bi.vertical_adapt", - width: o.triggerWidth || o.height, - height: o.height, - horizontalAlign: "left", - scrollable: false, - items: [{ - el: { - type: "bi.icon_button", - ref: _ref => { - this.clearBtn = _ref; - }, - cls: `close-h-font ${o.allowClear ? "clear-button" : ""}`, - stopPropagation: true, + items: [ + { + el: label, + width: "fill", + }, + { + el: o.allowClear + ? { + type: VerticalAdaptLayout.xtype, width: o.triggerWidth || o.height, - invisible: !isNotEmptyString(o.text), - handler: () => { - this.fireEvent(TextTrigger.EVENT_CLEAR); - }, - }, - }, { - el: triggerButton, - }], - } : triggerButton, - }], - }); + height: o.height, + horizontalAlign: "left", + scrollable: false, + items: [ + { + el: { + type: IconButton.xtype, + ref: _ref => { + this.clearBtn = _ref; + }, + cls: `close-h-font ${o.allowClear ? "clear-button" : ""}`, + stopPropagation: true, + width: o.triggerWidth || o.height, + invisible: !isNotEmptyString(o.text), + handler: () => { + this.fireEvent(TextTrigger.EVENT_CLEAR); + }, + }, + }, + { + el: triggerButton, + } + ], + } + : triggerButton, + } + ], + }; } getText() { const o = this.options; - + return isFunction(o.text) ? o.text() : o.text; } getDefaultText() { const o = this.options; - + return isFunction(o.defaultText) ? o.defaultText() : o.defaultText; } diff --git a/src/case/trigger/trigger.text.select.js b/src/case/trigger/trigger.text.select.js index 8094a424d..48af5c5de 100644 --- a/src/case/trigger/trigger.text.select.js +++ b/src/case/trigger/trigger.text.select.js @@ -1,6 +1,6 @@ +import { TextTrigger } from "./trigger.text"; import { shortcut, extend, emptyFn, createWidget, isFunction, isArray, Tree, each, contains, remove } from "@/core"; import { Trigger } from "@/base"; -import { TextTrigger } from "./trigger.text"; /** * 选择字段trigger @@ -11,9 +11,9 @@ import { TextTrigger } from "./trigger.text"; */ @shortcut() export class SelectTextTrigger extends Trigger { - static xtype = "bi.select_text_trigger" + static xtype = "bi.select_text_trigger"; - static EVENT_CLEAR = "EVENT_CLEAR" + static EVENT_CLEAR = "EVENT_CLEAR"; _defaultConfig() { return extend(super._defaultConfig(...arguments), { @@ -30,7 +30,7 @@ export class SelectTextTrigger extends Trigger { const o = this.options; const text = this._digest(o.value, o.items); this.trigger = createWidget({ - type: "bi.text_trigger", + type: TextTrigger.xtype, element: this, height: o.height, readonly: o.readonly, @@ -45,13 +45,15 @@ export class SelectTextTrigger extends Trigger { tipType: o.tipType, title: null, allowClear: o.allowClear, - listeners: [{ - eventName: TextTrigger.EVENT_CLEAR, - action: () => { - this.setText(""); - this.fireEvent(SelectTextTrigger.EVENT_CLEAR); + listeners: [ + { + eventName: TextTrigger.EVENT_CLEAR, + action: () => { + this.setText(""); + this.fireEvent(SelectTextTrigger.EVENT_CLEAR); + }, }, - }], + ], }); } @@ -67,7 +69,7 @@ export class SelectTextTrigger extends Trigger { each(val, (index, v) => { result.push(o.valueFormatter(v)); }); - + return result.join(","); } diff --git a/src/case/trigger/trigger.text.select.small.js b/src/case/trigger/trigger.text.select.small.js index 944ee1a51..2f3106a3b 100644 --- a/src/case/trigger/trigger.text.select.small.js +++ b/src/case/trigger/trigger.text.select.small.js @@ -1,3 +1,4 @@ +import { SmallTextTrigger } from "./trigger.text.small"; import { shortcut, extend, toPix, createWidget, isArray, deepContains, each, contains, Tree } from "@/core"; import { Trigger } from "@/base"; @@ -9,7 +10,7 @@ import { Trigger } from "@/base"; */ @shortcut() export class SmallSelectTextTrigger extends Trigger { - static xtype = "bi.small_select_text_trigger" + static xtype = "bi.small_select_text_trigger"; _defaultConfig() { return extend(super._defaultConfig(...arguments), { @@ -23,7 +24,7 @@ export class SmallSelectTextTrigger extends Trigger { const o = this.options; const obj = this._digest(o.value, o.items); this.trigger = createWidget({ - type: "bi.small_text_trigger", + type: SmallTextTrigger.xtype, element: this, height: toPix(o.height, 2), text: obj.text, diff --git a/src/case/trigger/trigger.text.small.js b/src/case/trigger/trigger.text.small.js index 9269a4210..524c2e711 100644 --- a/src/case/trigger/trigger.text.small.js +++ b/src/case/trigger/trigger.text.small.js @@ -1,5 +1,6 @@ -import { shortcut, extend, createWidget } from "@/core"; -import { Trigger } from "@/base"; +import { Label, Trigger } from "@/base"; +import { TriggerIconButton } from "../button"; +import { HorizontalFillLayout, shortcut, extend, createWidget } from "@/core"; /** * 文字trigger(右边小三角小一号的) == @@ -9,11 +10,11 @@ import { Trigger } from "@/base"; */ @shortcut() export class SmallTextTrigger extends Trigger { - static xtype = "bi.small_text_trigger" + static xtype = "bi.small_text_trigger"; _defaultConfig() { const conf = super._defaultConfig(...arguments); - + return extend(conf, { baseCls: `${conf.baseCls || ""} bi-text-trigger`, height: 20, @@ -25,7 +26,7 @@ export class SmallTextTrigger extends Trigger { super._init(...arguments); const o = this.options; this.text = createWidget({ - type: "bi.label", + type: Label.xtype, textAlign: "left", height: o.height, text: o.text, @@ -37,20 +38,23 @@ export class SmallTextTrigger extends Trigger { bgap: o.textBgap, }); this.trigerButton = createWidget({ - type: "bi.trigger_icon_button", + type: TriggerIconButton.xtype, width: o.triggerWidth || o.height, }); createWidget({ element: this, - type: "bi.horizontal_fill", - items: [{ - el: this.text, - width: "fill", - }, { - el: this.trigerButton, - width: "", - }], + type: HorizontalFillLayout.xtype, + items: [ + { + el: this.text, + width: "fill", + }, + { + el: this.trigerButton, + width: "", + } + ], }); } diff --git a/src/case/ztree/asynctree.js b/src/case/ztree/asynctree.js index d8d7028c6..fd186ae20 100644 --- a/src/case/ztree/asynctree.js +++ b/src/case/ztree/asynctree.js @@ -162,14 +162,15 @@ export class Asynctree extends TreeView { // 展开节点 _beforeExpandNode(treeId, treeNode) { - const self = this, o = this.options; + const self = this, + o = this.options; function complete(d) { const nodes = d.items || []; if (nodes.length > 0) { callback(self._dealWidthNodes(nodes), !!d.hasNext); } - }; + } function callback(nodes, hasNext) { self.nodes.addNodes(treeNode, nodes); @@ -184,12 +185,17 @@ export class Asynctree extends TreeView { // console.log(times); options = options || {}; const parentValues = treeNode.parentValues || self._getParentValues(treeNode); - const op = extend({}, o.paras, { - id: treeNode.id, - times: options.times, - parentValues: parentValues.concat(self._getNodeValue(treeNode)), - checkState: treeNode.getCheckStatus(), - }, options); + const op = extend( + {}, + o.paras, + { + id: treeNode.id, + times: options.times, + parentValues: parentValues.concat(self._getNodeValue(treeNode)), + checkState: treeNode.getCheckStatus(), + }, + options + ); o.itemsCreator(op, complete); } diff --git a/src/case/ztree/jquery.ztree.core-3.5.js b/src/case/ztree/jquery.ztree.core-3.5.js index f4e899044..0e1aedf39 100644 --- a/src/case/ztree/jquery.ztree.core-3.5.js +++ b/src/case/ztree/jquery.ztree.core-3.5.js @@ -13,7 +13,9 @@ */ (function ($) { - var settings = {}, roots = {}, caches = {}, + var settings = {}, + roots = {}, + caches = {}, //default consts of core _consts = { className: { @@ -22,7 +24,7 @@ LEVEL: "level", ICO_LOADING: "ico_loading", SWITCH: "switch", - NAME: 'node_name' + NAME: "node_name", }, event: { NODECREATED: "ztree_nodeCreated", @@ -33,14 +35,14 @@ ASYNC_ERROR: "ztree_async_error", REMOVE: "ztree_remove", SELECTED: "ztree_selected", - UNSELECTED: "ztree_unselected" + UNSELECTED: "ztree_unselected", }, id: { A: "_a", ICON: "_ico", SPAN: "_span", SWITCH: "_switch", - UL: "_ul" + UL: "_ul", }, line: { ROOT: "root", @@ -48,16 +50,16 @@ CENTER: "center", BOTTOM: "bottom", NOLINE: "noline", - LINE: "line" + LINE: "line", }, folder: { OPEN: "open", CLOSE: "close", - DOCU: "docu" + DOCU: "docu", }, node: { - CURSELECTED: "curSelectedNode" - } + CURSELECTED: "curSelectedNode", + }, }, //default setting of core _setting = { @@ -75,7 +77,7 @@ showIcon: true, showLine: true, showTitle: true, - txtSelectedEnable: false + txtSelectedEnable: false, }, data: { key: { @@ -84,7 +86,7 @@ name: "name", title: "", url: "url", - icon: "icon" + icon: "icon", }, render: { name: null, @@ -94,12 +96,12 @@ enable: false, idKey: "id", pIdKey: "pId", - rootPId: null + rootPId: null, }, keep: { parent: false, - leaf: false - } + leaf: false, + }, }, async: { enable: false, @@ -111,7 +113,7 @@ url: "", autoParam: [], otherParam: [], - dataFilter: null + dataFilter: null, }, callback: { beforeAsync: null, @@ -134,8 +136,8 @@ onMouseUp: null, onExpand: null, onCollapse: null, - onRemove: null - } + onRemove: null, + }, }, //default root of core //zTree use root to save full data @@ -151,7 +153,7 @@ r.noSelection = true; r.createdNodes = []; r.zId = 0; - r._ver = (new Date()).getTime(); + r._ver = new Date().getTime(); }, //default cache of core _initCache = function (setting) { @@ -188,7 +190,14 @@ }); o.bind(c.ASYNC_ERROR, function (event, treeId, node, XMLHttpRequest, textStatus, errorThrown) { - tools.apply(setting.callback.onAsyncError, [event, treeId, node, XMLHttpRequest, textStatus, errorThrown]); + tools.apply(setting.callback.onAsyncError, [ + event, + treeId, + node, + XMLHttpRequest, + textStatus, + errorThrown, + ]); }); o.bind(c.REMOVE, function (event, treeId, treeNode) { @@ -219,9 +228,12 @@ _eventProxy = function (event) { var target = event.target, setting = data.getSetting(event.data.treeId), - tId = "", node = null, - nodeEventType = "", treeEventType = "", - nodeEventCallback = null, treeEventCallback = null, + tId = "", + node = null, + nodeEventType = "", + treeEventType = "", + nodeEventCallback = null, + treeEventCallback = null, tmp = null; if (tools.eqs(event.type, "mousedown")) { @@ -259,34 +271,41 @@ if (tId.length > 0) { node = data.getNodeCache(setting, tId); switch (nodeEventType) { - case "switchNode" : + case "switchNode": var isParent = data.nodeIsParent(setting, node); if (!isParent) { nodeEventType = ""; - } else if (tools.eqs(event.type, "click") - || (tools.eqs(event.type, "dblclick") && tools.apply(setting.view.dblClickExpand, [setting.treeId, node], setting.view.dblClickExpand))) { + } else if ( + tools.eqs(event.type, "click") || + (tools.eqs(event.type, "dblclick") && + tools.apply( + setting.view.dblClickExpand, + [setting.treeId, node], + setting.view.dblClickExpand + )) + ) { nodeEventCallback = handler.onSwitchNode; } else { nodeEventType = ""; } break; - case "clickNode" : + case "clickNode": nodeEventCallback = handler.onClickNode; break; } } // event to zTree switch (treeEventType) { - case "mousedown" : + case "mousedown": treeEventCallback = handler.onZTreeMousedown; break; - case "mouseup" : + case "mouseup": treeEventCallback = handler.onZTreeMouseup; break; - case "dblclick" : + case "dblclick": treeEventCallback = handler.onZTreeDblclick; break; - case "contextmenu" : + case "contextmenu": treeEventCallback = handler.onZTreeContextmenu; break; } @@ -296,7 +315,7 @@ nodeEventType: nodeEventType, nodeEventCallback: nodeEventCallback, treeEventType: treeEventType, - treeEventCallback: treeEventCallback + treeEventCallback: treeEventCallback, }; return proxyResult; }, @@ -306,16 +325,16 @@ var r = data.getRoot(setting), children = data.nodeChildren(setting, n); n.level = level; - n.tId = setting.treeId + "_" + (++r.zId); + n.tId = setting.treeId + "_" + ++r.zId; n.parentTId = parentNode ? parentNode.tId : null; - n.open = (typeof n.open == "string") ? tools.eqs(n.open, "true") : !!n.open; + n.open = typeof n.open == "string" ? tools.eqs(n.open, "true") : !!n.open; var isParent = data.nodeIsParent(setting, n); if (tools.isArray(children)) { data.nodeIsParent(setting, n, true); n.zAsync = true; } else { isParent = data.nodeIsParent(setting, n, isParent); - n.open = (isParent && !setting.async.enable) ? n.open : false; + n.open = isParent && !setting.async.enable ? n.open : false; n.zAsync = !isParent; } n.isFirstNode = isFirstNode; @@ -349,7 +368,7 @@ afterA: [], innerBeforeA: [], innerAfterA: [], - zTreeTools: [] + zTreeTools: [], }, //method of operate data data = { @@ -394,7 +413,8 @@ _init.roots.push(initRoot); }, addNodesData: function (setting, parentNode, index, nodes) { - var children = data.nodeChildren(setting, parentNode), params; + var children = data.nodeChildren(setting, parentNode), + params; if (!children) { children = data.nodeChildren(setting, parentNode, []); index = -1; @@ -438,7 +458,9 @@ }, fixPIdKeyValue: function (setting, node) { if (setting.data.simpleData.enable) { - node[setting.data.simpleData.pIdKey] = node.parentTId ? node.getParentNode()[setting.data.simpleData.idKey] : setting.data.simpleData.rootPId; + node[setting.data.simpleData.pIdKey] = node.parentTId + ? node.getParentNode()[setting.data.simpleData.idKey] + : setting.data.simpleData.rootPId; } }, getAfterA: function (setting, node, array) { @@ -481,7 +503,7 @@ children = data.nodeChildren(setting, p); for (var i = 0, l = children.length - 1; i <= l; i++) { if (children[i] === node) { - return (i == l ? null : children[i + 1]); + return i == l ? null : children[i + 1]; } } return null; @@ -551,7 +573,7 @@ return result; }, getNodesByFilter: function (setting, nodes, filter, isSingle, invokeParam) { - if (!nodes) return (isSingle ? null : []); + if (!nodes) return isSingle ? null : []; var result = isSingle ? null : []; for (var i = 0, l = nodes.length; i < l; i++) { var node = nodes[i]; @@ -576,7 +598,7 @@ children = data.nodeChildren(setting, p); for (var i = 0, l = children.length; i < l; i++) { if (children[i] === node) { - return (i == 0 ? null : children[i - 1]); + return i == 0 ? null : children[i - 1]; } } return null; @@ -624,7 +646,7 @@ return null; } var key = setting.data.key.children; - if (typeof newChildren !== 'undefined') { + if (typeof newChildren !== "undefined") { node[key] = newChildren; } return node[key]; @@ -634,7 +656,7 @@ return false; } var key = setting.data.key.isParent; - if (typeof newIsParent !== 'undefined') { + if (typeof newIsParent !== "undefined") { if (typeof newIsParent === "string") { newIsParent = tools.eqs(newIsParent, "true"); } @@ -649,11 +671,11 @@ }, nodeName: function (setting, node, newName) { var key = setting.data.key.name; - if (typeof newName !== 'undefined') { + if (typeof newName !== "undefined") { node[key] = newName; } var rawName = "" + node[key]; - if (typeof setting.data.render.name === 'function') { + if (typeof setting.data.render.name === "function") { return setting.data.render.name.call(this, rawName, node); } return rawName; @@ -661,7 +683,7 @@ nodeTitle: function (setting, node) { var t = setting.data.key.title === "" ? setting.data.key.name : setting.data.key.title; var rawTitle = "" + node[t]; - if (typeof setting.data.render.title === 'function') { + if (typeof setting.data.render.title === "function") { return setting.data.render.title.call(this, rawTitle, node); } return rawTitle; @@ -719,7 +741,8 @@ } }, transformTozTreeFormat: function (setting, sNodes) { - var i, l, + var i, + l, key = setting.data.simpleData.idKey, parentKey = setting.data.simpleData.pIdKey; if (!key || key == "" || !sNodes) return []; @@ -746,7 +769,7 @@ } else { return [sNodes]; } - } + }, }, //method of event proxy event = { @@ -762,33 +785,33 @@ }, bindTree: function (setting) { var eventParam = { - treeId: setting.treeId + treeId: setting.treeId, }, o = setting.treeObj; if (!setting.view.txtSelectedEnable) { // for can't select text - o.bind('selectstart', handler.onSelectStart).css({ - "-moz-user-select": "-moz-none" + o.bind("selectstart", handler.onSelectStart).css({ + "-moz-user-select": "-moz-none", }); } - o.bind('click', eventParam, event.proxy); - o.bind('dblclick', eventParam, event.proxy); - o.bind('mouseover', eventParam, event.proxy); - o.bind('mouseout', eventParam, event.proxy); - o.bind('mousedown', eventParam, event.proxy); - o.bind('mouseup', eventParam, event.proxy); - o.bind('contextmenu', eventParam, event.proxy); + o.bind("click", eventParam, event.proxy); + o.bind("dblclick", eventParam, event.proxy); + o.bind("mouseover", eventParam, event.proxy); + o.bind("mouseout", eventParam, event.proxy); + o.bind("mousedown", eventParam, event.proxy); + o.bind("mouseup", eventParam, event.proxy); + o.bind("contextmenu", eventParam, event.proxy); }, unbindTree: function (setting) { var o = setting.treeObj; - o.unbind('selectstart', handler.onSelectStart) - .unbind('click', event.proxy) - .unbind('dblclick', event.proxy) - .unbind('mouseover', event.proxy) - .unbind('mouseout', event.proxy) - .unbind('mousedown', event.proxy) - .unbind('mouseup', event.proxy) - .unbind('contextmenu', event.proxy); + o.unbind("selectstart", handler.onSelectStart) + .unbind("click", event.proxy) + .unbind("dblclick", event.proxy) + .unbind("mouseover", event.proxy) + .unbind("mouseout", event.proxy) + .unbind("mousedown", event.proxy) + .unbind("mouseup", event.proxy) + .unbind("contextmenu", event.proxy); }, doProxy: function (e) { var results = []; @@ -805,7 +828,8 @@ var setting = data.getSetting(e.data.treeId); if (!tools.uCanDo(setting, e)) return true; var results = event.doProxy(e), - r = true, x = false; + r = true, + x = false; for (var i = 0, l = results.length; i < l; i++) { var proxyResult = results[i]; if (proxyResult.nodeEventCallback) { @@ -818,14 +842,15 @@ } } return r; - } + }, }, //method of event handler handler = { onSwitchNode: function (event, node) { var setting = data.getSetting(event.data.treeId); if (node.open) { - if (tools.apply(setting.callback.beforeCollapse, [setting.treeId, node], true) == false) return true; + if (tools.apply(setting.callback.beforeCollapse, [setting.treeId, node], true) == false) + return true; data.getRoot(setting).expandTriggerFlag = true; view.switchNode(setting, node); } else { @@ -837,8 +862,18 @@ }, onClickNode: function (event, node) { var setting = data.getSetting(event.data.treeId), - clickFlag = ((setting.view.autoCancelSelected && (event.ctrlKey || event.metaKey)) && data.isSelectedNode(setting, node)) ? 0 : (setting.view.autoCancelSelected && (event.ctrlKey || event.metaKey) && setting.view.selectedMulti) ? 2 : 1; - if (tools.apply(setting.callback.beforeClick, [setting.treeId, node, clickFlag], true) == false) return true; + clickFlag = + setting.view.autoCancelSelected && + (event.ctrlKey || event.metaKey) && + data.isSelectedNode(setting, node) + ? 0 + : setting.view.autoCancelSelected && + (event.ctrlKey || event.metaKey) && + setting.view.selectedMulti + ? 2 + : 1; + if (tools.apply(setting.callback.beforeClick, [setting.treeId, node, clickFlag], true) == false) + return true; if (clickFlag === 0) { view.cancelPreSelectedNode(setting, node); } else { @@ -873,17 +908,17 @@ if (tools.apply(setting.callback.beforeRightClick, [setting.treeId, node], true)) { tools.apply(setting.callback.onRightClick, [event, setting.treeId, node]); } - return (typeof setting.callback.onRightClick) != "function"; + return typeof setting.callback.onRightClick != "function"; }, onSelectStart: function (e) { var n = e.originalEvent.srcElement.nodeName.toLowerCase(); - return (n === "input" || n === "textarea"); - } + return n === "input" || n === "textarea"; + }, }, //method of tools for zTree tools = { apply: function (fun, param, defaultValue) { - if ((typeof fun) == "function") { + if (typeof fun == "function") { return fun.apply(zt, param ? param : []); } return defaultValue; @@ -891,13 +926,18 @@ canAsync: function (setting, node) { var children = data.nodeChildren(setting, node); var isParent = data.nodeIsParent(setting, node); - return (setting.async.enable && node && isParent && !(node.zAsync || (children && children.length > 0))); + return setting.async.enable && node && isParent && !(node.zAsync || (children && children.length > 0)); }, clone: function (obj) { if (obj === null) return null; var o = tools.isArray(obj) ? [] : {}; for (var i in obj) { - o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === "object" ? tools.clone(obj[i]) : obj[i]); + o[i] = + obj[i] instanceof Date + ? new Date(obj[i].getTime()) + : typeof obj[i] === "object" + ? tools.clone(obj[i]) + : obj[i]; } return o; }, @@ -908,10 +948,9 @@ return Object.prototype.toString.apply(arr) === "[object Array]"; }, isElement: function (o) { - return ( - typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2 - o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName === "string" - ); + return typeof HTMLElement === "object" + ? o instanceof HTMLElement //DOM2 + : o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName === "string"; }, $: function (node, exp, setting) { if (!!exp && typeof exp != "string") { @@ -928,7 +967,10 @@ if (!curDom) return null; while (curDom && curDom.id !== setting.treeId) { for (var i = 0, l = targetExpr.length; curDom.tagName && i < l; i++) { - if (tools.eqs(curDom.tagName, targetExpr[i].tagName) && curDom.getAttribute(targetExpr[i].attrName) !== null) { + if ( + tools.eqs(curDom.tagName, targetExpr[i].tagName) && + curDom.getAttribute(targetExpr[i].attrName) !== null + ) { return curDom; } } @@ -937,14 +979,14 @@ return null; }, getNodeMainDom: function (target) { - return ($(target).parent("li").get(0) || $(target).parentsUntil("li").parent().get(0)); + return $(target).parent("li").get(0) || $(target).parentsUntil("li").parent().get(0); }, isChildOrSelf: function (dom, parentId) { - return ($(dom).closest("#" + parentId).length > 0); + return $(dom).closest("#" + parentId).length > 0; }, uCanDo: function (setting, e) { return true; - } + }, }, //method of operate ztree dom view = { @@ -969,7 +1011,7 @@ view.replaceIcoClass(parentNode, target_icoObj, consts.folder.CLOSE); parentNode.open = false; target_ulObj.css({ - "display": "none" + display: "none", }); } @@ -987,9 +1029,10 @@ if (!nodes) return []; var html = []; - var tmpPNode = (parentNode) ? parentNode : data.getRoot(setting), + var tmpPNode = parentNode ? parentNode : data.getRoot(setting), tmpPChild = data.nodeChildren(setting, tmpPNode), - isFirstNode, isLastNode; + isFirstNode, + isLastNode; if (!tmpPChild || index >= tmpPChild.length - nodes.length) { index = -1; @@ -998,8 +1041,8 @@ for (var i = 0, l = nodes.length; i < l; i++) { var node = nodes[i]; if (initFlag) { - isFirstNode = ((index === 0 || tmpPChild.length == nodes.length) && (i == 0)); - isLastNode = (index < 0 && i == (nodes.length - 1)); + isFirstNode = (index === 0 || tmpPChild.length == nodes.length) && i == 0; + isLastNode = index < 0 && i == nodes.length - 1; data.initNode(setting, level, node, parentNode, isFirstNode, isLastNode, openFlag); data.addNodeCache(setting, node); } @@ -1009,7 +1052,15 @@ var children = data.nodeChildren(setting, node); if (children && children.length > 0) { //make child html first, because checkType - childHtml = view.appendNodes(setting, level + 1, children, node, -1, initFlag, openFlag && node.open); + childHtml = view.appendNodes( + setting, + level + 1, + children, + node, + -1, + initFlag, + openFlag && node.open + ); } if (openFlag) { view.makeDOMNodeMainBefore(html, setting, node); @@ -1022,7 +1073,7 @@ view.makeDOMNodeNameAfter(html, setting, node); data.getAfterA(setting, node, html); if (isParent && node.open) { - view.makeUlHtml(setting, node, html, childHtml.join('')); + view.makeUlHtml(setting, node, html, childHtml.join("")); } view.makeDOMNodeMainAfter(html, setting, node); data.addCreatedNode(setting, node); @@ -1043,8 +1094,8 @@ } var children = data.nodeChildren(setting, node), childHtml = view.appendNodes(setting, node.level + 1, children, node, -1, false, true); - view.makeUlHtml(setting, node, html, childHtml.join('')); - nObj.append(html.join('')); + view.makeUlHtml(setting, node, html, childHtml.join("")); + nObj.append(html.join("")); }, asyncNode: function (setting, node, isSilent, callback) { var i, l; @@ -1061,20 +1112,25 @@ if (node) { node.isAjaxing = true; var icoObj = $$(node, consts.id.ICON, setting); - icoObj.attr({ "style": "", "class": consts.className.BUTTON + " " + consts.className.ICO_LOADING }); + icoObj.attr({ style: "", class: consts.className.BUTTON + " " + consts.className.ICO_LOADING }); } var tmpParam = {}; var autoParam = tools.apply(setting.async.autoParam, [setting.treeId, node], setting.async.autoParam); for (i = 0, l = autoParam.length; node && i < l; i++) { - var pKey = autoParam[i].split("="), spKey = pKey; + var pKey = autoParam[i].split("="), + spKey = pKey; if (pKey.length > 1) { spKey = pKey[1]; pKey = pKey[0]; } tmpParam[spKey] = node[pKey]; } - var otherParam = tools.apply(setting.async.otherParam, [setting.treeId, node], setting.async.otherParam); + var otherParam = tools.apply( + setting.async.otherParam, + [setting.treeId, node], + setting.async.otherParam + ); if (tools.isArray(otherParam)) { for (i = 0, l = otherParam.length; i < l; i += 2) { tmpParam[otherParam[i]] = otherParam[i + 1]; @@ -1091,7 +1147,10 @@ cache: false, type: setting.async.type, url: tools.apply(setting.async.url, [setting.treeId, node], setting.async.url), - data: setting.async.contentType.indexOf('application/json') > -1 ? JSON.stringify(tmpParam) : tmpParam, + data: + setting.async.contentType.indexOf("application/json") > -1 + ? JSON.stringify(tmpParam) + : tmpParam, dataType: setting.async.dataType, headers: setting.async.headers, xhrFields: setting.async.xhrFields, @@ -1118,7 +1177,11 @@ } view.setNodeLineIcos(setting, node); if (newNodes && newNodes !== "") { - newNodes = tools.apply(setting.async.dataFilter, [setting.treeId, node, newNodes], newNodes); + newNodes = tools.apply( + setting.async.dataFilter, + [setting.treeId, node, newNodes], + newNodes + ); view.addNodes(setting, node, -1, !!newNodes ? tools.clone(newNodes) : [], !!isSilent); } else { view.addNodes(setting, node, -1, [], !!isSilent); @@ -1132,14 +1195,21 @@ } if (node) node.isAjaxing = null; view.setNodeLineIcos(setting, node); - setting.treeObj.trigger(consts.event.ASYNC_ERROR, [setting.treeId, node, XMLHttpRequest, textStatus, errorThrown]); - } + setting.treeObj.trigger(consts.event.ASYNC_ERROR, [ + setting.treeId, + node, + XMLHttpRequest, + textStatus, + errorThrown, + ]); + }, }); return true; }, cancelPreSelectedNode: function (setting, node, excludeNode) { var list = data.getRoot(setting).curSelectedList, - i, n; + i, + n; for (i = list.length - 1; i >= 0; i--) { n = list[i]; if (node === n || (!node && (!excludeNode || excludeNode !== n))) { @@ -1169,10 +1239,14 @@ createNodes: function (setting, level, nodes, parentNode, index) { if (!nodes || nodes.length == 0) return; var root = data.getRoot(setting), - openFlag = !parentNode || parentNode.open || !!$$(data.nodeChildren(setting, parentNode)[0], setting).get(0); + openFlag = + !parentNode || + parentNode.open || + !!$$(data.nodeChildren(setting, parentNode)[0], setting).get(0); root.createdNodes = []; var zTreeHtml = view.appendNodes(setting, level, nodes, parentNode, index, true, openFlag), - parentObj, nextObj; + parentObj, + nextObj; if (!parentNode) { parentObj = setting.treeObj; @@ -1189,9 +1263,9 @@ nextObj = parentObj.children()[index]; } if (index >= 0 && nextObj) { - $(nextObj).before(zTreeHtml.join('')); + $(nextObj).before(zTreeHtml.join("")); } else { - parentObj.append(zTreeHtml.join('')); + parentObj.append(zTreeHtml.join("")); } } @@ -1228,7 +1302,12 @@ callback = tmpCb; root.expandTriggerFlag = false; } - if (!node.open && isParent && ((!$$(node, consts.id.UL, setting).get(0)) || (children && children.length > 0 && !$$(children[0], setting).get(0)))) { + if ( + !node.open && + isParent && + (!$$(node, consts.id.UL, setting).get(0) || + (children && children.length > 0 && !$$(children[0], setting).get(0))) + ) { view.appendParentULDom(setting, node); view.createNodeCallback(setting); } @@ -1263,7 +1342,11 @@ } else { view.replaceSwitchClass(node, switchObj, consts.folder.CLOSE); view.replaceIcoClass(node, icoObj, consts.folder.CLOSE); - if (animateFlag == false || setting.view.expandSpeed == "" || !(children && children.length > 0)) { + if ( + animateFlag == false || + setting.view.expandSpeed == "" || + !(children && children.length > 0) + ) { ulObj.hide(); tools.apply(callback, []); } else { @@ -1288,13 +1371,14 @@ }, expandCollapseSonNode: function (setting, node, expandFlag, animateFlag, callback) { var root = data.getRoot(setting), - treeNodes = (node) ? data.nodeChildren(setting, node) : data.nodeChildren(setting, root), - selfAnimateSign = (node) ? false : animateFlag, + treeNodes = node ? data.nodeChildren(setting, node) : data.nodeChildren(setting, root), + selfAnimateSign = node ? false : animateFlag, expandTriggerFlag = data.getRoot(setting).expandTriggerFlag; data.getRoot(setting).expandTriggerFlag = false; if (treeNodes) { for (var i = 0, l = treeNodes.length; i < l; i++) { - if (treeNodes[i]) view.expandCollapseSonNode(setting, treeNodes[i], expandFlag, selfAnimateSign); + if (treeNodes[i]) + view.expandCollapseSonNode(setting, treeNodes[i], expandFlag, selfAnimateSign); } } data.getRoot(setting).expandTriggerFlag = expandTriggerFlag; @@ -1315,21 +1399,53 @@ }, makeDOMNodeIcon: function (html, setting, node) { var nameStr = data.nodeName(setting, node), - name = setting.view.nameIsHTML ? nameStr : nameStr.replace(/&/g, '&').replace(//g, '>'); - html.push("", name, ""); + name = setting.view.nameIsHTML + ? nameStr + : nameStr.replace(/&/g, "&").replace(//g, ">"); + html.push( + "", + name, + "" + ); }, makeDOMNodeLine: function (html, setting, node) { - html.push(""); + html.push( + "" + ); }, makeDOMNodeMainAfter: function (html, setting, node) { html.push(""); }, makeDOMNodeMainBefore: function (html, setting, node) { - html.push("
  • "); + html.push( + "
  • " + ); }, makeDOMNodeNameAfter: function (html, setting, node) { html.push(""); @@ -1343,24 +1459,36 @@ for (var f in fontcss) { fontStyle.push(f, ":", fontcss[f], ";"); } - html.push(" 0) ? " href='" + url + "'" : ""), " target='", view.makeNodeTarget(node), "' style='", fontStyle.join(''), - "'"); + html.push( + " 0 ? " href='" + url + "'" : "", + " target='", + view.makeNodeTarget(node), + "' style='", + fontStyle.join(""), + "'" + ); if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle) && title) { - html.push("title='", title.replace(/'/g, "'").replace(//g, '>'), "'"); + html.push("title='", title.replace(/'/g, "'").replace(//g, ">"), "'"); } html.push(">"); }, makeNodeFontCss: function (setting, node) { var fontCss = tools.apply(setting.view.fontCss, [setting.treeId, node], setting.view.fontCss); - return (fontCss && ((typeof fontCss) != "function")) ? fontCss : {}; + return fontCss && typeof fontCss != "function" ? fontCss : {}; }, makeNodeClasses: function (setting, node) { var classes = tools.apply(setting.view.nodeClasses, [setting.treeId, node], setting.view.nodeClasses); - return (classes && (typeof classes !== "function")) ? classes : { add: [], remove: [] }; + return classes && typeof classes !== "function" ? classes : { add: [], remove: [] }; }, makeNodeIcoClass: function (setting, node) { var icoCss = ["ico"]; @@ -1373,19 +1501,27 @@ icoCss.push(consts.folder.DOCU); } } - return "x-icon b-font " + consts.className.ICON + " " + icoCss.join('_'); + return "x-icon b-font " + consts.className.ICON + " " + icoCss.join("_"); }, makeNodeIcoStyle: function (setting, node) { var icoStyle = []; if (!node.isAjaxing) { var isParent = data.nodeIsParent(setting, node); - var icon = (isParent && node.iconOpen && node.iconClose) ? (node.open ? node.iconOpen : node.iconClose) : node[setting.data.key.icon]; + var icon = + isParent && node.iconOpen && node.iconClose + ? node.open + ? node.iconOpen + : node.iconClose + : node[setting.data.key.icon]; if (icon) icoStyle.push("background:url(", icon, ") 0 0 no-repeat;"); - if (setting.view.showIcon == false || !tools.apply(setting.view.showIcon, [setting.treeId, node], true)) { + if ( + setting.view.showIcon == false || + !tools.apply(setting.view.showIcon, [setting.treeId, node], true) + ) { icoStyle.push("display:none;"); } } - return icoStyle.join(''); + return icoStyle.join(""); }, makeNodeLineClass: function (setting, node) { var lineClass = []; @@ -1407,25 +1543,45 @@ } else { lineClass.push(consts.folder.DOCU); } - return view.makeNodeLineClassEx(node) + lineClass.join('_'); + return view.makeNodeLineClassEx(node) + lineClass.join("_"); }, makeNodeLineClassEx: function (node) { - return consts.className.BUTTON + " " + consts.className.LEVEL + node.level + " " + consts.className.SWITCH + " "; + return ( + consts.className.BUTTON + + " " + + consts.className.LEVEL + + node.level + + " " + + consts.className.SWITCH + + " " + ); }, makeNodeTarget: function (node) { - return (node.target || "_blank"); + return node.target || "_blank"; }, makeNodeUrl: function (setting, node) { var urlKey = setting.data.key.url; return node[urlKey] ? node[urlKey] : null; }, makeUlHtml: function (setting, node, html, content) { - html.push("