Browse Source

Merge branch 'es6' of ssh://code.fineres.com:7999/~treecat/fineui into es6

# Conflicts:
#	src/base/index.js
es6
Treecat 2 years ago
parent
commit
f29b613517
  1. 4
      demo/js/core/abstract/combination/demo.combo.js
  2. 4
      demo/js/core/abstract/combination/demo.combo_group.js
  3. 14
      src/base/0.base.js
  4. 2
      src/base/1.pane.js
  5. 972
      src/base/combination/bubble.js
  6. 682
      src/base/combination/combo.js
  7. 245
      src/base/combination/expander.js
  8. 326
      src/base/combination/group.button.js
  9. 98
      src/base/combination/group.combo.js
  10. 130
      src/base/combination/group.virtual.js
  11. 12
      src/base/combination/index.js
  12. 221
      src/base/combination/loader.js
  13. 162
      src/base/combination/navigation.js
  14. 306
      src/base/combination/searcher.js
  15. 278
      src/base/combination/switcher.js
  16. 177
      src/base/combination/tab.js
  17. 142
      src/base/combination/tree.button.js
  18. 54
      src/base/foundation/message.js
  19. 100
      src/base/index.js
  20. 4
      src/base/layer/index.js
  21. 2
      src/base/layer/layer.drawer.js
  22. 2
      src/base/layer/layer.popup.js
  23. 4
      src/base/layer/layer.searcher.js
  24. 3
      src/base/list/index.js
  25. 2
      src/base/list/listview.js
  26. 2
      src/base/list/virtualgrouplist.js
  27. 2
      src/base/list/virtuallist.js
  28. 2
      src/base/single/0.single.js
  29. 6
      src/base/single/1.text.js
  30. 4
      src/base/single/a/a.js
  31. 2
      src/base/single/button/button.basic.js
  32. 17
      src/base/single/button/index.js
  33. 5
      src/base/single/index.js
  34. 4
      src/base/single/tip/0.tip.js
  35. 3
      src/base/single/tip/index.js
  36. 4
      src/base/single/tip/tip.toast.js
  37. 4
      src/base/single/tip/tip.tooltip.js
  38. 145
      src/core/2.base.js
  39. 6
      src/core/3.ob.js
  40. 16
      src/core/4.widget.js
  41. 26
      src/core/5.inject.js
  42. 4
      src/core/action/action.js
  43. 4
      src/core/action/action.show.js
  44. 2
      src/core/action/index.js
  45. 4
      src/core/behavior/0.behavior.js
  46. 4
      src/core/behavior/behavior.highlight.js
  47. 4
      src/core/behavior/behavior.redmark.js
  48. 3
      src/core/behavior/index.js
  49. 4
      src/core/controller/0.controller.js
  50. 4
      src/core/controller/controller.broadcast.js
  51. 4
      src/core/controller/controller.bubbles.js
  52. 4
      src/core/controller/controller.drawer.js
  53. 4
      src/core/controller/controller.layer.js
  54. 4
      src/core/controller/controller.masker.js
  55. 4
      src/core/controller/controller.popover.js
  56. 4
      src/core/controller/controller.resizer.js
  57. 4
      src/core/controller/controller.tooltips.js
  58. 9
      src/core/controller/index.js
  59. 6
      src/core/func/__test__/function.test.js
  60. 1661
      src/core/func/alias.js
  61. 29
      src/core/func/array.js
  62. 615
      src/core/func/date.js
  63. 300
      src/core/func/function.js
  64. 6
      src/core/func/index.js
  65. 274
      src/core/func/number.js
  66. 224
      src/core/func/string.js
  67. 93
      src/core/index.js
  68. 52
      src/core/listener/listener.show.js
  69. 4
      src/core/loader/loader.style.js
  70. 123
      src/core/platform/web/detectElementResize.js
  71. 863
      src/core/utils/chinesePY.js

4
demo/js/core/abstract/combination/demo.combo.js

