UNPKG

veui

Version:

Baidu Enterprise UI for Vue.js.

1,657 lines (1,415 loc) 1.18 MB
import { get, includes as includes$1, reduce, camelCase as camelCase$1, isString, assign, isObject, isFunction, uniqueId, isPlainObject, defaults, startsWith, forEach, mapValues, compact, uniq, find as find$1, pickBy, merge as merge$1, findIndex, every, upperFirst, clone, clamp, pull as pull$1, findLastIndex, isNumber, last, remove, pick, omit, invert, difference, isEqual, isUndefined, kebabCase, zip, noop, fill, zipObject, map as map$1, mergeWith, union, cloneDeepWith, isNaN as isNaN$1, toNumber, filter as filter$1, debounce, throttle, escapeRegExp, cloneDeep, flatten, isInteger, flattenDeep, uniqBy, range, without, random, endsWith, some, repeat, flatMap, identity, intersection, padStart, times, constant, keys, entries, isEmpty as isEmpty$2, values, isNil } from 'lodash'; import Vue from 'vue'; import Popper from 'popper.js'; import FaIcon from 'vue-awesome/components/Icon'; import { getDaysInMonth, addDays, addWeeks, addMonths, addQuarters, addYears, startOfDay, startOfWeek, startOfMonth, startOfQuarter, startOfYear, format, parse } from 'date-fns'; import addMonths$1 from 'date-fns/addMonths'; import { parse as parse$1 } from 'bytes'; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function getTypedAncestorTracker(type) { var direct = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return { computed: _defineProperty({}, camelCase$1(type), function () { return getTypedAncestor(this, type, direct); }) }; } function getTypedAncestor(component, type, direct) { var current = component.$parent; while (current) { if (isType$1(current, type)) { return current; } // direct 是 boolean,那么只往上找一级 // direct 若是 vm,那么表示在这个 vm 下找 if (direct === true || current === direct) { break; } current = current.$parent; } return null; } function findAncestor(component, predicate) { var current = component.$parent; while (current) { if (predicate(current)) { return current; } current = current.$parent; } return null; } function isVueComponent(val) { return !!(val && val._isVue); } /** * 判断组件实例是否是某个类型 * * @param {Vue} vm 组件实例 * @param {string} type 类型 * @returns {boolean} 组件实例是否是指定的类型 */ function isType$1(vm, type) { return includes$1(get(vm, '$options.uiTypes', []), type); } /** * 判断组件实例是否为对 ui 机制透明 * * @param {Vue} vm 组件实例 */ function isTransparent(vm) { if (isType$1(vm, 'transparent')) { return true; } if (!vm.$vnode) { return false; } return isAbstractVNode(vm.$vnode); } /** * 判断虚拟DOM节点是否是抽象组件(transition/transition-group) * * @param {VNode} vnode 虚拟DOM节点 */ function isAbstractVNode(vnode) { var compOptions = vnode.componentOptions; return compOptions.Ctor.options.abstract || compOptions.tag === 'transition-group'; } /** * 检查组件是否是指定type或根的顶级type类型 * * @param {Vue} vm 组件实例 * @param {string} type 组件uiType * @param {string=} scopeType 指定查找的父组件uiTypes范围 * @return {boolean} 检查结果 */ function isTopMostOfType(vm, type, scopeType) { if (!isType$1(vm, type)) { return false; } else if (scopeType && isType$1(vm, scopeType)) { return true; } var current = vm.$parent; while (current && !isType$1(current, type)) { if (scopeType && isType$1(current, scopeType)) { current = null; break; } current = current.$parent; } return !current; } function getModelEvent(vm) { return get(vm, '$options.model.event', 'input'); } /** * 表单中空输入 * * @param {*} val 输入值 * @return {boolean} 是否空输入 */ function isEmpty$1(val) { return val == null || val === '' || Array.isArray(val) && !val.length; } // See https://github.com/vuejs/vue/blob/dev/src/platforms/web/util/style.js function parseStyleText(cssText) { var res = {}; var listDelimiter = /;(?![^(]*\))/g; var propertyDelimiter = /:(.+)/; cssText.split(listDelimiter).forEach(function (item) { if (item) { var tmp = item.split(propertyDelimiter); tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim()); } }); return res; } function parseClassName(className) { return className.split(/\s+/).filter(Boolean).reduce(function (acc, cur) { acc[cur] = true; return acc; }, {}); } function normalizeBindings(bindings, parse) { if (isString(bindings)) { return parse(bindings); } var result = {}; if (Array.isArray(bindings)) { bindings.forEach(function (binding) { assign(result, normalizeBindings(binding, parse)); }); } else if (isObject(bindings)) { assign(result, bindings); } return result; } /** * 统一将 string/object/array 形式的 class 转换成 object * @param {string | Array<string | Object> | Object<string, boolean>} klasses 待归一化的类表达式 * @return {Object<string, boolean>} object 形式的类表达式 */ function normalizeClass() { for (var _len = arguments.length, klasses = new Array(_len), _key = 0; _key < _len; _key++) { klasses[_key] = arguments[_key]; } return normalizeBindings(klasses, parseClassName); } /** * 统一将 string/object/array 形式的 class 转换成 object * @param {string | Array<string | Object> | Object<string, boolean>} styles 待归一化的样式表达式 * @return {Object<string, string>} object 形式的样式表达式 */ function normalizeStyle() { for (var _len2 = arguments.length, styles = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { styles[_key2] = arguments[_key2]; } return normalizeBindings(styles, parseStyleText); } function getConfigKey(name) { return name.replace(/^veui|-*/gi, '').toLowerCase(); } /** * Just transparently pass to Vue itself * we don't need to perform any additional check here */ var LOOSE_PROP_DEF = { default: null }; var RE_INDEX = /\d+/; function deepSet(obj, path, val) { var segments = path.split(/[[\].]/).map(function (s) { return s.match(RE_INDEX) ? Number(s) : s; }).filter(function (s) { return s !== ''; }); var context = obj; segments.forEach(function (s, index) { if (index === segments.length - 1) { Vue.set(context, s, val); return; } if (!(s in context)) { if (typeof segments[index + 1] === 'number') { Vue.set(context, s, []); } else { Vue.set(context, s, {}); } } context = context[s]; }); } var RE_NUMBER = /^-?(?:\d*(?:\.\d+)?|\.\d+)$/; function normalizeLength(val) { if (!val) { return null; } if (typeof val === 'number' || typeof val === 'string' && RE_NUMBER.test(val)) { return Number(val) !== 0 ? "".concat(val, "px") : null; } return val; } /** * 将输入值转化为对应整数,如果值非整数则返回 null * * @param {string|number} val 输入值 * @returns {?number} 转换后的整数数值 */ function normalizeInt(val) { var value = parseInt(val, 10); return isNaN(value) ? null : value; } var pxRe = /px$/; var percentRe = /%$/; function resolveOffset(val, base) { if (val == null || typeof base !== 'number' || isNaN(base)) { return 0; } var result = val; if (isString(val)) { if (pxRe.test(val)) { result = val.replace(pxRe, ''); } else if (percentRe.test(val)) { val = +val.replace(percentRe, '') / 100; result = base * val; } } result = Number(result); return isNaN(result) ? 0 : result; } function ignoreElements(names) { names = [].concat(names); names.forEach(function (name) { if (Vue.config.ignoredElements.indexOf(name) === -1) { Vue.config.ignoredElements.push(name); } }); } function getScopeAttrs(el) { return _toConsumableArray(el.attributes).map(function (attr) { return attr.nodeName; }).filter(function (name) { return name.indexOf('data-v-') === 0; }); } function inheritScopeAttrs(el, parent) { var attrs = getScopeAttrs(parent); var patched = []; attrs.forEach(function (attr) { if (!el.hasAttribute(attr)) { el.setAttribute(attr, ''); patched.push(attr); } }); return function removeInheritedScopeAttrs() { patched.forEach(function (attr) { return el.removeAttribute(attr); }); }; } function createPortal(el, target) { var parent = el.parentNode; // create a connection to the portal entrance // v-outside will honor this connection, so we'd // better document this somewhere properly (TODO) el.__portal__ = parent; var restore = inheritScopeAttrs(el, parent); target.appendChild(el); var removePortal = function removePortal() { delete el.__portal__; restore(); parent.appendChild(el); }; return removePortal; } function renderSlot(vm, name) { var props = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; return vm.$slots[name] || (vm.$scopedSlots[name] ? vm.$scopedSlots[name](props) : null) || null; } var Void = { render: function render(h) { return h(); } }; function forwardSlots(slots, vm) { var $scopedSlots = vm.$scopedSlots, $slots = vm.$slots, h = vm.$createElement; return reduce(slots, function (result, to, from) { if ($slots[from]) { result.slots.push(h('template', { slot: to }, $slots[from])); } else if ($scopedSlots[from]) { result.scopedSlots[to] = function (props) { return $scopedSlots[from](props); }; } return result; }, // JSX 中: // 1. scopedSlots 作为 props 传递,数据类型是: { name: props => slotContent } // 2. slots 作为 children 传递,数据类型是:[<template slot="name">slotContent</template>, ...] { scopedSlots: {}, slots: [] }); } var LOW_SURROGATE = /[\uD800-\uDBFF]/; function safeSlice(str, length) { if (str.length > length) { while (length--) { if (!LOW_SURROGATE.test(str[length])) { break; } } return str.slice(0, length + 1); } return str; } // 避免 vue invoke handler 导致的无限递归 function wrapListeners(listeners) { return reduce(listeners, function (acc, listener, key) { acc[key] = Array.isArray(listener) ? listener : [listener]; return acc; }, {}); } function renderTpl(message, data, compat) { var re = compat ? /\$?\{(\w+)\}/g : /\{(\w+)\}/g; return String(message).replace(re, function (match, key) { if (data[key] != null) { return data[key]; } return match; }); } function pull(array, target) { var index = array.indexOf(target); if (index >= 0) { array.splice(index, 1); } } function getEnumValidator(values) { return function validator(val) { return val == null || values.indexOf(val) >= 0; }; } function warn(message, vm) { { Vue.util.warn(message, vm); } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } var I18nManager = /*#__PURE__*/function () { function I18nManager() { _classCallCheck(this, I18nManager); _defineProperty(this, "store", new Vue({ data: { locale: 'zh-Hans' , store: {} }, methods: { register: function register(locale, data) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var key = options.ns ? "".concat(locale, ".").concat(options.ns) : "".concat(locale); deepSet(this.store, key, data); }, get: function get$1(path) { var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var locale = arguments.length > 2 ? arguments[2] : undefined; if (isString(data)) { // overloading get (path, locale) locale = data; } var key = "".concat(locale || this.locale, ".").concat(path); var message = get(this.store, key); if (!isString(message)) { return message; } return renderTpl(message, data); }, watch: function watch(path, callback, locale) { var _this = this; return this.$watch(function () { return _this.get(path, locale); }, function (val) { if (isFunction(callback)) { callback(val); } }); } } })); _defineProperty(this, "_locale", 'zh-Hans'); } _createClass(I18nManager, [{ key: "locale", get: function get() { return this.store.locale; }, set: function set(val) { if (val === this.store.locale) { return; } if (!this.store.store[val]) { warn("[veui-i18n] Locale `".concat(val, "` not found. Please register locale data before use.")); } this.store.locale = val; } }, { key: "register", value: function register(locale, data, options) { this.store.register(locale, data, options); } }, { key: "get", value: function get(path, data, locale) { return this.store.get(path, data, locale); } }, { key: "watch", value: function watch(path, callback, locale) { return this.store.watch(path, callback, locale); } }]); return I18nManager; }(); var i18nManager = new I18nManager(); function ownKeys$19(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$19(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$19(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$19(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } var CommonProviderImpl = { name: 'veui-provider', // for better readability in devtools uiTypes: ['transparent'], props: { // eslint-disable-next-line vue/require-prop-types value: {} }, render: function render() { return this.$slots.default; } }; function createContext(name, defaultValue) { var realName = name ? "".concat(name, "-provider") : CommonProviderImpl.name; var contextId = "__".concat(uniqueId(realName)); var RealProviderImpl = _objectSpread$19(_objectSpread$19({}, CommonProviderImpl), {}, { name: realName, inject: _defineProperty({}, contextId, { from: contextId, default: function _default() { return function () { return undefined; }; } }), provide: function provide() { var _this = this; return _defineProperty({}, contextId, function () { var parentContextValue = _this[contextId](); if (isPlainObject(parentContextValue) && isPlainObject(_this.value) // provide 的值时函数,最后在消费方的 computed 调用,这样保证最终值依赖每个 provider 的 this.value ) { return defaults({}, _this.value, parentContextValue); // 每层 provider 都会和上一层的值合并 } // 无法合并,则以最近的 provider 为准 return _this.value; }); } }); var Provider = { functional: true, // 这里实际上接受一个 value prop,用来传递 context,但是因为直接透传给 ProviderImpl,所以不用声明了 render: function render(h, context) { return wrapChildren(h, context, RealProviderImpl); } }; var useConsumer = function useConsumer(injectionKey) { return { inject: _defineProperty({}, contextId, { from: contextId, default: function _default() { return function () { return undefined; }; } }), computed: _defineProperty({}, injectionKey, function () { if (defaultValue) { defaultValue = typeof defaultValue === 'function' ? defaultValue() : defaultValue; // 消费方获取 context 值时和初始值做合并 return defaults({}, this[contextId](), defaultValue); } return this[contextId](); }) }; }; var Consumer = _objectSpread$19(_objectSpread$19({}, useConsumer('context')), {}, { render: function render() { return this.$scopedSlots.default(this.context); } }); return { Provider: Provider, Consumer: Consumer, useConsumer: useConsumer }; } function wrapChildren(h, _ref2, Provider) { var data = _ref2.data, children = _ref2.children; var value = data.attrs ? data.attrs.value : undefined; return children.map(function (child) { return h(Provider, { attrs: { value: value } // 分开避免相互影响 }, [child]); }); } var ConfigManager = /*#__PURE__*/function () { function ConfigManager() { _classCallCheck(this, ConfigManager); _defineProperty(this, "store", new Vue({ data: { store: {}, watchers: {} }, methods: { setConfig: function setConfig(obj, key, val, ns, override) { var _this = this; if (isObject(key)) { ns = val; val = key; Object.keys(val).forEach(function (k) { _this.setConfig(obj, k, val[k], ns, override); }); return; } if (typeof key !== 'string') { throw new Error('`Config key must be a string value.'); } var k = ns ? "".concat(ns, ".").concat(key) : key; if (!(k in obj) || override) { this.setConfigItem(obj, k, val); } }, setConfigItem: function setConfigItem(obj, key, val) { var _this2 = this; this.$set(obj, key, val); var relatedWatcherKeys = Object.keys(this.watchers).filter(function (k) { return startsWith(k, key); }); relatedWatcherKeys.forEach(function (watcherKey) { return _this2.unwatch(watcherKey); }); this.transformValue(obj, key, null); }, // 为了 @@xxx 和 i18n 配置联动起来 transformValue: function transformValue(context, key, path) { var _this3 = this; if (!context || context._isVue || context._Ctor) { return; } var watcherKey = path ? "".concat(path, ".").concat(key) : key; var val = context[key]; var watcher = this.watchers[watcherKey]; if (typeof val === 'string') { if (startsWith(val, '@@')) { var i18nKey = val.substring(2); if (watcher && watcher.key !== i18nKey) { // already watched another i18n key before, unwatch it watcher.unwatch(); } this.watchers[watcherKey] = { key: i18nKey, unwatch: i18nManager.watch(i18nKey, function (val) { context[key] = val; }) }; context[key] = i18nManager.get(i18nKey); } } else if (isObject(val) || Array.isArray(val)) { // recursively replace pointers forEach(val, function (_, k) { _this3.transformValue(val, k, watcherKey); }); } }, unwatch: function unwatch(key) { var watcher = this.watchers[key]; if (watcher) { watcher.unwatch(); delete this.watchers[key]; } }, set: function set(key, val, ns) { this.setConfig(this.store, key, val, ns, true); }, defaults: function defaults(key, val, ns) { this.setConfig(this.store, key, val, ns, false); }, get: function get(key) { return this.store[key]; } } })); } _createClass(ConfigManager, [{ key: "set", value: function set(key, val, ns) { this.store.set(key, val, ns); } }, { key: "defaults", value: function defaults(key, val, ns) { this.store.defaults(key, val, ns); } }, { key: "get", value: function get(path) { return this.store.get(path); } }, { key: "getAll", value: function getAll() { return this.store.store; } }]); return ConfigManager; }(); var config = new ConfigManager(); var configContext = createContext('veui-context', function () { return config.getAll(); }); var config$1 = config; var ui$1 = new ConfigManager(); function ownKeys$18(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$18(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$18(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$18(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } var UNKNOWN_KEY = '$unknown'; var DEFAULT_VAL = '__default__'; function callWithProps(val, props) { if (typeof val === 'function') { return val(props); } return val; } function useUi() { return { props: { ui: String }, computed: { uiParts: function uiParts() { var _this = this; var parts = this.getComponentConfig('parts') || {}; return mapValues(parts, function (ui) { return callWithProps(ui, _this.uiProps); }); }, declaredUiProps: function declaredUiProps() { var _this2 = this; var ui = (this.ui || '').trim(); var tokens = compact(uniq(ui.split(/\s+/))); var _this$uiConfig = this.uiConfig, uiConfig = _this$uiConfig === void 0 ? {} : _this$uiConfig; return tokens.reduce(function (result, token) { var name = find$1(Object.keys(uiConfig), function (name) { var _uiConfig$name = uiConfig[name], _uiConfig$name$boolea = _uiConfig$name.boolean, boolean = _uiConfig$name$boolea === void 0 ? false : _uiConfig$name$boolea, _uiConfig$name$values = _uiConfig$name.values, values = _uiConfig$name$values === void 0 ? [] : _uiConfig$name$values; if (boolean) { return token === name; } return includes$1(values, token); }); if (name) { if (result[name] && result[name] !== DEFAULT_VAL && result[name] !== uiConfig[name].default) { warn("[".concat(_this2.$options.name, "] Duplicated `").concat(name, "` value for `ui`: [").concat(result[name], "], [").concat(token, "].")); } var boolean = uiConfig[name].boolean; if (boolean) { result[name] = true; } else { result[name] = token; } } else { result[UNKNOWN_KEY].push(token); } return result; }, _defineProperty({}, UNKNOWN_KEY, [])); }, defaultUiProps: function defaultUiProps() { var _this$uiConfig2 = this.uiConfig, uiConfig = _this$uiConfig2 === void 0 ? {} : _this$uiConfig2; return Object.keys(uiConfig).reduce(function (result, name) { result[name] = null; var prop = uiConfig[name]; if (prop.boolean) { result[name] = false; } else { result[name] = prop.default || DEFAULT_VAL; } return result; }, {}); }, inheritableUiProps: function inheritableUiProps() { var _this3 = this; if (!this.uiConfig) { return this.uiProps; } return pickBy(this.uiProps, function (val, key) { var uiProp = _this3.uiConfig[key]; return val !== DEFAULT_VAL && uiProp && uiProp.inherit; }); }, uiProps: function uiProps() { var _ref = findAncestor(this, function (component) { return !isTransparent(component); }) || {}, _ref$inheritableUiPro = _ref.inheritableUiProps, inheritableUiProps = _ref$inheritableUiPro === void 0 ? {} : _ref$inheritableUiPro; return _objectSpread$18(_objectSpread$18(_objectSpread$18({}, this.defaultUiProps), inheritableUiProps), this.declaredUiProps); }, uiConfig: function uiConfig() { return this.getComponentConfig('ui'); }, uiData: function uiData() { var _this$uiConfig3 = this.uiConfig, uiConfig = _this$uiConfig3 === void 0 ? {} : _this$uiConfig3, uiProps = this.uiProps; return Object.keys(uiProps).filter(function (name) { return name !== UNKNOWN_KEY; }).reduce(function (result, name) { var data = get(uiConfig[name], ['data', uiProps[name]], {}); merge$1(result, data); return result; }, {}); }, icons: function icons() { var _this4 = this; var icons = this.getComponentConfig('icons'); if (typeof icons === 'function') { return icons(this.uiProps); } var uiIcons = this.uiData.icons || {}; return mapValues(_objectSpread$18(_objectSpread$18({}, icons), uiIcons), function (ui) { return callWithProps(ui, _this4.uiProps); }); }, illustrations: function illustrations() { var illustrations = this.getComponentConfig('illustrations'); if (typeof illustrations === 'function') { return illustrations(this.uiProps); } return illustrations; }, realUi: function realUi() { var props = this.uiProps; return uniq(Object.keys(props).map(function (key) { if (props[key] === true) { return key; } return key === UNKNOWN_KEY ? null : props[key]; }).filter(function (val) { return val && val !== DEFAULT_VAL && val !== false; }).concat(this.declaredUiProps[UNKNOWN_KEY])).join(' ') || null; } }, methods: { getComponentConfig: function getComponentConfig(key) { return ui$1.get("".concat(getConfigKey(this.$options.name), ".").concat(key)); } } }; } var ui = useUi(); function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function isVnode(vnode) { return isObject(vnode) && vnode.componentOptions; } /** * 判断是否指定值是否能够传入 getNodes 以获取 DOM nodes 。 * * @param {string|Vue|Node|Array<string>|Array<Vue>|Array<Node>} v 待判断的值 * @return {boolean} */ function isValidNodesResolver(v) { function isValid(item) { return isString(item) || item.$vnode || includes$1([1, 3], item.nodeType) || isVnode(item); } return isValid(v) || Array.isArray(v) && every(v, isValid); } /** * 根据ref拿到指定的DOM节点,主要有一下情况: * 1、如果ref是字符串,就需要从context下面找指定ref的组件实例或者DOM元素; * 2、如果ref直接就是组件实例,那就取ref.$el; * 3、如果ref直接就是文本节点或者元素节点,就返回ref。 * 4、否则返回空数组 * * @param {string|Vue|Node|Array<string>|Array<Vue>|Array<Node>} ref 目标节点标识 * @param {VueContext=} context 组件上下文,在ref为字符串的时候必传 * @return {Node} */ function getNodes(ref, context) { var vnodes = getVnodes(ref, context); return vnodes.map(function (item) { if (isVnode(item)) { return item.elm; } return item; }); } function getVnodes(ref, context) { if (!ref) { return []; } var vnodes; if (isString(ref)) { vnodes = context.$refs[ref]; if (!vnodes) { vnodes = []; } else { vnodes = Array.isArray(vnodes) ? vnodes : [vnodes]; } vnodes = vnodes.filter(Boolean).map(function (item) { return item.$vnode || item; }); } else { ref = Array.isArray(ref) ? ref : [ref]; vnodes = ref.map(function (item) { if (item.$vnode) { return item.$vnode; } else if (isVnode(item) || item.nodeType === 1 || item.nodeType === 3) { // vnode节点、dom元素节点和文本节点 return item; } }); } return vnodes; } /** * 获取与当前组件最接近的给定类型的祖先组件中,当前组件在其第几个直接子节点的位置 * @param {Vue} current 查找的组件实例 * @param {string|Vue} parentType 父级类型 * @returns {number} 该实例所在位置的索引,找不到返回 -1 */ function getIndexOfType(current, parentType) { var parent = parentType ? typeof parentType === 'string' ? getTypedAncestor(current, parentType) : parentType : current.$parent; if (parentType && !parent) { throw new Error("No ancestor typed as [".concat(parentType, "] found.")); } var parentVnodes = parent.$slots.default; if (parentVnodes) { parentVnodes = (Array.isArray(parentVnodes) ? parentVnodes : [parentVnodes]).filter(function (_ref) { var tag = _ref.tag; return !!tag; }); } while (current.$parent !== parent) { current = current.$parent; } var currentVnode = getVnodes(current)[0]; // 只是用于每次渲染时插入到当前位置的顺序 return findIndex(parentVnodes, function (vnode) { return vnode === currentVnode; }); } /** * 查找该组件的子孙组件中第一个有某个方法的组件实例,深度优先 * @param {Vue} context 查找的组件实例,即从 context.$children 开始查找 * @param {function(Vue): boolean} predicate 判断这个组件是否匹配 * @returns {?Vue} 找到的组件 */ function findComponent(context, predicate) { var comp = null; function walkChildren(children) { return children.some(function (i) { var match = predicate(i); if (match) { comp = i; } else if (i.$children && i.$children.length) { return walkChildren(i.$children); } return !!match; }); } walkChildren(context.$children || []); return comp; } /** * 给 targets 中的每个函数的第一个参数绑定为 vm,一般用于给 mixin 传递依赖时使用 * * @param {object} targets 需要被绑定的对象 * @param {Vue} vm vm实例 * @return object 绑定后的新对象 */ function bindVm(targets, vm) { return Object.keys(targets).reduce(function (acc, depName) { acc[depName] = typeof targets[depName] === 'function' ? function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return targets[depName].apply(targets, [vm].concat(args)); } : targets[depName]; return acc; }, {}); } function ownKeys$17(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$17(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$17(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$17(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } var DEFAULT_CHILDREN_KEY = 'children'; function walk$1(array, callback) { var alias = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_CHILDREN_KEY; var context = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; return _walk(array, callback, _objectSpread$17(_objectSpread$17({}, context), {}, { depth: 0, parents: [], parentIndices: [] }), alias); } function _walk(array, callback, context) { var alias = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : DEFAULT_CHILDREN_KEY; if (!array || !callback) { return; } var enter; var exit; if (typeof callback === 'function') { enter = callback; } else { enter = callback.enter; exit = callback.exit; } if (!enter && !exit) { return; } if (!Array.isArray(array)) { array = getChildrenByAlias(array, alias); if (!array) { return; } } var depth = context.depth, parents = context.parents, parentIndices = context.parentIndices; var result = []; array.forEach(function (item, index) { var _skip = false; var replaced = item; var settedContext = null; var selfContext = _objectSpread$17(_objectSpread$17({}, context), {}, { index: index, skip: function skip() { _skip = arguments.length ? !!(arguments.length <= 0 ? undefined : arguments[0]) : true; }, // 如果被 walk 的对象是可以修改的,可以直接修改 // 但是比如是 datasource prop,就只能用 replace 了 replace: function replace(newItem) { replaced = newItem; }, setContext: function setContext(context) { settedContext = context; } }); if (typeof enter === 'function') { enter(item, selfContext); } var children = _skip ? null : getChildrenByAlias(replaced, alias); if (children) { selfContext.childrenResult = _walk(children, callback, _objectSpread$17(_objectSpread$17(_objectSpread$17({}, context), settedContext), {}, { parents: [].concat(_toConsumableArray(parents), [replaced]), parentIndices: [].concat(_toConsumableArray(parentIndices), [index]), depth: depth + 1 }), alias); } if (typeof exit === 'function') { // 此时 exit 可以拿到 selfContext.childrenResult result.push(exit(replaced, selfContext)); } }); return result; } function find(array, predicate) { var alias = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_CHILDREN_KEY; var parents = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; if (!array || typeof predicate !== 'function') { return null; } var result = null; array.some(function (item) { if (predicate(item, parents)) { result = item; return true; } var children = getChildrenByAlias(item, alias); if (!children) { return false; } var inner = find(children, predicate, alias, [].concat(_toConsumableArray(parents), [item])); if (inner !== null) { result = inner; return true; } }); return result; } function findParents(array, predicate) { var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, _ref$alias = _ref.alias, alias = _ref$alias === void 0 ? DEFAULT_CHILDREN_KEY : _ref$alias, _ref$includeSelf = _ref.includeSelf, includeSelf = _ref$includeSelf === void 0 ? false : _ref$includeSelf; var parents = []; var self = find(array, function (item, pts) { var match = !!predicate(item); if (match) { parents = pts; } return match; }, alias); return self == null ? null : includeSelf ? parents.concat(self) : parents; } function getChildrenByAlias(obj, alias) { var keys = typeof alias === 'string' ? [alias] : alias; var key = find$1(keys, function (key) { return Array.isArray(obj[key]); }); return key ? obj[key] : null; } function mapDatasource(datasource, callback) { var childrenKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_CHILDREN_KEY; var isExit = typeof callback === 'function'; var enter = isExit ? null : callback.enter; var _exit = isExit ? callback : callback.exit; return walk$1(datasource, _objectSpread$17(_objectSpread$17({}, enter ? { enter: enter } : null), {}, { exit: function exit(item, context) { return _objectSpread$17(_objectSpread$17({}, _exit(item, context)), hasChildren(item, childrenKey) ? _defineProperty({}, childrenKey, context.childrenResult) : {}); } }), childrenKey); } function hasChildren(item) { var childrenKey = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : DEFAULT_CHILDREN_KEY; return !!item[childrenKey] && item[childrenKey].length !== 0; } function getLeaves$1(root, childrenKey) { return getDescendants(root, function (descendant) { return { keep: hasChildren(descendant, childrenKey) ? false : 'value' }; }, childrenKey); } function getGroupDescendants(root, childrenKey) { return getDescendants(root, function (descendant) { return { keep: hasChildren(descendant, childrenKey) ? 'value' : false }; }, childrenKey); } /** * 获取后代节点的值 * @param {object} root 父节点 * @param {Function} visit 控制如何获取后代节点的值,签名: (root, context) => ({keep, skipChildren}) * keep 为 false 表示不获取该节点的值,为 string 表示值对应的字段名 * skipChildren 为 boolean,表示是否跳过该节点之下的后代 * @param {string} childrenKey 子项的字段名 * @return {Array} 获取到的后代节点的值 */ function getDescendants(root, visit) { var childrenKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_CHILDREN_KEY; var result = []; if (typeof visit === 'string') { childrenKey = visit; visit = null; } walk$1(root, function (child, context) { var _ref4 = typeof visit === 'function' ? visit(child, context) : {}, _ref4$keep = _ref4.keep, keep = _ref4$keep === void 0 ? 'value' : _ref4$keep, skipChildren = _ref4.skipChildren; if (keep && child[keep] !== undefined) { result.push(child[keep]); } context.skip(!!skipChildren); }, childrenKey); return result; } function ownKeys$16(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$16(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$16(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$16(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function useParent$1(type, childrenType) { var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, _ref$childrenKey = _ref.childrenKey, childrenKey = _ref$childrenKey === void 0 ? 'items' : _ref$childrenKey, onBeforeRemoveChild = _ref.onBeforeRemoveChild; return { uiTypes: [type], data: function data() { return { coupled_children__: [] }; }, computed: _defineProperty({}, childrenKey, function () { return this.coupled_children__.map(function (_ref2) { var coupledProxy = _ref2.coupledProxy; return _objectSpread$16({}, coupledProxy); }); }), methods: { addChild: function addChild(child) { this.coupled_children__.push(child); }, removeChildById: function removeChildById(id) { var index = this.findChildIndexById(id); if (typeof this[onBeforeRemoveChild] === 'function') { this[onBeforeRemoveChild](id); } this.removeChildByIndex(index); return index; }, removeChildByIndex: function removeChildByIndex(index) { this.coupled_children__.splice(index, 1); }, findChildById: function findChildById(id) { return this.coupled_children__[this.findChildIndexById(id)]; }, findChildIndexById: function findChildIndexById(id) { return findIndex(this.coupled_children__, function (child) { return child.childId === id; }); }, getSortedItems: function getSortedItems() { var columns = this.coupled_children__; // 因为 slot 重新渲染会更新 $slot.default, 但是可能还没有导致子组件重新,所以子组件 vm.$vnode 还是引用老的vnode // 此时会找到 -1, 那么可以直接跳过本次,后续的 updated 再来排序 if (columns[0] && getIndexOfType(columns[0], this) === -1) { return columns; } var sorted = []; // 深度优先遍历,按找到 Column 的顺序直接 push 到 sorted 数组中去即可 walk$1(this.$slots.default, createVnodeWalker(sorted, childrenType)); return sorted; } }, updated: function updated() { var prevSorted = this.coupled_children__; var newSorted = this.getSortedItems(); // 判断是否存在顺序不一致,没有则不要设置,否则死循环 if (isDiff(prevSorted, newSorted)) { this.coupled_children__ = newSorted; } }, beforeDestroy: function beforeDestroy() { this.__coupled_destroying__ = true; } }; } function isDiff(prevSorted, newSorted) { return prevSorted !== newSorted && (prevSorted.length !== newSorted.length || newSorted.some(function (_ref3, index) { var childId = _ref3.childId; return childId !== prevSorted[index].childId; })); } function createVnodeWalker(sorted, childrenType) { var callback = function callback(vnode, _ref4) { var skip = _ref4.skip; var tag = vnode.tag, vm = vnode.componentInstance; if (vm) { var uiTypes = vm.$options.uiTypes; if (uiTypes && uiTypes.indexOf(childrenType) >= 0) { sorted.push(vm); } else { // 只能用 _vnode 了,且必须用数组包起来,因为 _vnode 可能还是组件,而没有 children,不能直接 walk // 穿透非 Column 的组件去继续找 walk$1([vm._vnode], callback); } // skip children skip(); } else { skip(!tag); } }; return callback; } /* ## fields [ 'columns', ['fixed', 'realFixed'], ['hasFoot', vm => () => !!(vm.$scopedSlots.foot || vm.$slots.foot)] }] */ function useChild(type, parentType, fields) { var _computed2; var _ref5 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}, _ref5$direct = _ref5.direct, direct = _ref5$direct === void 0 ? false : _ref5$direct; var parentKey = camelCase$1(parentType); return { uiTypes: [type], data: function data() { return { slotReactiveHelpers__: fields.reduce(function (slots, field) { if (Array.isArray(field) && field.length === 3) { // eslint-disable-next-line no-unused-vars var _field = _slicedToArray(field, 3); _field[0]; var mapper = _field[1], slotName = _field[2]; if (typeof mapper === 'function') { slots[slotName] = true; } } return slots; }, {}) }; }, computed: (_computed2 = {}, _defineProperty(_computed2, parentKey, function () { return getTypedAncestor(this, parentType, direct); }), _defineProperty(_computed2, "coupledProxy", function coupledProxy() { var _this = this; if (!Array.isArray(fields)) { throw new Error('[veui-coupled-child] `fields` must be an array.'); } return fields.reduce(function (proxy, field) { if (typeof field === 'string') { proxy[field] = _this[field]; } else if (Array.isArray(field) && field.length >= 2) { var _field2 = _slicedToArray(field, 3), key = _field2[0], mapper = _field2[1], slotName = _field2[2]; if (typeof mapper === 'string') { proxy[key] = _this[mapper]; } else if (typeof mapper === 'function') { var fn = mapper(_this); proxy[key] = slotName ? function () { // 通过访问响应式变量,让所有依赖的slots的地方得到通知 // eslint-disable-next-line no-void, space-unary-ops void _this.slotReactiveHelpers__[slotName]; return fn.apply(void 0, arguments); } : fn; } else { throw new Error('[veui-coupled-child] `fields` mapper must either be a string or a function'); } } else { throw new Error('[veui-coupled-child] `fields` item must either be a string, or a tuple of length 2 or 3.'); } return proxy; }, { id: this.childId }); }), _computed2), created: function created() { var parent = this[parentKey]; if (!parent) { return; } this.childId = uniqueId("veui-".concat(type, "-")); parent.addChild(this); }, updated: function updated() { var _this2 = this; var prevSlots = this._prevScoped || {}; Object.keys(this.slotReactiveHelpers__).forEach(function (slotName) { if (prevSlots[slotName] !== _this2.$scopedSlots[slotName]) { _this2.triggerSlotChange(slotName); } }); this._prevScoped = _objectSpread$16({}, this.$scopedSlots); }, methods: { triggerSlotChange: function triggerSlotChange(slotName) { // toggle 变量,触发更新 this.slotReactiveHelpers__[slotName] = !this.slotReactiveHelpers__[slotName]; } }, destroyed: function destroyed() { var parent = this[parentKey]; if (!parent || parent.__coupled_destroying__) { return; } parent.removeChildById(this.childId); } }; } function prefixify(name) { return "".concat('veui' , "-").concat(name); } var prefix = { methods: { $c: prefixify } }; function ownKeys$15(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$15(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$15(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$15(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } var options$1 = { methods: { isControlled: function isControlled(prop) { return _isControlled(this, prop); }, // 使用方法而非直接赋值:受控时赋值并未直接生效,而仅仅 emit 事件而已,直接让使用方使用赋值违反直觉 // commit 可以额外的给事件传递更多的参数 commit: function commit(prop, value) { var def = find$1(this._controlledProps, function (i) { return i.prop === prop; }); if (def) { for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } computedSetter.apply(void 0, [this, value, def].concat(args)); return; } throw new Error("[controllable] Unkown prop key: '".concat(prop, "' on committing.")); } } }; var errorMsg = '[controllable] prop config must be either a string, an object or an object array.'; /** * 自动将对应的 prop 转换成受控的 * @param {string|Object|[string|Object]} props - 定义的受控props * @return 转换后的 mixin */ function useControllable(p