diff --git a/src/base/1.pane.js b/src/base/1.pane.js index c87e33bfc..1f7f1cc59 100644 --- a/src/base/1.pane.js +++ b/src/base/1.pane.js @@ -6,7 +6,7 @@ * @extends BI.Widget * @abstract */ -import { Widget, shortcut } from "../core"; +import { Widget, shortcut, isNotEmptyString, extend, isNull, isEmpty } from "../core"; @shortcut() export default class Pane extends Widget { @@ -15,7 +15,7 @@ export default class Pane extends Widget { static EVENT_LOADING = "EVENT_LOADING"; _defaultConfig() { - return BI.extend(super._defaultConfig(), { + return extend(super._defaultConfig(), { _baseCls: "bi-pane", tipText: BI.i18nText("BI-No_Selected_Item"), loadingText: "", @@ -62,7 +62,7 @@ export default class Pane extends Widget { }); } BI.Layers.show(this.getName() + "-loading"); - } else if (BI.isNull(this._loading)) { + } else if (isNull(this._loading)) { loadingAnimation.element.css("zIndex", 1); BI.createWidget({ type: "bi.center_adapt", @@ -85,7 +85,7 @@ export default class Pane extends Widget { type: "bi.horizontal_adapt", items: [loadingTip], }]; - BI.isNotEmptyString(o.loadingText) && loadingTipItems.push({ + isNotEmptyString(o.loadingText) && loadingTipItems.push({ type: "bi.text", text: o.loadingText, tgap: this._getSize(10), @@ -109,7 +109,7 @@ export default class Pane extends Widget { } check() { - this.setTipVisible(BI.isEmpty(this.options.items)); + this.setTipVisible(isEmpty(this.options.items)); } setTipVisible(b) { diff --git a/src/core/2.base.js b/src/core/2.base.js index 7b200ed01..46bf10e92 100644 --- a/src/core/2.base.js +++ b/src/core/2.base.js @@ -21,127 +21,136 @@ var _applyFunc = function (name) { }; }; -// Utility -BI._.extend(BI, { - assert: function (v, is) { - if (this.isFunction(is)) { - if (!is(v)) { - throw new Error(v + " error"); - } else { - return true; - } - } - if (!this.isArray(is)) { - is = [is]; - } - if (!this.deepContains(is, v)) { +export function assert(v, is) { + if (isFunction(is)) { + if (!is(v)) { throw new Error(v + " error"); + } else { + return true; } - return true; - }, - - warn: function (message) { - console.warn(message); - }, - - UUID: function () { - var f = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; - var str = ""; - for (var i = 0; i < 16; i++) { - var r = parseInt(f.length * Math.random(), 10); - str += f[r]; - } - return str; - }, + } + if (!isArray(is)) { + is = [is]; + } + if (!deepContains(is, v)) { + throw new Error(v + " error"); + } + return true; +} + +export function warn(message) { + console.warn(message); +} + +export function UUID() { + var f = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; + var str = ""; + for (var i = 0; i < 16; i++) { + var r = _global.parseInt(f.length * Math.random(), 10); + str += f[r]; + } + return str; +} - isWidget: function (widget) { - return widget instanceof BI.Widget; - }, +export function isWidget(widget) { + return widget instanceof BI.Widget; +} - createWidgets: function (items, options, context) { - if (!BI.isArray(items)) { - throw new Error("items必须是数组", items); +export function createWidgets(items, options, context) { + if (!isArray(items)) { + throw new Error("items必须是数组", items); + } + if (isWidget(options)) { + context = options; + options = {}; + } else { + options || (options = {}); + } + return map(flatten(items), function (i, item) { + return BI.createWidget(item, deepClone(options), context); + }); +} + +export function createItems(data, innerAttr, outerAttr) { + innerAttr = isArray(innerAttr) ? innerAttr : makeArray(flatten(data).length, innerAttr || {}); + outerAttr = isArray(outerAttr) ? outerAttr : makeArray(flatten(data).length, outerAttr || {}); + return map(data, function (i, item) { + if (isArray(item)) { + return createItems(item, innerAttr, outerAttr); + } + if (item instanceof BI.Widget) { + return extend({}, innerAttr.shift(), outerAttr.shift(), { + type: null, + el: item + }); } - if (BI.isWidget(options)) { - context = options; - options = {}; - } else { - options || (options = {}); + if (innerAttr[0] instanceof BI.Widget) { + outerAttr.shift(); + return extend({}, item, { + el: innerAttr.shift() + }); } - return BI.map(BI.flatten(items), function (i, item) { - return BI.createWidget(item, BI.deepClone(options), context); - }); - }, - - createItems: function (data, innerAttr, outerAttr) { - innerAttr = BI.isArray(innerAttr) ? innerAttr : BI.makeArray(BI.flatten(data).length, innerAttr || {}); - outerAttr = BI.isArray(outerAttr) ? outerAttr : BI.makeArray(BI.flatten(data).length, outerAttr || {}); - return BI.map(data, function (i, item) { - if (BI.isArray(item)) { - return BI.createItems(item, innerAttr, outerAttr); - } - if (item instanceof BI.Widget) { - return BI.extend({}, innerAttr.shift(), outerAttr.shift(), { - type: null, - el: item - }); - } - if (innerAttr[0] instanceof BI.Widget) { - outerAttr.shift(); - return BI.extend({}, item, { - el: innerAttr.shift() - }); - } - if (item.el instanceof BI.Widget) { - innerAttr.shift(); - return BI.extend({}, outerAttr.shift(), { type: null }, item); - } - if (item.el) { - return BI.extend({}, outerAttr.shift(), item, { - el: BI.extend({}, innerAttr.shift(), item.el) - }); - } - return BI.extend({}, outerAttr.shift(), { - el: BI.extend({}, innerAttr.shift(), item) + if (item.el instanceof BI.Widget) { + innerAttr.shift(); + return extend({}, outerAttr.shift(), { type: null }, item); + } + if (item.el) { + return extend({}, outerAttr.shift(), item, { + el: extend({}, innerAttr.shift(), item.el) }); + } + return extend({}, outerAttr.shift(), { + el: extend({}, innerAttr.shift(), item) }); - }, - - // 用容器包装items - packageItems: function (items, layouts) { - for (var i = layouts.length - 1; i >= 0; i--) { - items = BI.map(items, function (k, it) { - return BI.extend({}, layouts[i], { - items: [ - BI.extend({}, layouts[i].el, { - el: it - }) - ] - }); + }); +} + +// 用容器包装items +export function packageItems(items, layouts) { + for (var i = layouts.length - 1; i >= 0; i--) { + items = map(items, function (k, it) { + return extend({}, layouts[i], { + items: [ + extend({}, layouts[i].el, { + el: it + }) + ] }); - } - return items; - }, + }); + } + return items; +} - formatEL: function (obj) { - if (obj && !obj.type && obj.el) { - return obj; - } - return { - el: obj - }; - }, +export function formatEL(obj) { + if (obj && !obj.type && obj.el) { + return obj; + } + return { + el: obj + }; +} - // 剥开EL - stripEL: function (obj) { - return obj.type && obj || obj.el || obj; - }, +// 剥开EL +export function stripEL(obj) { + return obj.type && obj || obj.el || obj; +} - trans2Element: function (widgets) { - return BI.map(widgets, function (i, wi) { - return wi.element; - }); - } +export function trans2Element(widgets) { + return map(widgets, (i, wi) => wi.element); +} + +// Utility +BI._.extend(BI, { + assert, + warn, + UUID, + isWidget, + createWidgets, + createItems, + packageItems, + formatEL, + stripEL, + trans2Element, }); // 集合相关方法 @@ -156,193 +165,242 @@ BI._.each(["get", "set", "each", "map", "reduce", "reduceRight", "find", "filter BI[name] = _applyFunc(name); } }); -BI._.extend(BI, { - // 数数 - count: function (from, to, predicate) { - var t; - if (predicate) { - for (t = from; t < to; t++) { - predicate(t); - } +export const where = BI.where; +export const findWhere = BI.findWhere; +export const invoke = BI.invoke; +export const pluck = BI.pluck; +export const shuffle = BI.shuffle; +export const sample = BI.sample; +export const toArray = BI.toArray; +export const size = BI.size; +export const get = BI.get; +export const set = BI.set; +export const each = BI.each; +export const map = BI.map; +export const reduce = BI.reduce; +export const reduceRight = BI.reduceRight; +export const find = BI.find; +export const filter = BI.filter; +export const reject = BI.reject; +export const every = BI.every; +export const all = BI.all; +export const some = BI.some; +export const any = BI.any; +export const max = BI.max; +export const min = BI.min; +export const sortBy = BI.sortBy; +export const groupBy = BI.groupBy; +export const indexBy = BI.indexBy; +export const countBy = BI.countBy; +export const partition = BI.partition; +export const clamp = BI.clamp; + +// 数数 +export function count(from, to, predicate) { + var t; + if (predicate) { + for (t = from; t < to; t++) { + predicate(t); } - return to - from; - }, - - // 倒数 - inverse: function (from, to, predicate) { - return BI.count(to, from, predicate); - }, - - firstKey: function (obj) { - var res = undefined; - BI.any(obj, function (key, value) { - res = key; - return true; - }); - return res; - }, - - lastKey: function (obj) { - var res = undefined; - BI.each(obj, function (key, value) { - res = key; - return true; - }); - return res; - }, + } + return to - from; +} + +// 倒数 +export function inverse(from, to, predicate) { + return count(to, from, predicate); +} + +export function firstKey(obj) { + let res = undefined; + any(obj, function (key, value) { + res = key; + return true; + }); + return res; +} + +export function lastKey(obj) { + let res = undefined; + each(obj, function (key, value) { + res = key; + return true; + }); + return res; +} + +export function firstObject(obj) { + let res = undefined; + any(obj, function (key, value) { + res = value; + return true; + }); + return res; +} + +export function lastObject(obj) { + let res = undefined; + each(obj, function (key, value) { + res = value; + return true; + }); + return res; +} + +export function concat(obj1, obj2) { + if (isKey(obj1)) { + return map([].slice.apply(arguments), function (idx, v) { + return v; + }).join(""); + } + if (isArray(obj1)) { + return BI._.concat.apply([], arguments); + } + if (isObject(obj1)) { + return extend.apply({}, arguments); + } +} - firstObject: function (obj) { - var res = undefined; - BI.any(obj, function (key, value) { - res = value; - return true; - }); - return res; - }, +export function backEach(obj, predicate, context) { + predicate = iteratee(predicate, context); + for (let index = obj.length - 1; index >= 0; index--) { + predicate(index, obj[index], obj); + } + return false; +} - lastObject: function (obj) { - var res = undefined; - BI.each(obj, function (key, value) { - res = value; +export function backAny(obj, predicate, context) { + predicate = iteratee(predicate, context); + for (let index = obj.length - 1; index >= 0; index--) { + if (predicate(index, obj[index], obj)) { return true; - }); - return res; - }, - - concat: function (obj1, obj2) { - if (BI.isKey(obj1)) { - return BI.map([].slice.apply(arguments), function (idx, v) { - return v; - }).join(""); - } - if (BI.isArray(obj1)) { - return BI._.concat.apply([], arguments); } - if (BI.isObject(obj1)) { - return BI._.extend.apply({}, arguments); - } - }, + } + return false; +} - backEach: function (obj, predicate, context) { - predicate = BI.iteratee(predicate, context); - for (var index = obj.length - 1; index >= 0; index--) { - predicate(index, obj[index], obj); +export function backEvery(obj, predicate, context) { + predicate = iteratee(predicate, context); + for (let index = obj.length - 1; index >= 0; index--) { + if (!predicate(index, obj[index], obj)) { + return false; } - return false; - }, + } + return true; +} - backAny: function (obj, predicate, context) { - predicate = BI.iteratee(predicate, context); - for (var index = obj.length - 1; index >= 0; index--) { - if (predicate(index, obj[index], obj)) { - return true; - } +export function backFindKey(obj, predicate, context) { + predicate = iteratee(predicate, context); + let objKeys = keys(obj), key; + for (let i = objKeys.length - 1; i >= 0; i--) { + key = objKeys[i]; + if (predicate(obj[key], key, obj)) { + return key; } - return false; - }, + } +} - backEvery: function (obj, predicate, context) { - predicate = BI.iteratee(predicate, context); - for (var index = obj.length - 1; index >= 0; index--) { - if (!predicate(index, obj[index], obj)) { - return false; - } - } - return true; - }, - - backFindKey: function (obj, predicate, context) { - predicate = BI.iteratee(predicate, context); - var keys = BI._.keys(obj), key; - for (var i = keys.length - 1; i >= 0; i--) { - key = keys[i]; - if (predicate(obj[key], key, obj)) { - return key; +export function backFind(obj, predicate, context) { + let key; + if (isArray(obj)) { + key = findLastIndex(obj, predicate, context); + } else { + key = backFindKey(obj, predicate, context); + } + if (key !== void 0 && key !== -1) { + return obj[key]; + } +} + +export function remove(obj, target, context) { + const targetIsFunction = isFunction(target); + target = targetIsFunction || isArray(target) ? target : [target]; + let i; + if (isArray(obj)) { + for (i = 0; i < obj.length; i++) { + if ((targetIsFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!targetIsFunction && contains(target, obj[i]))) { + obj.splice(i--, 1); } } - }, - - backFind: function (obj, predicate, context) { - var key; - if (BI.isArray(obj)) { - key = BI.findLastIndex(obj, predicate, context); - } else { - key = BI.backFindKey(obj, predicate, context); - } - if (key !== void 0 && key !== -1) { - return obj[key]; - } - }, - - remove: function (obj, target, context) { - var isFunction = BI.isFunction(target); - target = isFunction || BI.isArray(target) ? target : [target]; - var i; - if (BI.isArray(obj)) { - for (i = 0; i < obj.length; i++) { - if ((isFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!isFunction && BI.contains(target, obj[i]))) { - obj.splice(i--, 1); - } + } else { + each(obj, function (i, v) { + if ((targetIsFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!targetIsFunction && contains(target, obj[i]))) { + delete obj[i]; } + }); + } +} + +export function removeAt(obj, index) { + index = isArray(index) ? index : [index]; + let objIsArray = isArray(obj), i; + for (i = 0; i < index.length; i++) { + if (objIsArray) { + obj[index[i]] = "$deleteIndex"; } else { - BI.each(obj, function (i, v) { - if ((isFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!isFunction && BI.contains(target, obj[i]))) { - delete obj[i]; - } - }); - } - }, - - removeAt: function (obj, index) { - index = BI.isArray(index) ? index : [index]; - var isArray = BI.isArray(obj), i; - for (i = 0; i < index.length; i++) { - if (isArray) { - obj[index[i]] = "$deleteIndex"; - } else { - delete obj[index[i]]; - } - } - if (isArray) { - BI.remove(obj, "$deleteIndex"); + delete obj[index[i]]; } - }, - - string2Array: function (str) { - return str.split("&-&"); - }, - - array2String: function (array) { - return array.join("&-&"); - }, - - abc2Int: function (str) { - var idx = 0, start = "A", str = str.toUpperCase(); - for (var i = 0, len = str.length; i < len; ++i) { - idx = str.charAt(i).charCodeAt(0) - start.charCodeAt(0) + 26 * idx + 1; - if (idx > (2147483646 - str.charAt(i).charCodeAt(0) + start.charCodeAt(0)) / 26) { - return 0; - } - } - return idx; - }, - - int2Abc: function (num) { - var DIGITS = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; - var idx = num, str = ""; - if (num === 0) { - return ""; + } + if (objIsArray) { + remove(obj, "$deleteIndex"); + } +} + +export function string2Array(str) { + return str.split("&-&"); +} + +export function array2String(array) { + return array.join("&-&"); +} + +export function abc2Int(string) { + let idx = 0, start = "A", str = string.toUpperCase(); + for (let i = 0, len = str.length; i < len; ++i) { + idx = str.charAt(i).charCodeAt(0) - start.charCodeAt(0) + 26 * idx + 1; + if (idx > (2147483646 - str.charAt(i).charCodeAt(0) + start.charCodeAt(0)) / 26) { + return 0; } - while (idx !== 0) { - var t = idx % 26; - if (t === 0) { - t = 26; - } - str = DIGITS[t - 1] + str; - idx = (idx - t) / 26; + } + return idx; +} + +export function int2Abc(num) { + const DIGITS = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; + let idx = num, str = ""; + if (num === 0) { + return ""; + } + while (idx !== 0) { + let t = idx % 26; + if (t === 0) { + t = 26; } - return str; + str = DIGITS[t - 1] + str; + idx = (idx - t) / 26; } + return str; +} + +BI._.extend(BI, { + count, + inverse, + firstKey, + lastKey, + firstObject, + lastObject, + concat, + backEach, + backAny, + backEvery, + backFindKey, + backFind, + remove, + removeAt, + string2Array, + array2String, + abc2Int, + int2Abc, }); // 数组相关的方法 @@ -353,61 +411,89 @@ BI._.each(["first", "initial", "last", "rest", "compact", "flatten", "without", BI._.each(["findIndex", "findLastIndex"], function (name) { BI[name] = _applyFunc(name); }); -BI._.extend(BI, { - // 构建一个长度为length的数组 - makeArray: function (length, value) { - var res = []; - for (var i = 0; i < length; i++) { - if (BI.isNull(value)) { - res.push(i); - } else { - res.push(BI.deepClone(value)); - } +export const first = BI.first; +export const initial = BI.initial; +export const last = BI.last; +export const rest = BI.rest; +export const compact = BI.compact; +export const flatten = BI.flatten; +export const without = BI.without; +export const union = BI.union; +export const intersection = BI.intersection; +export const difference = BI.difference; +export const zip = BI.zip; +export const unzip = BI.unzip; +export const object = BI.object; +export const indexOf = BI.indexOf; +export const lastIndexOf = BI.lastIndexOf; +export const sortedIndex = BI.sortedIndex; +export const range = BI.range; +export const take = BI.take; +export const takeRight = BI.takeRight; +export const uniqBy = BI.uniqBy; +export const findIndex = BI.findIndex; +export const findLastIndex = BI.findLastIndex; + +// 构建一个长度为length的数组 +export function makeArray(length, value) { + let res = []; + for (let i = 0; i < length; i++) { + if (isNull(value)) { + res.push(i); + } else { + res.push(deepClone(value)); } - return res; - }, - - makeObject: function (array, value) { - var map = {}; - for (var i = 0; i < array.length; i++) { - if (BI.isNull(value)) { - map[array[i]] = array[i]; - } else if (BI.isFunction(value)) { - map[array[i]] = value(i, array[i]); - } else { - map[array[i]] = BI.deepClone(value); - } + } + return res; +} + +export function makeObject(array, value) { + let map = {}; + for (let i = 0; i < array.length; i++) { + if (isNull(value)) { + map[array[i]] = array[i]; + } else if (isFunction(value)) { + map[array[i]] = value(i, array[i]); + } else { + map[array[i]] = deepClone(value); } - return map; - }, + } + return map; +} - makeArrayByArray: function (array, value) { - var res = []; - if (!array) { - return res; - } - for (var i = 0, len = array.length; i < len; i++) { - if (BI.isArray(array[i])) { - res.push(BI.makeArrayByArray(array[i], value)); - } else { - res.push(BI.deepClone(value)); - } - } +export function makeArrayByArray(array, value) { + let res = []; + if (!array) { return res; - }, - - uniq: function (array, isSorted, iteratee, context) { - if (array == null) { - return []; - } - if (!BI._.isBoolean(isSorted)) { - context = iteratee; - iteratee = isSorted; - isSorted = false; + } + for (let i = 0, len = array.length; i < len; i++) { + if (isArray(array[i])) { + res.push(makeArrayByArray(array[i], value)); + } else { + res.push(deepClone(value)); } - iteratee && (iteratee = traverse(iteratee, context)); - return BI._.uniq.call(BI._, array, isSorted, iteratee, context); } + return res; +} + +export function uniq(array, isSorted, iteratee, context) { + if (array == null) { + return []; + } + if (!isBoolean(isSorted)) { + context = iteratee; + iteratee = isSorted; + isSorted = false; + } + iteratee && (iteratee = traverse(iteratee, context)); + return uniq.call(BI._, array, isSorted, iteratee, context); +} + +BI._.extend(BI, { + makeArray, + makeObject, + makeArrayByArray, + uniq, }); // 对象相关方法 @@ -417,244 +503,305 @@ BI._.each(["keys", "allKeys", "values", "pairs", "invert", "create", "functions" "isBoolean", "isDate", "isRegExp", "isError", "isNaN", "isUndefined", "zipObject", "cloneDeep"], function (name) { BI[name] = _apply(name); }); +export const keys = BI.keys; +export const allKeys = BI.allKeys; +export const values = BI.values; +export const pairs = BI.pairs; +export const invert = BI.invert; +export const create = BI.create; +export const functions = BI.functions; +export const extend = BI.extend; +export const extendOwn = BI.extendOwn; +export const defaults = BI.defaults; +export const clone = BI.clone; +export const property = BI.property; +export const propertyOf = BI.propertyOf; +export const matcher = BI.matcher; +export const isEqual = BI.isEqual; +export const isMatch = BI.isMatch; +export const isEmpty = BI.isEmpty; +export const isElement = BI.isElement; +export const isNumber = BI.isNumber; +export const isString = BI.isString; +export const isArray = BI.isArray; +export const isObject = BI.isObject; +export const isPlainObject = BI.isPlainObject; +export const isArguments = BI.isArguments; +export const isFunction = BI.isFunction; +export const isFinite = BI.isFinite; +export const isBoolean = BI.isBoolean; +export const isDate = BI.isDate; +export const isRegExp = BI.isRegExp; +export const isError = BI.isError; +export const isNaN = BI.isNaN; +export const isUndefined = BI.isUndefined; +export const zipObject = BI.zipObject; +export const cloneDeep = BI.cloneDeep; + BI._.each(["mapObject", "findKey", "pick", "omit", "tap"], function (name) { BI[name] = _applyFunc(name); }); -BI._.extend(BI, { - - inherit: function (sp, overrides) { - var sb = function () { - return sp.apply(this, arguments); - }; - var F = function () { - }, spp = sp.prototype; - F.prototype = spp; - sb.prototype = new F(); - sb.superclass = spp; - BI._.extend(sb.prototype, overrides, { - superclass: sp - }); - return sb; - }, - - init: function () { - // 先把准备环境准备好 - while (BI.prepares && BI.prepares.length > 0) { - BI.prepares.shift()(); - } - while (_global.___fineuiExposedFunction && _global.___fineuiExposedFunction.length > 0) { - _global.___fineuiExposedFunction.shift()(); - } - BI.initialized = true; - }, +export const mapObject = BI.mapObject; +export const findKey = BI.findKey; +export const pick = BI.pick; +export const omit = BI.omit; +export const tap = BI.tap; + +export function inherit(sp, overrides) { + let sb = function () { + return sp.apply(this, arguments); + }; + let F = function () { + }, spp = sp.prototype; + F.prototype = spp; + sb.prototype = new F(); + sb.superclass = spp; + extend(sb.prototype, overrides, { + superclass: sp + }); + return sb; +} + +export function init() { + // 先把准备环境准备好 + while (BI.prepares && BI.prepares.length > 0) { + BI.prepares.shift()(); + } + while (_global.___fineuiExposedFunction && _global.___fineuiExposedFunction.length > 0) { + _global.___fineuiExposedFunction.shift()(); + } + BI.initialized = true; +} - has: function (obj, keys) { - if (BI.isArray(keys)) { - if (keys.length === 0) { - return false; - } - return BI.every(keys, function (i, key) { - return BI._.has(obj, key); - }); - } - return BI._.has.apply(BI._, arguments); - }, - - freeze: function (value) { - // 在ES5中,如果这个方法的参数不是一个对象(一个原始值),那么它会导致 TypeError - // 在ES2015中,非对象参数将被视为要被冻结的普通对象,并被简单地返回 - if (Object.freeze && BI.isObject(value)) { - return Object.freeze(value); - } - return value; - }, - - // 数字和字符串可以作为key - isKey: function (key) { - return BI.isNumber(key) || (BI.isString(key) && key.length > 0); - }, - - // 忽略大小写的等于 - isCapitalEqual: function (a, b) { - a = BI.isNull(a) ? a : ("" + a).toLowerCase(); - b = BI.isNull(b) ? b : ("" + b).toLowerCase(); - return BI.isEqual(a, b); - }, - - isWidthOrHeight: function (w) { - if (typeof w === "number") { - return w >= 0; - } else if (typeof w === "string") { - return /^\d{1,3}(\.\d)?%$/.test(w) || w === "auto" || /^\d+(\.\d+)?px$/.test(w) || /^calc/.test(w); +export function has(obj, keys) { + if (isArray(keys)) { + if (keys.length === 0) { + return false; } - }, + return every(keys, function (i, key) { + return BI._.has(obj, key); + }); + } + return BI._.has.apply(BI._, arguments); +} + +export function freeze(value) { + // 在ES5中,如果这个方法的参数不是一个对象(一个原始值),那么它会导致 TypeError + // 在ES2015中,非对象参数将被视为要被冻结的普通对象,并被简单地返回 + if (Object.freeze && isObject(value)) { + return Object.freeze(value); + } + return value; +} + +// 数字和字符串可以作为key +export function isKey(key) { + return isNumber(key) || (isString(key) && key.length > 0); +} + +// 忽略大小写的等于 +export function isCapitalEqual(a, b) { + a = isNull(a) ? a : ("" + a).toLowerCase(); + b = isNull(b) ? b : ("" + b).toLowerCase(); + return isEqual(a, b); +} + +export function isWidthOrHeight(w) { + if (typeof w === "number") { + return w >= 0; + } else if (typeof w === "string") { + return /^\d{1,3}(\.\d)?%$/.test(w) || w === "auto" || /^\d+(\.\d+)?px$/.test(w) || /^calc/.test(w); + } +} - isNotNull: function (obj) { - return !BI.isNull(obj); - }, +export function isNotNull(obj) { + return !isNull(obj); +} - isNull: function (obj) { - return typeof obj === "undefined" || obj === null; - }, +export function isNull(obj) { + return typeof obj === "undefined" || obj === null; +} - isEmptyArray: function (arr) { - return BI.isArray(arr) && BI.isEmpty(arr); - }, +export function isEmptyArray(arr) { + return isArray(arr) && isEmpty(arr); +} - isNotEmptyArray: function (arr) { - return BI.isArray(arr) && !BI.isEmpty(arr); - }, +export function isNotEmptyArray(arr) { + return isArray(arr) && !isEmpty(arr); +} - isEmptyObject: function (obj) { - return BI.isEqual(obj, {}); - }, +export function isEmptyObject(obj) { + return isEqual(obj, {}); +} - isNotEmptyObject: function (obj) { - return BI.isPlainObject(obj) && !BI.isEmptyObject(obj); - }, +export function isNotEmptyObject(obj) { + return isPlainObject(obj) && !isEmptyObject(obj); +} - isEmptyString: function (obj) { - return BI.isString(obj) && obj.length === 0; - }, +export function isWindow(obj) { + return obj != null && obj == obj.window; +} - isNotEmptyString: function (obj) { - return BI.isString(obj) && !BI.isEmptyString(obj); - }, +export function isPromise(obj) { + return !!obj && (isObject(obj) || isFunction(obj)) && isFunction(obj.then); +} - isWindow: function (obj) { - return obj != null && obj == obj.window; - }, +BI._.extend(BI, { + inherit, + init, + has, + freeze, + isKey, + isCapitalEqual, + isWidthOrHeight, + isNotNull, + isNull, + isEmptyArray, + isNotEmptyArray, + isEmptyObject, + isNotEmptyObject, + isWindow, + isPromise, +}); - isPromise: function (obj) { - return !!obj && (BI.isObject(obj) || BI.isFunction(obj)) && BI.isFunction(obj.then); +export const deepClone = BI._.cloneDeep; +export const deepExtend = BI._.deepExtend; +export function isDeepMatch(object, attrs) { + let attrsKeys = keys(attrs), length = attrsKeys.length; + if (object == null) { + return !length; } -}); + const obj = Object(object); + for (let i = 0; i < length; i++) { + const key = attrsKeys[i]; + if (!isEqual(attrs[key], obj[key]) || !(key in obj)) { + return false; + } + } + return true; +} -// deep方法 -BI._.extend(BI, { - deepClone: BI._.cloneDeep, - deepExtend: BI._.merge, +export function contains(obj, target, fromIndex) { + if (!BI._.isArrayLike(obj)) obj = values(obj); + return indexOf(obj, target, typeof fromIndex === "number" && fromIndex) >= 0; +} - isDeepMatch: function (object, attrs) { - var keys = BI.keys(attrs), length = keys.length; - if (object == null) { - return !length; - } - var obj = Object(object); - for (var i = 0; i < length; i++) { - var key = keys[i]; - if (!BI.isEqual(attrs[key], obj[key]) || !(key in obj)) { - return false; - } - } - return true; - }, - - contains: function (obj, target, fromIndex) { - if (!BI._.isArrayLike(obj)) obj = BI._.values(obj); - return BI._.indexOf(obj, target, typeof fromIndex === "number" && fromIndex) >= 0; - }, - - deepContains: function (obj, copy) { - if (BI.isObject(copy)) { - return BI.any(obj, function (i, v) { - if (BI.isEqual(v, copy)) { - return true; - } - }); - } - return BI.contains(obj, copy); - }, +export function deepContains(obj, copy) { + if (isObject(copy)) { + return any(obj, (i, v) => isEqual(v, copy)); + } + return contains(obj, copy); +} - deepIndexOf: function (obj, target) { - for (var i = 0; i < obj.length; i++) { - if (BI.isEqual(target, obj[i])) { - return i; - } - } - return -1; - }, - - deepRemove: function (obj, target) { - var done = false; - var i; - if (BI.isArray(obj)) { - for (i = 0; i < obj.length; i++) { - if (BI.isEqual(target, obj[i])) { - obj.splice(i--, 1); - done = true; - } - } - } else { - BI.each(obj, function (i, v) { - if (BI.isEqual(target, obj[i])) { - delete obj[i]; - done = true; - } - }); +export function deepIndexOf(obj, target) { + for (let i = 0; i < obj.length; i++) { + if (isEqual(target, obj[i])) { + return i; } - return done; - }, - - deepWithout: function (obj, target) { - if (BI.isArray(obj)) { - var result = []; - for (var i = 0; i < obj.length; i++) { - if (!BI.isEqual(target, obj[i])) { - result.push(obj[i]); - } + } + return -1; +} + +export function deepRemove(obj, target) { + let done = false; + let i; + if (isArray(obj)) { + for (i = 0; i < obj.length; i++) { + if (isEqual(target, obj[i])) { + obj.splice(i--, 1); + done = true; } - return result; } - var result = {}; - BI.each(obj, function (i, v) { - if (!BI.isEqual(target, obj[i])) { - result[i] = v; - } - }); - return result; - - }, - - deepUnique: function (array) { - var result = []; - BI.each(array, function (i, item) { - if (!BI.deepContains(result, item)) { - result.push(item); + } else { + each(obj, (i, v) => { + if (isEqual(target, obj[i])) { + delete obj[i]; + done = true; } }); - return result; - }, - - // 比较两个对象得出不一样的key值 - deepDiff: function (object, other) { - object || (object = {}); - other || (other = {}); - var result = []; - var used = []; - for (var b in object) { - if (this.has(object, b)) { - if (!this.isEqual(object[b], other[b])) { - result.push(b); - } - used.push(b); + } + return done; +} + +export function deepWithout(obj, target) { + if (isArray(obj)) { + let result = []; + for (let i = 0; i < obj.length; i++) { + if (!isEqual(target, obj[i])) { + result.push(obj[i]); } } - for (var b in other) { - if (this.has(other, b) && !BI.contains(used, b)) { + return result; + } + let result = {}; + each(obj, (i, v) => { + if (!isEqual(target, obj[i])) { + result[i] = v; + } + }); + return result; +} + +export function deepUnique(array) { + let result = []; + each(array, (i, item) => { + if (!deepContains(result, item)) { + result.push(item); + } + }); + return result; +} + +// 比较两个对象得出不一样的key值 +export function deepDiff(object, other) { + object || (object = {}); + other || (other = {}); + let result = []; + let used = []; + for (let b in object) { + if (has(object, b)) { + if (!isEqual(object[b], other[b])) { result.push(b); } + used.push(b); + } + } + for (let b in other) { + if (has(other, b) && !contains(used, b)) { + result.push(b); } - return result; } + return result; +} + +// deep方法 +BI._.extend(BI, { + deepClone: BI._.cloneDeep, + deepExtend: BI._.merge, + isDeepMatch, + contains, + deepContains, + deepIndexOf, + deepRemove, + deepWithout, + deepUnique, + deepDiff, }); // 通用方法 -BI._.each(["uniqueId", "result", "chain", "iteratee", "escape", "unescape", "before", "after", "chunk"], function (name) { +BI._.each(["uniqueId", "result", "chain", "iteratee", "unescape", "before", "after", "chunk"], function (name) { BI[name] = function () { return BI._[name].apply(BI._, arguments); }; }); +export const uniqueId = BI.uniqueId; +export const result = BI.result; +export const chain = BI.chain; +export const iteratee = BI.iteratee; +export const unescape = BI.unescape; +export const before = BI.before; +export const after = BI.after; +export const chunk = BI.chunk; // 事件相关方法 BI._.each(["bind", "once", "partial", "debounce", "throttle", "delay", "defer", "wrap"], function (name) { @@ -662,627 +809,654 @@ BI._.each(["bind", "once", "partial", "debounce", "throttle", "delay", "defer", return BI._[name].apply(BI._, arguments); }; }); - -BI._.extend(BI, { - nextTick: (function () { - var callbacks = []; - var pending = false; - var timerFunc = void 0; - - function nextTickHandler() { - pending = false; - var copies = callbacks.slice(0); - callbacks.length = 0; - for (var i = 0; i < copies.length; i++) { - copies[i](); - } +export const bind = BI.bind; +export const once = BI.once; +export const partial = BI.partial; +export const debounce = BI.debounce; +export const throttle = BI.throttle; +export const delay = BI.delay; +export const defer = BI.defer; +export const wrap = BI.wrap; + +export const nextTick = (function () { + let callbacks = []; + let pending = false; + let timerFunc = void 0; + + function nextTickHandler() { + pending = false; + let copies = callbacks.slice(0); + callbacks.length = 0; + for (let i = 0; i < copies.length; i++) { + copies[i](); } + } - if (typeof Promise !== "undefined") { - var p = Promise.resolve(); - timerFunc = function timerFunc() { - p.then(nextTickHandler); - }; - } else if (typeof MutationObserver !== "undefined") { - var counter = 1; - var observer = new MutationObserver(nextTickHandler); - var textNode = document.createTextNode(String(counter)); - observer.observe(textNode, { - characterData: true - }); - timerFunc = function timerFunc() { - counter = (counter + 1) % 2; - textNode.data = String(counter); - }; - } else if (typeof setImmediate !== "undefined") { - timerFunc = function timerFunc() { - setImmediate(nextTickHandler); - }; - } else { - // Fallback to setTimeout. - timerFunc = function timerFunc() { - setTimeout(nextTickHandler, 0); - }; - } + if (typeof Promise !== "undefined") { + let p = Promise.resolve(); + timerFunc = function timerFunc() { + p.then(nextTickHandler); + }; + } else if (typeof MutationObserver !== "undefined") { + let counter = 1; + let observer = new MutationObserver(nextTickHandler); + let textNode = document.createTextNode(String(counter)); + observer.observe(textNode, { + characterData: true + }); + timerFunc = function timerFunc() { + counter = (counter + 1) % 2; + textNode.data = String(counter); + }; + } else if (typeof setImmediate !== "undefined") { + timerFunc = function timerFunc() { + setImmediate(nextTickHandler); + }; + } else { + // Fallback to setTimeout. + timerFunc = function timerFunc() { + setTimeout(nextTickHandler, 0); + }; + } - return function queueNextTick(cb) { - var _resolve = void 0; - var args = [].slice.call(arguments, 1); - callbacks.push(function () { - if (cb) { - try { - cb.apply(null, args); - } catch (e) { - console.error(e); - } - } else if (_resolve) { - _resolve.apply(null, args); + return function queueNextTick(cb) { + let _resolve = void 0; + let args = [].slice.call(arguments, 1); + callbacks.push(function () { + if (cb) { + try { + cb.apply(null, args); + } catch (e) { + console.error(e); } - }); - if (!pending) { - pending = true; - timerFunc(); - } - // $flow-disable-line - if (!cb && typeof Promise !== 'undefined') { - return new Promise(function (resolve, reject) { - _resolve = resolve; - }); + } else if (_resolve) { + _resolve.apply(null, args); } - }; - })() -}); + }); + if (!pending) { + pending = true; + timerFunc(); + } + // $flow-disable-line + if (!cb && typeof Promise !== 'undefined') { + return new Promise(function (resolve, reject) { + _resolve = resolve; + }); + } + }; +})(); + +BI._.extend(BI, { nextTick }); // 数字相关方法 BI._.each(["random"], function (name) { BI[name] = _apply(name); }); -BI._.extend(BI, { +export const random = BI.random; - parseInt: function (number) { - var radix = 10; - if (/^0x/g.test(number)) { - radix = 16; - } - try { - return parseInt(number, radix); - } catch (e) { - throw new Error(number + "parse int error"); - return NaN; - } - }, - - parseSafeInt: function (value) { - var MAX_SAFE_INTEGER = 9007199254740991; - return value - ? this.clamp(this.parseInt(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) - : (value === 0 ? value : 0); - }, - - parseFloat: function (number) { - try { - return parseFloat(number); - } catch (e) { - throw new Error(number + "parse float error"); - return NaN; - } - }, +export function parseInt(number) { + let radix = 10; + if (/^0x/g.test(number)) { + radix = 16; + } + try { + return _global.parseInt(number, radix); + } catch (e) { + throw new Error(number + "parse int error"); + return NaN; + } +} + +export function parseSafeInt(value) { + let MAX_SAFE_INTEGER = 9007199254740991; + return value + ? clamp(parseInt(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) + : (value === 0 ? value : 0); +} + +export function parseFloat(number) { + try { + return _global.parseFloat(number); + } catch (e) { + throw new Error(number + "parse float error"); + return NaN; + } +} - isNaturalNumber: function (number) { - if (/^\d+$/.test(number)) { - return true; - } - return false; - }, +export function isNaturalNumber(number) { + return /^\d+$/.test(number); +} - isPositiveInteger: function (number) { - if (/^\+?[1-9][0-9]*$/.test(number)) { - return true; - } - return false; - }, +export function isPositiveInteger(number) { + return /^\+?[1-9][0-9]*$/.test(number); +} - isNegativeInteger: function (number) { - if (/^\-[1-9][0-9]*$/.test(number)) { - return true; - } - return false; - }, +export function isNegativeInteger(number) { + return /^\-[1-9][0-9]*$/.test(number); +} - isInteger: function (number) { - if (/^\-?\d+$/.test(number)) { - return true; - } - return false; - }, +export function isInteger(number) { + return /^\-?\d+$/.test(number); +} - isNumeric: function (number) { - return !isNaN(parseFloat(number)) && isFinite(number); - }, +export function isNumeric(number) { + return !_global.isNaN(_global.parseFloat(number)) && _global.isFinite(number); +} - isFloat: function (number) { - if (/^([+-]?)\d*\.\d+$/.test(number)) { - return true; - } +export function isFloat(number) { + return /^([+-]?)\d*\.\d+$/.test(number); +} + +export function isOdd(number) { + if (!isInteger(number)) { return false; - }, + } + return (number & 1) === 1; +} - isOdd: function (number) { - if (!BI.isInteger(number)) { - return false; +export function isEven(number) { + if (!isInteger(number)) { + return false; + } + return (number & 1) === 0; +} + +export function sum(array, iteratee, context) { + let sum = 0; + each(array, (i, item) => { + if (iteratee) { + sum += Number(iteratee.apply(context, [i, item])); + } else { + sum += Number(item); } - return (number & 1) === 1; - }, + }); + return sum; +} - isEven: function (number) { - if (!BI.isInteger(number)) { - return false; - } - return (number & 1) === 0; - }, - - sum: function (array, iteratee, context) { - var sum = 0; - BI.each(array, function (i, item) { - if (iteratee) { - sum += Number(iteratee.apply(context, [i, item])); - } else { - sum += Number(item); - } - }); - return sum; - }, +export function average(array, iteratee, context) { + const sumResult = sum(array, iteratee, context); + return sumResult / array.length; +} - average: function (array, iteratee, context) { - var sum = BI.sum(array, iteratee, context); - return sum / array.length; - } +BI._.extend(BI, { + parseInt, + parseSafeInt, + parseFloat, + isNaturalNumber, + isPositiveInteger, + isNegativeInteger, + isInteger, + isNumeric, + isFloat, + isOdd, + isEven, + sum, + average, }); +export function trim() { + return BI._.trim.apply(BI._, arguments); +} + +export function toUpperCase(string) { + return (string + "").toLocaleUpperCase(); +} + +export function toLowerCase(string) { + return (string + "").toLocaleLowerCase(); +} + +export function isEndWithBlank(string) { + return /(\s|\u00A0)$/.test(string); +} + +export function isLiteral(exp) { + return /^\s?(true|false|-?[\d\.]+|'[^']*'|"[^"]*")\s?$/.test(exp); +} + +export function stripQuotes(str) { + const a = str.charCodeAt(0); + const b = str.charCodeAt(str.length - 1); + return a === b && (a === 0x22 || a === 0x27) + ? str.slice(1, -1) + : str; +} + +// background-color => backgroundColor +export function camelize(str) { + return str.replace(/-(.)/g, (_, character) => character.toUpperCase()); +} + +// backgroundColor => background-color +export function hyphenate(str) { + return str.replace(/([A-Z])/g, "-$1").toLowerCase(); +} + +export function isNotEmptyString(str) { + return isString(str) && !isEmpty(str); +} + +export function isEmptyString(str) { + return isString(str) && isEmpty(str); +} + +/** + * 通用解密方法 + * @param type 解密方式 + * @param text 文本 + * @param key 种子 + * @return {*} + */ +export function encrypt(type, text, key) { + switch (type) { + case BI.CRYPT_TYPE.AES: + default: + return BI.aesEncrypt(text, key); + } +} + +/** + * 通用解密方法 + * @param type 解密方式 + * @param text 文本 + * @param key 种子 + * @return {*} + */ +export function decrypt(type, text, key) { + switch (type) { + case BI.CRYPT_TYPE.AES: + default: + return BI.aesDecrypt(text, key); + } +} + +/** + * 对字符串中的'和\做编码处理 + * @static + * @param {String} string 要做编码处理的字符串 + * @return {String} 编码后的字符串 + */ +export function escape(string) { + return string.replace(/('|\\)/g, "\\$1"); +} + + +/** + * 让字符串通过指定字符做补齐的函数 + * + * var s = BI.leftPad('123', 5, '0');//s的值为:'00123' + * + * @static + * @param {String} val 原始值 + * @param {Number} size 总共需要的位数 + * @param {String} ch 用于补齐的字符 + * @return {String} 补齐后的字符串 + */ +export function leftPad(val, size, ch) { + let result = String(val); + if (!ch) { + ch = " "; + } + while (result.length < size) { + result = ch + result; + } + return result.toString(); +} + +/** + * 对字符串做替换的函数 + * + * var cls = 'my-class', text = 'Some text'; + * var res = BI.format('
{1}
', cls, text); + * //res的值为:'
Some text
'; + * + * @static + * @param {String} format 要做替换的字符串,替换字符串1,替换字符串2... + * @return {String} 做了替换后的字符串 + */ +export function format(format) { + var args = Array.prototype.slice.call(arguments, 1); + return format.replace(/\{(\d+)\}/g, (m, i) => args[i]); +} + // 字符串相关方法 BI._.extend(BI, { - trim: function () { - return BI._.trim.apply(BI._, arguments); - }, - - toUpperCase: function (string) { - return (string + "").toLocaleUpperCase(); - }, - - toLowerCase: function (string) { - return (string + "").toLocaleLowerCase(); - }, - - isEndWithBlank: function (string) { - return /(\s|\u00A0)$/.test(string); - }, - - isLiteral: function (exp) { - var literalValueRE = /^\s?(true|false|-?[\d\.]+|'[^']*'|"[^"]*")\s?$/; - return literalValueRE.test(exp); - }, - - stripQuotes: function (str) { - var a = str.charCodeAt(0); - var b = str.charCodeAt(str.length - 1); - return a === b && (a === 0x22 || a === 0x27) - ? str.slice(1, -1) - : str; - }, - - // background-color => backgroundColor - camelize: function (str) { - return str.replace(/-(.)/g, function (_, character) { - return character.toUpperCase(); - }); - }, - - // backgroundColor => background-color - hyphenate: function (str) { - return str.replace(/([A-Z])/g, "-$1").toLowerCase(); - }, - - isNotEmptyString: function (str) { - return BI.isString(str) && !BI.isEmpty(str); - }, - - isEmptyString: function (str) { - return BI.isString(str) && BI.isEmpty(str); - }, - - /** - * 通用加密方法 - */ - encrypt: function (type, text, key) { - switch (type) { - case BI.CRYPT_TYPE.AES: - default: - return BI.aesEncrypt(text, key); - } - }, - - /** - * 通用解密方法 - * @param type 解密方式 - * @param text 文本 - * @param key 种子 - * @return {*} - */ - decrypt: function (type, text, key) { - switch (type) { - case BI.CRYPT_TYPE.AES: - default: - return BI.aesDecrypt(text, key); - } - }, - - /** - * 对字符串中的'和\做编码处理 - * @static - * @param {String} string 要做编码处理的字符串 - * @return {String} 编码后的字符串 - */ - escape: function (string) { - return string.replace(/('|\\)/g, "\\$1"); - }, - - /** - * 让字符串通过指定字符做补齐的函数 - * - * var s = BI.leftPad('123', 5, '0');//s的值为:'00123' - * - * @static - * @param {String} val 原始值 - * @param {Number} size 总共需要的位数 - * @param {String} ch 用于补齐的字符 - * @return {String} 补齐后的字符串 - */ - leftPad: function (val, size, ch) { - var result = String(val); - if (!ch) { - ch = " "; - } - while (result.length < size) { - result = ch + result; - } - return result.toString(); - }, - - /** - * 对字符串做替换的函数 - * - * var cls = 'my-class', text = 'Some text'; - * var res = BI.format('
{1}
', cls, text); - * //res的值为:'
Some text
'; - * - * @static - * @param {String} format 要做替换的字符串,替换字符串1,替换字符串2... - * @return {String} 做了替换后的字符串 - */ - format: function (format) { - var args = Array.prototype.slice.call(arguments, 1); - return format.replace(/\{(\d+)\}/g, function (m, i) { - return args[i]; - }); - } + trim, + toUpperCase, + toLowerCase, + isEndWithBlank, + isLiteral, + stripQuotes, + camelize, + hyphenate, + isNotEmptyString, + isEmptyString, + encrypt, + decrypt, + escape, + leftPad, + format, }); -// 日期相关方法 -BI._.extend(BI, { - /** - * 是否是闰年 - * @param year - * @returns {boolean} - */ - isLeapYear: function (year) { - return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; - }, - - /** - * 检测是否在有效期 - * - * @param YY 年 - * @param MM 月 - * @param DD 日 - * @param minDate '1900-01-01' - * @param maxDate '2099-12-31' - * @returns {Array} 若无效返回无效状态,数组第一位为无效属性,第二位缺省为超下限,1为超上限 - */ - checkDateVoid: function (YY, MM, DD, minDate, maxDate) { - var back = []; - YY = YY | 0; - MM = MM | 0; - DD = DD | 0; - minDate = BI.isString(minDate) ? minDate.match(/\d+/g) : minDate; - maxDate = BI.isString(maxDate) ? maxDate.match(/\d+/g) : maxDate; - if (YY < minDate[0]) { - back = ["y"]; - } else if (YY > maxDate[0]) { - back = ["y", 1]; - } else if (YY >= minDate[0] && YY <= maxDate[0]) { - if (YY == minDate[0]) { - if (MM < minDate[1]) { - back = ["m"]; - } else if (MM == minDate[1]) { - if (DD < minDate[2]) { - back = ["d"]; - } +/** + * 是否是闰年 + * @param year + * @returns {boolean} + */ +export function isLeapYear(year) { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +/** + * 检测是否在有效期 + * + * @param YY 年 + * @param MM 月 + * @param DD 日 + * @param minDate '1900-01-01' + * @param maxDate '2099-12-31' + * @returns {Array} 若无效返回无效状态,数组第一位为无效属性,第二位缺省为超下限,1为超上限 + */ +export function checkDateVoid(YY, MM, DD, minDate, maxDate) { + let back = []; + YY = YY | 0; + MM = MM | 0; + DD = DD | 0; + minDate = isString(minDate) ? minDate.match(/\d+/g) : minDate; + maxDate = isString(maxDate) ? maxDate.match(/\d+/g) : maxDate; + if (YY < minDate[0]) { + back = ["y"]; + } else if (YY > maxDate[0]) { + back = ["y", 1]; + } else if (YY >= minDate[0] && YY <= maxDate[0]) { + if (YY == minDate[0]) { + if (MM < minDate[1]) { + back = ["m"]; + } else if (MM == minDate[1]) { + if (DD < minDate[2]) { + back = ["d"]; } } - if (YY == maxDate[0]) { - if (MM > maxDate[1]) { - back = ["m", 1]; - } else if (MM == maxDate[1]) { - if (DD > maxDate[2]) { - back = ["d", 1]; - } + } + if (YY == maxDate[0]) { + if (MM > maxDate[1]) { + back = ["m", 1]; + } else if (MM == maxDate[1]) { + if (DD > maxDate[2]) { + back = ["d", 1]; } } } - return back; - }, - - checkDateLegal: function (str) { - var ar = str.match(/\d+/g); - var YY = ar[0] | 0, MM = ar[1] | 0, DD = ar[2] | 0; - if (ar.length <= 1) { - return true; - } - if (ar.length <= 2) { - return MM >= 1 && MM <= 12; - } - var MD = BI.Date._MD.slice(0); - MD[1] = BI.isLeapYear(YY) ? 29 : 28; - return MM >= 1 && MM <= 12 && DD <= MD[MM - 1]; - }, - - /** 解析日期时间字符串 - * - * @param str - * @param fmt - * @returns {Date|Date} - * 年月日缺省值为当前日期, 时分秒缺省值为0 - */ - parseDateTime: function (str, fmt) { - var today = BI.getDate(); - var y; - var m; - var d; - // wei : 对于fmt为‘YYYYMM’或者‘YYYYMMdd’的格式,str的值为类似'201111'的形式,因为年月之间没有分隔符,所以正则表达式分割无效,导致bug7376。 - var a = str.split(/\W+/); - if (fmt.toLowerCase() == "%y%x" || fmt.toLowerCase() == "%y%x%d") { - var yearlength = 4; - var otherlength = 2; - a[0] = str.substring(0, yearlength); - a[1] = str.substring(yearlength, yearlength + otherlength); - a[2] = str.substring(yearlength + otherlength, yearlength + otherlength * 2); - } - var b = fmt.match(/%./g); - var i = 0, j = 0; - var hr = 0; - var min = 0; - var sec = 0; - for (i = 0; i < a.length; ++i) { - switch (b[i]) { - case "%d": - case "%e": - d = parseInt(a[i], 10); - break; + } + return back; +} - case "%X": - m = parseInt(a[i], 10) - 1; - break; - case "%x": - m = parseInt(a[i], 10) - 1; - break; +export function checkDateLegal(str) { + const ar = str.match(/\d+/g); + const YY = ar[0] | 0, MM = ar[1] | 0, DD = ar[2] | 0; + if (ar.length <= 1) { + return true; + } + if (ar.length <= 2) { + return MM >= 1 && MM <= 12; + } + let MD = BI.Date._MD.slice(0); + MD[1] = isLeapYear(YY) ? 29 : 28; + return MM >= 1 && MM <= 12 && DD <= MD[MM - 1]; +} - case "%Y": - case "%y": - y = parseInt(a[i], 10); - (y < 100) && (y += (y > 29) ? 1900 : 2000); - break; +/** 解析日期时间字符串 + * + * @param str + * @param fmt + * @returns {Date|Date} + * 年月日缺省值为当前日期, 时分秒缺省值为0 + */ +export function parseDateTime(str, fmt) { + const today = BI.getDate(); + let y; + let m; + let d; + // wei : 对于fmt为‘YYYYMM’或者‘YYYYMMdd’的格式,str的值为类似'201111'的形式,因为年月之间没有分隔符,所以正则表达式分割无效,导致bug7376。 + let a = str.split(/\W+/); + if (fmt.toLowerCase() == "%y%x" || fmt.toLowerCase() == "%y%x%d") { + let yearlength = 4; + let otherlength = 2; + a[0] = str.substring(0, yearlength); + a[1] = str.substring(yearlength, yearlength + otherlength); + a[2] = str.substring(yearlength + otherlength, yearlength + otherlength * 2); + } + let b = fmt.match(/%./g); + let i = 0, j = 0; + let hr = 0; + let min = 0; + let sec = 0; + for (i = 0; i < a.length; ++i) { + switch (b[i]) { + case "%d": + case "%e": + d = _global.parseInt(a[i], 10); + break; - case "%b": - case "%B": - for (j = 0; j < 12; ++j) { - if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { - m = j; - break; - } - } - break; + case "%X": + m = _global.parseInt(a[i], 10) - 1; + break; + case "%x": + m = _global.parseInt(a[i], 10) - 1; + break; - case "%H": - case "%I": - case "%k": - case "%l": - hr = parseInt(a[i], 10); - break; + case "%Y": + case "%y": + y = _global.parseInt(a[i], 10); + (y < 100) && (y += (y > 29) ? 1900 : 2000); + break; - case "%P": - case "%p": - if (/pm/i.test(a[i]) && hr < 12) { - hr += 12; - } else if (/am/i.test(a[i]) && hr >= 12) { - hr -= 12; - } - break; - case "%Q": - case "%q": - m = (parseInt(a[i], 10) - 1) * 3; - break; - case "%M": - min = parseInt(a[i], 10); - break; - case "%S": - sec = parseInt(a[i], 10); - break; - } - } - // if (!a[i]) { - // continue; - // } - if (isNaN(y)) { - y = today.getFullYear(); - } - if (isNaN(m)) { - m = today.getMonth(); - } - if (isNaN(d)) { - d = today.getDate(); - } - if (isNaN(hr)) { - hr = today.getHours(); - } - if (isNaN(min)) { - min = today.getMinutes(); - } - if (isNaN(sec)) { - sec = today.getSeconds(); - } - if (y != 0) { - return BI.getDate(y, m, d, hr, min, sec); - } - y = 0; - m = -1; - d = 0; - for (i = 0; i < a.length; ++i) { - if (a[i].search(/[a-zA-Z]+/) != -1) { - var t = -1; + case "%b": + case "%B": for (j = 0; j < 12; ++j) { if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { - t = j; + m = j; break; } } - if (t != -1) { - if (m != -1) { - d = m + 1; - } - m = t; - } - } else if (parseInt(a[i], 10) <= 12 && m == -1) { - m = a[i] - 1; - } else if (parseInt(a[i], 10) > 31 && y == 0) { - y = parseInt(a[i], 10); - (y < 100) && (y += (y > 29) ? 1900 : 2000); - } else if (d == 0) { - d = a[i]; - } - } - if (y == 0) { - y = today.getFullYear(); - } - if (m === -1) { - m = today.getMonth(); - } - if (m != -1 && d != 0) { - return BI.getDate(y, m, d, hr, min, sec); - } - return today; - }, - - getDate: function () { - var length = arguments.length; - var args = arguments; - var dt; - switch (length) { - // new Date() - case 0: - dt = new Date(); - break; - // new Date(long) - case 1: - dt = new Date(args[0]); - break; - // new Date(year, month) - case 2: - dt = new Date(args[0], args[1]); - break; - // new Date(year, month, day) - case 3: - dt = new Date(args[0], args[1], args[2]); - break; - // new Date(year, month, day, hour) - case 4: - dt = new Date(args[0], args[1], args[2], args[3]); - break; - // new Date(year, month, day, hour, minute) - case 5: - dt = new Date(args[0], args[1], args[2], args[3], args[4]); - break; - // new Date(year, month, day, hour, minute, second) - case 6: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); break; - // new Date(year, month, day, hour, minute, second, millisecond) - case 7: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - break; - default: - dt = new Date(); - break; - } - if (BI.isNotNull(BI.timeZone) && (arguments.length === 0 || (arguments.length === 1 && BI.isNumber(arguments[0])))) { - var localTime = dt.getTime(); - // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 - var localOffset = dt.getTimezoneOffset() * 60000; // 获得当地时间偏移的毫秒数 - var utc = localTime + localOffset; // utc即GMT时间标准时区 - return new Date(utc + BI.timeZone);// + Pool.timeZone.offset); - } - return dt; - - }, - - getTime: function () { - var length = arguments.length; - var args = arguments; - var dt; - switch (length) { - // new Date() - case 0: - dt = new Date(); - break; - // new Date(long) - case 1: - dt = new Date(args[0]); - break; - // new Date(year, month) - case 2: - dt = new Date(args[0], args[1]); - break; - // new Date(year, month, day) - case 3: - dt = new Date(args[0], args[1], args[2]); - break; - // new Date(year, month, day, hour) - case 4: - dt = new Date(args[0], args[1], args[2], args[3]); + + case "%H": + case "%I": + case "%k": + case "%l": + hr = _global.parseInt(a[i], 10); break; - // new Date(year, month, day, hour, minute) - case 5: - dt = new Date(args[0], args[1], args[2], args[3], args[4]); + + case "%P": + case "%p": + if (/pm/i.test(a[i]) && hr < 12) { + hr += 12; + } else if (/am/i.test(a[i]) && hr >= 12) { + hr -= 12; + } break; - // new Date(year, month, day, hour, minute, second) - case 6: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); + case "%Q": + case "%q": + m = (_global.parseInt(a[i], 10) - 1) * 3; break; - // new Date(year, month, day, hour, minute, second, millisecond) - case 7: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + case "%M": + min = _global.parseInt(a[i], 10); break; - default: - dt = new Date(); + case "%S": + sec = _global.parseInt(a[i], 10); break; } - if (BI.isNotNull(BI.timeZone)) { - // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 - return dt.getTime() - BI.timeZone - new Date().getTimezoneOffset() * 60000; + } + // if (!a[i]) { + // continue; + // } + if (isNaN(y)) { + y = today.getFullYear(); + } + if (isNaN(m)) { + m = today.getMonth(); + } + if (isNaN(d)) { + d = today.getDate(); + } + if (isNaN(hr)) { + hr = today.getHours(); + } + if (isNaN(min)) { + min = today.getMinutes(); + } + if (isNaN(sec)) { + sec = today.getSeconds(); + } + if (y != 0) { + return BI.getDate(y, m, d, hr, min, sec); + } + y = 0; + m = -1; + d = 0; + for (i = 0; i < a.length; ++i) { + if (a[i].search(/[a-zA-Z]+/) != -1) { + let t = -1; + for (j = 0; j < 12; ++j) { + if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { + t = j; + break; + } + } + if (t != -1) { + if (m != -1) { + d = m + 1; + } + m = t; + } + } else if (_global.parseInt(a[i], 10) <= 12 && m == -1) { + m = a[i] - 1; + } else if (_global.parseInt(a[i], 10) > 31 && y == 0) { + y = _global.parseInt(a[i], 10); + (y < 100) && (y += (y > 29) ? 1900 : 2000); + } else if (d == 0) { + d = a[i]; } - return dt.getTime(); - } -}); + if (y == 0) { + y = today.getFullYear(); + } + if (m === -1) { + m = today.getMonth(); + } + if (m != -1 && d != 0) { + return BI.getDate(y, m, d, hr, min, sec); + } + return today; +} + +export function getDate() { + const length = arguments.length; + const args = arguments; + let dt; + switch (length) { + // new Date() + case 0: + dt = new Date(); + break; + // new Date(long) + case 1: + dt = new Date(args[0]); + break; + // new Date(year, month) + case 2: + dt = new Date(args[0], args[1]); + break; + // new Date(year, month, day) + case 3: + dt = new Date(args[0], args[1], args[2]); + break; + // new Date(year, month, day, hour) + case 4: + dt = new Date(args[0], args[1], args[2], args[3]); + break; + // new Date(year, month, day, hour, minute) + case 5: + dt = new Date(args[0], args[1], args[2], args[3], args[4]); + break; + // new Date(year, month, day, hour, minute, second) + case 6: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); + break; + // new Date(year, month, day, hour, minute, second, millisecond) + case 7: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + break; + default: + dt = new Date(); + break; + } + if (isNotNull(BI.timeZone) && (arguments.length === 0 || (arguments.length === 1 && isNumber(arguments[0])))) { + const localTime = dt.getTime(); + // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 + const localOffset = dt.getTimezoneOffset() * 60000; // 获得当地时间偏移的毫秒数 + const utc = localTime + localOffset; // utc即GMT时间标准时区 + return new Date(utc + BI.timeZone);// + Pool.timeZone.offset); + } + return dt; +} + +export function getTime() { + const length = arguments.length; + const args = arguments; + let dt; + switch (length) { + // new Date() + case 0: + dt = new Date(); + break; + // new Date(long) + case 1: + dt = new Date(args[0]); + break; + // new Date(year, month) + case 2: + dt = new Date(args[0], args[1]); + break; + // new Date(year, month, day) + case 3: + dt = new Date(args[0], args[1], args[2]); + break; + // new Date(year, month, day, hour) + case 4: + dt = new Date(args[0], args[1], args[2], args[3]); + break; + // new Date(year, month, day, hour, minute) + case 5: + dt = new Date(args[0], args[1], args[2], args[3], args[4]); + break; + // new Date(year, month, day, hour, minute, second) + case 6: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); + break; + // new Date(year, month, day, hour, minute, second, millisecond) + case 7: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + break; + default: + dt = new Date(); + break; + } + if (isNotNull(BI.timeZone)) { + // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 + return dt.getTime() - BI.timeZone - new Date().getTimezoneOffset() * 60000; + } + return dt.getTime(); -// TODO: 暂时先直接export全部,下一步拆function -export default BI; \ No newline at end of file +} + +// 日期相关方法 +BI._.extend(BI, { + isLeapYear, + checkDateVoid, + checkDateLegal, + parseDateTime, + getDate, + getTime, +}); \ No newline at end of file diff --git a/src/core/3.ob.js b/src/core/3.ob.js index f6e9396de..5d0e9f7fb 100644 --- a/src/core/3.ob.js +++ b/src/core/3.ob.js @@ -1,4 +1,4 @@ -import BI from "./2.base"; +import { isFunction, isArray, isObject, isArguments, reduce, bind } from "./2.base"; function extend() { let target = arguments[0] || {}, length = arguments.length, i = 1, name, copy; @@ -49,11 +49,11 @@ export default class OB { _initProps(config) { let props = this.props; - if (BI.isFunction(this.props)) { + if (isFunction(this.props)) { props = this.props(config); } const defaultProps = extend(this._defaultConfig(config), props); - const modifiedDefaultProps = (config && config.type && OB.configFunctions[config.type + ".props"]) ? BI.reduce(OB.configFunctions[config.type + ".props"], function (value, conf, index) { + const modifiedDefaultProps = (config && config.type && OB.configFunctions[config.type + ".props"]) ? reduce(OB.configFunctions[config.type + ".props"], function (value, conf, index) { return extend(conf, value.fn(defaultProps, config, value.opt)); }, {}) : null; this.options = extend(defaultProps, modifiedDefaultProps, config); @@ -67,19 +67,19 @@ export default class OB { _initListeners() { if (this.options.listeners !== null) { BI._.each(this.options.listeners, (lis, eventName) => { - if (BI._.isFunction(lis)) { + if (isFunction(lis)) { this.on(eventName, lis); return; } - if (BI._.isArray(lis)) { + if (isArray(lis)) { BI._.each(lis, (l) => { this.on(eventName, l); }); return; } - (lis.target ? lis.target : this)[lis.once ? "once" : "on"](lis.eventName, BI._.bind(lis.action, this)); + (lis.target ? lis.target : this)[lis.once ? "once" : "on"](lis.eventName, bind(lis.action, this)); }); delete this.options.listeners; } @@ -89,10 +89,10 @@ export default class OB { _initRef() { const o = this.options; if (o.__ref) { - BI.isFunction(o.__ref) ? o.__ref.call(this, this) : o.__ref.current = this; + isFunction(o.__ref) ? o.__ref.call(this, this) : o.__ref.current = this; } if (o.ref) { - BI.isFunction(o.ref) ? o.ref.call(this, this) : o.ref.current = this; + isFunction(o.ref) ? o.ref.call(this, this) : o.ref.current = this; } } @@ -100,17 +100,17 @@ export default class OB { _purgeRef() { const o = this.options; if (o.__ref) { - BI.isFunction(o.__ref) ? o.__ref.call(null, null) : o.__ref.current = null; + isFunction(o.__ref) ? o.__ref.call(null, null) : o.__ref.current = null; o.__ref = null; } if (o.ref) { - BI.isFunction(o.ref) ? o.ref.call(null, null) : o.ref.current = null; + isFunction(o.ref) ? o.ref.call(null, null) : o.ref.current = null; o.ref = null; } } _getEvents() { - if (!BI._.isObject(this.events)) { + if (!isObject(this.events)) { this.events = {}; } @@ -125,7 +125,7 @@ export default class OB { on(eventName, fn) { eventName = eventName.toLowerCase(); let fns = this._getEvents()[eventName]; - if (!BI._.isArray(fns)) { + if (!isArray(fns)) { fns = []; this._getEvents()[eventName] = fns; } @@ -160,7 +160,7 @@ export default class OB { delete this._getEvents()[eventName]; } else { const fns = this._getEvents()[eventName]; - if (BI._.isArray(fns)) { + if (isArray(fns)) { const newFns = []; BI._.each(fns, function (ifn) { if (ifn !== fn) { @@ -189,8 +189,8 @@ export default class OB { fireEvent() { const eventName = arguments[0].toLowerCase(); const fns = this._getEvents()[eventName]; - if (BI.isArray(fns)) { - if (BI.isArguments(arguments[1])) { + if (isArray(fns)) { + if (isArguments(arguments[1])) { for (let i = 0; i < fns.length; i++) { if (fns[i].apply(this, arguments[1]) === false) { return false; @@ -216,6 +216,4 @@ export default class OB { } } -// BI.OB = BI.OB || OB; - BI.extend(BI, { OB }); diff --git a/src/core/4.widget.js b/src/core/4.widget.js index 1e6c4b746..728e70dfa 100644 --- a/src/core/4.widget.js +++ b/src/core/4.widget.js @@ -1,12 +1,12 @@ /** * Widget超类 - * @class BI.Widget - * @extends BI.OB + * @class Widget + * @extends OB * * @cfg {JSON} options 配置属性 */ -import BI from "./2.base"; +import { isFunction, isArray, each, extend, isPlainObject, isNull, uniqueId, isWidget, isWidthOrHeight, isKey, remove, any, isNotNull } from "./2.base"; import OB from "./3.ob"; const cancelAnimationFrame = @@ -23,20 +23,20 @@ function callLifeHook(self, life) { let hooks = [], hook; hook = self[life]; if (hook) { - hooks = hooks.concat(BI.isArray(hook) ? hook : [hook]); + hooks = hooks.concat(isArray(hook) ? hook : [hook]); } hook = self.options[life]; if (hook) { - hooks = hooks.concat(BI.isArray(hook) ? hook : [hook]); + hooks = hooks.concat(isArray(hook) ? hook : [hook]); } - BI.each(hooks, function (i, hook) { + each(hooks, function (i, hook) { hook.call(self); }); } export default class Widget extends OB { _defaultConfig () { - return BI.extend(super._defaultConfig(), { + return extend(super._defaultConfig(), { root: false, tagName: "div", attributes: null, @@ -67,9 +67,9 @@ export default class Widget extends OB { if (this.setup) { pushTarget(this); const delegate = this.setup(this.options); - if (BI.isPlainObject(delegate)) { + if (isPlainObject(delegate)) { // 如果setup返回一个json,即对外暴露的方法 - BI.extend(this, delegate); + extend(this, delegate); } else { this.render = delegate; } @@ -208,7 +208,7 @@ export default class Widget extends OB { this.element.addClass((o._baseCls || "") + " " + (o.baseCls || "") + " " + (o.extraCls || "")); } if (o.cls) { - if (BI.isFunction(o.cls)) { + if (isFunction(o.cls)) { const cls = this.__watch(o.cls, (context, newValue) => { this.element.removeClass(cls).addClass(cls = newValue); }); @@ -227,10 +227,10 @@ export default class Widget extends OB { this.element.data(o.data); } if (o.css) { - if (BI.isFunction(o.css)) { + if (isFunction(o.css)) { const css = this.__watch(o.css, (context, newValue) => { for (const k in css) { - if (BI.isNull(newValue[k])) { + if (isNull(newValue[k])) { newValue[k] = ""; } } @@ -250,7 +250,7 @@ export default class Widget extends OB { return getter.call(this, this); }, (handler && ((v) => { handler.call(this, this, v); - })) || BI.emptyFn, BI.extend({ deep: true }, options)); + })) || BI.emptyFn, extend({ deep: true }, options)); this._watchers.push(() => { watcher.teardown(); }); @@ -266,18 +266,18 @@ export default class Widget extends OB { */ _initRoot() { const o = this.options; - this.widgetName = o.widgetName || BI.uniqueId("widget"); + this.widgetName = o.widgetName || uniqueId("widget"); this._isRoot = o.root; this._children = {}; - if (BI.isWidget(o.element)) { + if (isWidget(o.element)) { this.element = this.options.element.element; this._parent = o.element; this._parent._children && this._parent.addWidget(this.widgetName, this); } else if (o.element) { - this.element = BI.Widget._renderEngine.createElement(this); + this.element = Widget._renderEngine.createElement(this); this._isRoot = true; } else { - this.element = BI.Widget._renderEngine.createElement(this); + this.element = Widget._renderEngine.createElement(this); } this.element._isWidget = true; // const widgets = this.element.data("__widgets") || []; @@ -288,14 +288,14 @@ export default class Widget extends OB { _initElementWidth() { const o = this.options; - if (BI.isWidthOrHeight(o.width)) { + if (isWidthOrHeight(o.width)) { this.element.css("width", BI.pixFormat(o.width)); } } _initElementHeight() { const o = this.options; - if (BI.isWidthOrHeight(o.height)) { + if (isWidthOrHeight(o.height)) { this.element.css("height", BI.pixFormat(o.height)); } } @@ -303,7 +303,7 @@ export default class Widget extends OB { _initVisual() { const o = this.options; if (o.invisible) { - const invisible = o.invisible = BI.isFunction(o.invisible) ? this.__watch(o.invisible, (context, newValue) => { + const invisible = o.invisible = isFunction(o.invisible) ? this.__watch(o.invisible, (context, newValue) => { this.setVisible(!newValue); }) : o.invisible; if (invisible) { @@ -317,7 +317,7 @@ export default class Widget extends OB { const o = this.options; if (o.disabled || o.invalid) { if (this.options.disabled) { - const disabled = o.disabled = BI.isFunction(o.disabled) ? this.__watch(o.disabled, (context, newValue) => { + const disabled = o.disabled = isFunction(o.disabled) ? this.__watch(o.disabled, (context, newValue) => { this.setEnable(!newValue); }) : o.disabled; if (disabled) { @@ -325,7 +325,7 @@ export default class Widget extends OB { } } if (this.options.invalid) { - const invalid = o.invalid = BI.isFunction(o.invalid) ? this.__watch(o.invalid, (context, newValue) => { + const invalid = o.invalid = isFunction(o.invalid) ? this.__watch(o.invalid, (context, newValue) => { this.setValid(!newValue); }) : o.invalid; if (invalid) { @@ -334,9 +334,9 @@ export default class Widget extends OB { } } if (o.effect) { - if (BI.isArray(o.effect)) { - if (BI.isArray(o.effect[0])) { - BI.each(o.effect, (i, effect) => { + if (isArray(o.effect)) { + if (isArray(o.effect[0])) { + each(o.effect, (i, effect) => { this.__watch(effect[0], effect[1]); }); } else { @@ -361,16 +361,16 @@ export default class Widget extends OB { this.__isMounting = true; // 当开启worker模式时,可以通过$render来实现另一种效果 const workerMode = BI.Providers.getProvider("bi.provider.system").getWorkerMode(); - const render = BI.isFunction(this.options.render) ? this.options.render : (workerMode ? (this.$render || this.render) : this.render); + const render = isFunction(this.options.render) ? this.options.render : (workerMode ? (this.$render || this.render) : this.render); let els = render && render.call(this); els = this.options.configRender ? this.options.configRender.call(this, els) : els; els = BI.Plugin.getRender(this.options.type, els); - if (BI.isPlainObject(els)) { + if (isPlainObject(els)) { els = [els]; } this.__initWatch(); - if (BI.isArray(els)) { - BI.each(els, (i, el) => { + if (isArray(els)) { + each(els, (i, el) => { if (el) { BI._lazyCreateWidget(el, { element: this @@ -475,7 +475,7 @@ export default class Widget extends OB { this.options._disabled = true; } // 递归将所有子组件使能 - BI.each(this._children, function (i, child) { + each(this._children, function (i, child) { !child._manualSetEnable && child._setEnable && child._setEnable(enable); }); } @@ -487,7 +487,7 @@ export default class Widget extends OB { this.options._invalid = true; } // 递归将所有子组件使有效 - BI.each(this._children, function (i, child) { + each(this._children, function (i, child) { !child._manualSetValid && child._setValid && child._setValid(valid); }); } @@ -581,7 +581,7 @@ export default class Widget extends OB { doBehavior() { const args = arguments; // 递归将所有子组件使有效 - BI.each(this._children, function (i, child) { + each(this._children, function (i, child) { child.doBehavior && child.doBehavior.apply(child, args); }); } @@ -596,32 +596,32 @@ export default class Widget extends OB { addWidget(name, widget) { const self = this; - if (name instanceof BI.Widget) { + if (name instanceof Widget) { widget = name; name = widget.getName(); } - if (BI.isKey(name)) { + if (isKey(name)) { name = name + ""; } - name = name || widget.getName() || BI.uniqueId("widget"); + name = name || widget.getName() || uniqueId("widget"); if (this._children[name]) { throw new Error("组件:组件名已存在,不能进行添加"); } widget._setParent && widget._setParent(this); widget.on(BI.Events.DESTROY, function () { // TODO: self待删 - BI.remove(self._children, this); + remove(self._children, this); }); return (this._children[name] = widget); } getWidgetByName(name) { - if (!BI.isKey(name) || name === this.getName()) { + if (!isKey(name) || name === this.getName()) { return this; } name = name + ""; let widget = void 0, other = {}; - BI.any(this._children, function (i, wi) { + any(this._children, function (i, wi) { if (i === name) { widget = wi; return true; @@ -629,7 +629,7 @@ export default class Widget extends OB { other[i] = wi; }); if (!widget) { - BI.any(other, function (i, wi) { + any(other, function (i, wi) { return (widget = wi.getWidgetByName(i)); }); } @@ -637,8 +637,8 @@ export default class Widget extends OB { } removeWidget(nameOrWidget) { - if (BI.isWidget(nameOrWidget)) { - BI.remove(this._children, nameOrWidget); + if (isWidget(nameOrWidget)) { + remove(this._children, nameOrWidget); } else { delete this._children[nameOrWidget]; } @@ -661,11 +661,11 @@ export default class Widget extends OB { } attr(key, value) { - if (BI.isPlainObject(key)) { - BI.each(key, (k, v) => this.attr(k, v)); + if (isPlainObject(key)) { + each(key, (k, v) => this.attr(k, v)); return; } - if (BI.isNotNull(value)) { + if (isNotNull(value)) { return this.options[key] = value; } return this.options[key]; @@ -728,7 +728,7 @@ export default class Widget extends OB { } __d() { - BI.each(this._children, function (i, widget) { + each(this._children, function (i, widget) { widget && widget._unMount && widget._unMount(); }); this._children = {}; @@ -766,7 +766,7 @@ export default class Widget extends OB { _empty () { this._assetMounted(); - BI.each(this._children, function (i, widget) { + each(this._children, function (i, widget) { widget && widget._unMount && widget._unMount(); }); this._children = {}; @@ -800,9 +800,9 @@ export default class Widget extends OB { // this.purgeListeners(); // 去掉组件绑定的watcher - BI.each(this._watchers, function (i, unwatches) { - unwatches = BI.isArray(unwatches) ? unwatches : [unwatches]; - BI.each(unwatches, function (j, unwatch) { + each(this._watchers, function (i, unwatches) { + unwatches = isArray(unwatches) ? unwatches : [unwatches]; + each(unwatches, function (j, unwatch) { unwatch(); }); }); @@ -840,39 +840,39 @@ export default class Widget extends OB { } }; -BI.extend(BI, { Widget }); +extend(BI, { Widget }); let context = null, current = null; const contextStack = [], currentStack = []; -BI.Widget.pushContext = function (_context) { +Widget.pushContext = function (_context) { if (context) contextStack.push(context); - BI.Widget.context = context = _context; + Widget.context = context = _context; }; -BI.Widget.popContext = function () { - BI.Widget.context = context = contextStack.pop(); +Widget.popContext = function () { + Widget.context = context = contextStack.pop(); }; -BI.Widget.execWithContext = function (context, execFunc) { - BI.Widget.pushContext(context); +Widget.execWithContext = function (context, execFunc) { + Widget.pushContext(context); try { execFunc(); } catch (e) { throw e; } finally { - BI.Widget.popContext(); + Widget.popContext(); } }; function pushTarget(_current) { if (current) currentStack.push(current); - BI.Widget.current = current = _current; + Widget.current = current = _current; } function popTarget() { - BI.Widget.current = current = currentStack.pop(); + Widget.current = current = currentStack.pop(); } BI.useStore = function (_store) { @@ -903,7 +903,7 @@ BI.useStore = function (_store) { } current._store = function () { const st = (_store || currentStore).apply(this, arguments); - BI.extend(delegate, st); + extend(delegate, st); return st; }; return current.$storeDelegate = delegate; @@ -912,7 +912,7 @@ BI.useStore = function (_store) { BI.useContext = function (inject) { // 通过组件找最近的store - const vm = BI.Widget.findStore(BI.Widget.current || BI.Widget.context); + const vm = Widget.findStore(Widget.current || Widget.context); if (vm) { if (inject) { if (vm.$$computed && inject in vm.$$computed) { @@ -938,17 +938,17 @@ BI.useContext = function (inject) { BI.watch = function (vm, watch, handler) { // 必须要保证组件当前环境存在 - if (BI.Widget.current) { + if (Widget.current) { if (vm instanceof BI.Model) { const watchers = []; - if (BI.isKey(watch)) { + if (isKey(watch)) { const k = watch; watch = {}; watch[k] = handler; } for (const key in watch) { const innerHandler = watch[key]; - if (BI.isArray(handler)) { + if (isArray(handler)) { for (let i = 0; i < handler.length; i++) { watchers.push(Fix.watch(vm.model, key, innerHandler, { store: vm @@ -961,14 +961,14 @@ BI.watch = function (vm, watch, handler) { } } // vm中一定有_widget - BI.Widget.current._watchers || (BI.Widget.current._watchers = []); - BI.Widget.current._watchers = BI.Widget.current._watchers.concat(watchers); + Widget.current._watchers || (Widget.current._watchers = []); + Widget.current._watchers = Widget.current._watchers.concat(watchers); return; } handler = watch; watch = vm; - BI.Widget.current.$watchDelayCallbacks || (BI.Widget.current.$watchDelayCallbacks = []); - BI.Widget.current.$watchDelayCallbacks.push([watch, handler]); + Widget.current.$watchDelayCallbacks || (Widget.current.$watchDelayCallbacks = []); + Widget.current.$watchDelayCallbacks.push([watch, handler]); } }; @@ -980,7 +980,7 @@ BI.onBeforeMount = function (beforeMount) { } if (!current.beforeMount) { current.beforeMount = []; - } else if (!BI.isArray(current.beforeMount)) { + } else if (!isArray(current.beforeMount)) { current.beforeMount = [current.beforeMount]; } current.beforeMount.push(beforeMount); @@ -994,7 +994,7 @@ BI.onMounted = function (mounted) { } if (!current.mounted) { current.mounted = []; - } else if (!BI.isArray(current.mounted)) { + } else if (!isArray(current.mounted)) { current.mounted = [current.mounted]; } current.mounted.push(mounted); @@ -1004,7 +1004,7 @@ BI.onBeforeUnmount = function (beforeDestroy) { if (current) { if (!current.beforeDestroy) { current.beforeDestroy = []; - } else if (!BI.isArray(current.beforeDestroy)) { + } else if (!isArray(current.beforeDestroy)) { current.beforeDestroy = [current.beforeDestroy]; } current.beforeDestroy.push(beforeDestroy); @@ -1014,19 +1014,19 @@ BI.onUnmounted = function (destroyed) { if (current) { if (!current.destroyed) { current.destroyed = []; - } else if (!BI.isArray(current.destroyed)) { + } else if (!isArray(current.destroyed)) { current.destroyed = [current.destroyed]; } current.destroyed.push(destroyed); } }; -BI.Widget.registerRenderEngine = function (engine) { - BI.Widget._renderEngine = engine; +Widget.registerRenderEngine = function (engine) { + Widget._renderEngine = engine; }; -BI.Widget.registerRenderEngine({ +Widget.registerRenderEngine({ createElement: function (widget) { - if (BI.isWidget(widget)) { + if (isWidget(widget)) { const o = widget.options; if (o.element) { return BI.$(o.element); @@ -1048,7 +1048,7 @@ BI.mount = function (widget, container, predicate, hydrate) { // 将widget的element元素都挂载好,并建立相互关系 widget.element.data("__widgets", [widget]); const res = widget._mount(true, false, false, function (w) { - BI.each(w._children, function (i, child) { + each(w._children, function (i, child) { const ws = child.element.data("__widgets"); if (!ws) { ws = []; @@ -1059,13 +1059,13 @@ BI.mount = function (widget, container, predicate, hydrate) { predicate && predicate.apply(this, arguments); }); // 将新的dom树属性(事件等)patch到已存在的dom上 - const c = BI.Widget._renderEngine.createElement; + const c = Widget._renderEngine.createElement; BI.DOM.patchProps(widget.element, c(c(container).children()[0])); const triggerLifeHook = function (w) { w.beforeMount && w.beforeMount(); w.mounted && w.mounted(); - BI.each(w._children, function (i, child) { + each(w._children, function (i, child) { triggerLifeHook(child); }); }; @@ -1074,7 +1074,7 @@ BI.mount = function (widget, container, predicate, hydrate) { return res; } if (container) { - BI.Widget._renderEngine.createElement(container).append(widget.element); + Widget._renderEngine.createElement(container).append(widget.element); } return widget._mount(true, false, false, predicate); }; diff --git a/src/core/index.js b/src/core/index.js index 3727548fc..0b0f014c0 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -56,4 +56,6 @@ export { ResizeController, TooltipsController, StyleLoaderManager, -} \ No newline at end of file +} + +export * from './2.base'; \ No newline at end of file