@ -29,7 +29,7 @@ Demo.Func = BI.inherit(BI.Widget, {
iconCls1: "close-ha-font", iconCls1: "close-ha-font",
iconCls2: "close-ha-font" iconCls2: "close-ha-font"
}, },
children: [{ items: [{
type: "bi.single_select_item", type: "bi.single_select_item",
height: 25, height: 25,
text: "一月", text: "一月",
@ -385,7 +385,7 @@ Demo.Func = BI.inherit(BI.Widget, {
}, },
width: 200 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({ var monthCombo = BI.createWidget({
type: "bi.combo", type: "bi.combo",

4
demo/js/core/abstract/combination/demo.combo_group.js

@ -12,7 +12,7 @@ Demo.Func = BI.inherit(BI.Widget, {
height: 25, height: 25,
iconCls: "close-ha-font" iconCls: "close-ha-font"
}, },
children: [{ items: [{
type: "bi.single_select_item", type: "bi.single_select_item",
height: 25, height: 25,
text: "一月", text: "一月",
@ -63,7 +63,7 @@ Demo.Func = BI.inherit(BI.Widget, {
}, },
width: 200 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({ return BI.createWidget({
type: "bi.left", type: "bi.left",

14
src/base/0.base.js

@ -7,7 +7,7 @@ import {
PopoverController, PopoverController,
ResizeController, ResizeController,
TooltipsController, TooltipsController,
StyleLoaderManager StyleLoaderManager,
} from "../core"; } from "../core";
const Resizers = new ResizeController(); const Resizers = new ResizeController();
@ -20,18 +20,6 @@ const Drawers = new DrawerController();
const Broadcasts = new BroadcastController(); const Broadcasts = new BroadcastController();
const StyleLoaders = new StyleLoaderManager(); const StyleLoaders = new StyleLoaderManager();
BI.extend(BI, {
Resizers,
Layers,
Maskers,
Bubbles,
Tooltips,
Popovers,
Drawers,
Broadcasts,
StyleLoaders
});
export { export {
Resizers, Resizers,
Layers, Layers,

2
src/base/1.pane.js

@ -10,7 +10,7 @@ import { Widget, shortcut, isNotEmptyString, extend, isNull, isEmpty, createWidg
import { Layers } from "./0.base"; import { Layers } from "./0.base";
@shortcut() @shortcut()
export default class Pane extends Widget { export class Pane extends Widget {
static xtype = "bi.pane"; static xtype = "bi.pane";
static EVENT_LOADED = "EVENT_LOADED"; static EVENT_LOADED = "EVENT_LOADED";
static EVENT_LOADING = "EVENT_LOADING"; static EVENT_LOADING = "EVENT_LOADING";

972
src/base/combination/bubble.js

File diff suppressed because it is too large Load Diff

682
src/base/combination/combo.js

@ -1,374 +1,374 @@
!(function () { /**
var needHideWhenAnotherComboOpen = {}; * @class BI.Combo
var currentOpenedCombos = {}; * @extends BI.Widget
*/
/** import { shortcut, Widget, Controller, extend, createWidget, nextTick, bind, isNotNull, isNull, isFunction, each } from "../../core";
* @class BI.Combo import { Bubble } from "./bubble";
* @extends BI.Widget import { Resizers } from "../0.base";
*/
BI.Combo = BI.inherit(BI.Bubble, {
_const: {
TRIANGLE_LENGTH: 12,
},
_defaultConfig: function () {
var conf = BI.Combo.superclass._defaultConfig.apply(this, arguments);
return BI.extend(conf, { let needHideWhenAnotherComboOpen = {};
baseCls: (conf.baseCls || "") + " bi-combo" + (BI.isIE() ? " hack" : ""), let currentOpenedCombos = {};
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: function () { @shortcut()
var self = this, o = this.options; export class Combo extends Bubble {
this._initCombo(); static xtype = "bi.combo";
// 延迟绑定事件,这样可以将自己绑定的事情优先执行
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);
}
}
});
self.element.on("mouseenter." + self.getName(), function (e) { static EVENT_TRIGGER_CHANGE = "EVENT_TRIGGER_CHANGE";
if (self.isEnabled() && self.isValid() && self.combo.isEnabled() && self.combo.isValid()) { static EVENT_CHANGE = "EVENT_CHANGE";
self.element.addClass(o.hoverClass); 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();
} }
}); if (type === BI.Events.EXPAND) {
self.element.on("mouseleave." + self.getName(), function (e) { this._popupView();
if (self.isEnabled() && self.isValid() && self.combo.isEnabled() && self.combo.isValid()) {
self.element.removeClass(o.hoverClass);
} }
}); if (type === BI.Events.COLLAPSE) {
this._hideView();
BI.createWidget(BI.extend({ }
element: this, if (type === BI.Events.EXPAND) {
scrolly: false, this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args);
}, BI.LogicFactory.createLogic("vertical", BI.extend(o.logic, { this.fireEvent(Combo.EVENT_EXPAND);
items: [ }
{ el: this.combo } if (type === BI.Events.COLLAPSE) {
], this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args);
})))); this.isViewVisible() && this.fireEvent(Combo.EVENT_COLLAPSE);
o.isDefaultInit && (this._assertPopupView()); }
BI.Resizers.add(this.getName(), BI.bind(function (e) { if (type === BI.Events.CLICK) {
// 如果resize对象是combo的子元素,则不应该收起,或交由hideChecker去处理 this.fireEvent(Combo.EVENT_TRIGGER_CHANGE, obj);
if (this.isViewVisible()) {
BI.isNotNull(e) ? this._hideIf(e) : this._hideView();
} }
}, 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) { this.element.on("mouseenter." + this.getName(), (e) => {
var o = this.options; if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid()) {
this.fireEvent(BI.Combo.EVENT_BEFORE_HIDEVIEW); this.element.addClass(hoverClass);
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.on("mouseleave." + this.getName(), (e) => {
this.element.removeClass(this.options.hoverClass); if (this.isEnabled() && this.isValid() && this.combo.isEnabled() && this.combo.isValid()) {
// 应对bi-focus-shadow在收起时不失焦 this.element.removeClass(hoverClass);
this.element.blur();
} }
});
this.element.removeClass(this.options.comboClass); createWidget(extend({
delete needHideWhenAnotherComboOpen[this.getName()]; element: this,
delete currentOpenedCombos[this.getName()]; scrolly: false,
}, BI.LogicFactory.createLogic("vertical", extend(logic, {
o.hideWhenClickOutside && BI.Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()).unbind("mousewheel." + this.getName()); items: [
BI.EVENT_BLUR && o.hideWhenBlur && BI.Widget._renderEngine.createElement(window).unbind("blur." + this.getName()); { el: this.combo }
this.fireEvent(BI.Combo.EVENT_AFTER_HIDEVIEW, e); ],
}, }))));
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) { _assertPopupView() {
var self = this, o = this.options; const { showArrow, value, hideWhenClickOutside, hideWhenBlur } = this.options;
this._assertPopupViewRender(); if (isNull(this.popupView)) {
this.fireEvent(BI.Combo.EVENT_BEFORE_POPUPVIEW); this.popupView = createWidget(isFunction(this.options.popup) ? this.options.popup() : this.options.popup, {
// popupVisible是为了获取其宽高, 放到可视范围之外以防止在IE下闪一下 type: "bi.popup_view",
this.popupView.css({ left: -99999, top: -99999 }); showArrow,
this.popupView.visible(); value,
BI.each(needHideWhenAnotherComboOpen, function (i, combo) { }, this);
if (i !== self.getName()) { this.popupView.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => {
if (combo && combo._hideIf(e, true) === true) { if (type === BI.Events.CLICK) {
delete needHideWhenAnotherComboOpen[i]; 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); _hideView(e) {
o.hideWhenClickOutside && BI.Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()).unbind("mousewheel." + this.getName()); const { hideWhenClickOutside, hideWhenBlur } = this.options;
o.hideWhenClickOutside && BI.Widget._renderEngine.createElement(document).unbind("mousewheel." + this.getName()); this.fireEvent(Combo.EVENT_BEFORE_HIDEVIEW);
BI.EVENT_BLUR && o.hideWhenBlur && BI.Widget._renderEngine.createElement(window).unbind("blur." + this.getName()); 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)); if (!e || !this.combo.element.__isMouseInBounds__(e)) {
o.hideWhenClickOutside && BI.Widget._renderEngine.createElement(document).bind("mousewheel." + this.getName(), BI.bind(this._hideIf, this)); this.element.removeClass(this.options.hoverClass);
BI.EVENT_BLUR && o.hideWhenBlur && BI.Widget._renderEngine.createElement(window).bind("blur." + this.getName(), BI.bind(this._hideIf, this)); // 应对bi-focus-shadow在收起时不失焦
this.fireEvent(BI.Combo.EVENT_AFTER_POPUPVIEW); this.element.blur();
}, }
adjustHeight: function (e) { this.element.removeClass(this.options.comboClass);
var o = this.options, p = {}; delete needHideWhenAnotherComboOpen[this.getName()];
if (!this.popupView) { delete currentOpenedCombos[this.getName()];
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;
var positionRelativeElement = BI.DOM.getPositionRelativeContainingBlock( hideWhenClickOutside && Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()).unbind("mousewheel." + this.getName());
BI.isNull(o.container) BI.EVENT_BLUR && hideWhenBlur && Widget._renderEngine.createElement(window).unbind("blur." + this.getName());
? this.element[0] this.fireEvent(Combo.EVENT_AFTER_HIDEVIEW, e);
: BI.isWidget(o.container) }
? o.container.element[0]
: BI.Widget._renderEngine.createElement(BI.isFunction(o.container) ? o.container() : o.container)[0]
);
switch (o.direction) { _popupView(e) {
case "bottom": const { hideWhenClickOutside, hideWhenBlur } = this.options;
case "bottom,right": this._assertPopupViewRender();
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); this.fireEvent(Combo.EVENT_BEFORE_POPUPVIEW);
break; // popupVisible是为了获取其宽高, 放到可视范围之外以防止在IE下闪一下
case "top": this.popupView.css({ left: -99999, top: -99999 });
case "top,right": this.popupView.visible();
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); each(needHideWhenAnotherComboOpen, (i, combo) => {
break; if (i !== this.getName()) {
case "left": if (combo && combo._hideIf(e, true) === true) {
case "left,bottom": delete needHideWhenAnotherComboOpen[i];
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;
} }
});
currentOpenedCombos[this.getName()] = this;
this.options.hideWhenAnotherComboOpen && (needHideWhenAnotherComboOpen[this.getName()] = this);
this.adjustWidth(e);
this.adjustHeight(e);
var width = this.combo.element.outerWidth(); this.element.addClass(this.options.comboClass);
var height = this.combo.element.outerHeight(); hideWhenClickOutside && Widget._renderEngine.createElement(document).unbind("mousedown." + this.getName()).unbind("mousewheel." + this.getName());
this.popupView.setDirection && this.popupView.setDirection(p.dir, { hideWhenClickOutside && Widget._renderEngine.createElement(document).unbind("mousewheel." + this.getName());
width: width, BI.EVENT_BLUR && hideWhenBlur && Widget._renderEngine.createElement(window).unbind("blur." + this.getName());
height: height,
offsetStyle: o.offsetStyle,
adjustXOffset: o.adjustXOffset,
adjustYOffset: o.adjustYOffset,
offset: this.combo.element.offset(),
});
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; if ("adaptHeight" in p) {
var scaleY = positonedRect.height / positionRelativeElement.offsetHeight; this.resetListHeight(p.adaptHeight);
}
p.top && (p.top = Math.round(p.top / scaleY + positionRelativeElement.scrollTop)); const width = this.combo.element.outerWidth();
p.left && (p.left = Math.round(p.left / scaleX + positionRelativeElement.scrollLeft)); 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) { const positonedRect = positionRelativeElement.getBoundingClientRect();
this.resetListHeight(p.adaptHeight);
}
if ("left" in p) { const scaleX = positonedRect.width / positionRelativeElement.offsetWidth;
this.popupView.element.css({ const scaleY = positonedRect.height / positionRelativeElement.offsetHeight;
left: p.left,
});
}
if ("top" in p) {
this.popupView.element.css({
top: p.top,
});
}
this.position = p;
this.popupView.setVisible(isVisible);
},
destroyed: function () { p.top && (p.top = p.top / scaleY);
BI.Widget._renderEngine.createElement(document) p.left && (p.left = p.left / scaleX);
.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";
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"; destroyed() {
BI.Combo.EVENT_AFTER_POPUPVIEW = "EVENT_AFTER_POPUPVIEW"; Widget._renderEngine.createElement(document)
BI.Combo.EVENT_BEFORE_HIDEVIEW = "EVENT_BEFORE_HIDEVIEW"; .unbind("click." + this.getName())
BI.Combo.EVENT_AFTER_HIDEVIEW = "EVENT_AFTER_HIDEVIEW"; .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 = {};
};

245
src/base/combination/expander.js

@ -6,9 +6,25 @@
* @class BI.Expander * @class BI.Expander
* @extends BI.Widget * @extends BI.Widget
*/ */
BI.Expander = BI.inherit(BI.Widget, { import { shortcut, Widget, Controller, extend, nextTick, each, debounce, isNull, createWidget } from "../../core";
_defaultConfig: function () {
return BI.extend(BI.Expander.superclass._defaultConfig.apply(this, arguments), { @shortcut()
export 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", baseCls: "bi-expander",
trigger: "click", trigger: "click",
toggle: true, toggle: true,
@ -19,48 +35,48 @@ BI.Expander = BI.inherit(BI.Widget, {
expanderClass: "bi-expander-popup", expanderClass: "bi-expander-popup",
hoverClass: "bi-expander-hover", hoverClass: "bi-expander-hover",
}); });
}, }
render: function () { render() {
var self = this, o = this.options; const { el, hoverClass, isDefaultInit } = this.options;
this._expanded = !!o.el.open; this._expanded = !!el.open;
this._initExpander(); this._initExpander();
// 延迟绑定事件,这样可以将自己绑定的事情优先执行 // 延迟绑定事件,这样可以将自己绑定的事情优先执行
BI.nextTick(() => { nextTick(() => {
!this.isDestroyed() && this._initPullDownAction(); !this.isDestroyed() && this._initPullDownAction();
}); });
this.expander.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { this.expander.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => {
if (self.isEnabled() && self.isValid()) { if (this.isEnabled() && this.isValid()) {
if (type === BI.Events.EXPAND) { if (type === BI.Events.EXPAND) {
self._popupView(); this._popupView();
} }
if (type === BI.Events.COLLAPSE) { if (type === BI.Events.COLLAPSE) {
self._hideView(); this._hideView();
} }
if (type === BI.Events.EXPAND) { if (type === BI.Events.EXPAND) {
self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args);
self.fireEvent(BI.Expander.EVENT_EXPAND); this.fireEvent(Expander.EVENT_EXPAND);
} }
if (type === BI.Events.COLLAPSE) { if (type === BI.Events.COLLAPSE) {
self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args);
self.isViewVisible() && self.fireEvent(BI.Expander.EVENT_COLLAPSE); this.isViewVisible() && this.fireEvent(Expander.EVENT_COLLAPSE);
} }
if (type === BI.Events.CLICK) { 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 () { this.element.hover(() => {
if (self.isEnabled() && self.isValid() && self.expander.isEnabled() && self.expander.isValid()) { if (this.isEnabled() && this.isValid() && this.expander.isEnabled() && this.expander.isValid()) {
self.element.addClass(o.hoverClass); this.element.addClass(hoverClass);
} }
}, function () { }, () => {
if (self.isEnabled() && self.isValid() && self.expander.isEnabled() && self.expander.isValid()) { if (this.isEnabled() && this.isValid() && this.expander.isEnabled() && this.expander.isValid()) {
self.element.removeClass(o.hoverClass); this.element.removeClass(hoverClass);
} }
}); });
BI.createWidget({ createWidget({
type: "bi.vertical", type: "bi.vertical",
scrolly: false, scrolly: false,
element: this, element: this,
@ -68,13 +84,13 @@ BI.Expander = BI.inherit(BI.Widget, {
{ el: this.expander } { el: this.expander }
], ],
}); });
o.isDefaultInit && this._assertPopupView(); isDefaultInit && this._assertPopupView();
if (this.expander.isOpened() === true) { if (this.expander.isOpened() === true) {
this._popupView(); this._popupView();
} }
}, }
_toggle: function () { _toggle() {
this._assertPopupViewRender(); this._assertPopupViewRender();
if (this.popupView.isVisible()) { if (this.popupView.isVisible()) {
this._hideView(); this._hideView();
@ -83,40 +99,40 @@ BI.Expander = BI.inherit(BI.Widget, {
this._popupView(); this._popupView();
} }
} }
}, }
_initPullDownAction: function () { _initPullDownAction() {
var self = this, o = this.options; const { toggle } = this.options;
var evs = this.options.trigger.split(","); const evs = this.options.trigger.split(",");
BI.each(evs, function (i, e) { each(evs, (i, e) => {
switch (e) { switch (e) {
case "hover": case "hover":
self.element[e](function (e) { this.element[e]((e) => {
if (self.isEnabled() && self.isValid() && self.expander.isEnabled() && self.expander.isValid()) { if (this.isEnabled() && this.isValid() && this.expander.isEnabled() && this.expander.isValid()) {
self._popupView(); this._popupView();
self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.expander); this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.expander);
self.fireEvent(BI.Expander.EVENT_EXPAND); this.fireEvent(Expander.EVENT_EXPAND);
} }
}, function () { }, () => {
if (self.isEnabled() && self.isValid() && self.expander.isEnabled() && self.expander.isValid() && o.toggle) { if (this.isEnabled() && this.isValid() && this.expander.isEnabled() && this.expander.isValid() && toggle) {
self._hideView(); this._hideView();
self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.expander); this.fireEvent(Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", this.expander);
self.fireEvent(BI.Expander.EVENT_COLLAPSE); this.fireEvent(Expander.EVENT_COLLAPSE);
} }
}); });
break; break;
case "click": case "click":
if (e) { if (e) {
self.element.off(e + "." + self.getName()).on(e + "." + self.getName(), BI.debounce(function (e) { this.element.off(e + "." + this.getName()).on(e + "." + this.getName(), debounce((e) => {
if (self.expander.element.__isMouseInBounds__(e)) { if (this.expander.element.__isMouseInBounds__(e)) {
if (self.isEnabled() && self.isValid() && self.expander.isEnabled() && self.expander.isValid()) { if (this.isEnabled() && this.isValid() && this.expander.isEnabled() && this.expander.isValid()) {
o.toggle ? self._toggle() : self._popupView(); toggle ? this._toggle() : this._popupView();
if (self.isExpanded()) { if (this.isExpanded()) {
self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.expander); this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.expander);
self.fireEvent(BI.Expander.EVENT_EXPAND); this.fireEvent(Expander.EVENT_EXPAND);
} else { } else {
self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.expander); this.fireEvent(Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", this.expander);
self.fireEvent(BI.Expander.EVENT_COLLAPSE); this.fireEvent(Expander.EVENT_COLLAPSE);
} }
} }
} }
@ -130,16 +146,16 @@ BI.Expander = BI.inherit(BI.Widget, {
break; break;
} }
}); });
}, }
_initExpander: function () { _initExpander() {
this.expander = BI.createWidget(this.options.el); this.expander = createWidget(this.options.el);
}, }
_assertPopupView: function () { _assertPopupView() {
var self = this, o = this.options; const { value } = this.options;
if (BI.isNull(this.popupView)) { if (isNull(this.popupView)) {
this.popupView = BI.createWidget(this.options.popup, { this.popupView = createWidget(this.options.popup, {
type: "bi.button_group", type: "bi.button_group",
cls: "expander-popup", cls: "expander-popup",
layouts: [{ layouts: [{
@ -147,26 +163,26 @@ BI.Expander = BI.inherit(BI.Widget, {
hgap: 0, hgap: 0,
vgap: 0, vgap: 0,
}], }],
value: o.value, value,
}, this); }, this);
this.popupView.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { this.popupView.on(Controller.EVENT_CHANGE, (type, value, obj, ...args)=> {
self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args);
if (type === BI.Events.CLICK) { if (type === BI.Events.CLICK) {
// self.setValue(self.getValue()); // self.setValue(self.getValue());
self.fireEvent(BI.Expander.EVENT_CHANGE, value, obj); this.fireEvent(Expander.EVENT_CHANGE, value, obj);
} }
}); });
this.popupView.setVisible(this.isExpanded()); this.popupView.setVisible(this.isExpanded());
BI.nextTick(function () { nextTick(() => {
self.fireEvent(BI.Expander.EVENT_AFTER_INIT); this.fireEvent(Expander.EVENT_AFTER_INIT);
}); });
} }
}, }
_assertPopupViewRender: function () { _assertPopupViewRender() {
this._assertPopupView(); this._assertPopupView();
if (!this._rendered) { if (!this._rendered) {
BI.createWidget({ createWidget({
type: "bi.vertical", type: "bi.vertical",
scrolly: false, scrolly: false,
element: this, element: this,
@ -176,113 +192,100 @@ BI.Expander = BI.inherit(BI.Widget, {
}); });
this._rendered = true; this._rendered = true;
} }
}, }
_hideView: function () { _hideView() {
this.fireEvent(BI.Expander.EVENT_BEFORE_HIDEVIEW); this.fireEvent(Expander.EVENT_BEFORE_HIDEVIEW);
this._expanded = false; this._expanded = false;
this.expander.setOpened(false); this.expander.setOpened(false);
this.popupView && this.popupView.invisible(); this.popupView && this.popupView.invisible();
this.element.removeClass(this.options.expanderClass); 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._assertPopupViewRender();
this.fireEvent(BI.Expander.EVENT_BEFORE_POPUPVIEW); this.fireEvent(Expander.EVENT_BEFORE_POPUPVIEW);
this._expanded = true; this._expanded = true;
this.expander.setOpened(true); this.expander.setOpened(true);
this.popupView.visible(); this.popupView.visible();
this.element.addClass(this.options.expanderClass); 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._assertPopupView();
this.popupView && this.popupView.populate.apply(this.popupView, arguments); this.popupView && this.popupView.populate.apply(this.popupView, arguments);
this.expander.populate && this.expander.populate.apply(this.expander, arguments); this.expander.populate && this.expander.populate.apply(this.expander, arguments);
}, }
_setEnable: function (arg) { _setEnable(arg) {
BI.Expander.superclass._setEnable.apply(this, arguments); super._setEnable(arguments);
!arg && this.element.removeClass(this.options.hoverClass); !arg && this.element.removeClass(this.options.hoverClass);
!arg && this.isViewVisible() && this._hideView(); !arg && this.isViewVisible() && this._hideView();
}, }
setValue: function (v) { setValue(v) {
this.expander.setValue(v); this.expander.setValue(v);
if (BI.isNull(this.popupView)) { if (isNull(this.popupView)) {
this.options.popup.value = v; this.options.popup.value = v;
} else { } else {
this.popupView.setValue(v); this.popupView.setValue(v);
} }
}, }
getValue: function () { getValue() {
if (BI.isNull(this.popupView)) { if (isNull(this.popupView)) {
return this.options.popup.value; return this.options.popup.value;
} else { } else {
return this.popupView.getValue(); return this.popupView.getValue();
} }
}, }
isViewVisible: function () { isViewVisible() {
return this.isEnabled() && this.expander.isEnabled() && !!this.popupView && this.popupView.isVisible(); return this.isEnabled() && this.expander.isEnabled() && !!this.popupView && this.popupView.isVisible();
}, }
isExpanded: function () { isExpanded() {
return this._expanded; return this._expanded;
}, }
showView: function () { showView() {
if (this.isEnabled() && this.expander.isEnabled()) { if (this.isEnabled() && this.expander.isEnabled()) {
this._popupView(); this._popupView();
} }
}, }
hideView: function () { hideView() {
this._hideView(); this._hideView();
}, }
getView: function () { getView() {
return this.popupView; return this.popupView;
}, }
getAllLeaves: function () { getAllLeaves() {
return this.popupView && this.popupView.getAllLeaves(); return this.popupView && this.popupView.getAllLeaves();
}, }
getNodeById: function (id) { getNodeById(id) {
if (this.expander.options.id === id) { if (this.expander.options.id === id) {
return this.expander; return this.expander;
} }
return this.popupView && this.popupView.getNodeById(id); return this.popupView && this.popupView.getNodeById(id);
}, }
getNodeByValue: function (value) { getNodeByValue(value) {
if (this.expander.getValue() === value) { if (this.expander.getValue() === value) {
return this.expander; return this.expander;
} }
return this.popupView && this.popupView.getNodeByValue(value); 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);
}
}

326
src/base/combination/group.button.js

@ -3,10 +3,16 @@
* @class BI.ButtonGroup * @class BI.ButtonGroup
* @extends BI.Widget * @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, { @shortcut()
_defaultConfig: function () { export class ButtonGroup extends Widget {
return BI.extend(BI.ButtonGroup.superclass._defaultConfig.apply(this, arguments), { static xtype = "bi.button_group";
static EVENT_CHANGE = "EVENT_CHANGE";
_defaultConfig() {
return extend(super._defaultConfig(arguments), {
baseCls: "bi-button-group", baseCls: "bi-button-group",
behaviors: {}, behaviors: {},
items: [], items: [],
@ -18,83 +24,84 @@ BI.ButtonGroup = BI.inherit(BI.Widget, {
vgap: 0, vgap: 0,
}], }],
}); });
}, }
render: function () { render() {
var self = this, o = this.options; const { behaviors: optionsBehaviors, items: optionsItems, value } = this.options;
var behaviors = {}; const behaviors = {};
BI.each(o.behaviors, function (key, rule) { each(optionsBehaviors, (key, rule) => {
behaviors[key] = BI.BehaviorFactory.createBehavior(key, { behaviors[key] = BI.BehaviorFactory.createBehavior(key, {
rule: rule, rule: rule,
}); });
}); });
this.behaviors = behaviors; this.behaviors = behaviors;
var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { const items = isFunction(optionsItems) ? this.__watch(optionsItems, (context, newValue) => {
self.populate(newValue); this.populate(newValue);
}) : o.items; }) : optionsItems;
this.populate(items); this.populate(items);
o.value = BI.isFunction(o.value) ? this.__watch(o.value, function (context, newValue) { this.options.value = isFunction(value) ? this.__watch(value, (context, newValue) => {
self.setValue(newValue); this.setValue(newValue);
}) : o.value; }) : value;
if (BI.isKey(o.value) || BI.isNotEmptyArray(o.value)) { if (isKey(value) || isNotEmptyArray(value)) {
this.setValue(o.value); this.setValue(value);
} }
}, }
_createBtns: function (items) { _createBtns(items) {
var btns; let btns;
BI.Widget.execWithContext(this, function () { Widget.execWithContext(this, () => {
btns = BI.createWidgets(BI.createItems(items, { btns = createWidgets(createItems(items, {
type: "bi.text_button", type: "bi.text_button",
})); }));
}); });
return btns; return btns;
}, }
_btnsCreator: function (items) { _btnsCreator(items) {
var self = this, args = Array.prototype.slice.call(arguments), o = this.options; const args = Array.prototype.slice.call(arguments);
var buttons = this._createBtns(items); const { chooseType } = this.options;
const buttons = this._createBtns(items);
args[0] = buttons; args[0] = buttons;
BI.each(this.behaviors, function (i, behavior) { each(this.behaviors, (i, behavior) => {
behavior.doBehavior.apply(behavior, args); behavior.doBehavior.apply(behavior, args);
}); });
BI.each(buttons, function (i, btn) { each(buttons, (i, btn) => {
btn.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { btn.on(Controller.EVENT_CHANGE, (type, value, obj, ...arg) => {
if (type === BI.Events.CLICK) { if (type === BI.Events.CLICK) {
switch (o.chooseType) { switch (chooseType) {
case BI.ButtonGroup.CHOOSE_TYPE_SINGLE: case ButtonGroup.CHOOSE_TYPE_SINGLE:
self.setValue(btn.getValue()); this.setValue(btn.getValue());
break; break;
case BI.ButtonGroup.CHOOSE_TYPE_NONE: case ButtonGroup.CHOOSE_TYPE_NONE:
self.setValue([]); this.setValue([]);
break; break;
default: default:
break; break;
} }
self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...arg);
self.fireEvent(BI.ButtonGroup.EVENT_CHANGE, value, obj); this.fireEvent(ButtonGroup.EVENT_CHANGE, value, obj);
} else { } else {
self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...arg);
} }
}); });
btn.on(BI.Events.DESTROY, function () { btn.on(BI.Events.DESTROY, () => {
BI.remove(self.buttons, btn); remove(this.buttons, btn);
}); });
}); });
return buttons; return buttons;
}, }
_packageBtns: function (btns) { _packageBtns(btns) {
var o = this.options; const { layouts: optionsLayouts } = this.options;
var layouts = BI.isArray(o.layouts) ? o.layouts : [o.layouts]; const layouts = isArray(optionsLayouts) ? optionsLayouts : [optionsLayouts];
for (var i = layouts.length - 1; i > 0; i--) { for (let i = layouts.length - 1; i > 0; i--) {
btns = BI.map(btns, function (k, it) { btns = map(btns, (k, it) => {
return BI.extend({}, layouts[i], { return extend({}, layouts[i], {
items: [ items: [
BI.extend({}, layouts[i].el, { extend({}, layouts[i].el, {
el: it, el: it,
}) })
], ],
@ -103,56 +110,57 @@ BI.ButtonGroup = BI.inherit(BI.Widget, {
} }
return btns; return btns;
}, }
_packageSimpleItems: function (btns) { _packageSimpleItems(btns) {
var o = this.options; const { items } = this.options;
return BI.map(o.items, function (i, item) { return map(items, (i, item) => {
if (BI.stripEL(item) === item) { if (stripEL(item) === item) {
return btns[i]; return btns[i];
} }
return BI.extend({}, item, { return extend({}, item, {
el: btns[i], el: btns[i],
}); });
}); });
}, }
_packageItems: function (items, packBtns) { _packageItems(items, packBtns) {
return BI.createItems(BI.makeArrayByArray(items, {}), BI.clone(packBtns)); return createItems(makeArrayByArray(items, {}), clone(packBtns));
}, }
_packageLayout: function (items) { _packageLayout(items) {
var o = this.options, layout = BI.deepClone(BI.isArray(o.layouts) ? o.layouts[0] : o.layouts); const { layouts } = this.options;
const layout = deepClone(isArray(layouts) ? layouts[0] : layouts);
var lay = BI.formatEL(layout).el; let lay = formatEL(layout).el;
while (lay && lay.items && !BI.isEmpty(lay.items)) { while (lay && lay.items && !isEmpty(lay.items)) {
lay = BI.formatEL(lay.items[0]).el; lay = formatEL(lay.items[0]).el;
} }
lay.items = items; lay.items = items;
return layout; return layout;
}, }
// 如果是一个简单的layout // 如果是一个简单的layout
_isSimpleLayout: function () { _isSimpleLayout() {
var o = this.options; 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 () { doBehavior() {
var args = Array.prototype.slice.call(arguments); const args = Array.prototype.slice.call(arguments);
args.unshift(this.buttons); args.unshift(this.buttons);
BI.each(this.behaviors, function (i, behavior) { each(this.behaviors, (i, behavior) => {
behavior.doBehavior.apply(behavior, args); behavior.doBehavior.apply(behavior, args);
}); });
}, }
prependItems: function (items) { prependItems(items) {
var btns = this._btnsCreator.apply(this, arguments); const btns = this._btnsCreator.apply(this, arguments);
this.buttons = BI.concat(btns, this.buttons); this.buttons = concat(btns, this.buttons);
if (this._isSimpleLayout() && this.layouts && this.layouts.prependItems) { if (this._isSimpleLayout() && this.layouts && this.layouts.prependItems) {
this.layouts.prependItems(btns); this.layouts.prependItems(btns);
@ -162,11 +170,11 @@ BI.ButtonGroup = BI.inherit(BI.Widget, {
items = this._packageItems(items, this._packageBtns(btns)); items = this._packageItems(items, this._packageBtns(btns));
this.layouts.prependItems(this._packageLayout(items).items); this.layouts.prependItems(this._packageLayout(items).items);
}, }
addItems: function (items) { addItems(items) {
var btns = this._btnsCreator.apply(this, arguments); const btns = this._btnsCreator.apply(this, arguments);
this.buttons = BI.concat(this.buttons, btns); this.buttons = concat(this.buttons, btns);
// 如果是一个简单的layout // 如果是一个简单的layout
if (this._isSimpleLayout() && this.layouts && this.layouts.addItems) { 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)); items = this._packageItems(items, this._packageBtns(btns));
this.layouts.addItems(this._packageLayout(items).items); this.layouts.addItems(this._packageLayout(items).items);
}, }
removeItemAt: function (indexes) { removeItemAt(indexes) {
BI.removeAt(this.buttons, indexes); removeAt(this.buttons, indexes);
this.layouts.removeItemAt(indexes); this.layouts.removeItemAt(indexes);
}, }
removeItems: function (values) { removeItems(values) {
values = BI.isArray(values) ? values : [values]; values = isArray(values) ? values : [values];
var deleted = []; const deleted = [];
BI.each(this.buttons, function (i, button) { each(this.buttons, (i, button) => {
if (BI.deepContains(values, button.getValue())) { if (deepContains(values, button.getValue())) {
deleted.push(i); deleted.push(i);
} }
}); });
BI.removeAt(this.buttons, deleted); removeAt(this.buttons, deleted);
this.layouts.removeItemAt(deleted); this.layouts.removeItemAt(deleted);
}, }
populate: function (items) { populate(items) {
items = items || []; items = items || [];
this.empty(); this.empty();
this.options.items = items; this.options.items = items;
@ -208,114 +216,114 @@ BI.ButtonGroup = BI.inherit(BI.Widget, {
items = this._packageItems(items, this._packageBtns(this.buttons)); 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) { setNotSelectedValue(v) {
v = BI.isArray(v) ? v : [v]; v = isArray(v) ? v : [v];
BI.each(this.buttons, function (i, item) { each(this.buttons, (i, item) => {
if (BI.deepContains(v, item.getValue())) { if (deepContains(v, item.getValue())) {
item.setSelected && item.setSelected(false); item.setSelected && item.setSelected(false);
} else { } else {
item.setSelected && item.setSelected(true); item.setSelected && item.setSelected(true);
} }
}); });
}, }
setEnabledValue: function (v) { setEnabledValue(v) {
v = BI.isArray(v) ? v : [v]; v = isArray(v) ? v : [v];
BI.each(this.buttons, function (i, item) { each(this.buttons, (i, item) => {
if (BI.deepContains(v, item.getValue())) { if (deepContains(v, item.getValue())) {
item.setEnable(true); item.setEnable(true);
} else { } else {
item.setEnable(false); item.setEnable(false);
} }
}); });
}, }
setValue: function (v) { setValue(v) {
v = BI.isArray(v) ? v : [v]; v = isArray(v) ? v : [v];
BI.each(this.buttons, function (i, item) { each(this.buttons, (i, item) => {
if (BI.deepContains(v, item.getValue())) { if (deepContains(v, item.getValue())) {
item.setSelected && item.setSelected(true); item.setSelected && item.setSelected(true);
} else { } else {
item.setSelected && item.setSelected(false); item.setSelected && item.setSelected(false);
} }
}); });
}, }
setValueMap: function (map) { setValueMap(map) {
map = map || {}; map = map || {};
BI.each(this.buttons, function (i, item) { each(this.buttons, (i, item) => {
if (BI.has(map, item.getValue())) { if (has(map, item.getValue())) {
item.setSelected && item.setSelected(true); item.setSelected && item.setSelected(true);
} else { } else {
item.setSelected && item.setSelected(false); item.setSelected && item.setSelected(false);
} }
}); });
}, }
setAllSelected: function (v) { setAllSelected(v) {
BI.each(this.getAllButtons(), function (i, btn) { each(this.getAllButtons(), (i, btn) => {
(btn.setSelected || btn.setAllSelected).apply(btn, [v]); (btn.setSelected || btn.setAllSelected).apply(btn, [v]);
}); });
}, }
getNotSelectedValue: function () { getNotSelectedValue() {
var v = []; const v = [];
BI.each(this.buttons, function (i, item) { each(this.buttons, (i, item) => {
if (item.isEnabled() && !(item.isSelected && item.isSelected())) { if (item.isEnabled() && !(item.isSelected && item.isSelected())) {
v.push(item.getValue()); v.push(item.getValue());
} }
}); });
return v; return v;
}, }
getValue: function () { getValue() {
var v = []; const v = [];
BI.each(this.buttons, function (i, item) { each(this.buttons, (i, item) => {
if (item.isEnabled() && item.isSelected && item.isSelected()) { if (item.isEnabled() && item.isSelected && item.isSelected()) {
v.push(item.getValue()); v.push(item.getValue());
} }
}); });
return v; return v;
}, }
getAllButtons: function () { getAllButtons() {
return this.buttons; return this.buttons;
}, }
getAllLeaves: function () { getAllLeaves() {
return this.buttons; return this.buttons;
}, }
getSelectedButtons: function () { getSelectedButtons() {
var btns = []; const btns = [];
BI.each(this.buttons, function (i, item) { each(this.buttons, (i, item) => {
if (item.isSelected && item.isSelected()) { if (item.isSelected && item.isSelected()) {
btns.push(item); btns.push(item);
} }
}); });
return btns; return btns;
}, }
getNotSelectedButtons: function () { getNotSelectedButtons() {
var btns = []; const btns = [];
BI.each(this.buttons, function (i, item) { each(this.buttons, (i, item) => {
if (item.isSelected && !item.isSelected()) { if (item.isSelected && !item.isSelected()) {
btns.push(item); btns.push(item);
} }
}); });
return btns; return btns;
}, }
getIndexByValue: function (value) { getIndexByValue(value) {
var index = -1; let index = -1;
BI.any(this.buttons, function (i, item) { any(this.buttons, (i, item) => {
if (item.isEnabled() && item.getValue() === value) { if (item.isEnabled() && item.getValue() === value) {
index = i; index = i;
@ -324,11 +332,11 @@ BI.ButtonGroup = BI.inherit(BI.Widget, {
}); });
return index; return index;
}, }
getNodeById: function (id) { getNodeById(id) {
var node; let node;
BI.any(this.buttons, function (i, item) { any(this.buttons, (i, item) => {
if (item.isEnabled() && item.options.id === id) { if (item.isEnabled() && item.options.id === id) {
node = item; node = item;
@ -337,11 +345,11 @@ BI.ButtonGroup = BI.inherit(BI.Widget, {
}); });
return node; return node;
}, }
getNodeByValue: function (value) { getNodeByValue(value) {
var node; let node;
BI.any(this.buttons, function (i, item) { any(this.buttons, (i, item) => {
if (item.isEnabled() && item.getValue() === value) { if (item.isEnabled() && item.getValue() === value) {
node = item; node = item;
@ -350,35 +358,33 @@ BI.ButtonGroup = BI.inherit(BI.Widget, {
}); });
return node; return node;
}, }
/** /**
* 滚动到指定的节点 * 滚动到指定的节点
*/ */
scrollToValue: function (value, scrollIntoViewOptions) { scrollToValue(value, scrollIntoViewOptions) {
var node = this.getNodeByValue(value); const node = this.getNodeByValue(value);
if (node) { if (node) {
node.element[0].scrollIntoView(scrollIntoViewOptions); node.element[0].scrollIntoView(scrollIntoViewOptions);
} }
}, }
empty: function () { empty() {
BI.ButtonGroup.superclass.empty.apply(this, arguments); super.empty(arguments);
this.options.items = []; this.options.items = [];
}, }
destroy: function () { destroy() {
BI.ButtonGroup.superclass.destroy.apply(this, arguments); super.destroy(arguments);
this.options.items = []; this.options.items = [];
}, }
}); }
BI.extend(BI.ButtonGroup, {
extend(ButtonGroup, {
CHOOSE_TYPE_SINGLE: BI.Selection.Single, CHOOSE_TYPE_SINGLE: BI.Selection.Single,
CHOOSE_TYPE_MULTI: BI.Selection.Multi, CHOOSE_TYPE_MULTI: BI.Selection.Multi,
CHOOSE_TYPE_ALL: BI.Selection.All, CHOOSE_TYPE_ALL: BI.Selection.All,
CHOOSE_TYPE_NONE: BI.Selection.None, CHOOSE_TYPE_NONE: BI.Selection.None,
CHOOSE_TYPE_DEFAULT: BI.Selection.Default, CHOOSE_TYPE_DEFAULT: BI.Selection.Default,
}); });
BI.ButtonGroup.EVENT_CHANGE = "EVENT_CHANGE";
BI.shortcut("bi.button_group", BI.ButtonGroup);

98
src/base/combination/group.combo.js

@ -2,9 +2,16 @@
* Created by GUY on 2015/8/10. * Created by GUY on 2015/8/10.
*/ */
BI.ComboGroup = BI.inherit(BI.Widget, { import { shortcut, Widget, Controller, extend, isEmpty, each, formatEL, clone, createWidget } from "../../core";
_defaultConfig: function () {
return BI.extend(BI.ComboGroup.superclass._defaultConfig.apply(this, arguments), { @shortcut()
export 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", baseCls: "bi-combo-group bi-list-item",
// 以下这些属性对每一个combo都是公用的 // 以下这些属性对每一个combo都是公用的
@ -28,69 +35,66 @@ BI.ComboGroup = BI.inherit(BI.Widget, {
}, },
}, },
}); });
}, }
render: function () { render() {
this._populate(this.options.el); this._populate(this.options.el);
}, }
_populate: function (item) { _populate(item) {
var self = this, o = this.options; const { items, action, height, direction, isDefaultInit, isNeedAdjustHeight, isNeedAdjustWidth, adjustLength, popup, container, trigger } = this.options;
var children = o.items; const children = items;
if (BI.isEmpty(children)) { if (isEmpty(children)) {
throw new Error("ComboGroup构造错误"); throw new Error("ComboGroup构造错误");
} }
BI.each(children, function (i, ch) { each(children, (i, ch) => {
var son = BI.formatEL(ch).el.children; const son = formatEL(ch).el.children;
ch = BI.formatEL(ch).el; ch = formatEL(ch).el;
if (!BI.isEmpty(son)) { if (!isEmpty(son)) {
ch.el = BI.clone(ch); ch.el = clone(ch);
ch.items = son; ch.items = son;
ch.type = "bi.combo_group"; ch.type = "bi.combo_group";
ch.action = o.action; ch.action = action;
ch.height = o.height; ch.height = height;
ch.direction = o.direction; ch.direction = direction;
ch.isDefaultInit = o.isDefaultInit; ch.isDefaultInit = isDefaultInit;
ch.isNeedAdjustHeight = o.isNeedAdjustHeight; ch.isNeedAdjustHeight = isNeedAdjustHeight;
ch.isNeedAdjustWidth = o.isNeedAdjustWidth; ch.isNeedAdjustWidth = isNeedAdjustWidth;
ch.adjustLength = o.adjustLength; ch.adjustLength = adjustLength;
ch.popup = o.popup; ch.popup = popup;
} }
}); });
this.combo = BI.createWidget({ this.combo = createWidget({
type: "bi.combo", type: "bi.combo",
element: this, element: this,
container: o.container, container,
height: o.height, height,
trigger: o.trigger, trigger,
direction: o.direction, direction,
isDefaultInit: o.isDefaultInit, isDefaultInit,
isNeedAdjustWidth: o.isNeedAdjustWidth, isNeedAdjustWidth,
isNeedAdjustHeight: o.isNeedAdjustHeight, isNeedAdjustHeight,
adjustLength: o.adjustLength, adjustLength,
el: item, el: item,
popup: BI.extend({}, o.popup, { popup: extend({}, popup, {
el: BI.extend({ el: extend({
items: children, items: children,
}, o.popup.el), }, popup.el),
}), }),
}); });
this.combo.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { this.combo.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => {
self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args);
if (type === BI.Events.CLICK) { 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(); return this.combo.getValue();
}, }
setValue: function (v) { setValue(v) {
this.combo.setValue(v); this.combo.setValue(v);
}, }
}); }
BI.ComboGroup.EVENT_CHANGE = "EVENT_CHANGE";
BI.shortcut("bi.combo_group", BI.ComboGroup);

130
src/base/combination/group.virtual.js

@ -1,6 +1,13 @@
BI.VirtualGroup = BI.inherit(BI.Widget, { import { shortcut, Widget, Controller, extend, isFunction, isKey, isArray, map, stripEL, deepClone, formatEL, isEmpty, each, createWidget } from "../../core";
_defaultConfig: function () {
return BI.extend(BI.VirtualGroup.superclass._defaultConfig.apply(this, arguments), { @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", baseCls: "bi-virtual-group",
items: [], items: [],
layouts: [{ layouts: [{
@ -9,36 +16,36 @@ BI.VirtualGroup = BI.inherit(BI.Widget, {
vgap: 0, vgap: 0,
}], }],
}); });
}, }
render: function () { render() {
var self = this, o = this.options; const { items: optionsItems, value } = this.options;
var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { const items = isFunction(optionsItems) ? this.__watch(optionsItems, (context, newValue) => {
self.populate(newValue); this.populate(newValue);
}) : o.items; }) : optionsItems;
this.populate(items); this.populate(items);
o.value = BI.isFunction(o.value) ? this.__watch(o.value, function (context, newValue) { this.options.value = isFunction(value) ? this.__watch(value, (context, newValue) => {
self.setValue(newValue); this.setValue(newValue);
}) : o.value; }) : value;
if (BI.isKey(o.value)) { if (isKey(value)) {
this.setValue(o.value); this.setValue(value);
} }
}, }
_packageBtns: function (items) { _packageBtns(items) {
var o = this.options; const o = this.options;
var map = this.buttonMap = {}; const map = this.buttonMap = {};
var layouts = BI.isArray(o.layouts) ? o.layouts : [o.layouts]; const layouts = isArray(o.layouts) ? o.layouts : [o.layouts];
for (let i = layouts.length - 1; i > 0; i--) { for (let i = layouts.length - 1; i > 0; i--) {
items = BI.map(items, function (k, it) { items = map(items, (k, it) => {
var el = BI.stripEL(it); const el = stripEL(it);
return BI.extend({}, layouts[i], { return extend({}, layouts[i], {
items: [ items: [
BI.extend({}, layouts[i].el, { extend({}, layouts[i].el, {
el: BI.extend({ el: extend({
ref: function (_ref) { ref: (_ref) => {
if (BI.isKey(map[el.value])) { if (isKey(map[el.value])) {
map[el.value] = _ref; map[el.value] = _ref;
} }
}, },
@ -50,33 +57,33 @@ BI.VirtualGroup = BI.inherit(BI.Widget, {
} }
return items; return items;
}, }
_packageLayout: function (items) { _packageLayout(items) {
var o = this.options; const o = this.options;
var layouts = BI.isArray(o.layouts) ? o.layouts : [o.layouts]; const layouts = isArray(o.layouts) ? o.layouts : [o.layouts];
var layout = BI.deepClone(layouts[0]); const layout = deepClone(layouts[0]);
var lay = BI.formatEL(layout).el; let lay = formatEL(layout).el;
while (lay && lay.items && !BI.isEmpty(lay.items)) { while (lay && lay.items && !isEmpty(lay.items)) {
lay = BI.formatEL(lay.items[0]).el; lay = formatEL(lay.items[0]).el;
} }
lay.items = items; lay.items = items;
return layout; return layout;
}, }
addItems: function (items) { addItems(items) {
this.layouts.addItems(items, this); this.layouts.addItems(items, this);
}, }
prependItems: function (items) { prependItems(items) {
this.layouts.prependItems(items, this); this.layouts.prependItems(items, this);
}, }
setValue: function (v) { setValue(v) {
v = BI.isArray(v) ? v : [v]; v = isArray(v) ? v : [v];
BI.each(this.buttonMap, function (key, item) { each(this.buttonMap, (key, item) => {
if (item) { if (item) {
if (v.deepContains(key)) { if (v.deepContains(key)) {
item.setSelected && item.setSelected(true); item.setSelected && item.setSelected(true);
@ -85,11 +92,11 @@ BI.VirtualGroup = BI.inherit(BI.Widget, {
} }
} }
}); });
}, }
getNotSelectedValue: function () { getNotSelectedValue() {
var v = []; const v = [];
BI.each(this.buttonMap, function (i, item) { each(this.buttonMap, (i, item) => {
if (item) { if (item) {
if (item.isEnabled() && !(item.isSelected && item.isSelected())) { if (item.isEnabled() && !(item.isSelected && item.isSelected())) {
v.push(item.getValue()); v.push(item.getValue());
@ -98,25 +105,25 @@ BI.VirtualGroup = BI.inherit(BI.Widget, {
}); });
return v; return v;
}, }
getNodeByValue: function (value) { getNodeByValue(value) {
return this.buttonMap[value]; return this.buttonMap[value];
}, }
/** /**
* 滚动到指定的节点 * 滚动到指定的节点
*/ */
scrollToValue: function (value, scrollIntoViewOptions) { scrollToValue(value, scrollIntoViewOptions) {
var node = this.getNodeByValue(value); const node = this.getNodeByValue(value);
if (node) { if (node) {
node.element[0].scrollIntoView(scrollIntoViewOptions); node.element[0].scrollIntoView(scrollIntoViewOptions);
} }
}, }
getValue: function () { getValue() {
var v = []; const v = [];
BI.each(this.buttonMap, function (i, item) { each(this.buttonMap, (i, item) => {
if (item) { if (item) {
if (item.isEnabled() && item.isSelected && item.isSelected()) { if (item.isEnabled() && item.isSelected && item.isSelected()) {
v.push(item.getValue()); v.push(item.getValue());
@ -125,21 +132,18 @@ BI.VirtualGroup = BI.inherit(BI.Widget, {
}); });
return v; return v;
}, }
populate: function (items) { populate(items) {
items = items || []; items = items || [];
this.options.items = items; this.options.items = items;
items = this._packageBtns(items); items = this._packageBtns(items);
if (!this.layouts) { if (!this.layouts) {
this.layouts = BI.createWidget(BI.extend({ element: this }, this._packageLayout(items))); this.layouts = createWidget(extend({ element: this }, this._packageLayout(items)));
} else { } else {
this.layouts.populate(items, { this.layouts.populate(items, {
context: this, context: this,
}); });
} }
}, }
}); }
BI.VirtualGroup.EVENT_CHANGE = "EVENT_CHANGE";
BI.shortcut("bi.virtual_group", BI.VirtualGroup);

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

221
src/base/combination/loader.js

@ -5,9 +5,16 @@
* @class BI.Loader * @class BI.Loader
* @extends BI.Widget * @extends BI.Widget
*/ */
BI.Loader = BI.inherit(BI.Widget, { import { shortcut, Widget, Controller, extend, createWidget, isEmpty, nextTick, bind, isFunction, isNotEmptyArray, isNumber, isObject, each } from "../../core";
_defaultConfig: function () {
return BI.extend(BI.Loader.superclass._defaultConfig.apply(this, arguments), { @shortcut()
export class Loader extends Widget {
static xtype = "bi.loader";
static EVENT_CHANGE = "EVENT_CHANGE";
_defaultConfig() {
return extend(super._defaultConfig(arguments), {
baseCls: "bi-loader", baseCls: "bi-loader",
direction: "top", direction: "top",
@ -33,115 +40,115 @@ BI.Loader = BI.inherit(BI.Widget, {
hasPrev: BI.emptyFn, hasPrev: BI.emptyFn,
hasNext: BI.emptyFn, hasNext: BI.emptyFn,
}); });
}, }
_prevLoad: function () { _prevLoad() {
var self = this, o = this.options; const o = this.options;
this.prev.setLoading(); this.prev.setLoading();
o.itemsCreator.apply(this, [{ times: --this.times }, function () { o.itemsCreator.apply(this, [{ times: --this.times }, (...args) => {
self.prev.setLoaded(); this.prev.setLoaded();
self.prependItems.apply(self, arguments); this.prependItems.apply(this, args);
}]); }]);
}, }
_nextLoad: function () { _nextLoad() {
var self = this, o = this.options; const o = this.options;
this.next.setLoading(); this.next.setLoading();
o.itemsCreator.apply(this, [{ times: ++this.times }, function () { o.itemsCreator.apply(this, [{ times: ++this.times }, (...args) => {
self.next.setLoaded(); this.next.setLoaded();
self.addItems.apply(self, arguments); this.addItems.apply(this, args);
}]); }]);
}, }
render: function () { render() {
var self = this, o = this.options; const { itemsCreator, prev, next, el, items: optionsItems, value, direction, logic, isDefaultInit } = this.options;
if (o.itemsCreator === false) { if (itemsCreator === false) {
o.prev = false; prev = false;
o.next = false; next = false;
} }
if (o.prev !== false) { if (prev !== false) {
this.prev = BI.createWidget(BI.extend({ this.prev = createWidget(extend({
type: "bi.loading_bar", type: "bi.loading_bar",
}, o.prev)); }, prev));
this.prev.on(BI.Controller.EVENT_CHANGE, function (type) { this.prev.on(Controller.EVENT_CHANGE, (type) => {
if (type === BI.Events.CLICK) { 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", type: "bi.button_group",
chooseType: 0, chooseType: 0,
items: o.items, items: optionsItems,
behaviors: {}, behaviors: {},
layouts: [{ layouts: [{
type: "bi.vertical", type: "bi.vertical",
}], }],
value: o.value, value,
}); });
this.button_group.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { this.button_group.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => {
self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args);
if (type === BI.Events.CLICK) { if (type === BI.Events.CLICK) {
self.fireEvent(BI.Loader.EVENT_CHANGE, obj); this.fireEvent(Loader.EVENT_CHANGE, obj);
} }
}); });
if (o.next !== false) { if (next !== false) {
this.next = BI.createWidget(BI.extend({ this.next = createWidget(extend({
type: "bi.loading_bar", type: "bi.loading_bar",
}, o.next)); }, next));
this.next.on(BI.Controller.EVENT_CHANGE, function (type) { this.next.on(Controller.EVENT_CHANGE, (type) => {
if (type === BI.Events.CLICK) { if (type === BI.Events.CLICK) {
self._nextLoad(); this._nextLoad();
} }
}); });
} }
BI.createWidget(BI.extend({ createWidget(extend({
element: this, element: this,
}, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend({ }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(direction), extend({
scrolly: true, scrolly: true,
}, o.logic, { }, logic, {
items: BI.LogicFactory.createLogicItemsByDirection(o.direction, this.prev, this.button_group, this.next), items: BI.LogicFactory.createLogicItemsByDirection(direction, this.prev, this.button_group, this.next),
})))); }))));
o.isDefaultInit && BI.isEmpty(o.items) && BI.nextTick(BI.bind(function () { isDefaultInit && isEmpty(optionsItems) && nextTick(bind(() => {
o.isDefaultInit && BI.isEmpty(o.items) && this._populate(); isDefaultInit && isEmpty(optionsItems) && this._populate();
}, this)); }, this));
var items = BI.isFunction(o.items) ? this.__watch(o.items, function (context, newValue) { const items = isFunction(optionsItems) ? this.__watch(optionsItems, (context, newValue) => {
self.populate(newValue); this.populate(newValue);
}) : o.items; }) : optionsItems;
if (BI.isNotEmptyArray(items)) { if (isNotEmptyArray(items)) {
this._populate(items); this._populate(items);
} }
}, }
hasPrev: function () { hasPrev() {
var o = this.options; const { count, hasPrev } = this.options;
if (BI.isNumber(o.count)) { if (isNumber(count)) {
return this.count < o.count; return this.count < count;
} }
return !!o.hasPrev.apply(this, [{ return !!hasPrev.apply(this, [{
times: this.times, times: this.times,
count: this.count, count: this.count,
}]); }]);
}, }
hasNext: function () { hasNext() {
var o = this.options; const { count, hasNext } = this.options;
if (BI.isNumber(o.count)) { if (isNumber(count)) {
return this.count < o.count; return this.count < count;
} }
return !!o.hasNext.apply(this, [{ return !!hasNext.apply(this, [{
times: this.times, times: this.times,
count: this.count, count: this.count,
}]); }]);
}, }
prependItems: function (items) { prependItems(items) {
this.count += items.length; this.count += items.length;
if (this.next !== false) { if (this.next !== false) {
if (this.hasPrev()) { if (this.hasPrev()) {
@ -152,11 +159,11 @@ BI.Loader = BI.inherit(BI.Widget, {
} }
} }
this.button_group.prependItems.apply(this.button_group, arguments); this.button_group.prependItems.apply(this.button_group, arguments);
}, }
addItems: function (items) { addItems(items) {
this.count += items.length; this.count += items.length;
if (BI.isObject(this.next)) { if (isObject(this.next)) {
if (this.hasNext()) { if (this.hasNext()) {
this.options.items = this.options.items.concat(items); this.options.items = this.options.items.concat(items);
this.next.setLoaded(); this.next.setLoaded();
@ -165,16 +172,16 @@ BI.Loader = BI.inherit(BI.Widget, {
} }
} }
this.button_group.addItems.apply(this.button_group, arguments); this.button_group.addItems.apply(this.button_group, arguments);
}, }
_populate: function (items) { _populate(items) {
var self = this, o = this.options; const o = this.options;
if (arguments.length === 0 && (BI.isFunction(o.itemsCreator))) { if (arguments.length === 0 && (isFunction(o.itemsCreator))) {
o.itemsCreator.apply(this, [{ times: 1 }, function () { o.itemsCreator.apply(this, [{ times: 1 }, (...args) => {
if (arguments.length === 0) { if (args.length === 0) {
throw new Error("参数不能为空"); throw new Error("参数不能为空");
} }
self.populate.apply(self, arguments); this.populate.apply(this, args);
o.onLoaded(); o.onLoaded();
}]); }]);
@ -184,14 +191,14 @@ BI.Loader = BI.inherit(BI.Widget, {
this.times = 1; this.times = 1;
this.count = 0; this.count = 0;
this.count += items.length; this.count += items.length;
if (BI.isObject(this.next)) { if (isObject(this.next)) {
if (this.hasNext()) { if (this.hasNext()) {
this.next.setLoaded(); this.next.setLoaded();
} else { } else {
this.next.invisible(); this.next.invisible();
} }
} }
if (BI.isObject(this.prev)) { if (isObject(this.prev)) {
if (this.hasPrev()) { if (this.hasPrev()) {
this.prev.setLoaded(); this.prev.setLoaded();
} else { } else {
@ -200,66 +207,64 @@ BI.Loader = BI.inherit(BI.Widget, {
} }
return true; return true;
}, }
populate: function () { populate() {
this._populate.apply(this, arguments) && this.button_group.populate.apply(this.button_group, arguments); 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); this.button_group.setNotSelectedValue.apply(this.button_group, arguments);
}, }
getNotSelectedValue: function () { getNotSelectedValue() {
return this.button_group.getNotSelectedValue(); return this.button_group.getNotSelectedValue();
}, }
setValue: function () { setValue() {
this.button_group.setValue.apply(this.button_group, arguments); this.button_group.setValue.apply(this.button_group, arguments);
}, }
getValue: function () { getValue() {
return this.button_group.getValue.apply(this.button_group, arguments); return this.button_group.getValue.apply(this.button_group, arguments);
}, }
getAllButtons: function () { getAllButtons() {
return this.button_group.getAllButtons(); return this.button_group.getAllButtons();
}, }
getAllLeaves: function () { getAllLeaves() {
return this.button_group.getAllLeaves(); return this.button_group.getAllLeaves();
}, }
getSelectedButtons: function () { getSelectedButtons() {
return this.button_group.getSelectedButtons(); return this.button_group.getSelectedButtons();
}, }
getNotSelectedButtons: function () { getNotSelectedButtons() {
return this.button_group.getNotSelectedButtons(); return this.button_group.getNotSelectedButtons();
}, }
getIndexByValue: function (value) { getIndexByValue(value) {
return this.button_group.getIndexByValue(value); return this.button_group.getIndexByValue(value);
}, }
getNodeById: function (id) { getNodeById(id) {
return this.button_group.getNodeById(id); return this.button_group.getNodeById(id);
}, }
getNodeByValue: function (value) { getNodeByValue(value) {
return this.button_group.getNodeByValue(value); return this.button_group.getNodeByValue(value);
}, }
empty: function () { empty() {
this.button_group.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); ob && ob.setVisible(false);
}); });
}, }
destroy: function () { destroy() {
BI.Loader.superclass.destroy.apply(this, arguments); super.destroy(arguments);
}, }
}); }
BI.Loader.EVENT_CHANGE = "EVENT_CHANGE";
BI.shortcut("bi.loader", BI.Loader);

162
src/base/combination/navigation.js

@ -1,10 +1,16 @@
/** /**
* Created by GUY on 2015/6/26. * 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, { @shortcut()
_defaultConfig: function () { export class Navigation extends Widget {
return BI.extend(BI.Navigation.superclass._defaultConfig.apply(this, arguments), { static xtype = "bi.navigation";
static EVENT_CHANGE = "EVENT_CHANGE";
_defaultConfig() {
return extend(super._defaultConfig(arguments), {
direction: "bottom", // top, bottom, left, right, custom direction: "bottom", // top, bottom, left, right, custom
logic: { logic: {
dynamic: false, dynamic: false,
@ -12,160 +18,158 @@ BI.Navigation = BI.inherit(BI.Widget, {
single: false, single: false,
showIndex: false, showIndex: false,
tab: false, tab: false,
cardCreator: function (v) { cardCreator: (v) => {
return BI.createWidget(); return createWidget();
}, },
afterCardCreated: BI.emptyFn, afterCardCreated: BI.emptyFn,
afterCardShow: BI.emptyFn, afterCardShow: BI.emptyFn,
}); });
}, }
render: function () { render() {
var self = this, o = this.options; const { direction, logic, cardCreator, showIndex } = this.options;
this.tab = BI.createWidget(this.options.tab, { type: "bi.button_group" }); this.tab = createWidget(this.options.tab, { type: "bi.button_group" });
this.cardMap = {}; this.cardMap = {};
this.showIndex = 0; this.showIndex = 0;
this.layout = BI.createWidget({ this.layout = createWidget({
type: "bi.card", type: "bi.card",
}); });
BI.createWidget(BI.extend({ createWidget(extend({
element: this, element: this,
}, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend({}, o.logic, { }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(direction), extend({}, logic, {
items: BI.LogicFactory.createLogicItemsByDirection(o.direction, this.tab, this.layout), items: BI.LogicFactory.createLogicItemsByDirection(direction, this.tab, this.layout),
})))); }))));
new BI.ShowListener({ new ShowListener({
eventObj: this.tab, eventObj: this.tab,
cardLayout: this.layout, cardLayout: this.layout,
cardNameCreator: function (v) { cardNameCreator: (v) => {
return self.showIndex + v; return this.showIndex + v;
}, },
cardCreator: function (v) { cardCreator: (v) => {
BI.Widget.execWithContext(self, function () { Widget.execWithContext(this, () => {
self.cardMap[v] = o.cardCreator(v); this.cardMap[v] = cardCreator(v);
}); });
return self.cardMap[v]; return this.cardMap[v];
}, },
afterCardCreated: BI.bind(this.afterCardCreated, this), afterCardCreated: bind(this.afterCardCreated, this),
afterCardShow: BI.bind(this.afterCardShow, this), afterCardShow: bind(this.afterCardShow, this),
}); });
if (BI.isFunction(o.showIndex)) { if (isFunction(showIndex)) {
this.__watch(o.showIndex, function (context, newValue) { this.__watch(showIndex, (context, newValue) => {
self.setSelect(newValue); this.setSelect(newValue);
}); });
} }
}, }
created: function () { created() {
var o = this.options; const { showIndex } = this.options;
if (o.showIndex !== false) { if (showIndex !== false) {
this.setSelect(o.showIndex); this.setSelect(showIndex);
} }
}, }
_deleteOtherCards: function (currCardName) { _deleteOtherCards(currCardName) {
var self = this, o = this.options; const { single } = this.options;
if (o.single === true) { if (single === true) {
BI.each(this.cardMap, function (name, card) { each(this.cardMap, (name, card) => {
if (name !== (currCardName + "")) { if (name !== (currCardName + "")) {
self.layout.deleteCardByName(name); this.layout.deleteCardByName(name);
delete self.cardMap[name]; delete this.cardMap[name];
} }
}); });
} }
}, }
afterCardCreated: function (v) { afterCardCreated(v) {
var self = this; this.cardMap[v].on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => {
this.cardMap[v].on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args);
self.fireEvent(BI.Controller.EVENT_CHANGE, arguments);
if (type === BI.Events.CLICK) { if (type === BI.Events.CLICK) {
self.fireEvent(BI.Navigation.EVENT_CHANGE, obj); this.fireEvent(Navigation.EVENT_CHANGE, obj);
} }
}); });
this.options.afterCardCreated.apply(this, arguments); this.options.afterCardCreated.apply(this, arguments);
}, }
afterCardShow: function (v) { afterCardShow(v) {
this.showIndex = v; this.showIndex = v;
this._deleteOtherCards(v); this._deleteOtherCards(v);
this.options.afterCardShow.apply(this, arguments); this.options.afterCardShow.apply(this, arguments);
}, }
populate: function () { populate() {
var card = this.layout.getShowingCard(); const card = this.layout.getShowingCard();
if (card) { if (card) {
return card.populate.apply(card, arguments); return card.populate.apply(card, arguments);
} }
}, }
_assertCard: function (v) { _assertCard(v) {
var self = this, o = this.options; const { cardCreator } = this.options;
if (!this.layout.isCardExisted(v)) { if (!this.layout.isCardExisted(v)) {
BI.Widget.execWithContext(self, function () { Widget.execWithContext(this, () => {
self.cardMap[v] = o.cardCreator(v); this.cardMap[v] = cardCreator(v);
}); });
this.layout.addCardByName(v, this.cardMap[v]); this.layout.addCardByName(v, this.cardMap[v]);
this.afterCardCreated(v); this.afterCardCreated(v);
} }
}, }
setSelect: function (v) { setSelect(v) {
this._assertCard(v); this._assertCard(v);
this.layout.showCardByName(v); this.layout.showCardByName(v);
this._deleteOtherCards(v); this._deleteOtherCards(v);
if (this.showIndex !== v) { if (this.showIndex !== v) {
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; return this.showIndex;
}, }
getSelectedCard: function () { getSelectedCard() {
if (BI.isKey(this.showIndex)) { if (isKey(this.showIndex)) {
return this.cardMap[this.showIndex]; return this.cardMap[this.showIndex];
} }
}, }
getAllCard: function() { getAllCard() {
return BI.values(this.cardMap); return values(this.cardMap);
}, }
/** /**
* @override * @override
*/ */
setValue: function (v) { setValue(v) {
var card = this.layout.getShowingCard(); const card = this.layout.getShowingCard();
if (card) { if (card) {
card.setValue(v); card.setValue(v);
} }
}, }
/** /**
* @override * @override
*/ */
getValue: function () { getValue() {
var card = this.layout.getShowingCard(); const card = this.layout.getShowingCard();
if (card) { if (card) {
return card.getValue(); return card.getValue();
} }
}, }
empty: function () { empty() {
this.layout.deleteAllCard(); this.layout.deleteAllCard();
this.cardMap = {}; 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);

306
src/base/combination/searcher.js

@ -5,10 +5,23 @@
* @class BI.Searcher * @class BI.Searcher
* @extends BI.Widget * @extends BI.Widget
*/ */
import { shortcut, Widget, Controller, extend, createWidget, debounce, bind, endWith, deepWithout, nextTick, isEmptyString, isNull } from "../../core";
BI.Searcher = BI.inherit(BI.Widget, { import { ButtonGroup } from "./group.button";
_defaultConfig: function () { import { Maskers } from "../0.base";
return BI.extend(BI.Searcher.superclass._defaultConfig.apply(this, arguments), {
@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";
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", baseCls: "bi-searcher",
lgap: 0, lgap: 0,
rgap: 0, rgap: 0,
@ -20,10 +33,10 @@ BI.Searcher = BI.inherit(BI.Widget, {
isDefaultInit: false, isDefaultInit: false,
isAutoSearch: true, // 是否自动搜索 isAutoSearch: true, // 是否自动搜索
isAutoSync: true, // 是否自动同步数据, 即是否保持搜索面板和adapter面板状态值的统一 isAutoSync: true, // 是否自动同步数据, 即是否保持搜索面板和adapter面板状态值的统一
chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, chooseType: ButtonGroup.CHOOSE_TYPE_SINGLE,
// isAutoSearch为false时启用 // isAutoSearch为false时启用
onSearch: function (op, callback) { onSearch: (op, callback) => {
callback([]); callback([]);
}, },
@ -40,190 +53,191 @@ BI.Searcher = BI.inherit(BI.Widget, {
offset: {}, offset: {},
}, },
}); });
}, }
render: function () { render() {
var self = this, o = this.options; 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", type: "bi.search_editor",
}); });
BI.createWidget({ createWidget({
type: "bi.vertical", type: "bi.vertical",
element: this, element: this,
lgap: o.lgap, lgap,
rgap: o.rgap, rgap,
tgap: o.tgap, tgap,
bgap: o.bgap, bgap,
vgap: o.vgap, vgap,
hgap: o.hgap, hgap,
items: [this.editor], 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, "leading": true,
"trailing": false, "trailing": false,
}); });
this.editor.on(BI.Controller.EVENT_CHANGE, function (type) { this.editor.on(Controller.EVENT_CHANGE, (type) => {
switch (type) { switch (type) {
case BI.Events.STARTEDIT: case BI.Events.STARTEDIT:
self._startSearch(); this._startSearch();
break; break;
case BI.Events.EMPTY: case BI.Events.EMPTY:
self._stopSearch(); this._stopSearch();
break; break;
case BI.Events.CHANGE: case BI.Events.CHANGE:
search(); search();
break; break;
case BI.Events.PAUSE: case BI.Events.PAUSE:
if (BI.endWith(this.getValue(), BI.BlankSplitChar)) { if (endWith(this.getValue(), BI.BlankSplitChar)) {
self._pauseSearch(); this._pauseSearch();
} }
break; break;
default: default:
break; break;
} }
}); });
}, }
_assertPopupView: function () { _assertPopupView() {
var self = this, o = this.options; const { masker, popup, chooseType, isAutoSync, adapter } = this.options;
if ((o.masker && !BI.Maskers.has(this.getName())) || (o.masker === false && !this.popupView)) { if ((masker && !Maskers.has(this.getName())) || (masker === false && !this.popupView)) {
this.popupView = BI.createWidget(o.popup, { this.popupView = createWidget(popup, {
type: "bi.searcher_view", type: "bi.searcher_view",
chooseType: o.chooseType, chooseType: chooseType,
}); });
this.popupView.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { this.popupView.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => {
self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args);
if (type === BI.Events.CLICK) { if (type === BI.Events.CLICK) {
if (o.isAutoSync) { if (isAutoSync) {
var values = o.adapter && o.adapter.getValue(); const values = adapter && adapter.getValue();
switch (o.chooseType) { switch (chooseType) {
case BI.ButtonGroup.CHOOSE_TYPE_SINGLE: case ButtonGroup.CHOOSE_TYPE_SINGLE:
o.adapter && o.adapter.setValue([obj.getValue()]); adapter && adapter.setValue([obj.getValue()]);
break; break;
case BI.ButtonGroup.CHOOSE_TYPE_MULTI: case ButtonGroup.CHOOSE_TYPE_MULTI:
if (!obj.isSelected()) { if (!obj.isSelected()) {
o.adapter && o.adapter.setValue(BI.deepWithout(values, obj.getValue())); adapter && adapter.setValue(deepWithout(values, obj.getValue()));
} }
values.push(obj.getValue()); values.push(obj.getValue());
o.adapter && o.adapter.setValue(values); adapter && adapter.setValue(values);
break; break;
default: default:
break; break;
} }
} }
self.fireEvent(BI.Searcher.EVENT_CHANGE, value, obj); this.fireEvent(Searcher.EVENT_CHANGE, value, obj);
} }
}); });
BI.nextTick(function () { nextTick(() => {
self.fireEvent(BI.Searcher.EVENT_AFTER_INIT); this.fireEvent(Searcher.EVENT_AFTER_INIT);
}); });
} }
if (o.masker && !BI.Maskers.has(this.getName())) { if (masker && !Maskers.has(this.getName())) {
BI.Maskers.create(this.getName(), o.adapter, BI.extend({ Maskers.create(this.getName(), adapter, extend({
container: this, container: this,
render: this.popupView, render: this.popupView,
}, o.masker), this); }, masker), this);
} }
}, }
_startSearch: function () { _startSearch() {
this._assertPopupView(); this._assertPopupView();
this._stop = false; this._stop = false;
this._isSearching = true; this._isSearching = true;
this.fireEvent(BI.Searcher.EVENT_START); this.fireEvent(Searcher.EVENT_START);
this.popupView.startSearch && this.popupView.startSearch(); this.popupView.startSearch && this.popupView.startSearch();
// 搜索前先清空dom // 搜索前先清空dom
// BI.Maskers.get(this.getName()).empty(); // BI.Maskers.get(this.getName()).empty();
BI.nextTick(function (name) { nextTick((name) => {
BI.Maskers.show(name); Maskers.show(name);
}, this.getName()); }, this.getName());
}, }
_pauseSearch: function () { _pauseSearch() {
this._stop = true; this._stop = true;
BI.nextTick(function (name) { nextTick((name) => {
BI.Maskers.hide(name); Maskers.hide(name);
}, this.getName()); }, this.getName());
if (this._isSearching === true) { if (this._isSearching === true) {
this.popupView && this.popupView.pauseSearch && this.popupView.pauseSearch(); this.popupView && this.popupView.pauseSearch && this.popupView.pauseSearch();
this.fireEvent(BI.Searcher.EVENT_PAUSE); this.fireEvent(Searcher.EVENT_PAUSE);
} }
this._isSearching = false; this._isSearching = false;
}, }
_stopSearch: function () { _stopSearch() {
var name = this.getName(); const name = this.getName();
this._stop = true; this._stop = true;
BI.Maskers.hide(name); Maskers.hide(name);
if (this._isSearching === true) { if (this._isSearching === true) {
this.popupView && this.popupView.stopSearch && this.popupView.stopSearch(); this.popupView && this.popupView.stopSearch && this.popupView.stopSearch();
this.fireEvent(BI.Searcher.EVENT_STOP); this.fireEvent(Searcher.EVENT_STOP);
} }
this._isSearching = false; this._isSearching = false;
}, }
_search: function () { _search() {
var self = this, o = this.options, keyword = this.editor.getValue(); const { isAutoSearch, adapter, isAutoSync, onSearch } = this.options;
const keyword = this.editor.getValue();
if (keyword === "" || this._stop) { if (keyword === "" || this._stop) {
return; return;
} }
if (o.isAutoSearch) { if (isAutoSearch) {
var items = (o.adapter && ((o.adapter.getItems && o.adapter.getItems()) || o.adapter.attr("items"))) || []; const items = (adapter && ((adapter.getItems && adapter.getItems()) || adapter.attr("items"))) || [];
var finding = BI.Func.getSearchResult(items, keyword); const finding = BI.Func.getSearchResult(items, keyword);
var match = finding.match, find = finding.find; const match = finding.match, find = finding.find;
this.popupView.populate(find, match, keyword); this.popupView.populate(find, match, keyword);
o.isAutoSync && o.adapter && o.adapter.getValue && this.popupView.setValue(o.adapter.getValue()); isAutoSync && adapter && adapter.getValue && this.popupView.setValue(adapter.getValue());
self.fireEvent(BI.Searcher.EVENT_SEARCHING); this.fireEvent(Searcher.EVENT_SEARCHING);
return; return;
} }
this.popupView.loading && this.popupView.loading(); this.popupView.loading && this.popupView.loading();
o.onSearch({ onSearch({
times: 1, times: 1,
keyword: keyword, keyword: keyword,
selectedValues: o.adapter && o.adapter.getValue(), selectedValues: adapter && adapter.getValue(),
}, function (searchResult, matchResult) { }, (searchResult, matchResult, ...arg) => {
if (!self._stop && keyword === self.editor.getValue()) { if (!this._stop && keyword === this.editor.getValue()) {
var args = [].slice.call(arguments); const args = [searchResult, matchResult, ...arg];
if (args.length > 0) { if (args.length > 0) {
args.push(keyword); args.push(keyword);
} }
BI.Maskers.show(self.getName()); Maskers.show(this.getName());
self.popupView.populate.apply(self.popupView, args); this.popupView.populate.apply(this.popupView, args);
o.isAutoSync && o.adapter && o.adapter.getValue && self.popupView.setValue(o.adapter.getValue()); isAutoSync && adapter && adapter.getValue && this.popupView.setValue(adapter.getValue());
self.popupView.loaded && self.popupView.loaded(); this.popupView.loaded && this.popupView.loaded();
self.fireEvent(BI.Searcher.EVENT_SEARCHING); this.fireEvent(Searcher.EVENT_SEARCHING);
} }
}); });
}, }
_getLastSearchKeyword: function () { _getLastSearchKeyword() {
if (this.isValid()) { if (this.isValid()) {
var res = this.editor.getValue().split(/\u200b\s\u200b/); const res = this.editor.getValue().split(/\u200b\s\u200b/);
if (BI.isEmptyString(res[res.length - 1])) { if (isEmptyString(res[res.length - 1])) {
res = res.slice(0, 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; this.options.adapter = adapter;
BI.Maskers.remove(this.getName()); Maskers.remove(this.getName());
}, }
doSearch: function () { doSearch() {
if (this.isSearching()) { if (this.isSearching()) {
this._search(); this._search();
} }
}, }
stopSearch: function () { stopSearch() {
this._stopSearch();// 先停止搜索,然后再去设置editor为空 this._stopSearch();// 先停止搜索,然后再去设置editor为空
// important:停止搜索必须退出编辑状态,这里必须加上try(input框不显示时blur会抛异常) // important:停止搜索必须退出编辑状态,这里必须加上try(input框不显示时blur会抛异常)
try { try {
@ -235,103 +249,95 @@ BI.Searcher = BI.inherit(BI.Widget, {
} finally { } finally {
this.editor.setValue(""); this.editor.setValue("");
} }
}, }
isSearching: function () { isSearching() {
return this._isSearching; return this._isSearching;
}, }
isViewVisible: function () { isViewVisible() {
return this.editor.isEnabled() && BI.Maskers.isVisible(this.getName()); return this.editor.isEnabled() && Maskers.isVisible(this.getName());
}, }
getView: function () { getView() {
return this.popupView; return this.popupView;
}, }
hasMatched: function () { hasMatched() {
this._assertPopupView(); this._assertPopupView();
return this.popupView.hasMatched(); return this.popupView.hasMatched();
}, }
adjustHeight: function () { adjustHeight() {
if (BI.Maskers.has(this.getName()) && BI.Maskers.get(this.getName()).isVisible()) { if (Maskers.has(this.getName()) && Maskers.get(this.getName()).isVisible()) {
BI.Maskers.show(this.getName()); Maskers.show(this.getName());
} }
}, }
adjustView: function () { adjustView() {
this.isViewVisible() && BI.Maskers.show(this.getName()); this.isViewVisible() && Maskers.show(this.getName());
}, }
setValue: function (v) { setValue(v) {
if (BI.isNull(this.popupView)) { if (isNull(this.popupView)) {
this.options.popup.value = v; this.options.popup.value = v;
} else { } else {
this.popupView.setValue(v); this.popupView.setValue(v);
} }
}, }
getKeyword: function () { getKeyword() {
return this._getLastSearchKeyword(); return this._getLastSearchKeyword();
}, }
getKeywords: function () { getKeywords() {
return this.editor.getKeywords(); return this.editor.getKeywords();
}, }
getValue: function () { getValue() {
var o = this.options; const { isAutoSync, adapter, popup } = this.options;
if (o.isAutoSync && o.adapter && o.adapter.getValue) { if (isAutoSync && adapter && adapter.getValue) {
return o.adapter.getValue(); return adapter.getValue();
} }
if (this.isSearching()) { if (this.isSearching()) {
return this.popupView.getValue(); return this.popupView.getValue();
} else if (o.adapter && o.adapter.getValue) { } else if (adapter && adapter.getValue) {
return o.adapter.getValue(); return adapter.getValue();
} }
if (BI.isNull(this.popupView)) { if (isNull(this.popupView)) {
return o.popup.value; return popup.value;
} }
return this.popupView.getValue(); return this.popupView.getValue();
}, }
populate: function (result, searchResult, keyword) { populate(result, searchResult, keyword) {
var o = this.options; const { isAutoSync, adapter } = this.options;
this._assertPopupView(); this._assertPopupView();
this.popupView.populate.apply(this.popupView, arguments); this.popupView.populate.apply(this.popupView, arguments);
if (o.isAutoSync && o.adapter && o.adapter.getValue) { if (isAutoSync && adapter && adapter.getValue) {
this.popupView.setValue(o.adapter.getValue()); this.popupView.setValue(adapter.getValue());
} }
}, }
empty: function () { empty() {
this.popupView && this.popupView.empty(); this.popupView && this.popupView.empty();
}, }
destroyed: function () { destroyed() {
BI.Maskers.remove(this.getName()); Maskers.remove(this.getName());
}, }
focus: function () { focus() {
this.editor.focus(); this.editor.focus();
}, }
blur: function () { blur() {
this.editor.blur(); this.editor.blur();
}, }
setWaterMark: function (v) { setWaterMark(v) {
this.editor.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);

278
src/base/combination/switcher.js

@ -6,9 +6,26 @@
* @class BI.Switcher * @class BI.Switcher
* @extends BI.Widget * @extends BI.Widget
*/ */
BI.Switcher = BI.inherit(BI.Widget, { import { shortcut, Widget, Controller, extend, nextTick, createWidget, each, debounce, isNull } from "../../core";
_defaultConfig: function () { import { Maskers } from "../0.base";
return BI.extend(BI.Switcher.superclass._defaultConfig.apply(this, arguments), {
@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";
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", baseCls: "bi-switcher",
direction: BI.Direction.Top, direction: BI.Direction.Top,
trigger: "click", trigger: "click",
@ -20,47 +37,47 @@ BI.Switcher = BI.inherit(BI.Widget, {
switcherClass: "bi-switcher-popup", switcherClass: "bi-switcher-popup",
hoverClass: "bi-switcher-hover", hoverClass: "bi-switcher-hover",
}); });
}, }
render: function () { render() {
var self = this, o = this.options; const { hoverClass, isDefaultInit } = this.options;
this._initSwitcher(); this._initSwitcher();
// 延迟绑定事件,这样可以将自己绑定的事情优先执行 // 延迟绑定事件,这样可以将自己绑定的事情优先执行
BI.nextTick(() => { nextTick(() => {
!this.isDestroyed() && this._initPullDownAction(); !this.isDestroyed() && this._initPullDownAction();
}); });
this.switcher.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { this.switcher.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => {
if (self.isEnabled() && self.isValid()) { if (this.isEnabled() && this.isValid()) {
if (type === BI.Events.EXPAND) { if (type === BI.Events.EXPAND) {
self._popupView(); this._popupView();
} }
if (type === BI.Events.COLLAPSE) { if (type === BI.Events.COLLAPSE) {
self._hideView(); this._hideView();
} }
if (type === BI.Events.EXPAND) { if (type === BI.Events.EXPAND) {
self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args);
self.fireEvent(BI.Switcher.EVENT_EXPAND); this.fireEvent(Switcher.EVENT_EXPAND);
} }
if (type === BI.Events.COLLAPSE) { if (type === BI.Events.COLLAPSE) {
self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args);
self.isViewVisible() && self.fireEvent(BI.Switcher.EVENT_COLLAPSE); this.isViewVisible() && this.fireEvent(Switcher.EVENT_COLLAPSE);
} }
if (type === BI.Events.CLICK) { 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 () { this.element.hover(() => {
if (self.isEnabled() && self.switcher.isEnabled()) { if (this.isEnabled() && this.switcher.isEnabled()) {
self.element.addClass(o.hoverClass); this.element.addClass(hoverClass);
} }
}, function () { }, () => {
if (self.isEnabled() && self.switcher.isEnabled()) { if (this.isEnabled() && this.switcher.isEnabled()) {
self.element.removeClass(o.hoverClass); this.element.removeClass(hoverClass);
} }
}); });
BI.createWidget({ createWidget({
type: "bi.vertical", type: "bi.vertical",
scrolly: false, scrolly: false,
element: this, element: this,
@ -68,10 +85,10 @@ BI.Switcher = BI.inherit(BI.Widget, {
{ el: this.switcher } { el: this.switcher }
], ],
}); });
o.isDefaultInit && (this._assertPopupView()); isDefaultInit && (this._assertPopupView());
}, }
_toggle: function () { _toggle() {
this._assertPopupView(); this._assertPopupView();
if (this.isExpanded()) { if (this.isExpanded()) {
this._hideView(); this._hideView();
@ -80,40 +97,40 @@ BI.Switcher = BI.inherit(BI.Widget, {
this._popupView(); this._popupView();
} }
} }
}, }
_initPullDownAction: function () { _initPullDownAction() {
var self = this, o = this.options; const { toggle } = this.options;
var evs = this.options.trigger.split(","); const evs = this.options.trigger.split(",");
BI.each(evs, function (i, e) { each(evs, (i, e) => {
switch (e) { switch (e) {
case "hover": case "hover":
self.element[e](function (e) { this.element[e]((e) => {
if (self.isEnabled() && self.switcher.isEnabled()) { if (this.isEnabled() && this.switcher.isEnabled()) {
self._popupView(); this._popupView();
self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.switcher); this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.switcher);
self.fireEvent(BI.Switcher.EVENT_EXPAND); this.fireEvent(Switcher.EVENT_EXPAND);
} }
}, function () { }, () => {
if (self.isEnabled() && self.switcher.isEnabled() && o.toggle) { if (this.isEnabled() && this.switcher.isEnabled() && toggle) {
self._hideView(); this._hideView();
self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.switcher); this.fireEvent(Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", this.switcher);
self.fireEvent(BI.Switcher.EVENT_COLLAPSE); this.fireEvent(Switcher.EVENT_COLLAPSE);
} }
}); });
break; break;
default : default :
if (e) { if (e) {
self.element.off(e + "." + self.getName()).on(e + "." + self.getName(), BI.debounce(function (e) { this.element.off(e + "." + this.getName()).on(e + "." + this.getName(), debounce((e) => {
if (self.switcher.element.__isMouseInBounds__(e)) { if (this.switcher.element.__isMouseInBounds__(e)) {
if (self.isEnabled() && self.switcher.isEnabled()) { if (this.isEnabled() && this.switcher.isEnabled()) {
o.toggle ? self._toggle() : self._popupView(); toggle ? this._toggle() : this._popupView();
if (self.isExpanded()) { if (this.isExpanded()) {
self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.switcher); this.fireEvent(Controller.EVENT_CHANGE, BI.Events.EXPAND, "", this.switcher);
self.fireEvent(BI.Switcher.EVENT_EXPAND); this.fireEvent(Switcher.EVENT_EXPAND);
} else { } else {
self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.switcher); this.fireEvent(Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", this.switcher);
self.fireEvent(BI.Switcher.EVENT_COLLAPSE); this.fireEvent(Switcher.EVENT_COLLAPSE);
} }
} }
} }
@ -125,36 +142,36 @@ BI.Switcher = BI.inherit(BI.Widget, {
break; break;
} }
}); });
}, }
_initSwitcher: function () { _initSwitcher() {
this.switcher = BI.createWidget(this.options.el, { this.switcher = createWidget(this.options.el, {
value: this.options.value, value: this.options.value,
}); });
}, }
_assertPopupView: function () { _assertPopupView() {
var self = this, o = this.options; const { popup, adapter, masker, value, direction } = this.options;
if (!this._created) { if (!this._created) {
this.popupView = BI.createWidget(o.popup, { this.popupView = createWidget(popup, {
type: "bi.button_group", 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", cls: "switcher-popup",
layouts: [{ layouts: [{
type: "bi.vertical", type: "bi.vertical",
hgap: 0, hgap: 0,
vgap: 0, vgap: 0,
}], }],
value: o.value, value,
}, this); }, this);
this.popupView.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { this.popupView.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => {
self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args);
if (type === BI.Events.CLICK) { 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) { if (direction !== BI.Direction.Custom && !adapter) {
BI.createWidget({ createWidget({
type: "bi.vertical", type: "bi.vertical",
scrolly: false, scrolly: false,
element: this, element: this,
@ -164,133 +181,120 @@ BI.Switcher = BI.inherit(BI.Widget, {
}); });
} }
this._created = true; this._created = true;
BI.nextTick(function () { nextTick(() => {
self.fireEvent(BI.Switcher.EVENT_AFTER_INIT); this.fireEvent(Switcher.EVENT_AFTER_INIT);
}); });
} }
}, }
_hideView: function () { _hideView() {
this.fireEvent(BI.Switcher.EVENT_BEFORE_HIDEVIEW); this.fireEvent(Switcher.EVENT_BEFORE_HIDEVIEW);
var self = this, o = this.options; const { adapter, switcherClass } = this.options;
o.adapter ? BI.Maskers.hide(self.getName()) : (self.popupView && self.popupView.setVisible(false)); adapter ? Maskers.hide(this.getName()) : (this.popupView && this.popupView.setVisible(false));
BI.nextTick(function () { nextTick(() => {
o.adapter ? BI.Maskers.hide(self.getName()) : (self.popupView && self.popupView.setVisible(false)); adapter ? Maskers.hide(this.getName()) : (this.popupView && this.popupView.setVisible(false));
self.element.removeClass(o.switcherClass); this.element.removeClass(switcherClass);
self.fireEvent(BI.Switcher.EVENT_AFTER_HIDEVIEW); this.fireEvent(Switcher.EVENT_AFTER_HIDEVIEW);
}); });
}, }
_popupView: function () { _popupView() {
var self = this, o = this.options; const { adapter, switcherClass } = this.options;
this._assertPopupView(); this._assertPopupView();
this.fireEvent(BI.Switcher.EVENT_BEFORE_POPUPVIEW); this.fireEvent(Switcher.EVENT_BEFORE_POPUPVIEW);
o.adapter ? BI.Maskers.show(this.getName()) : self.popupView.setVisible(true); adapter ? Maskers.show(this.getName()) : this.popupView.setVisible(true);
BI.nextTick(function (name) { nextTick((name) => {
o.adapter ? BI.Maskers.show(name) : self.popupView.setVisible(true); adapter ? Maskers.show(name) : this.popupView.setVisible(true);
self.element.addClass(o.switcherClass); this.element.addClass(switcherClass);
self.fireEvent(BI.Switcher.EVENT_AFTER_POPUPVIEW); this.fireEvent(Switcher.EVENT_AFTER_POPUPVIEW);
}, this.getName()); }, this.getName());
}, }
_populate: function () { _populate() {
this._assertPopupView(); this._assertPopupView();
this.popupView.populate.apply(this.popupView, arguments); this.popupView.populate.apply(this.popupView, arguments);
}, }
populate: function (items) { populate(items) {
this._populate.apply(this, arguments); this._populate.apply(this, arguments);
this.switcher.populate && this.switcher.populate.apply(this.switcher, arguments); this.switcher.populate && this.switcher.populate.apply(this.switcher, arguments);
}, }
_setEnable: function (arg) { _setEnable(arg) {
BI.Switcher.superclass._setEnable.apply(this, arguments); super._setEnable(arguments);
!arg && this.isViewVisible() && this._hideView(); !arg && this.isViewVisible() && this._hideView();
}, }
setValue: function (v) { setValue(v) {
this.switcher.setValue(v); this.switcher.setValue(v);
if (BI.isNull(this.popupView)) { if (isNull(this.popupView)) {
this.options.popup.value = v; this.options.popup.value = v;
} else { } else {
this.popupView.setValue(v); this.popupView.setValue(v);
} }
}, }
getValue: function () { getValue() {
if (BI.isNull(this.popupView)) { if (isNull(this.popupView)) {
return this.options.popup.value; return this.options.popup.value;
} else { } else {
return this.popupView.getValue(); return this.popupView.getValue();
} }
}, }
setAdapter: function (adapter) { setAdapter(adapter) {
this.options.adapter = adapter; this.options.adapter = adapter;
BI.Maskers.remove(this.getName()); Maskers.remove(this.getName());
}, }
isViewVisible: function () { isViewVisible() {
return this.isEnabled() && this.switcher.isEnabled() && 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(); return this.isViewVisible();
}, }
showView: function () { showView() {
if (this.isEnabled() && this.switcher.isEnabled()) { if (this.isEnabled() && this.switcher.isEnabled()) {
this._popupView(); this._popupView();
} }
}, }
hideView: function () { hideView() {
this._hideView(); this._hideView();
}, }
getView: function () { getView() {
return this.popupView; return this.popupView;
}, }
adjustView: function () { adjustView() {
this.isViewVisible() && BI.Maskers.show(this.getName()); this.isViewVisible() && Maskers.show(this.getName());
}, }
getAllLeaves: function () { getAllLeaves() {
return this.popupView && this.popupView.getAllLeaves(); return this.popupView && this.popupView.getAllLeaves();
}, }
getNodeById: function (id) { getNodeById(id) {
if (this.switcher.attr("id") === id) { if (this.switcher.attr("id") === id) {
return this.switcher; return this.switcher;
} }
return this.popupView && this.popupView.getNodeById(id); return this.popupView && this.popupView.getNodeById(id);
}, }
getNodeByValue: function (value) { getNodeByValue(value) {
if (this.switcher.getValue() === value) { if (this.switcher.getValue() === value) {
return this.switcher; return this.switcher;
} }
return this.popupView && this.popupView.getNodeByValue(value); return this.popupView && this.popupView.getNodeByValue(value);
}, }
empty: function () { empty() {
this.popupView && this.popupView.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);

177
src/base/combination/tab.js

@ -1,10 +1,16 @@
/** /**
* Created by GUY on 2015/6/26. * 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, { @shortcut()
_defaultConfig: function () { export class Tab extends Widget {
return BI.extend(BI.Tab.superclass._defaultConfig.apply(this, arguments), { static xtype = "bi.tab";
static EVENT_CHANGE = "EVENT_CHANGE";
_defaultConfig() {
return extend(super._defaultConfig(arguments), {
baseCls: "bi-tab", baseCls: "bi-tab",
direction: "top", // top, bottom, left, right, custom direction: "top", // top, bottom, left, right, custom
single: false, // 是不是单页面 single: false, // 是不是单页面
@ -13,87 +19,87 @@ BI.Tab = BI.inherit(BI.Widget, {
}, },
showIndex: false, showIndex: false,
tab: false, tab: false,
cardCreator: function (v) { cardCreator: (v) => {
return BI.createWidget(); return createWidget();
}, },
keepAlives: [], keepAlives: [],
}); });
}, }
render: function () { render() {
var self = this, o = this.options; const { tab, direction, logic, cardCreator } = this.options;
if (BI.isObject(o.tab)) { if (isObject(tab)) {
this.tab = BI.createWidget(this.options.tab, { type: "bi.button_group" }); this.tab = createWidget(this.options.tab, { type: "bi.button_group" });
this.tab.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { this.tab.on(Controller.EVENT_CHANGE, (type, value, obj, ...args) => {
self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); this.fireEvent(Controller.EVENT_CHANGE, type, value, obj, ...args);
}); });
} }
this.cardMap = {}; this.cardMap = {};
this.layout = BI.createWidget({ this.layout = createWidget({
type: "bi.card", type: "bi.card",
}); });
BI.createWidget(BI.extend({ createWidget(extend({
element: this, element: this,
}, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend({}, o.logic, { }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(direction), extend({}, logic, {
items: BI.LogicFactory.createLogicItemsByDirection(o.direction, this.tab, this.layout), items: BI.LogicFactory.createLogicItemsByDirection(direction, this.tab, this.layout),
})))); }))));
var listener = new BI.ShowListener({ const listener = new ShowListener({
eventObj: this.tab, eventObj: this.tab,
cardLayout: this.layout, cardLayout: this.layout,
cardCreator: function (v) { cardCreator: (v) => {
BI.Widget.execWithContext(self, function () { Widget.execWithContext(this, () => {
self.cardMap[v] = o.cardCreator(v); this.cardMap[v] = cardCreator(v);
}); });
return self.cardMap[v]; return this.cardMap[v];
}, },
afterCardShow: function (v) { afterCardShow: (v) => {
self._deleteOtherCards(v); this._deleteOtherCards(v);
self.curr = v; this.curr = v;
}, },
}); });
listener.on(BI.ShowListener.EVENT_CHANGE, function (value) { listener.on(ShowListener.EVENT_CHANGE, (value) => {
self.fireEvent(BI.Tab.EVENT_CHANGE, value, self); this.fireEvent(Tab.EVENT_CHANGE, value, this);
}); });
}, }
_deleteOtherCards: function (currCardName) { _deleteOtherCards(currCardName) {
var self = this, o = this.options; const { single } = this.options;
if (o.single === true) { if (single === true) {
BI.each(this.cardMap, function (name, card) { each(this.cardMap, (name, card) => {
if (name !== (currCardName + "") && self._keepAlive(name) !== true) { if (name !== (currCardName + "") && this._keepAlive(name) !== true) {
self.layout.deleteCardByName(name); this.layout.deleteCardByName(name);
delete self.cardMap[name]; delete this.cardMap[name];
} }
}); });
} }
}, }
_assertCard: function (v) { _assertCard(v) {
var self = this, o = this.options; const { cardCreator } = this.options;
if (!this.layout.isCardExisted(v)) { if (!this.layout.isCardExisted(v)) {
BI.Widget.execWithContext(this, function () { Widget.execWithContext(this, () => {
self.cardMap[v] = o.cardCreator(v); this.cardMap[v] = cardCreator(v);
}); });
this.layout.addCardByName(v, this.cardMap[v]); this.layout.addCardByName(v, this.cardMap[v]);
} }
}, }
_keepAlive: function (v) { _keepAlive(v) {
var o = this.options; 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 () { created() {
var self = this, o = this.options; const o = this.options;
let showIndex;
var showIndex; if (isFunction(o.showIndex)) {
if (BI.isFunction(o.showIndex)) { showIndex = this.__watch(o.showIndex, (context, newValue) => {
showIndex = this.__watch(o.showIndex, function (context, newValue) { this.setSelect(newValue);
self.setSelect(newValue);
}); });
} else { } else {
showIndex = o.showIndex; showIndex = o.showIndex;
@ -102,9 +108,9 @@ BI.Tab = BI.inherit(BI.Widget, {
if (showIndex !== false) { if (showIndex !== false) {
this.setSelect(showIndex); this.setSelect(showIndex);
} }
}, }
setSelect: function (v, action, callback) { setSelect(v, action, callback) {
this.tab && this.tab.setValue(v); this.tab && this.tab.setValue(v);
this._assertCard(v); this._assertCard(v);
this.layout.showCardByName(v, action, callback); this.layout.showCardByName(v, action, callback);
@ -112,69 +118,66 @@ BI.Tab = BI.inherit(BI.Widget, {
if (this.curr !== v) { if (this.curr !== v) {
this.curr = v; this.curr = v;
} }
}, }
removeTab: function (cardname) { removeTab(cardname) {
var self = this; any(this.cardMap, (name, card) => {
BI.any(this.cardMap, function (name, card) { if (isEqual(name, (cardname + ""))) {
if (BI.isEqual(name, (cardname + ""))) { this.layout.deleteCardByName(name);
self.layout.deleteCardByName(name); delete this.cardMap[name];
delete self.cardMap[name];
return true; return true;
} }
}); });
}, }
isCardExisted: function (cardName) { isCardExisted(cardName) {
return this.layout.isCardExisted(cardName); return this.layout.isCardExisted(cardName);
}, }
getSelect: function () { getSelect() {
return this.curr; return this.curr;
}, }
getSelectedTab: function () { getSelectedTab() {
return this.layout.getShowingCard(); return this.layout.getShowingCard();
}, }
getTab: function (v) { getTab(v) {
this._assertCard(v); this._assertCard(v);
return this.layout.getCardByName(v); return this.layout.getCardByName(v);
}, }
setValue: function (v) { setValue(v) {
var card = this.layout.getShowingCard(); const card = this.layout.getShowingCard();
if (card) { if (card) {
card.setValue(v); card.setValue(v);
} }
}, }
getValue: function () { getValue() {
var card = this.layout.getShowingCard(); const card = this.layout.getShowingCard();
if (card) { if (card) {
return card.getValue(); return card.getValue();
} }
}, }
populate: function () { populate() {
var card = this.layout.getShowingCard(); const card = this.layout.getShowingCard();
if (card) { if (card) {
return card.populate && card.populate.apply(card, arguments); return card.populate && card.populate.apply(card, arguments);
} }
}, }
empty: function () { empty() {
this.layout.deleteAllCard(); this.layout.deleteAllCard();
this.cardMap = {}; this.cardMap = {};
}, }
destroy: function () { destroy() {
this.cardMap = {}; this.cardMap = {};
BI.Tab.superclass.destroy.apply(this, arguments); super.destroy(arguments);
}, }
});
BI.Tab.EVENT_CHANGE = "EVENT_CHANGE";
BI.shortcut("bi.tab", BI.Tab); }

142
src/base/combination/tree.button.js

@ -3,67 +3,74 @@
* @class BI.ButtonTree * @class BI.ButtonTree
* @extends BI.ButtonGroup * @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, { @shortcut()
_defaultConfig: function () { export class ButtonTree extends ButtonGroup {
return BI.extend(BI.ButtonTree.superclass._defaultConfig.apply(this, arguments), { static xtype = "bi.button_tree";
static EVENT_CHANGE = "EVENT_CHANGE";
_defaultConfig() {
return extend(super._defaultConfig(arguments), {
baseCls: "bi-button-tree", baseCls: "bi-button-tree",
}); });
}, }
setNotSelectedValue: function (v) { setNotSelectedValue(v) {
v = BI.isArray(v) ? v : [v]; v = isArray(v) ? v : [v];
BI.each(this.buttons, function (i, item) { each(this.buttons, (i, item) => {
if (!BI.isFunction(item.setSelected)) { if (!isFunction(item.setSelected)) {
item.setNotSelectedValue(v); item.setNotSelectedValue(v);
return; return;
} }
if (BI.deepContains(v, item.getValue())) { if (deepContains(v, item.getValue())) {
item.setSelected(false); item.setSelected(false);
} else { } else {
item.setSelected(true); item.setSelected(true);
} }
}); });
}, }
setEnabledValue: function (v) { setEnabledValue(v) {
v = BI.isArray(v) ? v : [v]; v = isArray(v) ? v : [v];
BI.each(this.buttons, function (i, item) { each(this.buttons, (i, item) => {
if (BI.isFunction(item.setEnabledValue)) { if (isFunction(item.setEnabledValue)) {
item.setEnabledValue(v); item.setEnabledValue(v);
return; return;
} }
if (BI.deepContains(v, item.getValue())) { if (deepContains(v, item.getValue())) {
item.setEnable(true); item.setEnable(true);
} else { } else {
item.setEnable(false); item.setEnable(false);
} }
}); });
}, }
setValue: function (v) { setValue(v) {
v = BI.isArray(v) ? v : [v]; v = isArray(v) ? v : [v];
BI.each(this.buttons, function (i, item) { each(this.buttons, (i, item) => {
if (!BI.isFunction(item.setSelected)) { if (!isFunction(item.setSelected)) {
item.setValue(v); item.setValue(v);
return; return;
} }
if (BI.deepContains(v, item.getValue())) { if (deepContains(v, item.getValue())) {
item.setSelected(true); item.setSelected(true);
} else { } else {
item.setSelected(false); item.setSelected(false);
} }
}); });
}, }
getNotSelectedValue: function () { getNotSelectedValue() {
var v = []; let v = [];
BI.each(this.buttons, function (i, item) { each(this.buttons, (i, item) => {
if (item.isEnabled() && !BI.isFunction(item.setSelected)) { if (item.isEnabled() && !isFunction(item.setSelected)) {
v = BI.concat(v, item.getNotSelectedValue()); v = concat(v, item.getNotSelectedValue());
return; return;
} }
@ -73,13 +80,13 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, {
}); });
return v; return v;
}, }
getValue: function () { getValue() {
var v = []; let v = [];
BI.each(this.buttons, function (i, item) { each(this.buttons, (i, item) => {
if (item.isEnabled() && !BI.isFunction(item.setSelected)) { if (item.isEnabled() && !isFunction(item.setSelected)) {
v = BI.concat(v, item.getValue()); v = concat(v, item.getValue());
return; return;
} }
@ -89,12 +96,12 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, {
}); });
return v; return v;
}, }
getSelectedButtons: function () { getSelectedButtons() {
var btns = []; let btns = [];
BI.each(this.buttons, function (i, item) { each(this.buttons, (i, item) => {
if (item.isEnabled() && !BI.isFunction(item.setSelected)) { if (item.isEnabled() && !isFunction(item.setSelected)) {
btns = btns.concat(item.getSelectedButtons()); btns = btns.concat(item.getSelectedButtons());
return; return;
@ -105,12 +112,12 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, {
}); });
return btns; return btns;
}, }
getNotSelectedButtons: function () { getNotSelectedButtons() {
var btns = []; let btns = [];
BI.each(this.buttons, function (i, item) { each(this.buttons, (i, item) => {
if (item.isEnabled() && !BI.isFunction(item.setSelected)) { if (item.isEnabled() && !isFunction(item.setSelected)) {
btns = btns.concat(item.getNotSelectedButtons()); btns = btns.concat(item.getNotSelectedButtons());
return; return;
@ -121,13 +128,13 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, {
}); });
return btns; return btns;
}, }
// 获取所有的叶子节点 // 获取所有的叶子节点
getAllLeaves: function () { getAllLeaves() {
var leaves = []; let leaves = [];
BI.each(this.buttons, function (i, item) { each(this.buttons, (i, item) => {
if (item.isEnabled() && !BI.isFunction(item.setSelected)) { if (item.isEnabled() && !isFunction(item.setSelected)) {
leaves = leaves.concat(item.getAllLeaves()); leaves = leaves.concat(item.getAllLeaves());
return; return;
@ -138,13 +145,13 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, {
}); });
return leaves; return leaves;
}, }
getIndexByValue: function (value) { getIndexByValue(value) {
var index = -1; let index = -1;
BI.any(this.buttons, function (i, item) { any(this.buttons, (i, item) => {
var vs = item.getValue(); const vs = item.getValue();
if (item.isEnabled() && (vs === value || BI.contains(vs, value))) { if (item.isEnabled() && (vs === value || contains(vs, value))) {
index = i; index = i;
return true; return true;
@ -152,17 +159,17 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, {
}); });
return index; return index;
}, }
getNodeById: function (id) { getNodeById(id) {
var node; let node;
BI.any(this.buttons, function (i, item) { any(this.buttons, (i, item) => {
if (item.isEnabled()) { if (item.isEnabled()) {
if (item.attr("id") === id) { if (item.attr("id") === id) {
node = item; node = item;
return true; return true;
} else if (BI.isFunction(item.getNodeById)) { } else if (isFunction(item.getNodeById)) {
node = item.getNodeById(id); node = item.getNodeById(id);
if (node) { if (node) {
return true; return true;
@ -172,13 +179,13 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, {
}); });
return node; return node;
}, }
getNodeByValue: function (value) { getNodeByValue(value) {
var node; let node;
BI.any(this.buttons, function (i, item) { any(this.buttons, (i, item) => {
if (item.isEnabled()) { if (item.isEnabled()) {
if (BI.isFunction(item.getNodeByValue)) { if (isFunction(item.getNodeByValue)) {
node = item.getNodeByValue(value); node = item.getNodeByValue(value);
if (node) { if (node) {
return true; return true;
@ -192,8 +199,5 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, {
}); });
return node; return node;
}, }
}); }
BI.ButtonTree.EVENT_CHANGE = "EVENT_CHANGE";
BI.shortcut("bi.button_tree", BI.ButtonTree);

54
src/base/foundation/message.js

@ -3,12 +3,14 @@
* 弹出提示消息框用于模拟阻塞操作通过回调函数实现 * 弹出提示消息框用于模拟阻塞操作通过回调函数实现
* @class BI.Msg * @class BI.Msg
*/ */
BI.Msg = ((function () { import { Widget, isString, isNull, isFunction, createWidget, remove, each } from "../../core"
var $mask, $pop;
var messageShows = []; export const Msg = ((() => {
let $mask, $pop;
var toastStack = []; let messageShows = [];
let toastStack = [];
return { return {
alert: function (title, message, callback) { alert: function (title, message, callback) {
@ -21,13 +23,13 @@ BI.Msg = ((function () {
// BI.Msg.prompt(title, message, value, callback, min_width); // BI.Msg.prompt(title, message, value, callback, min_width);
}, },
toast: function (message, options, context) { toast: function (message, options, context) {
BI.isString(options) && (options = { level: options }); isString(options) && (options = { level: options });
options = options || {}; options = options || {};
context = context || BI.Widget._renderEngine.createElement("body"); context = context || Widget._renderEngine.createElement("body");
var level = options.level || "common"; const level = options.level || "common";
var autoClose = BI.isNull(options.autoClose) ? true : options.autoClose; const autoClose = isNull(options.autoClose) ? true : options.autoClose;
var callback = BI.isFunction(options.callback) ? options.callback : BI.emptyFn; const callback = isFunction(options.callback) ? options.callback : BI.emptyFn;
var toast = BI.createWidget({ const toast = createWidget({
type: "bi.toast", type: "bi.toast",
cls: "bi-message-animate bi-message-leave", cls: "bi-message-animate bi-message-leave",
level: level, level: level,
@ -37,9 +39,9 @@ BI.Msg = ((function () {
listeners: [{ listeners: [{
eventName: BI.Toast.EVENT_DESTORY, eventName: BI.Toast.EVENT_DESTORY,
action: function () { action: function () {
BI.remove(toastStack, toast.element); remove(toastStack, toast.element);
var _height = BI.SIZE_CONSANTS.TOAST_TOP; let _height = BI.SIZE_CONSANTS.TOAST_TOP;
BI.each(toastStack, function (i, element) { each(toastStack, function (i, element) {
element.css({ "top": _height }); element.css({ "top": _height });
_height += element.outerHeight() + 10; _height += element.outerHeight() + 10;
}); });
@ -47,11 +49,11 @@ BI.Msg = ((function () {
}, },
}], }],
}); });
var height = BI.SIZE_CONSANTS.TOAST_TOP; const height = BI.SIZE_CONSANTS.TOAST_TOP;
BI.each(toastStack, function (i, element) { each(toastStack, function (i, element) {
height += element.outerHeight() + 10; height += element.outerHeight() + 10;
}); });
BI.createWidget({ createWidget({
type: "bi.absolute", type: "bi.absolute",
element: context, element: context,
items: [{ items: [{
@ -75,7 +77,7 @@ BI.Msg = ((function () {
}; };
}, },
_show: function (hasCancel, title, message, callback) { _show: function (hasCancel, title, message, callback) {
BI.isNull($mask) && ($mask = BI.Widget._renderEngine.createElement("<div class=\"bi-z-index-mask\">").css({ isNull($mask) && ($mask = Widget._renderEngine.createElement("<div class=\"bi-z-index-mask\">").css({
position: "absolute", position: "absolute",
zIndex: BI.zIndex_tip - 2, zIndex: BI.zIndex_tip - 2,
top: 0, top: 0,
@ -84,7 +86,7 @@ BI.Msg = ((function () {
bottom: 0, bottom: 0,
opacity: 0.5, opacity: 0.5,
}).appendTo("body")); }).appendTo("body"));
$pop = BI.Widget._renderEngine.createElement("<div class=\"bi-message-depend\">").css({ $pop = Widget._renderEngine.createElement("<div class=\"bi-message-depend\">").css({
position: "absolute", position: "absolute",
zIndex: BI.zIndex_tip - 1, zIndex: BI.zIndex_tip - 1,
top: 0, top: 0,
@ -100,7 +102,7 @@ BI.Msg = ((function () {
$mask = null; $mask = null;
} }
} }
var controlItems = []; let controlItems = [];
if (hasCancel === true) { if (hasCancel === true) {
controlItems.push({ controlItems.push({
el: { el: {
@ -109,7 +111,7 @@ BI.Msg = ((function () {
level: "ignore", level: "ignore",
handler: function () { handler: function () {
close(); close();
if (BI.isFunction(callback)) { if (isFunction(callback)) {
callback.apply(null, [false]); callback.apply(null, [false]);
} }
}, },
@ -122,13 +124,13 @@ BI.Msg = ((function () {
text: BI.i18nText("BI-Basic_OK"), text: BI.i18nText("BI-Basic_OK"),
handler: function () { handler: function () {
close(); close();
if (BI.isFunction(callback)) { if (isFunction(callback)) {
callback.apply(null, [true]); callback.apply(null, [true]);
} }
}, },
}, },
}); });
var conf = { const conf = {
element: $pop, element: $pop,
type: "bi.center_adapt", type: "bi.center_adapt",
items: [ items: [
@ -141,13 +143,13 @@ BI.Msg = ((function () {
this.element.keyup(function (e) { this.element.keyup(function (e) {
if (e.keyCode === BI.KeyCode.ENTER) { if (e.keyCode === BI.KeyCode.ENTER) {
close(); close();
if (BI.isFunction(callback)) { if (isFunction(callback)) {
callback.apply(null, [true]); callback.apply(null, [true]);
} }
} else if (e.keyCode === BI.KeyCode.ESCAPE) { } else if (e.keyCode === BI.KeyCode.ESCAPE) {
close(); close();
if (hasCancel === true) { if (hasCancel === true) {
if (BI.isFunction(callback)) { if (isFunction(callback)) {
callback.apply(null, [false]); callback.apply(null, [false]);
} }
} }
@ -183,7 +185,7 @@ BI.Msg = ((function () {
// height: 50, // height: 50,
handler: function () { handler: function () {
close(); close();
if (BI.isFunction(callback)) { if (isFunction(callback)) {
callback.apply(null, [false]); callback.apply(null, [false]);
} }
}, },
@ -228,7 +230,7 @@ BI.Msg = ((function () {
], ],
}; };
messageShows[messageShows.length] = BI.createWidget(conf); messageShows[messageShows.length] = createWidget(conf);
}, },
}; };
})()); })());

100
src/base/index.js

@ -1,95 +1,31 @@
import Pane from "./1.pane"; import { Pane } from "./1.pane";
import Single from "./single/0.single"; import * as single from "./single";
import Text from "./single/1.text"; import * as layer from "./layer";
import A from "./single/a/a"; import * as list from "./list";
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 GridView from "./grid/grid";
import Pager from "./pager/pager"; import Pager from "./pager/pager";
import * as combination from "./combination";
import { Msg } from "./foundation/message";
import { BasicButton } from "./single/button/button.basic"; Object.assign(BI, {
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, Pane,
Single, ...layer,
Text, ...list,
A, ...single,
Tip,
Toast,
Tooltip,
Drawer,
Popover,
BarPopover,
PopupView,
SearcherView,
ListView,
VirtualGroupList,
VirtualList,
GridView, GridView,
Pager, Pager,
...combination,
Msg,
}); });
export * from "./0.base";
export * from "./combination";
export * from "./layer";
export * from "./list";
export * from "./single";
export { export {
Pane, Pane,
Single,
Text,
A,
Tip,
Toast,
Tooltip,
Drawer,
Popover,
BarPopover,
PopupView,
SearcherView,
ListView,
VirtualGroupList,
VirtualList,
GridView, GridView,
Pager, Pager,
Msg,
} }

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

2
src/base/layer/layer.drawer.js

@ -6,7 +6,7 @@
import { Widget, shortcut } from "../../core"; import { Widget, shortcut } from "../../core";
@shortcut() @shortcut()
export default class Drawer extends Widget { export class Drawer extends Widget {
SIZE = { SIZE = {
SMALL: "small", SMALL: "small",
NORMAL: "normal", NORMAL: "normal",

2
src/base/layer/layer.popup.js

@ -6,7 +6,7 @@
import { Widget, shortcut } from "../../core"; import { Widget, shortcut } from "../../core";
@shortcut() @shortcut()
export default class PopupView extends Widget { export class PopupView extends Widget {
_const = { _const = {
TRIANGLE_LENGTH: 12, TRIANGLE_LENGTH: 12,
} }

4
src/base/layer/layer.searcher.js

@ -7,10 +7,10 @@
*/ */
import { shortcut } from "../../core"; import { shortcut } from "../../core";
import Pane from "../1.pane"; import { Pane } from "../1.pane";
@shortcut() @shortcut()
export default class SearcherView extends Pane { export class SearcherView extends Pane {
static xtype = "bi.searcher_view"; static xtype = "bi.searcher_view";
static EVENT_CHANGE = "EVENT_CHANGE"; static EVENT_CHANGE = "EVENT_CHANGE";

3
src/base/list/index.js

@ -0,0 +1,3 @@
export { ListView } from "./listview";
export { VirtualGroupList } from "./virtualgrouplist";
export { VirtualList } from "./virtuallist";

2
src/base/list/listview.js

@ -7,7 +7,7 @@
*/ */
import { Widget, shortcut } from "../../core"; import { Widget, shortcut } from "../../core";
@shortcut() @shortcut()
export default class ListView extends Widget { export class ListView extends Widget {
props() { props() {
return { return {
baseCls: "bi-list-view", baseCls: "bi-list-view",

2
src/base/list/virtualgrouplist.js

@ -8,7 +8,7 @@
import { Widget, shortcut } from "../../core"; import { Widget, shortcut } from "../../core";
@shortcut() @shortcut()
export default class VirtualGroupList extends Widget { export class VirtualGroupList extends Widget {
props() { props() {
return { return {
baseCls: "bi-virtual-group-list", baseCls: "bi-virtual-group-list",

2
src/base/list/virtuallist.js

@ -8,7 +8,7 @@
import { Widget, shortcut } from "../../core"; import { Widget, shortcut } from "../../core";
@shortcut() @shortcut()
export default class VirtualList extends Widget { export class VirtualList extends Widget {
props() { props() {
return { return {
baseCls: "bi-virtual-list", baseCls: "bi-virtual-list",

2
src/base/single/0.single.js

@ -14,7 +14,7 @@ import { Widget, shortcut } from "../../core";
import { Tooltips } from "../0.base"; import { Tooltips } from "../0.base";
@shortcut() @shortcut()
export default class Single extends Widget { export class Single extends Widget {
static xtype = "bi.single"; static xtype = "bi.single";
_defaultConfig() { _defaultConfig() {

6
src/base/single/1.text.js

@ -3,11 +3,11 @@
* @class BI.Text * @class BI.Text
* @extends BI.Single * @extends BI.Single
*/ */
import { shortcut } from "../../core/decorator"; import { shortcut } from "../../core";
import { Single } from "../index"; import { Single } from "./0.single";
@shortcut() @shortcut()
export default class Text extends Single { export class Text extends Single {
static xtype = "bi.text"; static xtype = "bi.text";
props = { props = {

4
src/base/single/a/a.js

@ -7,9 +7,9 @@
* @abstract * @abstract
*/ */
import { shortcut } from "../../../core"; import { shortcut } from "../../../core";
import Text from "../1.text"; import { Text } from "../1.text";
@shortcut() @shortcut()
export default class A extends Text { export class A extends Text {
static xtype = "bi.a"; static xtype = "bi.a";
_defaultConfig() { _defaultConfig() {

2
src/base/single/button/button.basic.js

@ -1,4 +1,4 @@
import Single from "../0.single" import { Single } from "../0.single"
import { emptyFn, shortcut, extend, isFunction, createWidget, Widget, isObject, Controller } from "../../../core" import { emptyFn, shortcut, extend, isFunction, createWidget, Widget, isObject, Controller } from "../../../core"
/** /**

17
src/base/single/button/index.js

@ -0,0 +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";

5
src/base/single/index.js

@ -0,0 +1,5 @@
export { Single } from "./0.single";
export { Text } from "./1.text";
export { A } from "./a/a";
export * from "./tip";
export * from "./button"

4
src/base/single/tip/0.tip.js

@ -7,8 +7,8 @@
* @abstract * @abstract
*/ */
import Single from "../0.single"; import { Single } from "../0.single";
export default class Tip extends Single { export class Tip extends Single {
_defaultConfig() { _defaultConfig() {
const conf = super._defaultConfig(arguments); const conf = super._defaultConfig(arguments);
return BI.extend(conf, { return BI.extend(conf, {

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

4
src/base/single/tip/tip.toast.js

@ -7,9 +7,9 @@
*/ */
import { shortcut } from "../../../core"; import { shortcut } from "../../../core";
import Tip from "./0.tip"; import { Tip } from "./0.tip";
@shortcut() @shortcut()
export default class Toast extends Tip { export class Toast extends Tip {
_const= { _const= {
closableMinWidth: 146, closableMinWidth: 146,
minWidth: 100, minWidth: 100,

4
src/base/single/tip/tip.tooltip.js

@ -7,9 +7,9 @@
*/ */
import { shortcut } from "../../../core"; import { shortcut } from "../../../core";
import Tip from "./0.tip"; import { Tip } from "./0.tip";
@shortcut() @shortcut()
export default class Tooltip extends Tip { export class Tooltip extends Tip {
_const = { _const = {
hgap: 8, hgap: 8,
vgap: 4, vgap: 4,

145
src/core/2.base.js

@ -139,26 +139,14 @@ export function trans2Element(widgets) {
return map(widgets, (i, wi) => wi.element); 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._.each(["where", "findWhere", "invoke", "pluck", "shuffle", "sample", "toArray", "size"], function (name) {
BI[name] = _apply(name); BI[name] = _apply(name);
}); });
BI._.each(["get", "set", "each", "map", "reduce", "reduceRight", "find", "filter", "reject", "every", "all", "some", "any", "max", "min", BI._.each([
"sortBy", "groupBy", "indexBy", "countBy", "partition", "clamp"], function (name) { "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") { if (name === "any") {
BI[name] = _applyFunc("some"); BI[name] = _applyFunc("some");
} else { } else {
@ -382,30 +370,11 @@ export function int2Abc(num) {
return str; 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", BI._.each([
"difference", "zip", "unzip", "object", "indexOf", "lastIndexOf", "sortedIndex", "range", "take", "takeRight", "uniqBy"], function (name) { "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[name] = _apply(name);
}); });
BI._.each(["findIndex", "findLastIndex"], function (name) { BI._.each(["findIndex", "findLastIndex"], function (name) {
@ -489,18 +458,13 @@ export function uniq(array, isSorted, iteratee, context) {
return uniq.call(BI._, 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", BI._.each([
"keys", "allKeys", "values", "pairs", "invert", "create", "functions", "extend", "extendOwn",
"defaults", "clone", "property", "propertyOf", "matcher", "isEqual", "isMatch", "isEmpty", "defaults", "clone", "property", "propertyOf", "matcher", "isEqual", "isMatch", "isEmpty",
"isElement", "isNumber", "isString", "isArray", "isObject", "isPlainObject", "isArguments", "isFunction", "isFinite", "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); BI[name] = _apply(name);
}); });
export const keys = BI.keys; export const keys = BI.keys;
@ -646,26 +610,9 @@ export function isPromise(obj) {
return !!obj && (isObject(obj) || isFunction(obj)) && isFunction(obj.then); 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 deepClone = BI._.cloneDeep;
export const deepExtend = BI._.deepExtend; export const deepExtend = BI._.deepExtend;
export function isDeepMatch(object, attrs) { export function isDeepMatch(object, attrs) {
let attrsKeys = keys(attrs), length = attrsKeys.length; let attrsKeys = keys(attrs), length = attrsKeys.length;
if (object == null) { if (object == null) {
@ -774,20 +721,6 @@ export function deepDiff(object, other) {
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", "unescape", "before", "after", "chunk"], function (name) { BI._.each(["uniqueId", "result", "chain", "iteratee", "unescape", "before", "after", "chunk"], function (name) {
BI[name] = function () { BI[name] = function () {
@ -886,8 +819,6 @@ export const nextTick = (function () {
}; };
})(); })();
BI._.extend(BI, { nextTick });
// 数字相关方法 // 数字相关方法
BI._.each(["random"], function (name) { BI._.each(["random"], function (name) {
BI[name] = _apply(name); BI[name] = _apply(name);
@ -978,22 +909,6 @@ export function average(array, iteratee, context) {
return sumResult / array.length; return sumResult / array.length;
} }
BI._.extend(BI, {
parseInt,
parseSafeInt,
parseFloat,
isNaturalNumber,
isPositiveInteger,
isNegativeInteger,
isInteger,
isNumeric,
isFloat,
isOdd,
isEven,
sum,
average,
});
export function trim() { export function trim() {
return BI._.trim.apply(BI._, arguments); return BI._.trim.apply(BI._, arguments);
} }
@ -1119,25 +1034,6 @@ export function format(format) {
return format.replace(/\{(\d+)\}/g, (m, i) => args[i]); 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 * @param year
@ -1351,9 +1247,8 @@ export function parseDateTime(str, fmt) {
return today; return today;
} }
export function getDate() { export function getDate(...args) {
const length = arguments.length; const length = args.length;
const args = arguments;
let dt; let dt;
switch (length) { switch (length) {
// new Date() // new Date()
@ -1448,15 +1343,5 @@ export function getTime() {
return dt.getTime() - BI.timeZone - new Date().getTimezoneOffset() * 60000; return dt.getTime() - BI.timeZone - new Date().getTimezoneOffset() * 60000;
} }
return dt.getTime(); return dt.getTime();
} }
// 日期相关方法
BI._.extend(BI, {
isLeapYear,
checkDateVoid,
checkDateLegal,
parseDateTime,
getDate,
getTime,
});

6
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() { function obExtend() {
let target = arguments[0] || {}, length = arguments.length, i = 1, name, copy; let target = arguments[0] || {}, length = arguments.length, i = 1, name, copy;
@ -26,7 +26,7 @@ function obExtend() {
return target; return target;
} }
export default class OB { export class OB {
// props = {}; // props = {};
// init = null; // init = null;
@ -215,5 +215,3 @@ export default class OB {
this.purgeListeners(); this.purgeListeners();
} }
} }
extend(BI, { OB });

16
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 { isFunction, isArray, each, extend, isPlainObject, isNull, uniqueId, isWidget, isWidthOrHeight, isKey, remove, any, isNotNull } from "./2.base";
import OB from "./3.ob"; import { OB } from "./3.ob";
import { Providers, _lazyCreateWidget } from "./5.inject"; import { Providers, _lazyCreateWidget } from "./5.inject";
const cancelAnimationFrame = const cancelAnimationFrame =
@ -35,7 +35,7 @@ function callLifeHook(self, life) {
}); });
} }
export default class Widget extends OB { export class Widget extends OB {
_defaultConfig () { _defaultConfig () {
return extend(super._defaultConfig(), { return extend(super._defaultConfig(), {
root: false, root: false,
@ -1079,15 +1079,3 @@ export function mount(widget, container, predicate, hydrate) {
} }
return widget._mount(true, false, false, predicate); return widget._mount(true, false, false, predicate);
} }
extend(BI, {
Widget,
useStore,
useContext,
watch,
onBeforeMount,
onMounted,
onBeforeUnmount,
onUnmounted,
mount,
});

26
src/core/5.inject.js

@ -1,6 +1,6 @@
import { isFunction, isNull, isNotNull, isArray, each, isWidget, extend, init, isEmpty, remove } from "./2.base"; import { isFunction, isNull, isNotNull, isArray, each, isWidget, extend, init, isEmpty, remove } from "./2.base";
import OB from "./3.ob"; import { OB } from "./3.ob";
import Widget from "./4.widget" import { Widget } from "./4.widget"
let moduleInjection = {}, moduleInjectionMap = { let moduleInjection = {}, moduleInjectionMap = {
components: {}, components: {},
@ -39,7 +39,6 @@ export function module(xtype, cls) {
return () => Modules.getModule(xtype); return () => Modules.getModule(xtype);
} }
BI.module = BI.module || module;
let constantInjection = {}; let constantInjection = {};
export function constant(xtype, cls) { export function constant(xtype, cls) {
@ -51,7 +50,6 @@ export function constant(xtype, cls) {
return () => Constants.getConstant(xtype); return () => Constants.getConstant(xtype);
} }
BI.constant = BI.constant || constant;
let modelInjection = {}; let modelInjection = {};
export function model(xtype, cls) { export function model(xtype, cls) {
@ -63,7 +61,6 @@ export function model(xtype, cls) {
return (config) => Models.getModel(xtype, config); return (config) => Models.getModel(xtype, config);
} }
BI.model = BI.model || model;
let storeInjection = {}; let storeInjection = {};
export function store(xtype, cls) { export function store(xtype, cls) {
@ -75,7 +72,6 @@ export function store(xtype, cls) {
return (config) => Stores.getStore(xtype, config); return (config) => Stores.getStore(xtype, config);
} }
BI.store = BI.store || store;
let serviceInjection = {}; let serviceInjection = {};
export function service(xtype, cls) { export function service(xtype, cls) {
@ -87,7 +83,6 @@ export function service(xtype, cls) {
return (config) => Services.getService(xtype, config); return (config) => Services.getService(xtype, config);
} }
BI.service = BI.service || service;
let providerInjection = {}; let providerInjection = {};
export function provider(xtype, cls) { export function provider(xtype, cls) {
@ -99,7 +94,6 @@ export function provider(xtype, cls) {
return (config) => Providers.getProvider(xtype, config); return (config) => Providers.getProvider(xtype, config);
} }
BI.provider = BI.provider || provider;
let configFunctions = OB.configFunctions = {}; let configFunctions = OB.configFunctions = {};
const runConfigFunction = function (type, configFn) { const runConfigFunction = function (type, configFn) {
@ -200,12 +194,10 @@ export function config(type, configFn, opt) {
return runConfigFunction(type, configFn); return runConfigFunction(type, configFn);
} }
} }
BI.config = BI.config || config;
export function getReference(type, fn) { export function getReference(type, fn) {
return BI.Plugin.registerObject(type, fn); return BI.Plugin.registerObject(type, fn);
} }
BI.getReference = BI.getReference || getReference;
let actions = {}; let actions = {};
let globalAction = []; let globalAction = [];
@ -227,7 +219,6 @@ export function action(type, actionFn) {
} }
}; };
} }
BI.action = BI.action || action;
let points = {}; let points = {};
export function point(type, action, pointFn, after) { 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); points[type][action][after ? "after" : "before"].push(pointFn);
} }
BI.point = BI.point || point;
export const Modules = { export const Modules = {
getModule: function (type) { getModule: function (type) {
@ -255,7 +245,6 @@ export const Modules = {
return moduleInjection; return moduleInjection;
} }
} }
BI.Modules = BI.Modules || Modules;
export const Constants = { export const Constants = {
getConstant: function (type) { getConstant: function (type) {
@ -266,7 +255,6 @@ export const Constants = {
return isFunction(constantInjection[type]) ? constantInjection[type]() : constantInjection[type]; return isFunction(constantInjection[type]) ? constantInjection[type]() : constantInjection[type];
} }
} }
BI.Constants = BI.Constants || Constants;
const callPoint = function (inst, types) { const callPoint = function (inst, types) {
types = isArray(types) ? types : [types]; types = isArray(types) ? types : [types];
@ -319,7 +307,6 @@ export const Models = {
return inst; return inst;
} }
} }
BI.Models = BI.Models || Models;
let stores = {}; let stores = {};
export const Stores = { export const Stores = {
@ -338,7 +325,6 @@ export const Stores = {
return inst; return inst;
} }
} }
BI.Stores = BI.Stores || Stores;
let services = {}; let services = {};
export const Services = { export const Services = {
@ -354,7 +340,6 @@ export const Services = {
return services[type]; return services[type];
} }
} }
BI.Services = BI.Services || Services;
let providers = {}, let providers = {},
providerInstance = {}; providerInstance = {};
@ -373,7 +358,6 @@ export const Providers = {
return providerInstance[type]; return providerInstance[type];
} }
} }
BI.Providers = BI.Providers || Providers;
export const Actions = { export const Actions = {
runAction: function (type, event, config) { runAction: function (type, event, config) {
@ -396,7 +380,6 @@ export const Actions = {
}); });
} }
} }
BI.Actions = BI.Actions || Actions;
let kv = {}; let kv = {};
export function shortcut(xtype, cls) { export function shortcut(xtype, cls) {
@ -408,7 +391,6 @@ export function shortcut(xtype, cls) {
} }
kv[xtype] = cls; kv[xtype] = cls;
} }
BI.shortcut = BI.component = BI.shortcut || shortcut;
// 根据配置属性生成widget // 根据配置属性生成widget
const createRealWidget = function (config, context, lazy) { const createRealWidget = function (config, context, lazy) {
@ -496,18 +478,15 @@ export function createWidget(item, options, context, lazy) {
} }
throw new Error("组件:无法根据item创建组件", item); throw new Error("组件:无法根据item创建组件", item);
} }
BI.createWidget = BI.createWidget || createWidget;
export function _lazyCreateWidget (item, options, context) { export function _lazyCreateWidget (item, options, context) {
return createWidget(item, options, context, true); return createWidget(item, options, context, true);
} }
BI._lazyCreateWidget = BI._lazyCreateWidget || _lazyCreateWidget;
export function createElement() { export function createElement() {
const widget = createWidget.apply(this, arguments); const widget = createWidget.apply(this, arguments);
return widget.element; return widget.element;
} }
BI.createElement = BI.createElement || createElement;
export function getResource(type, config) { export function getResource(type, config) {
if (isNotNull(constantInjection[type])) { if (isNotNull(constantInjection[type])) {
@ -527,4 +506,3 @@ export function getResource(type, config) {
} }
throw new Error("未知类型: [" + type + "] 未定义"); throw new Error("未知类型: [" + type + "] 未定义");
} }
BI.getResource = BI.getResource || getResource;

4
src/core/action/action.js

@ -5,8 +5,8 @@
* @extends BI.OB * @extends BI.OB
* @abstract * @abstract
*/ */
import OB from "../3.ob"; import { OB } from "../3.ob";
export default class Action extends OB { export class Action extends OB {
props = { props = {
src: null, src: null,
tar: null tar: null

4
src/core/action/action.show.js

@ -4,8 +4,8 @@
* @class BI.ShowAction * @class BI.ShowAction
* @extends BI.Action * @extends BI.Action
*/ */
import Action from "./action"; import { Action } from "./action";
export default class ShowAction extends Action { export class ShowAction extends Action {
actionPerformed(src, tar, callback) { actionPerformed(src, tar, callback) {
tar = tar || this.options.tar; tar = tar || this.options.tar;
tar.setVisible(true); tar.setVisible(true);

2
src/core/action/index.js

@ -0,0 +1,2 @@
export { Action } from "./action";
export { ShowAction } from "./action.show";

4
src/core/behavior/0.behavior.js

@ -20,8 +20,8 @@ BI.BehaviorFactory = {
* @extends BI.OB * @extends BI.OB
*/ */
import OB from "../3.ob"; import { OB } from "../3.ob";
export default class Behavior extends OB { export class Behavior extends OB {
_defaultConfig() { _defaultConfig() {
return BI.extend(super._defaultConfig(arguments), { return BI.extend(super._defaultConfig(arguments), {
rule: () => true rule: () => true

4
src/core/behavior/behavior.highlight.js

@ -4,8 +4,8 @@
* @class BI.HighlightBehavior * @class BI.HighlightBehavior
* @extends BI.Behavior * @extends BI.Behavior
*/ */
import Behavior from "./0.behavior"; import { Behavior } from "./0.behavior";
export default class HighlightBehavior extends Behavior { export class HighlightBehavior extends Behavior {
doBehavior(items) { doBehavior(items) {
const args = Array.prototype.slice.call(arguments, 1), const args = Array.prototype.slice.call(arguments, 1),
o = this.options; o = this.options;

4
src/core/behavior/behavior.redmark.js

@ -4,8 +4,8 @@
* @class BI.RedMarkBehavior * @class BI.RedMarkBehavior
* @extends BI.Behavior * @extends BI.Behavior
*/ */
import Behavior from "./0.behavior"; import { Behavior } from "./0.behavior";
export default class RedMarkBehavior extends Behavior { export class RedMarkBehavior extends Behavior {
doBehavior(items) { doBehavior(items) {
const args = Array.prototype.slice.call(arguments, 1), const args = Array.prototype.slice.call(arguments, 1),
o = this.options; o = this.options;

3
src/core/behavior/index.js

@ -0,0 +1,3 @@
export { Behavior } from "./0.behavior";
export { HighlightBehavior } from "./behavior.highlight";
export { RedMarkBehavior } from "./behavior.redmark";

4
src/core/controller/0.controller.js

@ -6,7 +6,7 @@
* @extends BI.OB * @extends BI.OB
* @abstract * @abstract
*/ */
import OB from "../3.ob"; import { OB } from "../3.ob";
export default class Controller extends OB { export class Controller extends OB {
static EVENT_CHANGE = "__EVENT_CHANGE__"; static EVENT_CHANGE = "__EVENT_CHANGE__";
} }

4
src/core/controller/controller.broadcast.js

@ -4,8 +4,8 @@
* Created by GUY on 2015/12/23. * Created by GUY on 2015/12/23.
* @class * @class
*/ */
import Controller from "./0.controller"; import { Controller } from "./0.controller";
export default class BroadcastController extends Controller { export class BroadcastController extends Controller {
init() { init() {
this._broadcasts = {}; this._broadcasts = {};
} }

4
src/core/controller/controller.bubbles.js

@ -5,8 +5,8 @@
* Created by GUY on 2015/8/21. * Created by GUY on 2015/8/21.
* @class * @class
*/ */
import Controller from "./0.controller"; import { Controller } from "./0.controller";
export default class BubblesController extends Controller { export class BubblesController extends Controller {
init() { init() {
this.storeBubbles = {}; this.storeBubbles = {};
this.storePoppers = {}; this.storePoppers = {};

4
src/core/controller/controller.drawer.js

@ -4,8 +4,8 @@
* @class BI.popoverController * @class BI.popoverController
* @extends BI.Controller * @extends BI.Controller
*/ */
import Controller from "./0.controller"; import { Controller } from "./0.controller";
export default class DrawerController extends Controller { export class DrawerController extends Controller {
constructor() { constructor() {
super(); super();
this._constructor(); this._constructor();

4
src/core/controller/controller.layer.js

@ -4,8 +4,8 @@
* Created by GUY on 2015/6/24. * Created by GUY on 2015/6/24.
* @class * @class
*/ */
import Controller from "./0.controller"; import { Controller } from "./0.controller";
export default class LayerController extends Controller { export class LayerController extends Controller {
constructor() { constructor() {
super(); super();
this._constructor(); this._constructor();

4
src/core/controller/controller.masker.js

@ -4,8 +4,8 @@
* Created by GUY on 2015/6/24. * Created by GUY on 2015/6/24.
* @class * @class
*/ */
import LayerController from "./controller.layer"; import { LayerController } from "./controller.layer";
export default class MaskersController extends LayerController { export class MaskersController extends LayerController {
init() { init() {
super.init(arguments); super.init(arguments);
this.zindex = BI.zIndex_masker; this.zindex = BI.zIndex_masker;

4
src/core/controller/controller.popover.js

@ -4,8 +4,8 @@
* @class BI.popoverController * @class BI.popoverController
* @extends BI.Controller * @extends BI.Controller
*/ */
import Controller from "./0.controller"; import { Controller } from "./0.controller";
export default class PopoverController extends Controller { export class PopoverController extends Controller {
constructor() { constructor() {
super(); super();
this._constructor(); this._constructor();

4
src/core/controller/controller.resizer.js

@ -4,8 +4,8 @@
* Created by GUY on 2015/6/24. * Created by GUY on 2015/6/24.
* @class * @class
*/ */
import Controller from "./0.controller"; import { Controller } from "./0.controller";
export default class ResizeController extends Controller { export class ResizeController extends Controller {
init() { init() {
this.resizerManger = {}; this.resizerManger = {};

4
src/core/controller/controller.tooltips.js

@ -6,8 +6,8 @@
* @class BI.TooltipsController * @class BI.TooltipsController
* @extends BI.Controller * @extends BI.Controller
*/ */
import Controller from "./0.controller"; import { Controller } from "./0.controller";
export default class TooltipsController extends Controller { export class TooltipsController extends Controller {
init() { init() {
this.tooltipsManager = {}; this.tooltipsManager = {};
this.showingTips = {};// 存储正在显示的tooltip this.showingTips = {};// 存储正在显示的tooltip

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

6
src/core/func/__test__/function.test.js

@ -8,7 +8,7 @@ describe("core-function-test", function () {
* test_author_lei.wang * test_author_lei.wang
*/ */
it("createDistinctName-支持字符串数组", function () { 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, "name")).to.equal("name2");
expect(BI.Func.createDistinctName(names, "name2")).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 * test_author_lei.wang
*/ */
it("createDistinctName-支持对象数组数组", function () { 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, "name")).to.equal("name2");
expect(BI.Func.createDistinctName(names, "name2")).to.equal("name2"); expect(BI.Func.createDistinctName(names, "name2")).to.equal("name2");
}); });
}); });

1661
src/core/func/alias.js

File diff suppressed because it is too large Load Diff

29
src/core/func/array.js

@ -2,21 +2,18 @@
* 对数组对象的扩展 * 对数组对象的扩展
* @class Array * @class Array
*/ */
BI._.extend(BI, { export function pushArray(sArray, array) {
sArray.push(...array);
}
pushArray: function (sArray, array) { export function pushDistinct(sArray, obj) {
for (var i = 0; i < array.length; i++) { if (sArray.indexOf(obj) !== -1) {
sArray.push(array[i]); sArray.push(obj);
}
},
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 pushDistinctArray(sArray, array) {
for (let i = 0, len = array.length; i < len; i++) {
pushDistinct(sArray, array[i]);
}
}

615
src/core/func/date.js

@ -1,16 +1,14 @@
/** Constants used for time computations */ /** Constants used for time computations */
BI.Date = BI.Date || {}; import {getDate, getTime} from "../2.base";
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;
// Monday first, etc. const SECOND = 1000;
BI.Date._FD = 1; const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
// short month names const DAY = 24 * HOUR;
BI.Date._SMN = [0, const WEEK = 7 * DAY;
const _FD = 1;
const _SMN = [
0,
1, 1,
2, 2,
3, 3,
@ -21,292 +19,361 @@ BI.Date._SMN = [0,
8, 8,
9, 9,
10, 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. */ export const Date = {
BI.Date._MD = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; 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 the number of days in the current month
* 获取时区 */
* @returns {String} export function getMonthDays(date, month = date.getMonth()) {
*/ const year = date.getFullYear();
getTimezone: function (date) { if (((0 === (year % 4)) && ((0 !== (year % 100)) || (0 === (year % 400)))) && month === 1) {
return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, ""); return 29;
}, }
return _MD[month];
}
/** Returns the number of days in the current month */ /**
getMonthDays: function (date, month) { * 获取每月的最后一天
var year = date.getFullYear(); * @returns {Date}
if (typeof month === "undefined") { */
month = date.getMonth(); export function getLastDateOfMont(date) {
} return getDate(date.getFullYear(), date.getMonth(), getMonthDays(date));
if (((0 == (year % 4)) && ((0 != (year % 100)) || (0 == (year % 400)))) && month == 1) { }
return 29;
}
return BI.Date._MD[month];
}, /**
* 获取每月的最后一天
* @returns {Date}
*/
export function getLastDateOfMonth(date) {
return getDate(date.getFullYear(), date.getMonth(), getMonthDays(date));
}
/** /**
* 获取每月的最后一天 * Returns the number of day in the year.
* @returns {Date} * @param date
*/ * @returns {number}
getLastDateOfMonth: function (date) { */
return BI.getDate(date.getFullYear(), date.getMonth(), BI.getMonthDays(date)); export function getDayOfYear(date) {
}, 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);
}
/** 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) { * Returns the number of the week in year, as defined in ISO 8601.
var d = BI.getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); * @param date
var week = d.getDay(); * @returns {number}
var startOfWeek = BI.StartOfWeek % 7; */
var middleDay = (startOfWeek + 3) % 7; export function getWeekNumber(date) {
middleDay = middleDay || 7; const d = getDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
// 偏移到周周首之前需要多少天 const week = d.getDay();
var offsetWeekStartCount = week < startOfWeek ? (7 + week - startOfWeek) : (week - startOfWeek); const startOfWeek = BI.StartOfWeek % 7;
var offsetWeekMiddleCount = middleDay < startOfWeek ? (7 + middleDay - startOfWeek) : (middleDay - startOfWeek); let middleDay = (startOfWeek + 3) % 7;
d.setDate(d.getDate() - offsetWeekStartCount + offsetWeekMiddleCount); middleDay = middleDay || 7;
var ms = d.valueOf(); // 偏移到周周首之前需要多少天
d.setMonth(0); const offsetWeekStartCount = week < startOfWeek ? (7 + week - startOfWeek) : (week - startOfWeek);
d.setDate(1); const offsetWeekMiddleCount = middleDay < startOfWeek ? (7 + middleDay - startOfWeek) : (middleDay - startOfWeek);
return Math.floor((ms - d.valueOf()) / (7 * 864e5)) + 1; d.setDate(d.getDate() - offsetWeekStartCount + offsetWeekMiddleCount);
}, const ms = d.valueOf();
d.setMonth(0);
d.setDate(1);
return Math.floor((ms - d.valueOf()) / (7 * 864e5)) + 1;
}
getQuarter: function (date) { export function getQuarter(date) {
return Math.floor(date.getMonth() / 3) + 1; 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) { export function getOffsetQuarter(date, n) {
var dt = BI.getDate(BI.getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds())); const dt = getDate(getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
var day = dt.getDate(); let day = dt.getDate();
var monthDay = BI.getMonthDays(BI.getDate(dt.getFullYear(), dt.getMonth() + BI.parseInt(n) * 3, 1)); const monthDay = BI.getMonthDays(getDate(dt.getFullYear(), dt.getMonth() + parseInt(n, 10) * 3, 1));
if (day > monthDay) { if (day > monthDay) {
day = monthDay; day = monthDay;
} }
dt.setDate(day); dt.setDate(day);
dt.setMonth(dt.getMonth() + parseInt(n) * 3); dt.setMonth(dt.getMonth() + parseInt(n, 10) * 3);
return dt; return dt;
}, }
// 得到本季度的起始月份 /**
getQuarterStartMonth: function (date) { * 得到本季度的起始月份
var quarterStartMonth = 0; * @param date
var nowMonth = date.getMonth(); * @returns {number}
if (nowMonth < 3) { */
quarterStartMonth = 0; export function getQuarterStartMonth(date) {
} let quarterStartMonth = 0;
if (2 < nowMonth && nowMonth < 6) { const nowMonth = date.getMonth();
quarterStartMonth = 3; if (nowMonth < 3) {
} quarterStartMonth = 0;
if (5 < nowMonth && nowMonth < 9) { }
quarterStartMonth = 6; if (2 < nowMonth && nowMonth < 6) {
} quarterStartMonth = 3;
if (nowMonth > 8) { }
quarterStartMonth = 9; if (5 < nowMonth && nowMonth < 9) {
} quarterStartMonth = 6;
return quarterStartMonth; }
}, if (nowMonth > 8) {
// 获得本季度的起始日期 quarterStartMonth = 9;
getQuarterStartDate: function (date) { }
return BI.getDate(date.getFullYear(), BI.getQuarterStartMonth(date), 1); return quarterStartMonth;
}, }
// 得到本季度的结束日期
getQuarterEndDate: function (date) {
var quarterEndMonth = BI.getQuarterStartMonth(date) + 2;
return BI.getDate(date.getFullYear(), quarterEndMonth, BI.getMonthDays(date, quarterEndMonth));
},
// 指定日期n个月之前或之后的日期 /**
getOffsetMonth: function (date, n) { * 获得本季度的起始日期
var dt = BI.getDate(BI.getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds())); * @param date
var day = dt.getDate(); * @returns {Date}
var monthDay = BI.getMonthDays(BI.getDate(dt.getFullYear(), dt.getMonth() + parseInt(n), 1)); */
if (day > monthDay) { export function getQuarterStartDate(date) {
day = monthDay; return getDate(date.getFullYear(), getQuarterStartMonth(date), 1);
} }
dt.setDate(day);
dt.setMonth(dt.getMonth() + parseInt(n));
return dt;
},
// 获得本周的起始日期 /**
getWeekStartDate: function (date) { * 得到本季度的结束日期
var w = date.getDay(); * @param date
var startOfWeek = BI.StartOfWeek % 7; * @returns {Date}
return BI.getOffsetDate(date, BI.Date._OFFSET[w < startOfWeek ? (7 + w - startOfWeek) : (w - startOfWeek)]); */
}, export function getQuarterEndDate(date) {
// 得到本周的结束日期 const quarterEndMonth = getQuarterStartMonth(date) + 2;
getWeekEndDate: function (date) { return getDate(date.getFullYear(), quarterEndMonth, getMonthDays(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);
},
getFullDayName: function (index) { /**
return [BI.i18nText("BI-Basic_Sunday"), * 指定日期n个月之前或之后的日期
BI.i18nText("BI-Basic_Monday"), * @param date
BI.i18nText("BI-Basic_Tuesday"), * @param n
BI.i18nText("BI-Basic_Wednesday"), * @returns {Date}
BI.i18nText("BI-Basic_Thursday"), */
BI.i18nText("BI-Basic_Friday"), export function getOffsetMonth(date, n) {
BI.i18nText("BI-Basic_Saturday"), const dt = getDate(getTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
BI.i18nText("BI-Basic_Sunday")][index]; let day = dt.getDate();
}, const 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"), * @param date
BI.i18nText("BI-Basic_Simple_Tuesday"), * @returns {Date}
BI.i18nText("BI-Basic_Simple_Wednesday"), */
BI.i18nText("BI-Basic_Simple_Thursday"), export function getWeekStartDate(date) {
BI.i18nText("BI-Basic_Simple_Friday"), const w = date.getDay();
BI.i18nText("BI-Basic_Simple_Saturday"), const startOfWeek = BI.StartOfWeek % 7;
BI.i18nText("BI-Basic_Simple_Sunday")][index]; 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"), * @param date
BI.i18nText("BI-Basic_March"), * @returns {Date}
BI.i18nText("BI-Basic_April"), */
BI.i18nText("BI-Basic_May"), export function getWeekEndDate(date) {
BI.i18nText("BI-Basic_June"), const w = date.getDay();
BI.i18nText("BI-Basic_July"), const startOfWeek = BI.StartOfWeek % 7;
BI.i18nText("BI-Basic_August"), return getOffsetDate(date, _OFFSET[w < startOfWeek ? (7 + w - startOfWeek) : (w - startOfWeek)] + 6);
BI.i18nText("BI-Basic_September"), }
BI.i18nText("BI-Basic_October"),
BI.i18nText("BI-Basic_November"),
BI.i18nText("BI-Basic_December")][index]
},
getQuarterName: function (index) { export function getFullDayName(index) {
return ["", BI.i18nText("BI-Quarter_1"), return [
BI.i18nText("BI-Quarter_2"), BI.i18nText("BI-Basic_Sunday"),
BI.i18nText("BI-Quarter_3"), BI.i18nText("BI-Basic_Monday"),
BI.i18nText("BI-Quarter_4")][index]; 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];
}
// 格式化打印日期 export function getShortDayName(index) {
print: function (date, str) { return [
var m = date.getMonth(); BI.i18nText("BI-Basic_Simple_Sunday"),
var d = date.getDate(); BI.i18nText("BI-Basic_Simple_Monday"),
var y = date.getFullYear(); BI.i18nText("BI-Basic_Simple_Tuesday"),
var yWith4number = y + ""; BI.i18nText("BI-Basic_Simple_Wednesday"),
while (yWith4number.length < 4) { BI.i18nText("BI-Basic_Simple_Thursday"),
yWith4number = "0" + yWith4number; BI.i18nText("BI-Basic_Simple_Friday"),
} BI.i18nText("BI-Basic_Simple_Saturday"),
var wn = BI.getWeekNumber(date); BI.i18nText("BI-Basic_Simple_Sunday")
var qr = BI.getQuarter(date); ][index];
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;
var re = /%./g; export function getMonthName(index) {
BI.isKhtml = BI.isKhtml || function () { return [
if(!_global.navigator) { BI.i18nText("BI-Basic_January"),
return false; BI.i18nText("BI-Basic_February"),
} BI.i18nText("BI-Basic_March"),
return /Konqueror|Safari|KHTML/i.test(navigator.userAgent); 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标准周的计数会影响年 export function getQuarterName(index) {
if ((str.indexOf("%Y") !== -1 || str.indexOf("%y") !== -1) && (str.indexOf("%W") !== -1 || str.indexOf("%U") !== -1 || str.indexOf("%V") !== -1)) { return [
switch (wn) { "",
// 如果周数是1,但是当前却在12月,表示此周数为下一年的 BI.i18nText("BI-Quarter_1"),
case 1: BI.i18nText("BI-Quarter_2"),
if (m === 11) { BI.i18nText("BI-Quarter_3"),
s["%y"] = parseInt(s["%y"]) + 1; BI.i18nText("BI-Quarter_4")
s["%Y"] = parseInt(s["%Y"]) + 1; ][index];
} }
break;
// 如果周数是53,但是当前却在1月,表示此周数为上一年的
case 53:
if (m === 0) {
s["%y"] = parseInt(s["%y"]) - 1;
s["%Y"] = parseInt(s["%Y"]) - 1;
}
break;
default:
break;
}
}
if (!BI.isKhtml()) { /**
return str.replace(re, function (par) { * 格式化打印日期
return s[par] || par; * @param date
}); * @param str
* @returns {*}
*/
export function print(date, str) {
const m = date.getMonth();
const d = date.getDate();
const y = date.getFullYear();
let yWith4number = y + "";
while (yWith4number.length < 4) {
yWith4number = "0" + yWith4number;
}
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;
}
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]
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;
let re = /%./g;
BI.isKhtml = BI.isKhtml || function () {
if (!_global.navigator) {
return false;
} }
var a = str.match(re); return /Konqueror|Safari|KHTML/i.test(navigator.userAgent);
for (var i = 0; i < a.length; i++) { };
var tmp = s[a[i]];
if (tmp) { // 包含年周的格式化,ISO8601标准周的计数会影响年
re = new RegExp(a[i], "g"); if ((str.indexOf("%Y") !== -1 || str.indexOf("%y") !== -1) && (str.indexOf("%W") !== -1 || str.indexOf("%U") !== -1 || str.indexOf("%V") !== -1)) {
str = str.replace(re, tmp); 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;
});
} }
}); 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);
}
}
return str;
}

300
src/core/func/function.js

@ -2,167 +2,173 @@
* 基本的函数 * 基本的函数
* Created by GUY on 2015/6/24. * Created by GUY on 2015/6/24.
*/ */
BI.Func = BI.Func || {}; import {every, isKey, isArray, toUpperCase, each, stripEL, isNotNull, isNull, isObject} from "../2.base";
BI._.extend(BI.Func, { import {makeFirstPY} from "../utils/chinesePY";
/**
* 创建唯一的名字 /**
* @param array * 创建唯一的名字
* @param name * @param array
* @returns {*} * @param name
*/ * @returns {*}
createDistinctName: function (array, name) { */
var src = name, idx = 1; export function createDistinctName(array, name) {
name = name || ""; let src = name, idx = 1;
while (true) { name = name || "";
if (BI.every(array, function (i, item) { while (true) {
return BI.isKey(item) ? item !== name : item.name !== name; if (every(array, function (i, item) {
})) { return isKey(item) ? item !== name : item.name !== name;
break; })) {
} break;
name = src + (idx++);
} }
return name; name = src + (idx++);
}, }
return name;
}
/** /**
* 获取字符宽度 * 获取字符宽度
* @param str * @param str
* @return {number} * @return {number}
*/ */
getGBWidth: function (str) { export function getGBWidth(str) {
str = str + ""; str = str + "";
str = str.replace(/[^\x00-\xff]/g, "xx"); str = str.replace(/[^\x00-\xff]/g, "xx");
return Math.ceil(str.length / 2); return Math.ceil(str.length / 2);
}, }
/** /**
* 获取搜索结果 * 获取搜索结果
* @param items * @param items
* @param keyword * @param keyword
* @param param 搜索哪个属性 * @param param 搜索哪个属性
*/ */
getSearchResult: function (items, keyword, param) { export function getSearchResult(items, keyword, param) {
var isArray = BI.isArray(items); const array = isArray(items);
items = isArray ? BI.flatten(items) : items; items = array ? BI.flatten(items) : items;
param || (param = "text"); param || (param = "text");
if (!BI.isKey(keyword)) { if (!isKey(keyword)) {
return { return {
find: items, find: items,
match: isArray ? [] : {} match: array ? [] : {},
}; };
}
let t, text, py;
keyword = toUpperCase(keyword);
const matched = array ? [] : {}, find = array ? [] : {};
each(items, function (i, item) {
// 兼容item为null的处理
if (isNull(item)) {
return;
} }
var t, text, py; t = stripEL(item);
keyword = BI.toUpperCase(keyword); text = [t[param], t.text, t.value, t.name, t].find(isNotNull);
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);
});
if (BI.isNull(text) || BI.isObject(text)) return; if (isNull(text) || isObject(text)) return;
py = BI.makeFirstPY(text, { py = makeFirstPY(text, {
splitChar: "\u200b" splitChar: "\u200b",
}); });
text = BI.toUpperCase(text); text = toUpperCase(text);
py = BI.toUpperCase(py); py = toUpperCase(py);
var pidx; let pidx;
if (text.indexOf(keyword) > -1) { if (text.indexOf(keyword) > -1) {
if (text === keyword) { if (text === keyword) {
isArray ? matched.push(item) : (matched[i] = item); array ? matched.push(item) : (matched[i] = item);
} else { } else {
isArray ? find.push(item) : (find[i] = item); array ? find.push(item) : (find[i] = item);
} }
// BI-56386 这边两个pid / text.length是为了防止截取的首字符串不是完整的,但光这样做还不够,即时错位了,也不能说明就不符合条件 } else { // BI-56386 这边两个pid / text.length是为了防止截取的首字符串不是完整的,但光这样做还不够,即时错位了,也不能说明就不符合条件
} else if (pidx = py.indexOf(keyword), (pidx > -1)) { pidx = py.indexOf(keyword);
if (pidx > -1) {
if (text === keyword || keyword.length === text.length) { if (text === keyword || keyword.length === text.length) {
isArray ? matched.push(item) : (matched[i] = item); array ? matched.push(item) : (matched[i] = item);
} else { } else {
isArray ? find.push(item) : (find[i] = item); array ? find.push(item) : (find[i] = item);
} }
} }
}); }
return { });
match: matched, return {
find: find 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 items.sort(function (item1, item2) { /**
var str1 = getTextOfItem(item1, key); * 获取按GB2312排序的结果
var str2 = getTextOfItem(item2, key); * @param items
if (BI.isNull(str1) && BI.isNull(str2)) { * @param key
return 0; * @return {any[]}
} */
if (BI.isNull(str1)) { export function getSortedResult(items, key) {
return -1; const getTextOfItem = BI.isFunction(key) ? key :
} function (item, key) {
if (BI.isNull(str2)) { if (BI.isNotNull(key)) {
return 1; return item[key];
}
if (str1 === str2) {
return 0;
} }
var len1 = str1.length, len2 = str2.length; if (BI.isNotNull(item.text)) {
for (var i = 0; i < len1 && i < len2; i++) { return item.text;
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]);
}
} }
return len1 - len2; if (BI.isNotNull(item.value)) {
}); return item.value;
}
});
BI._.extend(BI, {
beforeFunc: function (sFunc, func) {
var __self = sFunc;
return function () {
if (func.apply(sFunc, arguments) === false) {
return false;
} }
return __self.apply(sFunc, arguments); return item;
}; };
},
afterFunc: function (sFunc, func) { return items.sort(function (item1, item2) {
var __self = sFunc; const str1 = getTextOfItem(item1, key);
return function () { const str2 = getTextOfItem(item2, key);
var ret = __self.apply(sFunc, arguments); if (BI.isNull(str1) && BI.isNull(str2)) {
if (ret === false) { return 0;
return false; }
if (BI.isNull(str1)) {
return -1;
}
if (BI.isNull(str2)) {
return 1;
}
if (str1 === str2) {
return 0;
}
const len1 = str1.length, len2 = str2.length;
for (let i = 0; i < len1 && i < len2; 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]);
} }
func.apply(sFunc, arguments); }
return ret; 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;
};
}
export const Func = {
createDistinctName,
getGBWidth,
getSearchResult,
getSortedResult,
};

6
src/core/func/index.js

@ -0,0 +1,6 @@
export * from "./alias";
export * from "./array";
export * from "./date";
export * from "./function";
export * from "./number";
export * from "./string";

274
src/core/func/number.js

@ -1,156 +1,154 @@
BI._.extend(BI, { // 给Number类型增加一个add方法,调用起来更加方便。
// 给Number类型增加一个add方法,调用起来更加方便。 export function add(num, arg) {
add: function (num, arg) { return accAdd(arg, num);
return accAdd(arg, num);
/** /**
** 加法函数用来得到精确的加法结果 ** 加法函数用来得到精确的加法结果
** 说明javascript的加法结果会有误差在两个浮点数相加的时候会比较明显这个函数返回较为精确的加法结果 ** 说明javascript的加法结果会有误差在两个浮点数相加的时候会比较明显这个函数返回较为精确的加法结果
** 调用accAdd(arg1,arg2) ** 调用accAdd(arg1,arg2)
** 返回值arg1加上arg2的精确结果 ** 返回值arg1加上arg2的精确结果
**/ **/
function accAdd (arg1, arg2) { function accAdd(arg1, arg2) {
var r1, r2, m, c; let r1, r2, m, c;
try { try {
r1 = arg1.toString().split(".")[1].length; r1 = arg1.toString().split(".")[1].length;
} catch (e) { } catch (e) {
r1 = 0; r1 = 0;
} }
try { try {
r2 = arg2.toString().split(".")[1].length; r2 = arg2.toString().split(".")[1].length;
} catch (e) { } catch (e) {
r2 = 0; r2 = 0;
} }
c = Math.abs(r1 - r2); c = Math.abs(r1 - r2);
m = Math.pow(10, Math.max(r1, r2)); m = Math.pow(10, Math.max(r1, r2));
if (c > 0) { if (c > 0) {
var cm = Math.pow(10, c); const cm = Math.pow(10, c);
if (r1 > r2) { 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 {
arg1 = Number(arg1.toString().replace(".", "")); arg1 = Number(arg1.toString().replace(".", ""));
arg2 = Number(arg2.toString().replace(".", "")) * cm;
} else {
arg1 = Number(arg1.toString().replace(".", "")) * cm;
arg2 = Number(arg2.toString().replace(".", "")); 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方法,调用起来更加方便。 // 给Number类型增加一个sub方法,调用起来更加方便。
sub: function (num, arg) { export function sub(num, arg) {
return accSub(num, arg); return accSub(num, arg);
/** /**
** 减法函数用来得到精确的减法结果 ** 减法函数用来得到精确的减法结果
** 说明javascript的减法结果会有误差在两个浮点数相减的时候会比较明显这个函数返回较为精确的减法结果 ** 说明javascript的减法结果会有误差在两个浮点数相减的时候会比较明显这个函数返回较为精确的减法结果
** 调用accSub(arg1,arg2) ** 调用accSub(arg1,arg2)
** 返回值arg1加上arg2的精确结果 ** 返回值arg1加上arg2的精确结果
**/ **/
function accSub (arg1, arg2) { function accSub(arg1, arg2) {
var r1, r2, m, n; let r1, r2, m, n;
try { try {
r1 = arg1.toString().split(".")[1].length; r1 = arg1.toString().split(".")[1].length;
} catch (e) { } catch (e) {
r1 = 0; r1 = 0;
} }
try { try {
r2 = arg2.toString().split(".")[1].length; r2 = arg2.toString().split(".")[1].length;
} catch (e) { } catch (e) {
r2 = 0; 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);
} }
}, 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方法,调用起来更加方便。 // 给Number类型增加一个mul方法,调用起来更加方便。
mul: function (num, arg) { export function mul(num, arg) {
return accMul(arg, num); return accMul(arg, num);
/** /**
** 乘法函数用来得到精确的乘法结果 ** 乘法函数用来得到精确的乘法结果
** 说明javascript的乘法结果会有误差在两个浮点数相乘的时候会比较明显这个函数返回较为精确的乘法结果 ** 说明javascript的乘法结果会有误差在两个浮点数相乘的时候会比较明显这个函数返回较为精确的乘法结果
** 调用accMul(arg1,arg2) ** 调用accMul(arg1,arg2)
** 返回值arg1乘以 arg2的精确结果 ** 返回值arg1乘以 arg2的精确结果
**/ **/
function accMul (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 { try {
m += s1.split(".")[1].length; m += s1.split(".")[1].length;
} catch (e) { } catch (e) {
}
try {
m += s2.split(".")[1].length;
} catch (e) {
}
return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
} }
}, try {
m += s2.split(".")[1].length;
// 给Number类型增加一个div方法,调用起来更加方便。 } catch (e) {
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;
} }
return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}
}
/** // 给Number类型增加一个div方法,调用起来更加方便。
* 精确乘法 export function div(num, arg) {
*/ return accDivide(num, arg);
function times (num1, num2) {
var others = []; /**
for (var _i = 2; _i < arguments.length; _i++) { * Return digits length of a number
others[_i - 2] = arguments[_i]; * @param {*number} num Input number
} */
if (others.length > 0) { function digitLength(num) {
return times.apply(void 0, [times(num1, num2), others[0]].concat(others.slice(1))); // Get digit length of e
} const eSplit = num.toString().split(/[eE]/);
var num1Changed = float2Fixed(num1); const len = (eSplit[0].split(".")[1] || "").length - (+(eSplit[1] || 0));
var num2Changed = float2Fixed(num2); return len > 0 ? len : 0;
var baseNum = digitLength(num1) + digitLength(num2); }
var leftValue = num1Changed * num2Changed;
return leftValue / Math.pow(10, baseNum); /**
* 把小数转成整数支持科学计数法如果是小数则放大成整数
* @param {*number} num 输入数
*/
function float2Fixed(num) {
if (num.toString().indexOf("e") === -1) {
return Number(num.toString().replace(".", ""));
} }
const dLen = digitLength(num);
return dLen > 0 ? num * Math.pow(10, dLen) : num;
}
/** /**
* 精确除法 * 精确乘法
*/ */
function accDivide (num1, num2) { function times(num1, num2) {
var others = []; const others = [];
for (var _i = 2; _i < arguments.length; _i++) { for (let _i = 2; _i < arguments.length; _i++) {
others[_i - 2] = arguments[_i]; others[_i - 2] = arguments[_i];
} }
if (others.length > 0) { if (others.length > 0) {
return accDivide.apply(void 0, [accDivide(num1, num2), others[0]].concat(others.slice(1))); return times.apply(void 0, [times(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)));
} }
const num1Changed = float2Fixed(num1);
const num2Changed = float2Fixed(num2);
const baseNum = digitLength(num1) + digitLength(num2);
const leftValue = num1Changed * num2Changed;
return leftValue / Math.pow(10, baseNum);
} }
}); /**
* 精确除法
*/
function accDivide(num1, num2) {
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)));
}
const num1Changed = float2Fixed(num1);
const num2Changed = float2Fixed(num2);
return times((num1Changed / num2Changed), Math.pow(10, digitLength(num2) - digitLength(num1)));
}
}

224
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.substring(0, startTag.length) == startTag;
}
/** /**
* 判断字符串是否已指定的字符串开始 * 判断字符串是否以指定的字符串结束
* @param str source字符串 * @param str source字符串
* @param {String} startTag 指定的开始字符串 * @param {String} endTag 指定的字符串
* @return {Boolean} 如果字符串以指定字符串开始则返回true否则返回false * @return {Boolean} 如果字符串以指定字符串结束则返回true否则返回false
*/ */
startWith: function (str, startTag) { export function endWith(str, endTag) {
str = str || ""; if (endTag == null || endTag == "" || str.length === 0 || endTag.length > str.length) {
if (startTag == null || startTag == "" || str.length === 0 || startTag.length > str.length) { return false;
return false; }
} return str.substring(str.length - endTag.length) == endTag;
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;
},
/** /**
* 获取url中指定名字的参数 * 获取url中指定名字的参数
* @param str source字符串 * @param str source字符串
* @param {String} name 参数的名字 * @param {String} name 参数的名字
* @return {String} 参数的值 * @return {String} 参数的值
*/ */
getQuery: function (str, name) { export function getQuery(str, name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = str.substr(str.indexOf("?") + 1).match(reg); const r = str.substr(str.indexOf("?") + 1).match(reg);
if (r) { if (r) {
return unescape(r[2]); return unescape(r[2]);
} }
return null; return null;
}, }
/** /**
* 给url加上给定的参数 * 给url加上给定的参数
* @param str source字符串 * @param str source字符串
* @param {Object} paras 参数对象是一个键值对对象 * @param {Object} paras 参数对象是一个键值对对象
* @return {String} 添加了给定参数的url * @return {String} 添加了给定参数的url
*/ */
appendQuery: function (str, paras) { export function appendQuery(str, paras) {
if (!paras) { if (!paras) {
return str; return str;
} }
var src = str; let src = str;
// 没有问号说明还没有参数 // 没有问号说明还没有参数
if (src.indexOf("?") === -1) { if (src.indexOf("?") === -1) {
src += "?"; src += "?";
} }
// 如果以问号结尾,说明没有其他参数 // 如果以问号结尾,说明没有其他参数
if (BI.endWith(src, "?") !== false) { if (BI.endWith(src, "?") !== false) {
} else { } else {
src += "&"; src += "&";
} }
BI._.each(paras, function (value, name) { BI._.each(paras, function (value, name) {
if (typeof(name) === "string") { if (typeof (name) === "string") {
src += name + "=" + value + "&"; 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;
} }
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 str source字符串
* @param {String} sub 子字符串 * @param {String} start 指定的字符
* @return {Number[]} 子字符串在父字符串中出现的所有位置组成的数组 * @returns {String} 以指定字符开头的字符串
*/ */
allIndexOf: function (str, sub) { export function perfectStart(str, start) {
if (typeof sub !== "string") { if (BI.startWith(str, start)) {
return []; return str;
} }
var location = []; return start + str;
var offset = 0;
while (str.length > 0) { }
var loc = str.indexOf(sub);
if (loc === -1) { /**
break; * 获取字符串中某字符串的所有项位置数组
} * @param str source字符串
location.push(offset + loc); * @param {String} sub 子字符串
str = str.substring(loc + sub.length, str.length); * @return {Number[]} 子字符串在父字符串中出现的所有位置组成的数组
offset += loc + sub.length; */
export function allIndexOf(str, sub) {
if (typeof sub !== "string") {
return [];
}
const location = [];
let offset = 0;
while (str.length > 0) {
const 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;
} }
}); return location;
}

93
src/core/index.js

@ -1,66 +1,45 @@
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";
BI.extend(BI, { import * as base from "./2.base";
OB, import * as ob from "./3.ob";
Widget, import * as widget from "./4.widget";
Action, import * as inject from "./5.inject";
ShowAction, import * as action from "./action";
Behavior, import * as behavior from "./behavior";
HighlightBehavior, import * as controllers from "./controller";
RedMarkBehavior, import * as func from "./func";
Controller, import { StyleLoaderManager } from "./loader/loader.style";
BroadcastController, import "./h";
BubblesController, import { ShowListener } from "./listener/listener.show";
DrawerController, import { shortcut } from "./decorator";
LayerController,
MaskersController,
PopoverController,
ResizeController,
TooltipsController,
StyleLoaderManager,
});
export * from './2.base'; export * from "./2.base";
export * from './4.widget'; export * from "./3.ob";
export * from './5.inject'; export * from "./4.widget";
export * from "./5.inject";
export * from "./action";
export * from "./behavior";
export * from "./controller";
export * from "./func";
// 有了后删掉 // 有了后删掉
export const emptyFn = () => { } export const emptyFn = () => { }
export { export {
StyleLoaderManager,
ShowListener,
shortcut, shortcut,
OB, }
Widget,
Action, Object.assign(BI, {
ShowAction, ...base,
Behavior, ...ob,
HighlightBehavior, ...widget,
RedMarkBehavior, ...inject,
Controller, ...behavior,
BroadcastController, component: inject.shortcut,
BubblesController, ...action,
DrawerController, ...controllers,
LayerController, ...func,
MaskersController,
PopoverController,
ResizeController,
TooltipsController,
StyleLoaderManager, StyleLoaderManager,
} ShowListener,
});

52
src/core/listener/listener.show.js

@ -5,44 +5,50 @@
* @class BI.ShowListener * @class BI.ShowListener
* @extends BI.OB * @extends BI.OB
*/ */
BI.ShowListener = BI.inherit(BI.OB, { import { OB } from "../3.ob";
props: function () { import { isArray, isNull, nextTick, } from "../2.base";
import { createWidget } from "../5.inject";
import { Controller } from "../controller/0.controller";
export class ShowListener extends OB {
static EVENT_CHANGE = "EVENT_CHANGE";
props() {
return { return {
eventObj: BI.createWidget(), eventObj: createWidget(),
cardLayout: null, cardLayout: null,
cardNameCreator: function (v) { cardNameCreator: (v) => {
return v; return v;
}, },
cardCreator: BI.emptyFn, cardCreator: BI.emptyFn,
afterCardCreated: BI.emptyFn, afterCardCreated: BI.emptyFn,
afterCardShow: BI.emptyFn afterCardShow: BI.emptyFn
}; };
}, }
init: function () { init() {
var self = this, o = this.options; const { eventObj, cardLayout, afterCardCreated, cardNameCreator, cardCreator, afterCardShow } = this.options;
if (o.eventObj) { if (eventObj) {
o.eventObj.on(BI.Controller.EVENT_CHANGE, function (type, v, ob) { eventObj.on(Controller.EVENT_CHANGE, (type, v, ob) => {
if (type === BI.Events.CLICK) { if (type === BI.Events.CLICK) {
v = v || o.eventObj.getValue(); v = v || eventObj.getValue();
v = BI.isArray(v) ? (v.length > 1 ? v.toString() : v[0]) : v; v = isArray(v) ? (v.length > 1 ? v.toString() : v[0]) : v;
if (BI.isNull(v)) { if (isNull(v)) {
throw new Error("不能为null"); throw new Error("不能为null");
} }
var cardName = o.cardNameCreator(v); var cardName = cardNameCreator(v);
if (!o.cardLayout.isCardExisted(cardName)) { if (!cardLayout.isCardExisted(cardName)) {
var card = o.cardCreator(cardName); const card = cardCreator(cardName);
o.cardLayout.addCardByName(cardName, card); cardLayout.addCardByName(cardName, card);
o.afterCardCreated(cardName); afterCardCreated(cardName);
} }
o.cardLayout.showCardByName(cardName); cardLayout.showCardByName(cardName);
BI.nextTick(function () { nextTick(() => {
o.afterCardShow(cardName); afterCardShow(cardName);
self.fireEvent(BI.ShowListener.EVENT_CHANGE, cardName); this.fireEvent(ShowListener.EVENT_CHANGE, cardName);
}); });
} }
}); });
} }
} }
}); }
BI.ShowListener.EVENT_CHANGE = "EVENT_CHANGE";

4
src/core/loader/loader.style.js

@ -4,9 +4,9 @@
* Created by GUY on 2015/9/7. * Created by GUY on 2015/9/7.
* @class * @class
*/ */
import OB from "../3.ob"; import { OB } from "../3.ob";
export default class StyleLoaderManager extends OB { export class StyleLoaderManager extends OB {
_defaultConfig() { _defaultConfig() {
return BI.extend(super._defaultConfig(arguments), {}); return BI.extend(super._defaultConfig(arguments), {});
} }

123
src/core/platform/web/detectElementResize.js

@ -323,7 +323,22 @@ var ResizeObserverPolyfill = (function (exports) {
}; };
var CATCH_PERIOD = 250; var CATCH_PERIOD = 250;
var observerConfig = { attributes: true, characterData: true, childList: true, subtree: true }; 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) { var time = function (timeout) {
if (timeout === void 0) { if (timeout === void 0) {
timeout = 0; timeout = 0;
@ -412,14 +427,17 @@ var ResizeObserverPolyfill = (function (exports) {
}; };
var skipNotifyOnElement = function (target) { 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 () { var ResizeObservation = (function () {
function ResizeObservation(target, observedBox) { function ResizeObservation(target, observedBox) {
this.target = target; this.target = target;
this.observedBox = observedBox || ResizeObserverBoxOptions.CONTENT_BOX; this.observedBox = observedBox || ResizeObserverBoxOptions.CONTENT_BOX;
this.lastReportedSize = { this.lastReportedSize = {
inlineSize: -1, blockSize: -1 inlineSize: -1,
blockSize: -1
}; };
} }
@ -428,7 +446,8 @@ var ResizeObserverPolyfill = (function (exports) {
if (skipNotifyOnElement(this.target)) { if (skipNotifyOnElement(this.target)) {
this.lastReportedSize = size; 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 true;
} }
return false; return false;
@ -534,64 +553,58 @@ var ResizeObserverPolyfill = (function (exports) {
return ResizeObserver; return ResizeObserver;
}()); }());
exports.ResizeObserver = ResizeObserver; return ResizeObserver;
exports.ResizeObserverEntry = ResizeObserverEntry; })();
exports.ResizeObserverSize = ResizeObserverSize;
Object.defineProperty(exports, '__esModule', { value: true });
return exports;
})({});
var ResizeObserver = window.ResizeObserver || ResizeObserverPolyfill.ResizeObserver;
!(function () { var ResizeObserver = window.ResizeObserver || ResizeObserverPolyfill;
var addResizeListener = function (element, fn) { var addResizeListener = function (element, fn) {
if (ResizeObserver) { if (ResizeObserver) {
if (!element.__resizeObserver__) { if (!element.__resizeObserver__) {
var resizeObserver = new ResizeObserver(function () { var resizeObserver = new ResizeObserver(function () {
element.__resizeListeners__.forEach(function (listener) { element.__resizeListeners__.forEach(function (listener) {
BI.$(element).is(":visible") && listener(); BI.$(element).is(":visible") && listener();
});
}); });
resizeObserver.observe(element); });
element.__resizeObserver__ = resizeObserver; resizeObserver.observe(element);
} element.__resizeObserver__ = resizeObserver;
if (!element.__resizeListeners__) {
element.__resizeListeners__ = [];
}
element.__resizeListeners__.push(fn);
} }
}; if (!element.__resizeListeners__) {
var removeResizeListener = function (element, fn) { element.__resizeListeners__ = [];
if (ResizeObserver) { }
if (BI.isNull(fn)) { element.__resizeListeners__.push(fn);
element.__resizeListeners__ = []; }
};
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__ && element.__resizeObserver__.unobserve(element);
element.__resizeObserver__ = null; 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 = { export const ResizeDetector = {
addResizeListener: function (widget, fn) { addResizeListener: function (widget, fn) {
addResizeListener(widget.element[0], fn); addResizeListener(widget.element[0], fn);
return function () { return function () {
removeResizeListener(widget.element[0], fn);
};
}, removeResizeListener: function (widget, fn) {
removeResizeListener(widget.element[0], fn); removeResizeListener(widget.element[0], fn);
} };
}; }, removeResizeListener: function (widget, fn) {
})(); removeResizeListener(widget.element[0], fn);
}
};
Object.assign(BI, {
ResizeDetector
});

863
src/core/utils/chinesePY.js

File diff suppressed because one or more lines are too long
Loading…
Cancel
Save