define(['exports', 'axios', 'qs', 'lodash', 'jquery', 'recast', 'lay-excel', 'xlsx'], function (exports, axios, Qs, _, $$1, recast, LAY_EXCEL, XLSX) { 'use strict'; var axios__default = 'default' in axios ? axios['default'] : axios; Qs = Qs && Object.prototype.hasOwnProperty.call(Qs, 'default') ? Qs['default'] : Qs; _ = _ && Object.prototype.hasOwnProperty.call(_, 'default') ? _['default'] : _; $$1 = $$1 && Object.prototype.hasOwnProperty.call($$1, 'default') ? $$1['default'] : $$1; LAY_EXCEL = LAY_EXCEL && Object.prototype.hasOwnProperty.call(LAY_EXCEL, 'default') ? LAY_EXCEL['default'] : LAY_EXCEL; XLSX = XLSX && Object.prototype.hasOwnProperty.call(XLSX, 'default') ? XLSX['default'] : XLSX; var labelWidth = 80; var windows = { modal: true, width: 900, height: 600, maximizable: true, constrain: true, shadow: false, }; var date = { labelAlign: 'right', labelWidth: labelWidth, }; var combo = { labelAlign: 'right', labelWidth: labelWidth, valueField: 'id', displayField: 'text', autoLoad: true, mode: 'local', forceSelection: true, triggerAction: 'all', enableKeyEvents: true, }; var comboGrid = { selectOnTab: true, pickerHeight: 500, pickerWidth: 850, editEnable: null, }; var comboGridPicker = { xtype: 'yvgrid', layout: 'fit', selModel: { selType: 'rowmodel', mode: 'SINGLE' }, }; var comboGridMulti = { selectOnTab: true, pickerHeight: 500, pickerWidth: 850, editEnable: null, splitChar: ',', displayField: 'text', valueField: 'id', autoLoad: true, }; var comboGridMultiPicker = { selType: 'checkboxmodel', selModel: { type: 'checkboxmodel', checkOnly: false }, }; var numberfield = { labelAlign: 'right', decimalPrecision: 6, labelWidth: labelWidth, }; var checkbox = { labelAlign: 'right', labelWidth: labelWidth, checkedValue: true, uncheckedValue: false, }; var checkboxgroup = { labelAlign: 'right', labelWidth: labelWidth, }; var radio = { labelAlign: 'right', labelWidth: labelWidth, }; var radiogroup = { labelAlign: 'right', labelWidth: labelWidth, simpleValue: true, layout: 'hbox', defaults: { xtype: 'radio', name: 'type', margin: '0 15 0 0' }, }; var form = { margin: '5 5 0 0', border: false, defaults: { margin: '0 0 5 0', border: false, }, }; var column = { filter: { type: 'string' }, }; var grid = { border: true, columnLines: true, rowLines: true, plugins: { cellediting: { clicksToEdit: 1, }, gridfilters: true }, multiColumnSort: true, viewConfig: { enableTextSelection: true, sortOnClick: false, emptyText: '没有数据' }, selModel: { type: 'checkboxmodel', checkOnly: false }, pagination: true, pageSize: 50, pageSizeOption: ['20', '50', '100', '200', '300', '500', '1000'], hideFootbar: false, hideRefresh: false, hideExport: false, hideAutoSize: false, hideClearFilter: false, hideSaveGridUIConfig: false, hideClearGridUIConfig: false, autoLoad: true, remoteSort: false, remoteFilter: false, enableLocking: true, syncRowHeight: false, enableColumnMove: true, enableColumnHide: true, enableColumnResize: true, hidden: false, disabled: false, exportExcelPageSize: 100, exportExcelCurrentPage: 1, exportExcelTotal: 0, }; var fieldContainer = { labelAlign: 'right', labelWidth: labelWidth, layout: 'hbox', defaults: { flex: 1, } }; var tree = { autoLoad: true, hideFilter: false, hideToolbar: false, hideRefresh: false, hideExpand: false, hideCollapse: false, }; var search = { labelAlign: 'right', labelWidth: labelWidth, }; var text = { labelAlign: 'right', labelWidth: labelWidth, msgTarget: 'qtip', }; var toolbar = { overflowHandler: 'menu', }; var tbfill = {}; var tbseparator = {}; var button = {}; var fieldSet = { margin: '5 5 0 0', border: false, defaults: { margin: '0 0 5 0', border: false, }, }; var storeAjax = { timeout: 60000 }; var panel = {}; var splitter = {}; var maintab = {}; var rows = {}; var cols = { defaults: { flex: 1 }, }; var bpmn = { hideRefresh: false, autoLoad: true, dataSource: '', bpmnConfig: {} }; var Defaults = /*#__PURE__*/Object.freeze({ __proto__: null, windows: windows, date: date, combo: combo, comboGrid: comboGrid, comboGridPicker: comboGridPicker, comboGridMulti: comboGridMulti, comboGridMultiPicker: comboGridMultiPicker, numberfield: numberfield, checkbox: checkbox, checkboxgroup: checkboxgroup, radio: radio, radiogroup: radiogroup, form: form, column: column, grid: grid, fieldContainer: fieldContainer, tree: tree, search: search, text: text, toolbar: toolbar, tbfill: tbfill, tbseparator: tbseparator, button: button, fieldSet: fieldSet, storeAjax: storeAjax, panel: panel, splitter: splitter, maintab: maintab, rows: rows, cols: cols, bpmn: bpmn }); var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function commonjsRequire () { throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs'); } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var dist = createCommonjsModule(function (module, exports) { (function (global, factory) { module.exports = factory() ; }(commonjsGlobal, (function () { function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var _global = createCommonjsModule(function (module) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self // eslint-disable-next-line no-new-func : Function('return this')(); if (typeof __g == 'number') { __g = global; } // eslint-disable-line no-undef }); var _core = createCommonjsModule(function (module) { var core = module.exports = { version: '2.6.5' }; if (typeof __e == 'number') { __e = core; } // eslint-disable-line no-undef }); var _core_1 = _core.version; var _isObject = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; var _anObject = function (it) { if (!_isObject(it)) { throw TypeError(it + ' is not an object!'); } return it; }; var _fails = function (exec) { try { return !!exec(); } catch (e) { return true; } }; // Thank's IE8 for his funny defineProperty var _descriptors = !_fails(function () { return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; }); var document = _global.document; // typeof document.createElement is 'object' in old IE var is = _isObject(document) && _isObject(document.createElement); var _domCreate = function (it) { return is ? document.createElement(it) : {}; }; var _ie8DomDefine = !_descriptors && !_fails(function () { return Object.defineProperty(_domCreate('div'), 'a', { get: function () { return 7; } }).a != 7; }); // 7.1.1 ToPrimitive(input [, PreferredType]) // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string var _toPrimitive = function (it, S) { if (!_isObject(it)) { return it; } var fn, val; if (S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) { return val; } if (typeof (fn = it.valueOf) == 'function' && !_isObject(val = fn.call(it))) { return val; } if (!S && typeof (fn = it.toString) == 'function' && !_isObject(val = fn.call(it))) { return val; } throw TypeError("Can't convert object to primitive value"); }; var dP = Object.defineProperty; var f = _descriptors ? Object.defineProperty : function defineProperty(O, P, Attributes) { _anObject(O); P = _toPrimitive(P, true); _anObject(Attributes); if (_ie8DomDefine) { try { return dP(O, P, Attributes); } catch (e) { /* empty */ } } if ('get' in Attributes || 'set' in Attributes) { throw TypeError('Accessors not supported!'); } if ('value' in Attributes) { O[P] = Attributes.value; } return O; }; var _objectDp = { f: f }; var _propertyDesc = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; var _hide = _descriptors ? function (object, key, value) { return _objectDp.f(object, key, _propertyDesc(1, value)); } : function (object, key, value) { object[key] = value; return object; }; var hasOwnProperty = {}.hasOwnProperty; var _has = function (it, key) { return hasOwnProperty.call(it, key); }; var id = 0; var px = Math.random(); var _uid = function (key) { return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; var _shared = createCommonjsModule(function (module) { var SHARED = '__core-js_shared__'; var store = _global[SHARED] || (_global[SHARED] = {}); (module.exports = function (key, value) { return store[key] || (store[key] = value !== undefined ? value : {}); })('versions', []).push({ version: _core.version, mode: 'global', copyright: '© 2019 Denis Pushkarev (zloirock.ru)' }); }); var _functionToString = _shared('native-function-to-string', Function.toString); var _redefine = createCommonjsModule(function (module) { var SRC = _uid('src'); var TO_STRING = 'toString'; var TPL = ('' + _functionToString).split(TO_STRING); _core.inspectSource = function (it) { return _functionToString.call(it); }; (module.exports = function (O, key, val, safe) { var isFunction = typeof val == 'function'; if (isFunction) { _has(val, 'name') || _hide(val, 'name', key); } if (O[key] === val) { return; } if (isFunction) { _has(val, SRC) || _hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); } if (O === _global) { O[key] = val; } else if (!safe) { delete O[key]; _hide(O, key, val); } else if (O[key]) { O[key] = val; } else { _hide(O, key, val); } // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative })(Function.prototype, TO_STRING, function toString() { return typeof this == 'function' && this[SRC] || _functionToString.call(this); }); }); var _aFunction = function (it) { if (typeof it != 'function') { throw TypeError(it + ' is not a function!'); } return it; }; // optional / simple context binding var _ctx = function (fn, that, length) { _aFunction(fn); if (that === undefined) { return fn; } switch (length) { case 1: return function (a) { return fn.call(that, a); }; case 2: return function (a, b) { return fn.call(that, a, b); }; case 3: return function (a, b, c) { return fn.call(that, a, b, c); }; } return function (/* ...args */) { return fn.apply(that, arguments); }; }; var PROTOTYPE = 'prototype'; var $export = function (type, name, source) { var IS_FORCED = type & $export.F; var IS_GLOBAL = type & $export.G; var IS_STATIC = type & $export.S; var IS_PROTO = type & $export.P; var IS_BIND = type & $export.B; var target = IS_GLOBAL ? _global : IS_STATIC ? _global[name] || (_global[name] = {}) : (_global[name] || {})[PROTOTYPE]; var exports = IS_GLOBAL ? _core : _core[name] || (_core[name] = {}); var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}); var key, own, out, exp; if (IS_GLOBAL) { source = name; } for (key in source) { // contains in native own = !IS_FORCED && target && target[key] !== undefined; // export native or passed out = (own ? target : source)[key]; // bind timers to global for call from export context exp = IS_BIND && own ? _ctx(out, _global) : IS_PROTO && typeof out == 'function' ? _ctx(Function.call, out) : out; // extend global if (target) { _redefine(target, key, out, type & $export.U); } // export if (exports[key] != out) { _hide(exports, key, exp); } if (IS_PROTO && expProto[key] != out) { expProto[key] = out; } } }; _global.core = _core; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` var _export = $export; // 7.1.4 ToInteger var ceil = Math.ceil; var floor = Math.floor; var _toInteger = function (it) { return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; // 7.2.1 RequireObjectCoercible(argument) var _defined = function (it) { if (it == undefined) { throw TypeError("Can't call method on " + it); } return it; }; // true -> String#at // false -> String#codePointAt var _stringAt = function (TO_STRING) { return function (that, pos) { var s = String(_defined(that)); var i = _toInteger(pos); var l = s.length; var a, b; if (i < 0 || i >= l) { return TO_STRING ? '' : undefined; } a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; var $at = _stringAt(false); _export(_export.P, 'String', { // 21.1.3.3 String.prototype.codePointAt(pos) codePointAt: function codePointAt(pos) { return $at(this, pos); } }); var codePointAt = _core.String.codePointAt; var max = Math.max; var min = Math.min; var _toAbsoluteIndex = function (index, length) { index = _toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; var fromCharCode = String.fromCharCode; var $fromCodePoint = String.fromCodePoint; // length should be 1, old FF problem _export(_export.S + _export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { // 21.1.2.2 String.fromCodePoint(...codePoints) fromCodePoint: function fromCodePoint(x) { var arguments$1 = arguments; // eslint-disable-line no-unused-vars var res = []; var aLen = arguments.length; var i = 0; var code; while (aLen > i) { code = +arguments$1[i++]; if (_toAbsoluteIndex(code, 0x10ffff) !== code) { throw RangeError(code + ' is not a valid code point'); } res.push(code < 0x10000 ? fromCharCode(code) : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) ); } return res.join(''); } }); var fromCodePoint = _core.String.fromCodePoint; // This is a generated file. Do not edit. var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/; var ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/; var ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/; var unicode = { Space_Separator: Space_Separator, ID_Start: ID_Start, ID_Continue: ID_Continue }; var util = { isSpaceSeparator: function isSpaceSeparator (c) { return typeof c === 'string' && unicode.Space_Separator.test(c) }, isIdStartChar: function isIdStartChar (c) { return typeof c === 'string' && ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c === '$') || (c === '_') || unicode.ID_Start.test(c) ) }, isIdContinueChar: function isIdContinueChar (c) { return typeof c === 'string' && ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c === '$') || (c === '_') || (c === '\u200C') || (c === '\u200D') || unicode.ID_Continue.test(c) ) }, isDigit: function isDigit (c) { return typeof c === 'string' && /[0-9]/.test(c) }, isHexDigit: function isHexDigit (c) { return typeof c === 'string' && /[0-9A-Fa-f]/.test(c) }, }; var source; var parseState; var stack; var pos; var line; var column; var token; var key; var root; var parse = function parse (text, reviver) { source = String(text); parseState = 'start'; stack = []; pos = 0; line = 1; column = 0; token = undefined; key = undefined; root = undefined; do { token = lex(); // This code is unreachable. // if (!parseStates[parseState]) { // throw invalidParseState() // } parseStates[parseState](); } while (token.type !== 'eof') if (typeof reviver === 'function') { return internalize({'': root}, '', reviver) } return root }; function internalize (holder, name, reviver) { var value = holder[name]; if (value != null && typeof value === 'object') { for (var key in value) { var replacement = internalize(value, key, reviver); if (replacement === undefined) { delete value[key]; } else { value[key] = replacement; } } } return reviver.call(holder, name, value) } var lexState; var buffer; var doubleQuote; var sign; var c; function lex () { lexState = 'default'; buffer = ''; doubleQuote = false; sign = 1; for (;;) { c = peek(); // This code is unreachable. // if (!lexStates[lexState]) { // throw invalidLexState(lexState) // } var token = lexStates[lexState](); if (token) { return token } } } function peek () { if (source[pos]) { return String.fromCodePoint(source.codePointAt(pos)) } } function read () { var c = peek(); if (c === '\n') { line++; column = 0; } else if (c) { column += c.length; } else { column++; } if (c) { pos += c.length; } return c } var lexStates = { default: function default$1 () { switch (c) { case '\t': case '\v': case '\f': case ' ': case '\u00A0': case '\uFEFF': case '\n': case '\r': case '\u2028': case '\u2029': read(); return case '/': read(); lexState = 'comment'; return case undefined: read(); return newToken('eof') } if (util.isSpaceSeparator(c)) { read(); return } // This code is unreachable. // if (!lexStates[parseState]) { // throw invalidLexState(parseState) // } return lexStates[parseState]() }, comment: function comment () { switch (c) { case '*': read(); lexState = 'multiLineComment'; return case '/': read(); lexState = 'singleLineComment'; return } throw invalidChar(read()) }, multiLineComment: function multiLineComment () { switch (c) { case '*': read(); lexState = 'multiLineCommentAsterisk'; return case undefined: throw invalidChar(read()) } read(); }, multiLineCommentAsterisk: function multiLineCommentAsterisk () { switch (c) { case '*': read(); return case '/': read(); lexState = 'default'; return case undefined: throw invalidChar(read()) } read(); lexState = 'multiLineComment'; }, singleLineComment: function singleLineComment () { switch (c) { case '\n': case '\r': case '\u2028': case '\u2029': read(); lexState = 'default'; return case undefined: read(); return newToken('eof') } read(); }, value: function value () { switch (c) { case '{': case '[': return newToken('punctuator', read()) case 'n': read(); literal('ull'); return newToken('null', null) case 't': read(); literal('rue'); return newToken('boolean', true) case 'f': read(); literal('alse'); return newToken('boolean', false) case '-': case '+': if (read() === '-') { sign = -1; } lexState = 'sign'; return case '.': buffer = read(); lexState = 'decimalPointLeading'; return case '0': buffer = read(); lexState = 'zero'; return case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': buffer = read(); lexState = 'decimalInteger'; return case 'I': read(); literal('nfinity'); return newToken('numeric', Infinity) case 'N': read(); literal('aN'); return newToken('numeric', NaN) case '"': case "'": doubleQuote = (read() === '"'); buffer = ''; lexState = 'string'; return } throw invalidChar(read()) }, identifierNameStartEscape: function identifierNameStartEscape () { if (c !== 'u') { throw invalidChar(read()) } read(); var u = unicodeEscape(); switch (u) { case '$': case '_': break default: if (!util.isIdStartChar(u)) { throw invalidIdentifier() } break } buffer += u; lexState = 'identifierName'; }, identifierName: function identifierName () { switch (c) { case '$': case '_': case '\u200C': case '\u200D': buffer += read(); return case '\\': read(); lexState = 'identifierNameEscape'; return } if (util.isIdContinueChar(c)) { buffer += read(); return } return newToken('identifier', buffer) }, identifierNameEscape: function identifierNameEscape () { if (c !== 'u') { throw invalidChar(read()) } read(); var u = unicodeEscape(); switch (u) { case '$': case '_': case '\u200C': case '\u200D': break default: if (!util.isIdContinueChar(u)) { throw invalidIdentifier() } break } buffer += u; lexState = 'identifierName'; }, sign: function sign$1 () { switch (c) { case '.': buffer = read(); lexState = 'decimalPointLeading'; return case '0': buffer = read(); lexState = 'zero'; return case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': buffer = read(); lexState = 'decimalInteger'; return case 'I': read(); literal('nfinity'); return newToken('numeric', sign * Infinity) case 'N': read(); literal('aN'); return newToken('numeric', NaN) } throw invalidChar(read()) }, zero: function zero () { switch (c) { case '.': buffer += read(); lexState = 'decimalPoint'; return case 'e': case 'E': buffer += read(); lexState = 'decimalExponent'; return case 'x': case 'X': buffer += read(); lexState = 'hexadecimal'; return } return newToken('numeric', sign * 0) }, decimalInteger: function decimalInteger () { switch (c) { case '.': buffer += read(); lexState = 'decimalPoint'; return case 'e': case 'E': buffer += read(); lexState = 'decimalExponent'; return } if (util.isDigit(c)) { buffer += read(); return } return newToken('numeric', sign * Number(buffer)) }, decimalPointLeading: function decimalPointLeading () { if (util.isDigit(c)) { buffer += read(); lexState = 'decimalFraction'; return } throw invalidChar(read()) }, decimalPoint: function decimalPoint () { switch (c) { case 'e': case 'E': buffer += read(); lexState = 'decimalExponent'; return } if (util.isDigit(c)) { buffer += read(); lexState = 'decimalFraction'; return } return newToken('numeric', sign * Number(buffer)) }, decimalFraction: function decimalFraction () { switch (c) { case 'e': case 'E': buffer += read(); lexState = 'decimalExponent'; return } if (util.isDigit(c)) { buffer += read(); return } return newToken('numeric', sign * Number(buffer)) }, decimalExponent: function decimalExponent () { switch (c) { case '+': case '-': buffer += read(); lexState = 'decimalExponentSign'; return } if (util.isDigit(c)) { buffer += read(); lexState = 'decimalExponentInteger'; return } throw invalidChar(read()) }, decimalExponentSign: function decimalExponentSign () { if (util.isDigit(c)) { buffer += read(); lexState = 'decimalExponentInteger'; return } throw invalidChar(read()) }, decimalExponentInteger: function decimalExponentInteger () { if (util.isDigit(c)) { buffer += read(); return } return newToken('numeric', sign * Number(buffer)) }, hexadecimal: function hexadecimal () { if (util.isHexDigit(c)) { buffer += read(); lexState = 'hexadecimalInteger'; return } throw invalidChar(read()) }, hexadecimalInteger: function hexadecimalInteger () { if (util.isHexDigit(c)) { buffer += read(); return } return newToken('numeric', sign * Number(buffer)) }, string: function string () { switch (c) { case '\\': read(); buffer += escape(); return case '"': if (doubleQuote) { read(); return newToken('string', buffer) } buffer += read(); return case "'": if (!doubleQuote) { read(); return newToken('string', buffer) } buffer += read(); return case '\n': case '\r': throw invalidChar(read()) case '\u2028': case '\u2029': separatorChar(c); break case undefined: throw invalidChar(read()) } buffer += read(); }, start: function start () { switch (c) { case '{': case '[': return newToken('punctuator', read()) // This code is unreachable since the default lexState handles eof. // case undefined: // return newToken('eof') } lexState = 'value'; }, beforePropertyName: function beforePropertyName () { switch (c) { case '$': case '_': buffer = read(); lexState = 'identifierName'; return case '\\': read(); lexState = 'identifierNameStartEscape'; return case '}': return newToken('punctuator', read()) case '"': case "'": doubleQuote = (read() === '"'); lexState = 'string'; return } if (util.isIdStartChar(c)) { buffer += read(); lexState = 'identifierName'; return } throw invalidChar(read()) }, afterPropertyName: function afterPropertyName () { if (c === ':') { return newToken('punctuator', read()) } throw invalidChar(read()) }, beforePropertyValue: function beforePropertyValue () { lexState = 'value'; }, afterPropertyValue: function afterPropertyValue () { switch (c) { case ',': case '}': return newToken('punctuator', read()) } throw invalidChar(read()) }, beforeArrayValue: function beforeArrayValue () { if (c === ']') { return newToken('punctuator', read()) } lexState = 'value'; }, afterArrayValue: function afterArrayValue () { switch (c) { case ',': case ']': return newToken('punctuator', read()) } throw invalidChar(read()) }, end: function end () { // This code is unreachable since it's handled by the default lexState. // if (c === undefined) { // read() // return newToken('eof') // } throw invalidChar(read()) }, }; function newToken (type, value) { return { type: type, value: value, line: line, column: column, } } function literal (s) { for (var i = 0, list = s; i < list.length; i += 1) { var c = list[i]; var p = peek(); if (p !== c) { throw invalidChar(read()) } read(); } } function escape () { var c = peek(); switch (c) { case 'b': read(); return '\b' case 'f': read(); return '\f' case 'n': read(); return '\n' case 'r': read(); return '\r' case 't': read(); return '\t' case 'v': read(); return '\v' case '0': read(); if (util.isDigit(peek())) { throw invalidChar(read()) } return '\0' case 'x': read(); return hexEscape() case 'u': read(); return unicodeEscape() case '\n': case '\u2028': case '\u2029': read(); return '' case '\r': read(); if (peek() === '\n') { read(); } return '' case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': throw invalidChar(read()) case undefined: throw invalidChar(read()) } return read() } function hexEscape () { var buffer = ''; var c = peek(); if (!util.isHexDigit(c)) { throw invalidChar(read()) } buffer += read(); c = peek(); if (!util.isHexDigit(c)) { throw invalidChar(read()) } buffer += read(); return String.fromCodePoint(parseInt(buffer, 16)) } function unicodeEscape () { var buffer = ''; var count = 4; while (count-- > 0) { var c = peek(); if (!util.isHexDigit(c)) { throw invalidChar(read()) } buffer += read(); } return String.fromCodePoint(parseInt(buffer, 16)) } var parseStates = { start: function start () { if (token.type === 'eof') { throw invalidEOF() } push(); }, beforePropertyName: function beforePropertyName () { switch (token.type) { case 'identifier': case 'string': key = token.value; parseState = 'afterPropertyName'; return case 'punctuator': // This code is unreachable since it's handled by the lexState. // if (token.value !== '}') { // throw invalidToken() // } pop(); return case 'eof': throw invalidEOF() } // This code is unreachable since it's handled by the lexState. // throw invalidToken() }, afterPropertyName: function afterPropertyName () { // This code is unreachable since it's handled by the lexState. // if (token.type !== 'punctuator' || token.value !== ':') { // throw invalidToken() // } if (token.type === 'eof') { throw invalidEOF() } parseState = 'beforePropertyValue'; }, beforePropertyValue: function beforePropertyValue () { if (token.type === 'eof') { throw invalidEOF() } push(); }, beforeArrayValue: function beforeArrayValue () { if (token.type === 'eof') { throw invalidEOF() } if (token.type === 'punctuator' && token.value === ']') { pop(); return } push(); }, afterPropertyValue: function afterPropertyValue () { // This code is unreachable since it's handled by the lexState. // if (token.type !== 'punctuator') { // throw invalidToken() // } if (token.type === 'eof') { throw invalidEOF() } switch (token.value) { case ',': parseState = 'beforePropertyName'; return case '}': pop(); } // This code is unreachable since it's handled by the lexState. // throw invalidToken() }, afterArrayValue: function afterArrayValue () { // This code is unreachable since it's handled by the lexState. // if (token.type !== 'punctuator') { // throw invalidToken() // } if (token.type === 'eof') { throw invalidEOF() } switch (token.value) { case ',': parseState = 'beforeArrayValue'; return case ']': pop(); } // This code is unreachable since it's handled by the lexState. // throw invalidToken() }, end: function end () { // This code is unreachable since it's handled by the lexState. // if (token.type !== 'eof') { // throw invalidToken() // } }, }; function push () { var value; switch (token.type) { case 'punctuator': switch (token.value) { case '{': value = {}; break case '[': value = []; break } break case 'null': case 'boolean': case 'numeric': case 'string': value = token.value; break // This code is unreachable. // default: // throw invalidToken() } if (root === undefined) { root = value; } else { var parent = stack[stack.length - 1]; if (Array.isArray(parent)) { parent.push(value); } else { parent[key] = value; } } if (value !== null && typeof value === 'object') { stack.push(value); if (Array.isArray(value)) { parseState = 'beforeArrayValue'; } else { parseState = 'beforePropertyName'; } } else { var current = stack[stack.length - 1]; if (current == null) { parseState = 'end'; } else if (Array.isArray(current)) { parseState = 'afterArrayValue'; } else { parseState = 'afterPropertyValue'; } } } function pop () { stack.pop(); var current = stack[stack.length - 1]; if (current == null) { parseState = 'end'; } else if (Array.isArray(current)) { parseState = 'afterArrayValue'; } else { parseState = 'afterPropertyValue'; } } // This code is unreachable. // function invalidParseState () { // return new Error(`JSON5: invalid parse state '${parseState}'`) // } // This code is unreachable. // function invalidLexState (state) { // return new Error(`JSON5: invalid lex state '${state}'`) // } function invalidChar (c) { if (c === undefined) { return syntaxError(("JSON5: invalid end of input at " + line + ":" + column)) } return syntaxError(("JSON5: invalid character '" + (formatChar(c)) + "' at " + line + ":" + column)) } function invalidEOF () { return syntaxError(("JSON5: invalid end of input at " + line + ":" + column)) } // This code is unreachable. // function invalidToken () { // if (token.type === 'eof') { // return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) // } // const c = String.fromCodePoint(token.value.codePointAt(0)) // return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`) // } function invalidIdentifier () { column -= 5; return syntaxError(("JSON5: invalid identifier character at " + line + ":" + column)) } function separatorChar (c) { console.warn(("JSON5: '" + (formatChar(c)) + "' in strings is not valid ECMAScript; consider escaping")); } function formatChar (c) { var replacements = { "'": "\\'", '"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', '\v': '\\v', '\0': '\\0', '\u2028': '\\u2028', '\u2029': '\\u2029', }; if (replacements[c]) { return replacements[c] } if (c < ' ') { var hexString = c.charCodeAt(0).toString(16); return '\\x' + ('00' + hexString).substring(hexString.length) } return c } function syntaxError (message) { var err = new SyntaxError(message); err.lineNumber = line; err.columnNumber = column; return err } var stringify = function stringify (value, replacer, space) { var stack = []; var indent = ''; var propertyList; var replacerFunc; var gap = ''; var quote; if ( replacer != null && typeof replacer === 'object' && !Array.isArray(replacer) ) { space = replacer.space; quote = replacer.quote; replacer = replacer.replacer; } if (typeof replacer === 'function') { replacerFunc = replacer; } else if (Array.isArray(replacer)) { propertyList = []; for (var i = 0, list = replacer; i < list.length; i += 1) { var v = list[i]; var item = (void 0); if (typeof v === 'string') { item = v; } else if ( typeof v === 'number' || v instanceof String || v instanceof Number ) { item = String(v); } if (item !== undefined && propertyList.indexOf(item) < 0) { propertyList.push(item); } } } if (space instanceof Number) { space = Number(space); } else if (space instanceof String) { space = String(space); } if (typeof space === 'number') { if (space > 0) { space = Math.min(10, Math.floor(space)); gap = ' '.substr(0, space); } } else if (typeof space === 'string') { gap = space.substr(0, 10); } return serializeProperty('', {'': value}) function serializeProperty (key, holder) { var value = holder[key]; if (value != null) { if (typeof value.toJSON5 === 'function') { value = value.toJSON5(key); } else if (typeof value.toJSON === 'function') { value = value.toJSON(key); } } if (replacerFunc) { value = replacerFunc.call(holder, key, value); } if (value instanceof Number) { value = Number(value); } else if (value instanceof String) { value = String(value); } else if (value instanceof Boolean) { value = value.valueOf(); } switch (value) { case null: return 'null' case true: return 'true' case false: return 'false' } if (typeof value === 'string') { return quoteString(value) } if (typeof value === 'number') { return String(value) } if (typeof value === 'object') { return Array.isArray(value) ? serializeArray(value) : serializeObject(value) } return undefined } function quoteString (value) { var quotes = { "'": 0.1, '"': 0.2, }; var replacements = { "'": "\\'", '"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', '\v': '\\v', '\0': '\\0', '\u2028': '\\u2028', '\u2029': '\\u2029', }; var product = ''; for (var i = 0; i < value.length; i++) { var c = value[i]; switch (c) { case "'": case '"': quotes[c]++; product += c; continue case '\0': if (util.isDigit(value[i + 1])) { product += '\\x00'; continue } } if (replacements[c]) { product += replacements[c]; continue } if (c < ' ') { var hexString = c.charCodeAt(0).toString(16); product += '\\x' + ('00' + hexString).substring(hexString.length); continue } product += c; } var quoteChar = quote || Object.keys(quotes).reduce(function (a, b) { return (quotes[a] < quotes[b]) ? a : b; }); product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]); return quoteChar + product + quoteChar } function serializeObject (value) { if (stack.indexOf(value) >= 0) { throw TypeError('Converting circular structure to JSON5') } stack.push(value); var stepback = indent; indent = indent + gap; var keys = propertyList || Object.keys(value); var partial = []; for (var i = 0, list = keys; i < list.length; i += 1) { var key = list[i]; var propertyString = serializeProperty(key, value); if (propertyString !== undefined) { var member = serializeKey(key) + ':'; if (gap !== '') { member += ' '; } member += propertyString; partial.push(member); } } var final; if (partial.length === 0) { final = '{}'; } else { var properties; if (gap === '') { properties = partial.join(','); final = '{' + properties + '}'; } else { var separator = ',\n' + indent; properties = partial.join(separator); final = '{\n' + indent + properties + ',\n' + stepback + '}'; } } stack.pop(); indent = stepback; return final } function serializeKey (key) { if (key.length === 0) { return quoteString(key) } var firstChar = String.fromCodePoint(key.codePointAt(0)); if (!util.isIdStartChar(firstChar)) { return quoteString(key) } for (var i = firstChar.length; i < key.length; i++) { if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) { return quoteString(key) } } return key } function serializeArray (value) { if (stack.indexOf(value) >= 0) { throw TypeError('Converting circular structure to JSON5') } stack.push(value); var stepback = indent; indent = indent + gap; var partial = []; for (var i = 0; i < value.length; i++) { var propertyString = serializeProperty(String(i), value); partial.push((propertyString !== undefined) ? propertyString : 'null'); } var final; if (partial.length === 0) { final = '[]'; } else { if (gap === '') { var properties = partial.join(','); final = '[' + properties + ']'; } else { var separator = ',\n' + indent; var properties$1 = partial.join(separator); final = '[\n' + indent + properties$1 + ',\n' + stepback + ']'; } } stack.pop(); indent = stepback; return final } }; var JSON5 = { parse: parse, stringify: stringify, }; var lib = JSON5; var es5 = lib; return es5; }))); }); var moment$1 = createCommonjsModule(function (module, exports) { (function (global, factory) { module.exports = factory() ; }(commonjsGlobal, (function () { var hookCallback; function hooks() { return hookCallback.apply(null, arguments); } // This is done to register the method called with moment() // without creating circular dependencies. function setHookCallback(callback) { hookCallback = callback; } function isArray(input) { return ( input instanceof Array || Object.prototype.toString.call(input) === '[object Array]' ); } function isObject(input) { // IE8 will treat undefined and null as object if it wasn't for // input != null return ( input != null && Object.prototype.toString.call(input) === '[object Object]' ); } function hasOwnProp(a, b) { return Object.prototype.hasOwnProperty.call(a, b); } function isObjectEmpty(obj) { if (Object.getOwnPropertyNames) { return Object.getOwnPropertyNames(obj).length === 0; } else { var k; for (k in obj) { if (hasOwnProp(obj, k)) { return false; } } return true; } } function isUndefined(input) { return input === void 0; } function isNumber(input) { return ( typeof input === 'number' || Object.prototype.toString.call(input) === '[object Number]' ); } function isDate(input) { return ( input instanceof Date || Object.prototype.toString.call(input) === '[object Date]' ); } function map(arr, fn) { var res = [], i; for (i = 0; i < arr.length; ++i) { res.push(fn(arr[i], i)); } return res; } function extend(a, b) { for (var i in b) { if (hasOwnProp(b, i)) { a[i] = b[i]; } } if (hasOwnProp(b, 'toString')) { a.toString = b.toString; } if (hasOwnProp(b, 'valueOf')) { a.valueOf = b.valueOf; } return a; } function createUTC(input, format, locale, strict) { return createLocalOrUTC(input, format, locale, strict, true).utc(); } function defaultParsingFlags() { // We need to deep clone this object. return { empty: false, unusedTokens: [], unusedInput: [], overflow: -2, charsLeftOver: 0, nullInput: false, invalidEra: null, invalidMonth: null, invalidFormat: false, userInvalidated: false, iso: false, parsedDateParts: [], era: null, meridiem: null, rfc2822: false, weekdayMismatch: false, }; } function getParsingFlags(m) { if (m._pf == null) { m._pf = defaultParsingFlags(); } return m._pf; } var some; if (Array.prototype.some) { some = Array.prototype.some; } else { some = function (fun) { var t = Object(this), len = t.length >>> 0, i; for (i = 0; i < len; i++) { if (i in t && fun.call(this, t[i], i, t)) { return true; } } return false; }; } function isValid(m) { if (m._isValid == null) { var flags = getParsingFlags(m), parsedParts = some.call(flags.parsedDateParts, function (i) { return i != null; }), isNowValid = !isNaN(m._d.getTime()) && flags.overflow < 0 && !flags.empty && !flags.invalidEra && !flags.invalidMonth && !flags.invalidWeekday && !flags.weekdayMismatch && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || (flags.meridiem && parsedParts)); if (m._strict) { isNowValid = isNowValid && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0 && flags.bigHour === undefined; } if (Object.isFrozen == null || !Object.isFrozen(m)) { m._isValid = isNowValid; } else { return isNowValid; } } return m._isValid; } function createInvalid(flags) { var m = createUTC(NaN); if (flags != null) { extend(getParsingFlags(m), flags); } else { getParsingFlags(m).userInvalidated = true; } return m; } // Plugins that add properties should also add the key here (null value), // so we can properly clone ourselves. var momentProperties = (hooks.momentProperties = []), updateInProgress = false; function copyConfig(to, from) { var i, prop, val; if (!isUndefined(from._isAMomentObject)) { to._isAMomentObject = from._isAMomentObject; } if (!isUndefined(from._i)) { to._i = from._i; } if (!isUndefined(from._f)) { to._f = from._f; } if (!isUndefined(from._l)) { to._l = from._l; } if (!isUndefined(from._strict)) { to._strict = from._strict; } if (!isUndefined(from._tzm)) { to._tzm = from._tzm; } if (!isUndefined(from._isUTC)) { to._isUTC = from._isUTC; } if (!isUndefined(from._offset)) { to._offset = from._offset; } if (!isUndefined(from._pf)) { to._pf = getParsingFlags(from); } if (!isUndefined(from._locale)) { to._locale = from._locale; } if (momentProperties.length > 0) { for (i = 0; i < momentProperties.length; i++) { prop = momentProperties[i]; val = from[prop]; if (!isUndefined(val)) { to[prop] = val; } } } return to; } // Moment prototype object function Moment(config) { copyConfig(this, config); this._d = new Date(config._d != null ? config._d.getTime() : NaN); if (!this.isValid()) { this._d = new Date(NaN); } // Prevent infinite loop in case updateOffset creates new moment // objects. if (updateInProgress === false) { updateInProgress = true; hooks.updateOffset(this); updateInProgress = false; } } function isMoment(obj) { return ( obj instanceof Moment || (obj != null && obj._isAMomentObject != null) ); } function warn(msg) { if ( hooks.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn ) { console.warn('Deprecation warning: ' + msg); } } function deprecate(msg, fn) { var firstTime = true; return extend(function () { if (hooks.deprecationHandler != null) { hooks.deprecationHandler(null, msg); } if (firstTime) { var args = [], arg, i, key; for (i = 0; i < arguments.length; i++) { arg = ''; if (typeof arguments[i] === 'object') { arg += '\n[' + i + '] '; for (key in arguments[0]) { if (hasOwnProp(arguments[0], key)) { arg += key + ': ' + arguments[0][key] + ', '; } } arg = arg.slice(0, -2); // Remove trailing comma and space } else { arg = arguments[i]; } args.push(arg); } warn( msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + new Error().stack ); firstTime = false; } return fn.apply(this, arguments); }, fn); } var deprecations = {}; function deprecateSimple(name, msg) { if (hooks.deprecationHandler != null) { hooks.deprecationHandler(name, msg); } if (!deprecations[name]) { warn(msg); deprecations[name] = true; } } hooks.suppressDeprecationWarnings = false; hooks.deprecationHandler = null; function isFunction(input) { return ( (typeof Function !== 'undefined' && input instanceof Function) || Object.prototype.toString.call(input) === '[object Function]' ); } function set(config) { var prop, i; for (i in config) { if (hasOwnProp(config, i)) { prop = config[i]; if (isFunction(prop)) { this[i] = prop; } else { this['_' + i] = prop; } } } this._config = config; // Lenient ordinal parsing accepts just a number in addition to // number + (possibly) stuff coming from _dayOfMonthOrdinalParse. // TODO: Remove "ordinalParse" fallback in next major release. this._dayOfMonthOrdinalParseLenient = new RegExp( (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + '|' + /\d{1,2}/.source ); } function mergeConfigs(parentConfig, childConfig) { var res = extend({}, parentConfig), prop; for (prop in childConfig) { if (hasOwnProp(childConfig, prop)) { if (isObject(parentConfig[prop]) && isObject(childConfig[prop])) { res[prop] = {}; extend(res[prop], parentConfig[prop]); extend(res[prop], childConfig[prop]); } else if (childConfig[prop] != null) { res[prop] = childConfig[prop]; } else { delete res[prop]; } } } for (prop in parentConfig) { if ( hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject(parentConfig[prop]) ) { // make sure changes to properties don't modify parent config res[prop] = extend({}, res[prop]); } } return res; } function Locale(config) { if (config != null) { this.set(config); } } var keys; if (Object.keys) { keys = Object.keys; } else { keys = function (obj) { var i, res = []; for (i in obj) { if (hasOwnProp(obj, i)) { res.push(i); } } return res; }; } var defaultCalendar = { sameDay: '[Today at] LT', nextDay: '[Tomorrow at] LT', nextWeek: 'dddd [at] LT', lastDay: '[Yesterday at] LT', lastWeek: '[Last] dddd [at] LT', sameElse: 'L', }; function calendar(key, mom, now) { var output = this._calendar[key] || this._calendar['sameElse']; return isFunction(output) ? output.call(mom, now) : output; } function zeroFill(number, targetLength, forceSign) { var absNumber = '' + Math.abs(number), zerosToFill = targetLength - absNumber.length, sign = number >= 0; return ( (sign ? (forceSign ? '+' : '') : '-') + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber ); } var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, formatFunctions = {}, formatTokenFunctions = {}; // token: 'M' // padded: ['MM', 2] // ordinal: 'Mo' // callback: function () { this.month() + 1 } function addFormatToken(token, padded, ordinal, callback) { var func = callback; if (typeof callback === 'string') { func = function () { return this[callback](); }; } if (token) { formatTokenFunctions[token] = func; } if (padded) { formatTokenFunctions[padded[0]] = function () { return zeroFill(func.apply(this, arguments), padded[1], padded[2]); }; } if (ordinal) { formatTokenFunctions[ordinal] = function () { return this.localeData().ordinal( func.apply(this, arguments), token ); }; } } function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ''); } return input.replace(/\\/g, ''); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = '', i; for (i = 0; i < length; i++) { output += isFunction(array[i]) ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.localeData().invalidDate(); } format = expandFormat(format, m.localeData()); formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format); return formatFunctions[format](m); } function expandFormat(format, locale) { var i = 5; function replaceLongDateFormatTokens(input) { return locale.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace( localFormattingTokens, replaceLongDateFormatTokens ); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } var defaultLongDateFormat = { LTS: 'h:mm:ss A', LT: 'h:mm A', L: 'MM/DD/YYYY', LL: 'MMMM D, YYYY', LLL: 'MMMM D, YYYY h:mm A', LLLL: 'dddd, MMMM D, YYYY h:mm A', }; function longDateFormat(key) { var format = this._longDateFormat[key], formatUpper = this._longDateFormat[key.toUpperCase()]; if (format || !formatUpper) { return format; } this._longDateFormat[key] = formatUpper .match(formattingTokens) .map(function (tok) { if ( tok === 'MMMM' || tok === 'MM' || tok === 'DD' || tok === 'dddd' ) { return tok.slice(1); } return tok; }) .join(''); return this._longDateFormat[key]; } var defaultInvalidDate = 'Invalid date'; function invalidDate() { return this._invalidDate; } var defaultOrdinal = '%d', defaultDayOfMonthOrdinalParse = /\d{1,2}/; function ordinal(number) { return this._ordinal.replace('%d', number); } var defaultRelativeTime = { future: 'in %s', past: '%s ago', s: 'a few seconds', ss: '%d seconds', m: 'a minute', mm: '%d minutes', h: 'an hour', hh: '%d hours', d: 'a day', dd: '%d days', w: 'a week', ww: '%d weeks', M: 'a month', MM: '%d months', y: 'a year', yy: '%d years', }; function relativeTime(number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return isFunction(output) ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); } function pastFuture(diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return isFunction(format) ? format(output) : format.replace(/%s/i, output); } var aliases = {}; function addUnitAlias(unit, shorthand) { var lowerCase = unit.toLowerCase(); aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit; } function normalizeUnits(units) { return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (hasOwnProp(inputObject, prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } var priorities = {}; function addUnitPriority(unit, priority) { priorities[unit] = priority; } function getPrioritizedUnits(unitsObj) { var units = [], u; for (u in unitsObj) { if (hasOwnProp(unitsObj, u)) { units.push({ unit: u, priority: priorities[u] }); } } units.sort(function (a, b) { return a.priority - b.priority; }); return units; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } function absFloor(number) { if (number < 0) { // -0 -> 0 return Math.ceil(number) || 0; } else { return Math.floor(number); } } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { value = absFloor(coercedNumber); } return value; } function makeGetSet(unit, keepTime) { return function (value) { if (value != null) { set$1(this, unit, value); hooks.updateOffset(this, keepTime); return this; } else { return get(this, unit); } }; } function get(mom, unit) { return mom.isValid() ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN; } function set$1(mom, unit, value) { if (mom.isValid() && !isNaN(value)) { if ( unit === 'FullYear' && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29 ) { value = toInt(value); mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit]( value, mom.month(), daysInMonth(value, mom.month()) ); } else { mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); } } } // MOMENTS function stringGet(units) { units = normalizeUnits(units); if (isFunction(this[units])) { return this[units](); } return this; } function stringSet(units, value) { if (typeof units === 'object') { units = normalizeObjectUnits(units); var prioritized = getPrioritizedUnits(units), i; for (i = 0; i < prioritized.length; i++) { this[prioritized[i].unit](units[prioritized[i].unit]); } } else { units = normalizeUnits(units); if (isFunction(this[units])) { return this[units](value); } } return this; } var match1 = /\d/, // 0 - 9 match2 = /\d\d/, // 00 - 99 match3 = /\d{3}/, // 000 - 999 match4 = /\d{4}/, // 0000 - 9999 match6 = /[+-]?\d{6}/, // -999999 - 999999 match1to2 = /\d\d?/, // 0 - 99 match3to4 = /\d\d\d\d?/, // 999 - 9999 match5to6 = /\d\d\d\d\d\d?/, // 99999 - 999999 match1to3 = /\d{1,3}/, // 0 - 999 match1to4 = /\d{1,4}/, // 0 - 9999 match1to6 = /[+-]?\d{1,6}/, // -999999 - 999999 matchUnsigned = /\d+/, // 0 - inf matchSigned = /[+-]?\d+/, // -inf - inf matchOffset = /Z|[+-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 // any word (or two) characters or numbers including two/three word month in arabic. // includes scottish gaelic two word and hyphenated months matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i, regexes; regexes = {}; function addRegexToken(token, regex, strictRegex) { regexes[token] = isFunction(regex) ? regex : function (isStrict, localeData) { return isStrict && strictRegex ? strictRegex : regex; }; } function getParseRegexForToken(token, config) { if (!hasOwnProp(regexes, token)) { return new RegExp(unescapeFormat(token)); } return regexes[token](config._strict, config._locale); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function unescapeFormat(s) { return regexEscape( s .replace('\\', '') .replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function ( matched, p1, p2, p3, p4 ) { return p1 || p2 || p3 || p4; }) ); } function regexEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } var tokens = {}; function addParseToken(token, callback) { var i, func = callback; if (typeof token === 'string') { token = [token]; } if (isNumber(callback)) { func = function (input, array) { array[callback] = toInt(input); }; } for (i = 0; i < token.length; i++) { tokens[token[i]] = func; } } function addWeekParseToken(token, callback) { addParseToken(token, function (input, array, config, token) { config._w = config._w || {}; callback(input, config._w, config, token); }); } function addTimeToArrayFromToken(token, input, config) { if (input != null && hasOwnProp(tokens, token)) { tokens[token](input, config._a, config, token); } } var YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, WEEK = 7, WEEKDAY = 8; function mod(n, x) { return ((n % x) + x) % x; } var indexOf; if (Array.prototype.indexOf) { indexOf = Array.prototype.indexOf; } else { indexOf = function (o) { // I know var i; for (i = 0; i < this.length; ++i) { if (this[i] === o) { return i; } } return -1; }; } function daysInMonth(year, month) { if (isNaN(year) || isNaN(month)) { return NaN; } var modMonth = mod(month, 12); year += (month - modMonth) / 12; return modMonth === 1 ? isLeapYear(year) ? 29 : 28 : 31 - ((modMonth % 7) % 2); } // FORMATTING addFormatToken('M', ['MM', 2], 'Mo', function () { return this.month() + 1; }); addFormatToken('MMM', 0, 0, function (format) { return this.localeData().monthsShort(this, format); }); addFormatToken('MMMM', 0, 0, function (format) { return this.localeData().months(this, format); }); // ALIASES addUnitAlias('month', 'M'); // PRIORITY addUnitPriority('month', 8); // PARSING addRegexToken('M', match1to2); addRegexToken('MM', match1to2, match2); addRegexToken('MMM', function (isStrict, locale) { return locale.monthsShortRegex(isStrict); }); addRegexToken('MMMM', function (isStrict, locale) { return locale.monthsRegex(isStrict); }); addParseToken(['M', 'MM'], function (input, array) { array[MONTH] = toInt(input) - 1; }); addParseToken(['MMM', 'MMMM'], function (input, array, config, token) { var month = config._locale.monthsParse(input, token, config._strict); // if we didn't find a month name, mark the date as invalid. if (month != null) { array[MONTH] = month; } else { getParsingFlags(config).invalidMonth = input; } }); // LOCALES var defaultLocaleMonths = 'January_February_March_April_May_June_July_August_September_October_November_December'.split( '_' ), defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split( '_' ), MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/, defaultMonthsShortRegex = matchWord, defaultMonthsRegex = matchWord; function localeMonths(m, format) { if (!m) { return isArray(this._months) ? this._months : this._months['standalone']; } return isArray(this._months) ? this._months[m.month()] : this._months[ (this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone' ][m.month()]; } function localeMonthsShort(m, format) { if (!m) { return isArray(this._monthsShort) ? this._monthsShort : this._monthsShort['standalone']; } return isArray(this._monthsShort) ? this._monthsShort[m.month()] : this._monthsShort[ MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone' ][m.month()]; } function handleStrictParse(monthName, format, strict) { var i, ii, mom, llc = monthName.toLocaleLowerCase(); if (!this._monthsParse) { // this is not used this._monthsParse = []; this._longMonthsParse = []; this._shortMonthsParse = []; for (i = 0; i < 12; ++i) { mom = createUTC([2000, i]); this._shortMonthsParse[i] = this.monthsShort( mom, '' ).toLocaleLowerCase(); this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase(); } } if (strict) { if (format === 'MMM') { ii = indexOf.call(this._shortMonthsParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._longMonthsParse, llc); return ii !== -1 ? ii : null; } } else { if (format === 'MMM') { ii = indexOf.call(this._shortMonthsParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._longMonthsParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._longMonthsParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortMonthsParse, llc); return ii !== -1 ? ii : null; } } } function localeMonthsParse(monthName, format, strict) { var i, mom, regex; if (this._monthsParseExact) { return handleStrictParse.call(this, monthName, format, strict); } if (!this._monthsParse) { this._monthsParse = []; this._longMonthsParse = []; this._shortMonthsParse = []; } // TODO: add sorting // Sorting makes sure if one month (or abbr) is a prefix of another // see sorting in computeMonthsParse for (i = 0; i < 12; i++) { // make the regex if we don't have it already mom = createUTC([2000, i]); if (strict && !this._longMonthsParse[i]) { this._longMonthsParse[i] = new RegExp( '^' + this.months(mom, '').replace('.', '') + '$', 'i' ); this._shortMonthsParse[i] = new RegExp( '^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i' ); } if (!strict && !this._monthsParse[i]) { regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if ( strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName) ) { return i; } else if ( strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName) ) { return i; } else if (!strict && this._monthsParse[i].test(monthName)) { return i; } } } // MOMENTS function setMonth(mom, value) { var dayOfMonth; if (!mom.isValid()) { // No op return mom; } if (typeof value === 'string') { if (/^\d+$/.test(value)) { value = toInt(value); } else { value = mom.localeData().monthsParse(value); // TODO: Another silent failure? if (!isNumber(value)) { return mom; } } } dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); return mom; } function getSetMonth(value) { if (value != null) { setMonth(this, value); hooks.updateOffset(this, true); return this; } else { return get(this, 'Month'); } } function getDaysInMonth() { return daysInMonth(this.year(), this.month()); } function monthsShortRegex(isStrict) { if (this._monthsParseExact) { if (!hasOwnProp(this, '_monthsRegex')) { computeMonthsParse.call(this); } if (isStrict) { return this._monthsShortStrictRegex; } else { return this._monthsShortRegex; } } else { if (!hasOwnProp(this, '_monthsShortRegex')) { this._monthsShortRegex = defaultMonthsShortRegex; } return this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex; } } function monthsRegex(isStrict) { if (this._monthsParseExact) { if (!hasOwnProp(this, '_monthsRegex')) { computeMonthsParse.call(this); } if (isStrict) { return this._monthsStrictRegex; } else { return this._monthsRegex; } } else { if (!hasOwnProp(this, '_monthsRegex')) { this._monthsRegex = defaultMonthsRegex; } return this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex; } } function computeMonthsParse() { function cmpLenRev(a, b) { return b.length - a.length; } var shortPieces = [], longPieces = [], mixedPieces = [], i, mom; for (i = 0; i < 12; i++) { // make the regex if we don't have it already mom = createUTC([2000, i]); shortPieces.push(this.monthsShort(mom, '')); longPieces.push(this.months(mom, '')); mixedPieces.push(this.months(mom, '')); mixedPieces.push(this.monthsShort(mom, '')); } // Sorting makes sure if one month (or abbr) is a prefix of another it // will match the longer piece. shortPieces.sort(cmpLenRev); longPieces.sort(cmpLenRev); mixedPieces.sort(cmpLenRev); for (i = 0; i < 12; i++) { shortPieces[i] = regexEscape(shortPieces[i]); longPieces[i] = regexEscape(longPieces[i]); } for (i = 0; i < 24; i++) { mixedPieces[i] = regexEscape(mixedPieces[i]); } this._monthsRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); this._monthsShortRegex = this._monthsRegex; this._monthsStrictRegex = new RegExp( '^(' + longPieces.join('|') + ')', 'i' ); this._monthsShortStrictRegex = new RegExp( '^(' + shortPieces.join('|') + ')', 'i' ); } // FORMATTING addFormatToken('Y', 0, 0, function () { var y = this.year(); return y <= 9999 ? zeroFill(y, 4) : '+' + y; }); addFormatToken(0, ['YY', 2], 0, function () { return this.year() % 100; }); addFormatToken(0, ['YYYY', 4], 0, 'year'); addFormatToken(0, ['YYYYY', 5], 0, 'year'); addFormatToken(0, ['YYYYYY', 6, true], 0, 'year'); // ALIASES addUnitAlias('year', 'y'); // PRIORITIES addUnitPriority('year', 1); // PARSING addRegexToken('Y', matchSigned); addRegexToken('YY', match1to2, match2); addRegexToken('YYYY', match1to4, match4); addRegexToken('YYYYY', match1to6, match6); addRegexToken('YYYYYY', match1to6, match6); addParseToken(['YYYYY', 'YYYYYY'], YEAR); addParseToken('YYYY', function (input, array) { array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); }); addParseToken('YY', function (input, array) { array[YEAR] = hooks.parseTwoDigitYear(input); }); addParseToken('Y', function (input, array) { array[YEAR] = parseInt(input, 10); }); // HELPERS function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } // HOOKS hooks.parseTwoDigitYear = function (input) { return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); }; // MOMENTS var getSetYear = makeGetSet('FullYear', true); function getIsLeapYear() { return isLeapYear(this.year()); } function createDate(y, m, d, h, M, s, ms) { // can't just apply() to create a date: // https://stackoverflow.com/q/181348 var date; // the date constructor remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0) { // preserve leap years using a full 400 year cycle, then reset date = new Date(y + 400, m, d, h, M, s, ms); if (isFinite(date.getFullYear())) { date.setFullYear(y); } } else { date = new Date(y, m, d, h, M, s, ms); } return date; } function createUTCDate(y) { var date, args; // the Date.UTC function remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0) { args = Array.prototype.slice.call(arguments); // preserve leap years using a full 400 year cycle, then reset args[0] = y + 400; date = new Date(Date.UTC.apply(null, args)); if (isFinite(date.getUTCFullYear())) { date.setUTCFullYear(y); } } else { date = new Date(Date.UTC.apply(null, arguments)); } return date; } // start-of-first-week - start-of-year function firstWeekOffset(year, dow, doy) { var // first-week day -- which january is always in the first week (4 for iso, 1 for other) fwd = 7 + dow - doy, // first-week day local weekday -- which local weekday is fwd fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; return -fwdlw + fwd - 1; } // https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, dow, doy) { var localWeekday = (7 + weekday - dow) % 7, weekOffset = firstWeekOffset(year, dow, doy), dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, resYear, resDayOfYear; if (dayOfYear <= 0) { resYear = year - 1; resDayOfYear = daysInYear(resYear) + dayOfYear; } else if (dayOfYear > daysInYear(year)) { resYear = year + 1; resDayOfYear = dayOfYear - daysInYear(year); } else { resYear = year; resDayOfYear = dayOfYear; } return { year: resYear, dayOfYear: resDayOfYear, }; } function weekOfYear(mom, dow, doy) { var weekOffset = firstWeekOffset(mom.year(), dow, doy), week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, resWeek, resYear; if (week < 1) { resYear = mom.year() - 1; resWeek = week + weeksInYear(resYear, dow, doy); } else if (week > weeksInYear(mom.year(), dow, doy)) { resWeek = week - weeksInYear(mom.year(), dow, doy); resYear = mom.year() + 1; } else { resYear = mom.year(); resWeek = week; } return { week: resWeek, year: resYear, }; } function weeksInYear(year, dow, doy) { var weekOffset = firstWeekOffset(year, dow, doy), weekOffsetNext = firstWeekOffset(year + 1, dow, doy); return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; } // FORMATTING addFormatToken('w', ['ww', 2], 'wo', 'week'); addFormatToken('W', ['WW', 2], 'Wo', 'isoWeek'); // ALIASES addUnitAlias('week', 'w'); addUnitAlias('isoWeek', 'W'); // PRIORITIES addUnitPriority('week', 5); addUnitPriority('isoWeek', 5); // PARSING addRegexToken('w', match1to2); addRegexToken('ww', match1to2, match2); addRegexToken('W', match1to2); addRegexToken('WW', match1to2, match2); addWeekParseToken(['w', 'ww', 'W', 'WW'], function ( input, week, config, token ) { week[token.substr(0, 1)] = toInt(input); }); // HELPERS // LOCALES function localeWeek(mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; } var defaultLocaleWeek = { dow: 0, // Sunday is the first day of the week. doy: 6, // The week that contains Jan 6th is the first week of the year. }; function localeFirstDayOfWeek() { return this._week.dow; } function localeFirstDayOfYear() { return this._week.doy; } // MOMENTS function getSetWeek(input) { var week = this.localeData().week(this); return input == null ? week : this.add((input - week) * 7, 'd'); } function getSetISOWeek(input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add((input - week) * 7, 'd'); } // FORMATTING addFormatToken('d', 0, 'do', 'day'); addFormatToken('dd', 0, 0, function (format) { return this.localeData().weekdaysMin(this, format); }); addFormatToken('ddd', 0, 0, function (format) { return this.localeData().weekdaysShort(this, format); }); addFormatToken('dddd', 0, 0, function (format) { return this.localeData().weekdays(this, format); }); addFormatToken('e', 0, 0, 'weekday'); addFormatToken('E', 0, 0, 'isoWeekday'); // ALIASES addUnitAlias('day', 'd'); addUnitAlias('weekday', 'e'); addUnitAlias('isoWeekday', 'E'); // PRIORITY addUnitPriority('day', 11); addUnitPriority('weekday', 11); addUnitPriority('isoWeekday', 11); // PARSING addRegexToken('d', match1to2); addRegexToken('e', match1to2); addRegexToken('E', match1to2); addRegexToken('dd', function (isStrict, locale) { return locale.weekdaysMinRegex(isStrict); }); addRegexToken('ddd', function (isStrict, locale) { return locale.weekdaysShortRegex(isStrict); }); addRegexToken('dddd', function (isStrict, locale) { return locale.weekdaysRegex(isStrict); }); addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { var weekday = config._locale.weekdaysParse(input, token, config._strict); // if we didn't get a weekday name, mark the date as invalid if (weekday != null) { week.d = weekday; } else { getParsingFlags(config).invalidWeekday = input; } }); addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { week[token] = toInt(input); }); // HELPERS function parseWeekday(input, locale) { if (typeof input !== 'string') { return input; } if (!isNaN(input)) { return parseInt(input, 10); } input = locale.weekdaysParse(input); if (typeof input === 'number') { return input; } return null; } function parseIsoWeekday(input, locale) { if (typeof input === 'string') { return locale.weekdaysParse(input) % 7 || 7; } return isNaN(input) ? null : input; } // LOCALES function shiftWeekdays(ws, n) { return ws.slice(n, 7).concat(ws.slice(0, n)); } var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split( '_' ), defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), defaultWeekdaysRegex = matchWord, defaultWeekdaysShortRegex = matchWord, defaultWeekdaysMinRegex = matchWord; function localeWeekdays(m, format) { var weekdays = isArray(this._weekdays) ? this._weekdays : this._weekdays[ m && m !== true && this._weekdays.isFormat.test(format) ? 'format' : 'standalone' ]; return m === true ? shiftWeekdays(weekdays, this._week.dow) : m ? weekdays[m.day()] : weekdays; } function localeWeekdaysShort(m) { return m === true ? shiftWeekdays(this._weekdaysShort, this._week.dow) : m ? this._weekdaysShort[m.day()] : this._weekdaysShort; } function localeWeekdaysMin(m) { return m === true ? shiftWeekdays(this._weekdaysMin, this._week.dow) : m ? this._weekdaysMin[m.day()] : this._weekdaysMin; } function handleStrictParse$1(weekdayName, format, strict) { var i, ii, mom, llc = weekdayName.toLocaleLowerCase(); if (!this._weekdaysParse) { this._weekdaysParse = []; this._shortWeekdaysParse = []; this._minWeekdaysParse = []; for (i = 0; i < 7; ++i) { mom = createUTC([2000, 1]).day(i); this._minWeekdaysParse[i] = this.weekdaysMin( mom, '' ).toLocaleLowerCase(); this._shortWeekdaysParse[i] = this.weekdaysShort( mom, '' ).toLocaleLowerCase(); this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); } } if (strict) { if (format === 'dddd') { ii = indexOf.call(this._weekdaysParse, llc); return ii !== -1 ? ii : null; } else if (format === 'ddd') { ii = indexOf.call(this._shortWeekdaysParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } } else { if (format === 'dddd') { ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } else if (format === 'ddd') { ii = indexOf.call(this._shortWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._minWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortWeekdaysParse, llc); return ii !== -1 ? ii : null; } } } function localeWeekdaysParse(weekdayName, format, strict) { var i, mom, regex; if (this._weekdaysParseExact) { return handleStrictParse$1.call(this, weekdayName, format, strict); } if (!this._weekdaysParse) { this._weekdaysParse = []; this._minWeekdaysParse = []; this._shortWeekdaysParse = []; this._fullWeekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already mom = createUTC([2000, 1]).day(i); if (strict && !this._fullWeekdaysParse[i]) { this._fullWeekdaysParse[i] = new RegExp( '^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i' ); this._shortWeekdaysParse[i] = new RegExp( '^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i' ); this._minWeekdaysParse[i] = new RegExp( '^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i' ); } if (!this._weekdaysParse[i]) { regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if ( strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName) ) { return i; } else if ( strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName) ) { return i; } else if ( strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName) ) { return i; } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { return i; } } } // MOMENTS function getSetDayOfWeek(input) { if (!this.isValid()) { return input != null ? this : NaN; } var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.localeData()); return this.add(input - day, 'd'); } else { return day; } } function getSetLocaleDayOfWeek(input) { if (!this.isValid()) { return input != null ? this : NaN; } var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; return input == null ? weekday : this.add(input - weekday, 'd'); } function getSetISODayOfWeek(input) { if (!this.isValid()) { return input != null ? this : NaN; } // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. if (input != null) { var weekday = parseIsoWeekday(input, this.localeData()); return this.day(this.day() % 7 ? weekday : weekday - 7); } else { return this.day() || 7; } } function weekdaysRegex(isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysStrictRegex; } else { return this._weekdaysRegex; } } else { if (!hasOwnProp(this, '_weekdaysRegex')) { this._weekdaysRegex = defaultWeekdaysRegex; } return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex; } } function weekdaysShortRegex(isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysShortStrictRegex; } else { return this._weekdaysShortRegex; } } else { if (!hasOwnProp(this, '_weekdaysShortRegex')) { this._weekdaysShortRegex = defaultWeekdaysShortRegex; } return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex; } } function weekdaysMinRegex(isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysMinStrictRegex; } else { return this._weekdaysMinRegex; } } else { if (!hasOwnProp(this, '_weekdaysMinRegex')) { this._weekdaysMinRegex = defaultWeekdaysMinRegex; } return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex; } } function computeWeekdaysParse() { function cmpLenRev(a, b) { return b.length - a.length; } var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], i, mom, minp, shortp, longp; for (i = 0; i < 7; i++) { // make the regex if we don't have it already mom = createUTC([2000, 1]).day(i); minp = regexEscape(this.weekdaysMin(mom, '')); shortp = regexEscape(this.weekdaysShort(mom, '')); longp = regexEscape(this.weekdays(mom, '')); minPieces.push(minp); shortPieces.push(shortp); longPieces.push(longp); mixedPieces.push(minp); mixedPieces.push(shortp); mixedPieces.push(longp); } // Sorting makes sure if one weekday (or abbr) is a prefix of another it // will match the longer piece. minPieces.sort(cmpLenRev); shortPieces.sort(cmpLenRev); longPieces.sort(cmpLenRev); mixedPieces.sort(cmpLenRev); this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); this._weekdaysShortRegex = this._weekdaysRegex; this._weekdaysMinRegex = this._weekdaysRegex; this._weekdaysStrictRegex = new RegExp( '^(' + longPieces.join('|') + ')', 'i' ); this._weekdaysShortStrictRegex = new RegExp( '^(' + shortPieces.join('|') + ')', 'i' ); this._weekdaysMinStrictRegex = new RegExp( '^(' + minPieces.join('|') + ')', 'i' ); } // FORMATTING function hFormat() { return this.hours() % 12 || 12; } function kFormat() { return this.hours() || 24; } addFormatToken('H', ['HH', 2], 0, 'hour'); addFormatToken('h', ['hh', 2], 0, hFormat); addFormatToken('k', ['kk', 2], 0, kFormat); addFormatToken('hmm', 0, 0, function () { return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2); }); addFormatToken('hmmss', 0, 0, function () { return ( '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2) ); }); addFormatToken('Hmm', 0, 0, function () { return '' + this.hours() + zeroFill(this.minutes(), 2); }); addFormatToken('Hmmss', 0, 0, function () { return ( '' + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2) ); }); function meridiem(token, lowercase) { addFormatToken(token, 0, 0, function () { return this.localeData().meridiem( this.hours(), this.minutes(), lowercase ); }); } meridiem('a', true); meridiem('A', false); // ALIASES addUnitAlias('hour', 'h'); // PRIORITY addUnitPriority('hour', 13); // PARSING function matchMeridiem(isStrict, locale) { return locale._meridiemParse; } addRegexToken('a', matchMeridiem); addRegexToken('A', matchMeridiem); addRegexToken('H', match1to2); addRegexToken('h', match1to2); addRegexToken('k', match1to2); addRegexToken('HH', match1to2, match2); addRegexToken('hh', match1to2, match2); addRegexToken('kk', match1to2, match2); addRegexToken('hmm', match3to4); addRegexToken('hmmss', match5to6); addRegexToken('Hmm', match3to4); addRegexToken('Hmmss', match5to6); addParseToken(['H', 'HH'], HOUR); addParseToken(['k', 'kk'], function (input, array, config) { var kInput = toInt(input); array[HOUR] = kInput === 24 ? 0 : kInput; }); addParseToken(['a', 'A'], function (input, array, config) { config._isPm = config._locale.isPM(input); config._meridiem = input; }); addParseToken(['h', 'hh'], function (input, array, config) { array[HOUR] = toInt(input); getParsingFlags(config).bigHour = true; }); addParseToken('hmm', function (input, array, config) { var pos = input.length - 2; array[HOUR] = toInt(input.substr(0, pos)); array[MINUTE] = toInt(input.substr(pos)); getParsingFlags(config).bigHour = true; }); addParseToken('hmmss', function (input, array, config) { var pos1 = input.length - 4, pos2 = input.length - 2; array[HOUR] = toInt(input.substr(0, pos1)); array[MINUTE] = toInt(input.substr(pos1, 2)); array[SECOND] = toInt(input.substr(pos2)); getParsingFlags(config).bigHour = true; }); addParseToken('Hmm', function (input, array, config) { var pos = input.length - 2; array[HOUR] = toInt(input.substr(0, pos)); array[MINUTE] = toInt(input.substr(pos)); }); addParseToken('Hmmss', function (input, array, config) { var pos1 = input.length - 4, pos2 = input.length - 2; array[HOUR] = toInt(input.substr(0, pos1)); array[MINUTE] = toInt(input.substr(pos1, 2)); array[SECOND] = toInt(input.substr(pos2)); }); // LOCALES function localeIsPM(input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return (input + '').toLowerCase().charAt(0) === 'p'; } var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i, // Setting the hour should keep the time, because the user explicitly // specified which hour they want. So trying to maintain the same hour (in // a new timezone) makes sense. Adding/subtracting hours does not follow // this rule. getSetHour = makeGetSet('Hours', true); function localeMeridiem(hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } } var baseConfig = { calendar: defaultCalendar, longDateFormat: defaultLongDateFormat, invalidDate: defaultInvalidDate, ordinal: defaultOrdinal, dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, relativeTime: defaultRelativeTime, months: defaultLocaleMonths, monthsShort: defaultLocaleMonthsShort, week: defaultLocaleWeek, weekdays: defaultLocaleWeekdays, weekdaysMin: defaultLocaleWeekdaysMin, weekdaysShort: defaultLocaleWeekdaysShort, meridiemParse: defaultLocaleMeridiemParse, }; // internal storage for locale config files var locales = {}, localeFamilies = {}, globalLocale; function commonPrefix(arr1, arr2) { var i, minl = Math.min(arr1.length, arr2.length); for (i = 0; i < minl; i += 1) { if (arr1[i] !== arr2[i]) { return i; } } return minl; } function normalizeLocale(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // pick the locale from the array // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root function chooseLocale(names) { var i = 0, j, next, locale, split; while (i < names.length) { split = normalizeLocale(names[i]).split('-'); j = split.length; next = normalizeLocale(names[i + 1]); next = next ? next.split('-') : null; while (j > 0) { locale = loadLocale(split.slice(0, j).join('-')); if (locale) { return locale; } if ( next && next.length >= j && commonPrefix(split, next) >= j - 1 ) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return globalLocale; } function loadLocale(name) { var oldLocale = null, aliasedRequire; // TODO: Find a better way to register and load all the locales in Node if ( locales[name] === undefined && 'object' !== 'undefined' && module && module.exports ) { try { oldLocale = globalLocale._abbr; aliasedRequire = commonjsRequire; aliasedRequire('./locale/' + name); getSetGlobalLocale(oldLocale); } catch (e) { // mark as not found to avoid repeating expensive file require call causing high CPU // when trying to find en-US, en_US, en-us for every format call locales[name] = null; // null means not found } } return locales[name]; } // This function will load locale and then set the global locale. If // no arguments are passed in, it will simply return the current global // locale key. function getSetGlobalLocale(key, values) { var data; if (key) { if (isUndefined(values)) { data = getLocale(key); } else { data = defineLocale(key, values); } if (data) { // moment.duration._locale = moment._locale = data; globalLocale = data; } else { if (typeof console !== 'undefined' && console.warn) { //warn user if arguments are passed but the locale could not be set console.warn( 'Locale ' + key + ' not found. Did you forget to load it?' ); } } } return globalLocale._abbr; } function defineLocale(name, config) { if (config !== null) { var locale, parentConfig = baseConfig; config.abbr = name; if (locales[name] != null) { deprecateSimple( 'defineLocaleOverride', 'use moment.updateLocale(localeName, config) to change ' + 'an existing locale. moment.defineLocale(localeName, ' + 'config) should only be used for creating a new locale ' + 'See http://momentjs.com/guides/#/warnings/define-locale/ for more info.' ); parentConfig = locales[name]._config; } else if (config.parentLocale != null) { if (locales[config.parentLocale] != null) { parentConfig = locales[config.parentLocale]._config; } else { locale = loadLocale(config.parentLocale); if (locale != null) { parentConfig = locale._config; } else { if (!localeFamilies[config.parentLocale]) { localeFamilies[config.parentLocale] = []; } localeFamilies[config.parentLocale].push({ name: name, config: config, }); return null; } } } locales[name] = new Locale(mergeConfigs(parentConfig, config)); if (localeFamilies[name]) { localeFamilies[name].forEach(function (x) { defineLocale(x.name, x.config); }); } // backwards compat for now: also set the locale // make sure we set the locale AFTER all child locales have been // created, so we won't end up with the child locale set. getSetGlobalLocale(name); return locales[name]; } else { // useful for testing delete locales[name]; return null; } } function updateLocale(name, config) { if (config != null) { var locale, tmpLocale, parentConfig = baseConfig; if (locales[name] != null && locales[name].parentLocale != null) { // Update existing child locale in-place to avoid memory-leaks locales[name].set(mergeConfigs(locales[name]._config, config)); } else { // MERGE tmpLocale = loadLocale(name); if (tmpLocale != null) { parentConfig = tmpLocale._config; } config = mergeConfigs(parentConfig, config); if (tmpLocale == null) { // updateLocale is called for creating a new locale // Set abbr so it will have a name (getters return // undefined otherwise). config.abbr = name; } locale = new Locale(config); locale.parentLocale = locales[name]; locales[name] = locale; } // backwards compat for now: also set the locale getSetGlobalLocale(name); } else { // pass null for config to unupdate, useful for tests if (locales[name] != null) { if (locales[name].parentLocale != null) { locales[name] = locales[name].parentLocale; if (name === getSetGlobalLocale()) { getSetGlobalLocale(name); } } else if (locales[name] != null) { delete locales[name]; } } } return locales[name]; } // returns locale data function getLocale(key) { var locale; if (key && key._locale && key._locale._abbr) { key = key._locale._abbr; } if (!key) { return globalLocale; } if (!isArray(key)) { //short-circuit everything else locale = loadLocale(key); if (locale) { return locale; } key = [key]; } return chooseLocale(key); } function listLocales() { return keys(locales); } function checkOverflow(m) { var overflow, a = m._a; if (a && getParsingFlags(m).overflow === -2) { overflow = a[MONTH] < 0 || a[MONTH] > 11 ? MONTH : a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH]) ? DATE : a[HOUR] < 0 || a[HOUR] > 24 || (a[HOUR] === 24 && (a[MINUTE] !== 0 || a[SECOND] !== 0 || a[MILLISECOND] !== 0)) ? HOUR : a[MINUTE] < 0 || a[MINUTE] > 59 ? MINUTE : a[SECOND] < 0 || a[SECOND] > 59 ? SECOND : a[MILLISECOND] < 0 || a[MILLISECOND] > 999 ? MILLISECOND : -1; if ( getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE) ) { overflow = DATE; } if (getParsingFlags(m)._overflowWeeks && overflow === -1) { overflow = WEEK; } if (getParsingFlags(m)._overflowWeekday && overflow === -1) { overflow = WEEKDAY; } getParsingFlags(m).overflow = overflow; } return m; } // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, tzRegex = /Z|[+-]\d\d(?::?\d\d)?/, isoDates = [ ['YYYYYY-MM-DD', /[+-]\d{6}-\d\d-\d\d/], ['YYYY-MM-DD', /\d{4}-\d\d-\d\d/], ['GGGG-[W]WW-E', /\d{4}-W\d\d-\d/], ['GGGG-[W]WW', /\d{4}-W\d\d/, false], ['YYYY-DDD', /\d{4}-\d{3}/], ['YYYY-MM', /\d{4}-\d\d/, false], ['YYYYYYMMDD', /[+-]\d{10}/], ['YYYYMMDD', /\d{8}/], ['GGGG[W]WWE', /\d{4}W\d{3}/], ['GGGG[W]WW', /\d{4}W\d{2}/, false], ['YYYYDDD', /\d{7}/], ['YYYYMM', /\d{6}/, false], ['YYYY', /\d{4}/, false], ], // iso time formats and regexes isoTimes = [ ['HH:mm:ss.SSSS', /\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss,SSSS', /\d\d:\d\d:\d\d,\d+/], ['HH:mm:ss', /\d\d:\d\d:\d\d/], ['HH:mm', /\d\d:\d\d/], ['HHmmss.SSSS', /\d\d\d\d\d\d\.\d+/], ['HHmmss,SSSS', /\d\d\d\d\d\d,\d+/], ['HHmmss', /\d\d\d\d\d\d/], ['HHmm', /\d\d\d\d/], ['HH', /\d\d/], ], aspNetJsonRegex = /^\/?Date\((-?\d+)/i, // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3 rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/, obsOffsets = { UT: 0, GMT: 0, EDT: -4 * 60, EST: -5 * 60, CDT: -5 * 60, CST: -6 * 60, MDT: -6 * 60, MST: -7 * 60, PDT: -7 * 60, PST: -8 * 60, }; // date from iso format function configFromISO(config) { var i, l, string = config._i, match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string), allowTime, dateFormat, timeFormat, tzFormat; if (match) { getParsingFlags(config).iso = true; for (i = 0, l = isoDates.length; i < l; i++) { if (isoDates[i][1].exec(match[1])) { dateFormat = isoDates[i][0]; allowTime = isoDates[i][2] !== false; break; } } if (dateFormat == null) { config._isValid = false; return; } if (match[3]) { for (i = 0, l = isoTimes.length; i < l; i++) { if (isoTimes[i][1].exec(match[3])) { // match[2] should be 'T' or space timeFormat = (match[2] || ' ') + isoTimes[i][0]; break; } } if (timeFormat == null) { config._isValid = false; return; } } if (!allowTime && timeFormat != null) { config._isValid = false; return; } if (match[4]) { if (tzRegex.exec(match[4])) { tzFormat = 'Z'; } else { config._isValid = false; return; } } config._f = dateFormat + (timeFormat || '') + (tzFormat || ''); configFromStringAndFormat(config); } else { config._isValid = false; } } function extractFromRFC2822Strings( yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr ) { var result = [ untruncateYear(yearStr), defaultLocaleMonthsShort.indexOf(monthStr), parseInt(dayStr, 10), parseInt(hourStr, 10), parseInt(minuteStr, 10), ]; if (secondStr) { result.push(parseInt(secondStr, 10)); } return result; } function untruncateYear(yearStr) { var year = parseInt(yearStr, 10); if (year <= 49) { return 2000 + year; } else if (year <= 999) { return 1900 + year; } return year; } function preprocessRFC2822(s) { // Remove comments and folding whitespace and replace multiple-spaces with a single space return s .replace(/\([^)]*\)|[\n\t]/g, ' ') .replace(/(\s\s+)/g, ' ') .replace(/^\s\s*/, '') .replace(/\s\s*$/, ''); } function checkWeekday(weekdayStr, parsedInput, config) { if (weekdayStr) { // TODO: Replace the vanilla JS Date object with an independent day-of-week check. var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), weekdayActual = new Date( parsedInput[0], parsedInput[1], parsedInput[2] ).getDay(); if (weekdayProvided !== weekdayActual) { getParsingFlags(config).weekdayMismatch = true; config._isValid = false; return false; } } return true; } function calculateOffset(obsOffset, militaryOffset, numOffset) { if (obsOffset) { return obsOffsets[obsOffset]; } else if (militaryOffset) { // the only allowed military tz is Z return 0; } else { var hm = parseInt(numOffset, 10), m = hm % 100, h = (hm - m) / 100; return h * 60 + m; } } // date and time from ref 2822 format function configFromRFC2822(config) { var match = rfc2822.exec(preprocessRFC2822(config._i)), parsedArray; if (match) { parsedArray = extractFromRFC2822Strings( match[4], match[3], match[2], match[5], match[6], match[7] ); if (!checkWeekday(match[1], parsedArray, config)) { return; } config._a = parsedArray; config._tzm = calculateOffset(match[8], match[9], match[10]); config._d = createUTCDate.apply(null, config._a); config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); getParsingFlags(config).rfc2822 = true; } else { config._isValid = false; } } // date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict function configFromString(config) { var matched = aspNetJsonRegex.exec(config._i); if (matched !== null) { config._d = new Date(+matched[1]); return; } configFromISO(config); if (config._isValid === false) { delete config._isValid; } else { return; } configFromRFC2822(config); if (config._isValid === false) { delete config._isValid; } else { return; } if (config._strict) { config._isValid = false; } else { // Final attempt, use Input Fallback hooks.createFromInputFallback(config); } } hooks.createFromInputFallback = deprecate( 'value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), ' + 'which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are ' + 'discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.', function (config) { config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); } ); // Pick the first defined of two or three arguments. function defaults(a, b, c) { if (a != null) { return a; } if (b != null) { return b; } return c; } function currentDateArray(config) { // hooks is actually the exported moment object var nowValue = new Date(hooks.now()); if (config._useUTC) { return [ nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate(), ]; } return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function configFromArray(config) { var i, date, input = [], currentDate, expectedWeekday, yearToUse; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { dayOfYearFromWeekInfo(config); } //if the day of the year is set, figure out what it is if (config._dayOfYear != null) { yearToUse = defaults(config._a[YEAR], currentDate[YEAR]); if ( config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0 ) { getParsingFlags(config)._overflowDayOfYear = true; } date = createUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; i < 7; i++) { config._a[i] = input[i] = config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i]; } // Check for 24:00:00.000 if ( config._a[HOUR] === 24 && config._a[MINUTE] === 0 && config._a[SECOND] === 0 && config._a[MILLISECOND] === 0 ) { config._nextDay = true; config._a[HOUR] = 0; } config._d = (config._useUTC ? createUTCDate : createDate).apply( null, input ); expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay(); // Apply timezone offset from input. The actual utcOffset can be changed // with parseZone. if (config._tzm != null) { config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); } if (config._nextDay) { config._a[HOUR] = 24; } // check for mismatching day of week if ( config._w && typeof config._w.d !== 'undefined' && config._w.d !== expectedWeekday ) { getParsingFlags(config).weekdayMismatch = true; } } function dayOfYearFromWeekInfo(config) { var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek; w = config._w; if (w.GG != null || w.W != null || w.E != null) { dow = 1; doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on // how we interpret now (local, utc, fixed offset). So create // a now version of current config (take local/utc/offset flags, and // create now). weekYear = defaults( w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year ); week = defaults(w.W, 1); weekday = defaults(w.E, 1); if (weekday < 1 || weekday > 7) { weekdayOverflow = true; } } else { dow = config._locale._week.dow; doy = config._locale._week.doy; curWeek = weekOfYear(createLocal(), dow, doy); weekYear = defaults(w.gg, config._a[YEAR], curWeek.year); // Default to current week. week = defaults(w.w, curWeek.week); if (w.d != null) { // weekday -- low day numbers are considered next week weekday = w.d; if (weekday < 0 || weekday > 6) { weekdayOverflow = true; } } else if (w.e != null) { // local weekday -- counting starts from beginning of week weekday = w.e + dow; if (w.e < 0 || w.e > 6) { weekdayOverflow = true; } } else { // default to beginning of week weekday = dow; } } if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { getParsingFlags(config)._overflowWeeks = true; } else if (weekdayOverflow != null) { getParsingFlags(config)._overflowWeekday = true; } else { temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } } // constant that refers to the ISO standard hooks.ISO_8601 = function () {}; // constant that refers to the RFC 2822 form hooks.RFC_2822 = function () {}; // date from string and format string function configFromStringAndFormat(config) { // TODO: Move this to another part of the creation flow to prevent circular deps if (config._f === hooks.ISO_8601) { configFromISO(config); return; } if (config._f === hooks.RFC_2822) { configFromRFC2822(config); return; } config._a = []; getParsingFlags(config).empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0, era; tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { getParsingFlags(config).unusedInput.push(skipped); } string = string.slice( string.indexOf(parsedInput) + parsedInput.length ); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { getParsingFlags(config).empty = false; } else { getParsingFlags(config).unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { getParsingFlags(config).unusedTokens.push(token); } } // add remaining unparsed input length to the string getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { getParsingFlags(config).unusedInput.push(string); } // clear _12h flag if hour is <= 12 if ( config._a[HOUR] <= 12 && getParsingFlags(config).bigHour === true && config._a[HOUR] > 0 ) { getParsingFlags(config).bigHour = undefined; } getParsingFlags(config).parsedDateParts = config._a.slice(0); getParsingFlags(config).meridiem = config._meridiem; // handle meridiem config._a[HOUR] = meridiemFixWrap( config._locale, config._a[HOUR], config._meridiem ); // handle era era = getParsingFlags(config).era; if (era !== null) { config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]); } configFromArray(config); checkOverflow(config); } function meridiemFixWrap(locale, hour, meridiem) { var isPm; if (meridiem == null) { // nothing to do return hour; } if (locale.meridiemHour != null) { return locale.meridiemHour(hour, meridiem); } else if (locale.isPM != null) { // Fallback isPm = locale.isPM(meridiem); if (isPm && hour < 12) { hour += 12; } if (!isPm && hour === 12) { hour = 0; } return hour; } else { // this is not supposed to happen return hour; } } // date from string and array of format strings function configFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore, validFormatFound, bestFormatIsValid = false; if (config._f.length === 0) { getParsingFlags(config).invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; validFormatFound = false; tempConfig = copyConfig({}, config); if (config._useUTC != null) { tempConfig._useUTC = config._useUTC; } tempConfig._f = config._f[i]; configFromStringAndFormat(tempConfig); if (isValid(tempConfig)) { validFormatFound = true; } // if there is any input that was not parsed add a penalty for that format currentScore += getParsingFlags(tempConfig).charsLeftOver; //or tokens currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; getParsingFlags(tempConfig).score = currentScore; if (!bestFormatIsValid) { if ( scoreToBeat == null || currentScore < scoreToBeat || validFormatFound ) { scoreToBeat = currentScore; bestMoment = tempConfig; if (validFormatFound) { bestFormatIsValid = true; } } } else { if (currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } } extend(config, bestMoment || tempConfig); } function configFromObject(config) { if (config._d) { return; } var i = normalizeObjectUnits(config._i), dayOrDate = i.day === undefined ? i.date : i.day; config._a = map( [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond], function (obj) { return obj && parseInt(obj, 10); } ); configFromArray(config); } function createFromConfig(config) { var res = new Moment(checkOverflow(prepareConfig(config))); if (res._nextDay) { // Adding is smart enough around DST res.add(1, 'd'); res._nextDay = undefined; } return res; } function prepareConfig(config) { var input = config._i, format = config._f; config._locale = config._locale || getLocale(config._l); if (input === null || (format === undefined && input === '')) { return createInvalid({ nullInput: true }); } if (typeof input === 'string') { config._i = input = config._locale.preparse(input); } if (isMoment(input)) { return new Moment(checkOverflow(input)); } else if (isDate(input)) { config._d = input; } else if (isArray(format)) { configFromStringAndArray(config); } else if (format) { configFromStringAndFormat(config); } else { configFromInput(config); } if (!isValid(config)) { config._d = null; } return config; } function configFromInput(config) { var input = config._i; if (isUndefined(input)) { config._d = new Date(hooks.now()); } else if (isDate(input)) { config._d = new Date(input.valueOf()); } else if (typeof input === 'string') { configFromString(config); } else if (isArray(input)) { config._a = map(input.slice(0), function (obj) { return parseInt(obj, 10); }); configFromArray(config); } else if (isObject(input)) { configFromObject(config); } else if (isNumber(input)) { // from milliseconds config._d = new Date(input); } else { hooks.createFromInputFallback(config); } } function createLocalOrUTC(input, format, locale, strict, isUTC) { var c = {}; if (format === true || format === false) { strict = format; format = undefined; } if (locale === true || locale === false) { strict = locale; locale = undefined; } if ( (isObject(input) && isObjectEmpty(input)) || (isArray(input) && input.length === 0) ) { input = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c._isAMomentObject = true; c._useUTC = c._isUTC = isUTC; c._l = locale; c._i = input; c._f = format; c._strict = strict; return createFromConfig(c); } function createLocal(input, format, locale, strict) { return createLocalOrUTC(input, format, locale, strict, false); } var prototypeMin = deprecate( 'moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', function () { var other = createLocal.apply(null, arguments); if (this.isValid() && other.isValid()) { return other < this ? this : other; } else { return createInvalid(); } } ), prototypeMax = deprecate( 'moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', function () { var other = createLocal.apply(null, arguments); if (this.isValid() && other.isValid()) { return other > this ? this : other; } else { return createInvalid(); } } ); // Pick a moment m from moments so that m[fn](other) is true for all // other. This relies on the function fn to be transitive. // // moments should either be an array of moment objects or an array, whose // first element is an array of moment objects. function pickBy(fn, moments) { var res, i; if (moments.length === 1 && isArray(moments[0])) { moments = moments[0]; } if (!moments.length) { return createLocal(); } res = moments[0]; for (i = 1; i < moments.length; ++i) { if (!moments[i].isValid() || moments[i][fn](res)) { res = moments[i]; } } return res; } // TODO: Use [].sort instead? function min() { var args = [].slice.call(arguments, 0); return pickBy('isBefore', args); } function max() { var args = [].slice.call(arguments, 0); return pickBy('isAfter', args); } var now = function () { return Date.now ? Date.now() : +new Date(); }; var ordering = [ 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond', ]; function isDurationValid(m) { var key, unitHasDecimal = false, i; for (key in m) { if ( hasOwnProp(m, key) && !( indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])) ) ) { return false; } } for (i = 0; i < ordering.length; ++i) { if (m[ordering[i]]) { if (unitHasDecimal) { return false; // only allow non-integers for smallest unit } if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) { unitHasDecimal = true; } } } return true; } function isValid$1() { return this._isValid; } function createInvalid$1() { return createDuration(NaN); } function Duration(duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || normalizedInput.isoWeek || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; this._isValid = isDurationValid(normalizedInput); // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible to translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + quarters * 3 + years * 12; this._data = {}; this._locale = getLocale(); this._bubble(); } function isDuration(obj) { return obj instanceof Duration; } function absRound(number) { if (number < 0) { return Math.round(-1 * number) * -1; } else { return Math.round(number); } } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ( (dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i])) ) { diffs++; } } return diffs + lengthDiff; } // FORMATTING function offset(token, separator) { addFormatToken(token, 0, 0, function () { var offset = this.utcOffset(), sign = '+'; if (offset < 0) { offset = -offset; sign = '-'; } return ( sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~offset % 60, 2) ); }); } offset('Z', ':'); offset('ZZ', ''); // PARSING addRegexToken('Z', matchShortOffset); addRegexToken('ZZ', matchShortOffset); addParseToken(['Z', 'ZZ'], function (input, array, config) { config._useUTC = true; config._tzm = offsetFromString(matchShortOffset, input); }); // HELPERS // timezone chunker // '+10:00' > ['10', '00'] // '-1530' > ['-15', '30'] var chunkOffset = /([\+\-]|\d\d)/gi; function offsetFromString(matcher, string) { var matches = (string || '').match(matcher), chunk, parts, minutes; if (matches === null) { return null; } chunk = matches[matches.length - 1] || []; parts = (chunk + '').match(chunkOffset) || ['-', 0, 0]; minutes = +(parts[1] * 60) + toInt(parts[2]); return minutes === 0 ? 0 : parts[0] === '+' ? minutes : -minutes; } // Return a moment from input, that is local/utc/zone equivalent to model. function cloneWithOffset(input, model) { var res, diff; if (model._isUTC) { res = model.clone(); diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(); // Use low-level api, because this fn is low-level api. res._d.setTime(res._d.valueOf() + diff); hooks.updateOffset(res, false); return res; } else { return createLocal(input).local(); } } function getDateOffset(m) { // On Firefox.24 Date#getTimezoneOffset returns a floating point. // https://github.com/moment/moment/pull/1871 return -Math.round(m._d.getTimezoneOffset()); } // HOOKS // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. hooks.updateOffset = function () {}; // MOMENTS // keepLocalTime = true means only change the timezone, without // affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]--> // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset // +0200, so we adjust the time as needed, to be valid. // // Keeping the time actually adds/subtracts (one hour) // from the actual represented time. That is why we call updateOffset // a second time. In case it wants us to change the offset again // _changeInProgress == true case, then we have to adjust, because // there is no such time in the given timezone. function getSetOffset(input, keepLocalTime, keepMinutes) { var offset = this._offset || 0, localAdjust; if (!this.isValid()) { return input != null ? this : NaN; } if (input != null) { if (typeof input === 'string') { input = offsetFromString(matchShortOffset, input); if (input === null) { return this; } } else if (Math.abs(input) < 16 && !keepMinutes) { input = input * 60; } if (!this._isUTC && keepLocalTime) { localAdjust = getDateOffset(this); } this._offset = input; this._isUTC = true; if (localAdjust != null) { this.add(localAdjust, 'm'); } if (offset !== input) { if (!keepLocalTime || this._changeInProgress) { addSubtract( this, createDuration(input - offset, 'm'), 1, false ); } else if (!this._changeInProgress) { this._changeInProgress = true; hooks.updateOffset(this, true); this._changeInProgress = null; } } return this; } else { return this._isUTC ? offset : getDateOffset(this); } } function getSetZone(input, keepLocalTime) { if (input != null) { if (typeof input !== 'string') { input = -input; } this.utcOffset(input, keepLocalTime); return this; } else { return -this.utcOffset(); } } function setOffsetToUTC(keepLocalTime) { return this.utcOffset(0, keepLocalTime); } function setOffsetToLocal(keepLocalTime) { if (this._isUTC) { this.utcOffset(0, keepLocalTime); this._isUTC = false; if (keepLocalTime) { this.subtract(getDateOffset(this), 'm'); } } return this; } function setOffsetToParsedOffset() { if (this._tzm != null) { this.utcOffset(this._tzm, false, true); } else if (typeof this._i === 'string') { var tZone = offsetFromString(matchOffset, this._i); if (tZone != null) { this.utcOffset(tZone); } else { this.utcOffset(0, true); } } return this; } function hasAlignedHourOffset(input) { if (!this.isValid()) { return false; } input = input ? createLocal(input).utcOffset() : 0; return (this.utcOffset() - input) % 60 === 0; } function isDaylightSavingTime() { return ( this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset() ); } function isDaylightSavingTimeShifted() { if (!isUndefined(this._isDSTShifted)) { return this._isDSTShifted; } var c = {}, other; copyConfig(c, this); c = prepareConfig(c); if (c._a) { other = c._isUTC ? createUTC(c._a) : createLocal(c._a); this._isDSTShifted = this.isValid() && compareArrays(c._a, other.toArray()) > 0; } else { this._isDSTShifted = false; } return this._isDSTShifted; } function isLocal() { return this.isValid() ? !this._isUTC : false; } function isUtcOffset() { return this.isValid() ? this._isUTC : false; } function isUtc() { return this.isValid() ? this._isUTC && this._offset === 0 : false; } // ASP.NET json date format regex var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/, // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere // and further modified to allow for strings containing both week and day isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; function createDuration(input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, diffRes; if (isDuration(input)) { duration = { ms: input._milliseconds, d: input._days, M: input._months, }; } else if (isNumber(input) || !isNaN(+input)) { duration = {}; if (key) { duration[key] = +input; } else { duration.milliseconds = +input; } } else if ((match = aspNetRegex.exec(input))) { sign = match[1] === '-' ? -1 : 1; duration = { y: 0, d: toInt(match[DATE]) * sign, h: toInt(match[HOUR]) * sign, m: toInt(match[MINUTE]) * sign, s: toInt(match[SECOND]) * sign, ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match }; } else if ((match = isoRegex.exec(input))) { sign = match[1] === '-' ? -1 : 1; duration = { y: parseIso(match[2], sign), M: parseIso(match[3], sign), w: parseIso(match[4], sign), d: parseIso(match[5], sign), h: parseIso(match[6], sign), m: parseIso(match[7], sign), s: parseIso(match[8], sign), }; } else if (duration == null) { // checks for null or undefined duration = {}; } else if ( typeof duration === 'object' && ('from' in duration || 'to' in duration) ) { diffRes = momentsDifference( createLocal(duration.from), createLocal(duration.to) ); duration = {}; duration.ms = diffRes.milliseconds; duration.M = diffRes.months; } ret = new Duration(duration); if (isDuration(input) && hasOwnProp(input, '_locale')) { ret._locale = input._locale; } if (isDuration(input) && hasOwnProp(input, '_isValid')) { ret._isValid = input._isValid; } return ret; } createDuration.fn = Duration.prototype; createDuration.invalid = createInvalid$1; function parseIso(inp, sign) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; } function positiveMomentsDifference(base, other) { var res = {}; res.months = other.month() - base.month() + (other.year() - base.year()) * 12; if (base.clone().add(res.months, 'M').isAfter(other)) { --res.months; } res.milliseconds = +other - +base.clone().add(res.months, 'M'); return res; } function momentsDifference(base, other) { var res; if (!(base.isValid() && other.isValid())) { return { milliseconds: 0, months: 0 }; } other = cloneWithOffset(other, base); if (base.isBefore(other)) { res = positiveMomentsDifference(base, other); } else { res = positiveMomentsDifference(other, base); res.milliseconds = -res.milliseconds; res.months = -res.months; } return res; } // TODO: remove 'name' arg after deprecation is removed function createAdder(direction, name) { return function (val, period) { var dur, tmp; //invert the arguments, but complain about it if (period !== null && !isNaN(+period)) { deprecateSimple( name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period). ' + 'See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.' ); tmp = val; val = period; period = tmp; } dur = createDuration(val, period); addSubtract(this, dur, direction); return this; }; } function addSubtract(mom, duration, isAdding, updateOffset) { var milliseconds = duration._milliseconds, days = absRound(duration._days), months = absRound(duration._months); if (!mom.isValid()) { // No op return; } updateOffset = updateOffset == null ? true : updateOffset; if (months) { setMonth(mom, get(mom, 'Month') + months * isAdding); } if (days) { set$1(mom, 'Date', get(mom, 'Date') + days * isAdding); } if (milliseconds) { mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding); } if (updateOffset) { hooks.updateOffset(mom, days || months); } } var add = createAdder(1, 'add'), subtract = createAdder(-1, 'subtract'); function isString(input) { return typeof input === 'string' || input instanceof String; } // type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined function isMomentInput(input) { return ( isMoment(input) || isDate(input) || isString(input) || isNumber(input) || isNumberOrStringArray(input) || isMomentInputObject(input) || input === null || input === undefined ); } function isMomentInputObject(input) { var objectTest = isObject(input) && !isObjectEmpty(input), propertyTest = false, properties = [ 'years', 'year', 'y', 'months', 'month', 'M', 'days', 'day', 'd', 'dates', 'date', 'D', 'hours', 'hour', 'h', 'minutes', 'minute', 'm', 'seconds', 'second', 's', 'milliseconds', 'millisecond', 'ms', ], i, property; for (i = 0; i < properties.length; i += 1) { property = properties[i]; propertyTest = propertyTest || hasOwnProp(input, property); } return objectTest && propertyTest; } function isNumberOrStringArray(input) { var arrayTest = isArray(input), dataTypeTest = false; if (arrayTest) { dataTypeTest = input.filter(function (item) { return !isNumber(item) && isString(input); }).length === 0; } return arrayTest && dataTypeTest; } function isCalendarSpec(input) { var objectTest = isObject(input) && !isObjectEmpty(input), propertyTest = false, properties = [ 'sameDay', 'nextDay', 'lastDay', 'nextWeek', 'lastWeek', 'sameElse', ], i, property; for (i = 0; i < properties.length; i += 1) { property = properties[i]; propertyTest = propertyTest || hasOwnProp(input, property); } return objectTest && propertyTest; } function getCalendarFormat(myMoment, now) { var diff = myMoment.diff(now, 'days', true); return diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; } function calendar$1(time, formats) { // Support for single parameter, formats only overload to the calendar function if (arguments.length === 1) { if (!arguments[0]) { time = undefined; formats = undefined; } else if (isMomentInput(arguments[0])) { time = arguments[0]; formats = undefined; } else if (isCalendarSpec(arguments[0])) { formats = arguments[0]; time = undefined; } } // We want to compare the start of today, vs this. // Getting start-of-today depends on whether we're local/utc/offset or not. var now = time || createLocal(), sod = cloneWithOffset(now, this).startOf('day'), format = hooks.calendarFormat(this, sod) || 'sameElse', output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]); return this.format( output || this.localeData().calendar(format, this, createLocal(now)) ); } function clone() { return new Moment(this); } function isAfter(input, units) { var localInput = isMoment(input) ? input : createLocal(input); if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(units) || 'millisecond'; if (units === 'millisecond') { return this.valueOf() > localInput.valueOf(); } else { return localInput.valueOf() < this.clone().startOf(units).valueOf(); } } function isBefore(input, units) { var localInput = isMoment(input) ? input : createLocal(input); if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(units) || 'millisecond'; if (units === 'millisecond') { return this.valueOf() < localInput.valueOf(); } else { return this.clone().endOf(units).valueOf() < localInput.valueOf(); } } function isBetween(from, to, units, inclusivity) { var localFrom = isMoment(from) ? from : createLocal(from), localTo = isMoment(to) ? to : createLocal(to); if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) { return false; } inclusivity = inclusivity || '()'; return ( (inclusivity[0] === '(' ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && (inclusivity[1] === ')' ? this.isBefore(localTo, units) : !this.isAfter(localTo, units)) ); } function isSame(input, units) { var localInput = isMoment(input) ? input : createLocal(input), inputMs; if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(units) || 'millisecond'; if (units === 'millisecond') { return this.valueOf() === localInput.valueOf(); } else { inputMs = localInput.valueOf(); return ( this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf() ); } } function isSameOrAfter(input, units) { return this.isSame(input, units) || this.isAfter(input, units); } function isSameOrBefore(input, units) { return this.isSame(input, units) || this.isBefore(input, units); } function diff(input, units, asFloat) { var that, zoneDelta, output; if (!this.isValid()) { return NaN; } that = cloneWithOffset(input, this); if (!that.isValid()) { return NaN; } zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; units = normalizeUnits(units); switch (units) { case 'year': output = monthDiff(this, that) / 12; break; case 'month': output = monthDiff(this, that); break; case 'quarter': output = monthDiff(this, that) / 3; break; case 'second': output = (this - that) / 1e3; break; // 1000 case 'minute': output = (this - that) / 6e4; break; // 1000 * 60 case 'hour': output = (this - that) / 36e5; break; // 1000 * 60 * 60 case 'day': output = (this - that - zoneDelta) / 864e5; break; // 1000 * 60 * 60 * 24, negate dst case 'week': output = (this - that - zoneDelta) / 6048e5; break; // 1000 * 60 * 60 * 24 * 7, negate dst default: output = this - that; } return asFloat ? output : absFloor(output); } function monthDiff(a, b) { if (a.date() < b.date()) { // end-of-month calculations work correct when the start month has more // days than the end month. return -monthDiff(b, a); } // difference in months var wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()), // b is in (anchor - 1 month, anchor + 1 month) anchor = a.clone().add(wholeMonthDiff, 'months'), anchor2, adjust; if (b - anchor < 0) { anchor2 = a.clone().add(wholeMonthDiff - 1, 'months'); // linear across the month adjust = (b - anchor) / (anchor - anchor2); } else { anchor2 = a.clone().add(wholeMonthDiff + 1, 'months'); // linear across the month adjust = (b - anchor) / (anchor2 - anchor); } //check for negative zero, return zero if negative zero return -(wholeMonthDiff + adjust) || 0; } hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ'; hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]'; function toString() { return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); } function toISOString(keepOffset) { if (!this.isValid()) { return null; } var utc = keepOffset !== true, m = utc ? this.clone().utc() : this; if (m.year() < 0 || m.year() > 9999) { return formatMoment( m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ' ); } if (isFunction(Date.prototype.toISOString)) { // native implementation is ~50x faster, use it when we can if (utc) { return this.toDate().toISOString(); } else { return new Date(this.valueOf() + this.utcOffset() * 60 * 1000) .toISOString() .replace('Z', formatMoment(m, 'Z')); } } return formatMoment( m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ' ); } /** * Return a human readable representation of a moment that can * also be evaluated to get a new moment which is the same * * @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects */ function inspect() { if (!this.isValid()) { return 'moment.invalid(/* ' + this._i + ' */)'; } var func = 'moment', zone = '', prefix, year, datetime, suffix; if (!this.isLocal()) { func = this.utcOffset() === 0 ? 'moment.utc' : 'moment.parseZone'; zone = 'Z'; } prefix = '[' + func + '("]'; year = 0 <= this.year() && this.year() <= 9999 ? 'YYYY' : 'YYYYYY'; datetime = '-MM-DD[T]HH:mm:ss.SSS'; suffix = zone + '[")]'; return this.format(prefix + year + datetime + suffix); } function format(inputString) { if (!inputString) { inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat; } var output = formatMoment(this, inputString); return this.localeData().postformat(output); } function from(time, withoutSuffix) { if ( this.isValid() && ((isMoment(time) && time.isValid()) || createLocal(time).isValid()) ) { return createDuration({ to: this, from: time }) .locale(this.locale()) .humanize(!withoutSuffix); } else { return this.localeData().invalidDate(); } } function fromNow(withoutSuffix) { return this.from(createLocal(), withoutSuffix); } function to(time, withoutSuffix) { if ( this.isValid() && ((isMoment(time) && time.isValid()) || createLocal(time).isValid()) ) { return createDuration({ from: this, to: time }) .locale(this.locale()) .humanize(!withoutSuffix); } else { return this.localeData().invalidDate(); } } function toNow(withoutSuffix) { return this.to(createLocal(), withoutSuffix); } // If passed a locale key, it will set the locale for this // instance. Otherwise, it will return the locale configuration // variables for this instance. function locale(key) { var newLocaleData; if (key === undefined) { return this._locale._abbr; } else { newLocaleData = getLocale(key); if (newLocaleData != null) { this._locale = newLocaleData; } return this; } } var lang = deprecate( 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', function (key) { if (key === undefined) { return this.localeData(); } else { return this.locale(key); } } ); function localeData() { return this._locale; } var MS_PER_SECOND = 1000, MS_PER_MINUTE = 60 * MS_PER_SECOND, MS_PER_HOUR = 60 * MS_PER_MINUTE, MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR; // actual modulo - handles negative numbers (for dates before 1970): function mod$1(dividend, divisor) { return ((dividend % divisor) + divisor) % divisor; } function localStartOfDate(y, m, d) { // the date constructor remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0) { // preserve leap years using a full 400 year cycle, then reset return new Date(y + 400, m, d) - MS_PER_400_YEARS; } else { return new Date(y, m, d).valueOf(); } } function utcStartOfDate(y, m, d) { // Date.UTC remaps years 0-99 to 1900-1999 if (y < 100 && y >= 0) { // preserve leap years using a full 400 year cycle, then reset return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS; } else { return Date.UTC(y, m, d); } } function startOf(units) { var time, startOfDate; units = normalizeUnits(units); if (units === undefined || units === 'millisecond' || !this.isValid()) { return this; } startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; switch (units) { case 'year': time = startOfDate(this.year(), 0, 1); break; case 'quarter': time = startOfDate( this.year(), this.month() - (this.month() % 3), 1 ); break; case 'month': time = startOfDate(this.year(), this.month(), 1); break; case 'week': time = startOfDate( this.year(), this.month(), this.date() - this.weekday() ); break; case 'isoWeek': time = startOfDate( this.year(), this.month(), this.date() - (this.isoWeekday() - 1) ); break; case 'day': case 'date': time = startOfDate(this.year(), this.month(), this.date()); break; case 'hour': time = this._d.valueOf(); time -= mod$1( time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR ); break; case 'minute': time = this._d.valueOf(); time -= mod$1(time, MS_PER_MINUTE); break; case 'second': time = this._d.valueOf(); time -= mod$1(time, MS_PER_SECOND); break; } this._d.setTime(time); hooks.updateOffset(this, true); return this; } function endOf(units) { var time, startOfDate; units = normalizeUnits(units); if (units === undefined || units === 'millisecond' || !this.isValid()) { return this; } startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; switch (units) { case 'year': time = startOfDate(this.year() + 1, 0, 1) - 1; break; case 'quarter': time = startOfDate( this.year(), this.month() - (this.month() % 3) + 3, 1 ) - 1; break; case 'month': time = startOfDate(this.year(), this.month() + 1, 1) - 1; break; case 'week': time = startOfDate( this.year(), this.month(), this.date() - this.weekday() + 7 ) - 1; break; case 'isoWeek': time = startOfDate( this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7 ) - 1; break; case 'day': case 'date': time = startOfDate(this.year(), this.month(), this.date() + 1) - 1; break; case 'hour': time = this._d.valueOf(); time += MS_PER_HOUR - mod$1( time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR ) - 1; break; case 'minute': time = this._d.valueOf(); time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1; break; case 'second': time = this._d.valueOf(); time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1; break; } this._d.setTime(time); hooks.updateOffset(this, true); return this; } function valueOf() { return this._d.valueOf() - (this._offset || 0) * 60000; } function unix() { return Math.floor(this.valueOf() / 1000); } function toDate() { return new Date(this.valueOf()); } function toArray() { var m = this; return [ m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond(), ]; } function toObject() { var m = this; return { years: m.year(), months: m.month(), date: m.date(), hours: m.hours(), minutes: m.minutes(), seconds: m.seconds(), milliseconds: m.milliseconds(), }; } function toJSON() { // new Date(NaN).toJSON() === null return this.isValid() ? this.toISOString() : null; } function isValid$2() { return isValid(this); } function parsingFlags() { return extend({}, getParsingFlags(this)); } function invalidAt() { return getParsingFlags(this).overflow; } function creationData() { return { input: this._i, format: this._f, locale: this._locale, isUTC: this._isUTC, strict: this._strict, }; } addFormatToken('N', 0, 0, 'eraAbbr'); addFormatToken('NN', 0, 0, 'eraAbbr'); addFormatToken('NNN', 0, 0, 'eraAbbr'); addFormatToken('NNNN', 0, 0, 'eraName'); addFormatToken('NNNNN', 0, 0, 'eraNarrow'); addFormatToken('y', ['y', 1], 'yo', 'eraYear'); addFormatToken('y', ['yy', 2], 0, 'eraYear'); addFormatToken('y', ['yyy', 3], 0, 'eraYear'); addFormatToken('y', ['yyyy', 4], 0, 'eraYear'); addRegexToken('N', matchEraAbbr); addRegexToken('NN', matchEraAbbr); addRegexToken('NNN', matchEraAbbr); addRegexToken('NNNN', matchEraName); addRegexToken('NNNNN', matchEraNarrow); addParseToken(['N', 'NN', 'NNN', 'NNNN', 'NNNNN'], function ( input, array, config, token ) { var era = config._locale.erasParse(input, token, config._strict); if (era) { getParsingFlags(config).era = era; } else { getParsingFlags(config).invalidEra = input; } }); addRegexToken('y', matchUnsigned); addRegexToken('yy', matchUnsigned); addRegexToken('yyy', matchUnsigned); addRegexToken('yyyy', matchUnsigned); addRegexToken('yo', matchEraYearOrdinal); addParseToken(['y', 'yy', 'yyy', 'yyyy'], YEAR); addParseToken(['yo'], function (input, array, config, token) { var match; if (config._locale._eraYearOrdinalRegex) { match = input.match(config._locale._eraYearOrdinalRegex); } if (config._locale.eraYearOrdinalParse) { array[YEAR] = config._locale.eraYearOrdinalParse(input, match); } else { array[YEAR] = parseInt(input, 10); } }); function localeEras(m, format) { var i, l, date, eras = this._eras || getLocale('en')._eras; for (i = 0, l = eras.length; i < l; ++i) { switch (typeof eras[i].since) { case 'string': // truncate time date = hooks(eras[i].since).startOf('day'); eras[i].since = date.valueOf(); break; } switch (typeof eras[i].until) { case 'undefined': eras[i].until = +Infinity; break; case 'string': // truncate time date = hooks(eras[i].until).startOf('day').valueOf(); eras[i].until = date.valueOf(); break; } } return eras; } function localeErasParse(eraName, format, strict) { var i, l, eras = this.eras(), name, abbr, narrow; eraName = eraName.toUpperCase(); for (i = 0, l = eras.length; i < l; ++i) { name = eras[i].name.toUpperCase(); abbr = eras[i].abbr.toUpperCase(); narrow = eras[i].narrow.toUpperCase(); if (strict) { switch (format) { case 'N': case 'NN': case 'NNN': if (abbr === eraName) { return eras[i]; } break; case 'NNNN': if (name === eraName) { return eras[i]; } break; case 'NNNNN': if (narrow === eraName) { return eras[i]; } break; } } else if ([name, abbr, narrow].indexOf(eraName) >= 0) { return eras[i]; } } } function localeErasConvertYear(era, year) { var dir = era.since <= era.until ? +1 : -1; if (year === undefined) { return hooks(era.since).year(); } else { return hooks(era.since).year() + (year - era.offset) * dir; } } function getEraName() { var i, l, val, eras = this.localeData().eras(); for (i = 0, l = eras.length; i < l; ++i) { // truncate time val = this.clone().startOf('day').valueOf(); if (eras[i].since <= val && val <= eras[i].until) { return eras[i].name; } if (eras[i].until <= val && val <= eras[i].since) { return eras[i].name; } } return ''; } function getEraNarrow() { var i, l, val, eras = this.localeData().eras(); for (i = 0, l = eras.length; i < l; ++i) { // truncate time val = this.clone().startOf('day').valueOf(); if (eras[i].since <= val && val <= eras[i].until) { return eras[i].narrow; } if (eras[i].until <= val && val <= eras[i].since) { return eras[i].narrow; } } return ''; } function getEraAbbr() { var i, l, val, eras = this.localeData().eras(); for (i = 0, l = eras.length; i < l; ++i) { // truncate time val = this.clone().startOf('day').valueOf(); if (eras[i].since <= val && val <= eras[i].until) { return eras[i].abbr; } if (eras[i].until <= val && val <= eras[i].since) { return eras[i].abbr; } } return ''; } function getEraYear() { var i, l, dir, val, eras = this.localeData().eras(); for (i = 0, l = eras.length; i < l; ++i) { dir = eras[i].since <= eras[i].until ? +1 : -1; // truncate time val = this.clone().startOf('day').valueOf(); if ( (eras[i].since <= val && val <= eras[i].until) || (eras[i].until <= val && val <= eras[i].since) ) { return ( (this.year() - hooks(eras[i].since).year()) * dir + eras[i].offset ); } } return this.year(); } function erasNameRegex(isStrict) { if (!hasOwnProp(this, '_erasNameRegex')) { computeErasParse.call(this); } return isStrict ? this._erasNameRegex : this._erasRegex; } function erasAbbrRegex(isStrict) { if (!hasOwnProp(this, '_erasAbbrRegex')) { computeErasParse.call(this); } return isStrict ? this._erasAbbrRegex : this._erasRegex; } function erasNarrowRegex(isStrict) { if (!hasOwnProp(this, '_erasNarrowRegex')) { computeErasParse.call(this); } return isStrict ? this._erasNarrowRegex : this._erasRegex; } function matchEraAbbr(isStrict, locale) { return locale.erasAbbrRegex(isStrict); } function matchEraName(isStrict, locale) { return locale.erasNameRegex(isStrict); } function matchEraNarrow(isStrict, locale) { return locale.erasNarrowRegex(isStrict); } function matchEraYearOrdinal(isStrict, locale) { return locale._eraYearOrdinalRegex || matchUnsigned; } function computeErasParse() { var abbrPieces = [], namePieces = [], narrowPieces = [], mixedPieces = [], i, l, eras = this.eras(); for (i = 0, l = eras.length; i < l; ++i) { namePieces.push(regexEscape(eras[i].name)); abbrPieces.push(regexEscape(eras[i].abbr)); narrowPieces.push(regexEscape(eras[i].narrow)); mixedPieces.push(regexEscape(eras[i].name)); mixedPieces.push(regexEscape(eras[i].abbr)); mixedPieces.push(regexEscape(eras[i].narrow)); } this._erasRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); this._erasNameRegex = new RegExp('^(' + namePieces.join('|') + ')', 'i'); this._erasAbbrRegex = new RegExp('^(' + abbrPieces.join('|') + ')', 'i'); this._erasNarrowRegex = new RegExp( '^(' + narrowPieces.join('|') + ')', 'i' ); } // FORMATTING addFormatToken(0, ['gg', 2], 0, function () { return this.weekYear() % 100; }); addFormatToken(0, ['GG', 2], 0, function () { return this.isoWeekYear() % 100; }); function addWeekYearFormatToken(token, getter) { addFormatToken(0, [token, token.length], 0, getter); } addWeekYearFormatToken('gggg', 'weekYear'); addWeekYearFormatToken('ggggg', 'weekYear'); addWeekYearFormatToken('GGGG', 'isoWeekYear'); addWeekYearFormatToken('GGGGG', 'isoWeekYear'); // ALIASES addUnitAlias('weekYear', 'gg'); addUnitAlias('isoWeekYear', 'GG'); // PRIORITY addUnitPriority('weekYear', 1); addUnitPriority('isoWeekYear', 1); // PARSING addRegexToken('G', matchSigned); addRegexToken('g', matchSigned); addRegexToken('GG', match1to2, match2); addRegexToken('gg', match1to2, match2); addRegexToken('GGGG', match1to4, match4); addRegexToken('gggg', match1to4, match4); addRegexToken('GGGGG', match1to6, match6); addRegexToken('ggggg', match1to6, match6); addWeekParseToken(['gggg', 'ggggg', 'GGGG', 'GGGGG'], function ( input, week, config, token ) { week[token.substr(0, 2)] = toInt(input); }); addWeekParseToken(['gg', 'GG'], function (input, week, config, token) { week[token] = hooks.parseTwoDigitYear(input); }); // MOMENTS function getSetWeekYear(input) { return getSetWeekYearHelper.call( this, input, this.week(), this.weekday(), this.localeData()._week.dow, this.localeData()._week.doy ); } function getSetISOWeekYear(input) { return getSetWeekYearHelper.call( this, input, this.isoWeek(), this.isoWeekday(), 1, 4 ); } function getISOWeeksInYear() { return weeksInYear(this.year(), 1, 4); } function getISOWeeksInISOWeekYear() { return weeksInYear(this.isoWeekYear(), 1, 4); } function getWeeksInYear() { var weekInfo = this.localeData()._week; return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); } function getWeeksInWeekYear() { var weekInfo = this.localeData()._week; return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy); } function getSetWeekYearHelper(input, week, weekday, dow, doy) { var weeksTarget; if (input == null) { return weekOfYear(this, dow, doy).year; } else { weeksTarget = weeksInYear(input, dow, doy); if (week > weeksTarget) { week = weeksTarget; } return setWeekAll.call(this, input, week, weekday, dow, doy); } } function setWeekAll(weekYear, week, weekday, dow, doy) { var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); this.year(date.getUTCFullYear()); this.month(date.getUTCMonth()); this.date(date.getUTCDate()); return this; } // FORMATTING addFormatToken('Q', 0, 'Qo', 'quarter'); // ALIASES addUnitAlias('quarter', 'Q'); // PRIORITY addUnitPriority('quarter', 7); // PARSING addRegexToken('Q', match1); addParseToken('Q', function (input, array) { array[MONTH] = (toInt(input) - 1) * 3; }); // MOMENTS function getSetQuarter(input) { return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + (this.month() % 3)); } // FORMATTING addFormatToken('D', ['DD', 2], 'Do', 'date'); // ALIASES addUnitAlias('date', 'D'); // PRIORITY addUnitPriority('date', 9); // PARSING addRegexToken('D', match1to2); addRegexToken('DD', match1to2, match2); addRegexToken('Do', function (isStrict, locale) { // TODO: Remove "ordinalParse" fallback in next major release. return isStrict ? locale._dayOfMonthOrdinalParse || locale._ordinalParse : locale._dayOfMonthOrdinalParseLenient; }); addParseToken(['D', 'DD'], DATE); addParseToken('Do', function (input, array) { array[DATE] = toInt(input.match(match1to2)[0]); }); // MOMENTS var getSetDayOfMonth = makeGetSet('Date', true); // FORMATTING addFormatToken('DDD', ['DDDD', 3], 'DDDo', 'dayOfYear'); // ALIASES addUnitAlias('dayOfYear', 'DDD'); // PRIORITY addUnitPriority('dayOfYear', 4); // PARSING addRegexToken('DDD', match1to3); addRegexToken('DDDD', match3); addParseToken(['DDD', 'DDDD'], function (input, array, config) { config._dayOfYear = toInt(input); }); // HELPERS // MOMENTS function getSetDayOfYear(input) { var dayOfYear = Math.round( (this.clone().startOf('day') - this.clone().startOf('year')) / 864e5 ) + 1; return input == null ? dayOfYear : this.add(input - dayOfYear, 'd'); } // FORMATTING addFormatToken('m', ['mm', 2], 0, 'minute'); // ALIASES addUnitAlias('minute', 'm'); // PRIORITY addUnitPriority('minute', 14); // PARSING addRegexToken('m', match1to2); addRegexToken('mm', match1to2, match2); addParseToken(['m', 'mm'], MINUTE); // MOMENTS var getSetMinute = makeGetSet('Minutes', false); // FORMATTING addFormatToken('s', ['ss', 2], 0, 'second'); // ALIASES addUnitAlias('second', 's'); // PRIORITY addUnitPriority('second', 15); // PARSING addRegexToken('s', match1to2); addRegexToken('ss', match1to2, match2); addParseToken(['s', 'ss'], SECOND); // MOMENTS var getSetSecond = makeGetSet('Seconds', false); // FORMATTING addFormatToken('S', 0, 0, function () { return ~~(this.millisecond() / 100); }); addFormatToken(0, ['SS', 2], 0, function () { return ~~(this.millisecond() / 10); }); addFormatToken(0, ['SSS', 3], 0, 'millisecond'); addFormatToken(0, ['SSSS', 4], 0, function () { return this.millisecond() * 10; }); addFormatToken(0, ['SSSSS', 5], 0, function () { return this.millisecond() * 100; }); addFormatToken(0, ['SSSSSS', 6], 0, function () { return this.millisecond() * 1000; }); addFormatToken(0, ['SSSSSSS', 7], 0, function () { return this.millisecond() * 10000; }); addFormatToken(0, ['SSSSSSSS', 8], 0, function () { return this.millisecond() * 100000; }); addFormatToken(0, ['SSSSSSSSS', 9], 0, function () { return this.millisecond() * 1000000; }); // ALIASES addUnitAlias('millisecond', 'ms'); // PRIORITY addUnitPriority('millisecond', 16); // PARSING addRegexToken('S', match1to3, match1); addRegexToken('SS', match1to3, match2); addRegexToken('SSS', match1to3, match3); var token, getSetMillisecond; for (token = 'SSSS'; token.length <= 9; token += 'S') { addRegexToken(token, matchUnsigned); } function parseMs(input, array) { array[MILLISECOND] = toInt(('0.' + input) * 1000); } for (token = 'S'; token.length <= 9; token += 'S') { addParseToken(token, parseMs); } getSetMillisecond = makeGetSet('Milliseconds', false); // FORMATTING addFormatToken('z', 0, 0, 'zoneAbbr'); addFormatToken('zz', 0, 0, 'zoneName'); // MOMENTS function getZoneAbbr() { return this._isUTC ? 'UTC' : ''; } function getZoneName() { return this._isUTC ? 'Coordinated Universal Time' : ''; } var proto = Moment.prototype; proto.add = add; proto.calendar = calendar$1; proto.clone = clone; proto.diff = diff; proto.endOf = endOf; proto.format = format; proto.from = from; proto.fromNow = fromNow; proto.to = to; proto.toNow = toNow; proto.get = stringGet; proto.invalidAt = invalidAt; proto.isAfter = isAfter; proto.isBefore = isBefore; proto.isBetween = isBetween; proto.isSame = isSame; proto.isSameOrAfter = isSameOrAfter; proto.isSameOrBefore = isSameOrBefore; proto.isValid = isValid$2; proto.lang = lang; proto.locale = locale; proto.localeData = localeData; proto.max = prototypeMax; proto.min = prototypeMin; proto.parsingFlags = parsingFlags; proto.set = stringSet; proto.startOf = startOf; proto.subtract = subtract; proto.toArray = toArray; proto.toObject = toObject; proto.toDate = toDate; proto.toISOString = toISOString; proto.inspect = inspect; if (typeof Symbol !== 'undefined' && Symbol.for != null) { proto[Symbol.for('nodejs.util.inspect.custom')] = function () { return 'Moment<' + this.format() + '>'; }; } proto.toJSON = toJSON; proto.toString = toString; proto.unix = unix; proto.valueOf = valueOf; proto.creationData = creationData; proto.eraName = getEraName; proto.eraNarrow = getEraNarrow; proto.eraAbbr = getEraAbbr; proto.eraYear = getEraYear; proto.year = getSetYear; proto.isLeapYear = getIsLeapYear; proto.weekYear = getSetWeekYear; proto.isoWeekYear = getSetISOWeekYear; proto.quarter = proto.quarters = getSetQuarter; proto.month = getSetMonth; proto.daysInMonth = getDaysInMonth; proto.week = proto.weeks = getSetWeek; proto.isoWeek = proto.isoWeeks = getSetISOWeek; proto.weeksInYear = getWeeksInYear; proto.weeksInWeekYear = getWeeksInWeekYear; proto.isoWeeksInYear = getISOWeeksInYear; proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear; proto.date = getSetDayOfMonth; proto.day = proto.days = getSetDayOfWeek; proto.weekday = getSetLocaleDayOfWeek; proto.isoWeekday = getSetISODayOfWeek; proto.dayOfYear = getSetDayOfYear; proto.hour = proto.hours = getSetHour; proto.minute = proto.minutes = getSetMinute; proto.second = proto.seconds = getSetSecond; proto.millisecond = proto.milliseconds = getSetMillisecond; proto.utcOffset = getSetOffset; proto.utc = setOffsetToUTC; proto.local = setOffsetToLocal; proto.parseZone = setOffsetToParsedOffset; proto.hasAlignedHourOffset = hasAlignedHourOffset; proto.isDST = isDaylightSavingTime; proto.isLocal = isLocal; proto.isUtcOffset = isUtcOffset; proto.isUtc = isUtc; proto.isUTC = isUtc; proto.zoneAbbr = getZoneAbbr; proto.zoneName = getZoneName; proto.dates = deprecate( 'dates accessor is deprecated. Use date instead.', getSetDayOfMonth ); proto.months = deprecate( 'months accessor is deprecated. Use month instead', getSetMonth ); proto.years = deprecate( 'years accessor is deprecated. Use year instead', getSetYear ); proto.zone = deprecate( 'moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', getSetZone ); proto.isDSTShifted = deprecate( 'isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', isDaylightSavingTimeShifted ); function createUnix(input) { return createLocal(input * 1000); } function createInZone() { return createLocal.apply(null, arguments).parseZone(); } function preParsePostFormat(string) { return string; } var proto$1 = Locale.prototype; proto$1.calendar = calendar; proto$1.longDateFormat = longDateFormat; proto$1.invalidDate = invalidDate; proto$1.ordinal = ordinal; proto$1.preparse = preParsePostFormat; proto$1.postformat = preParsePostFormat; proto$1.relativeTime = relativeTime; proto$1.pastFuture = pastFuture; proto$1.set = set; proto$1.eras = localeEras; proto$1.erasParse = localeErasParse; proto$1.erasConvertYear = localeErasConvertYear; proto$1.erasAbbrRegex = erasAbbrRegex; proto$1.erasNameRegex = erasNameRegex; proto$1.erasNarrowRegex = erasNarrowRegex; proto$1.months = localeMonths; proto$1.monthsShort = localeMonthsShort; proto$1.monthsParse = localeMonthsParse; proto$1.monthsRegex = monthsRegex; proto$1.monthsShortRegex = monthsShortRegex; proto$1.week = localeWeek; proto$1.firstDayOfYear = localeFirstDayOfYear; proto$1.firstDayOfWeek = localeFirstDayOfWeek; proto$1.weekdays = localeWeekdays; proto$1.weekdaysMin = localeWeekdaysMin; proto$1.weekdaysShort = localeWeekdaysShort; proto$1.weekdaysParse = localeWeekdaysParse; proto$1.weekdaysRegex = weekdaysRegex; proto$1.weekdaysShortRegex = weekdaysShortRegex; proto$1.weekdaysMinRegex = weekdaysMinRegex; proto$1.isPM = localeIsPM; proto$1.meridiem = localeMeridiem; function get$1(format, index, field, setter) { var locale = getLocale(), utc = createUTC().set(setter, index); return locale[field](utc, format); } function listMonthsImpl(format, index, field) { if (isNumber(format)) { index = format; format = undefined; } format = format || ''; if (index != null) { return get$1(format, index, field, 'month'); } var i, out = []; for (i = 0; i < 12; i++) { out[i] = get$1(format, i, field, 'month'); } return out; } // () // (5) // (fmt, 5) // (fmt) // (true) // (true, 5) // (true, fmt, 5) // (true, fmt) function listWeekdaysImpl(localeSorted, format, index, field) { if (typeof localeSorted === 'boolean') { if (isNumber(format)) { index = format; format = undefined; } format = format || ''; } else { format = localeSorted; index = format; localeSorted = false; if (isNumber(format)) { index = format; format = undefined; } format = format || ''; } var locale = getLocale(), shift = localeSorted ? locale._week.dow : 0, i, out = []; if (index != null) { return get$1(format, (index + shift) % 7, field, 'day'); } for (i = 0; i < 7; i++) { out[i] = get$1(format, (i + shift) % 7, field, 'day'); } return out; } function listMonths(format, index) { return listMonthsImpl(format, index, 'months'); } function listMonthsShort(format, index) { return listMonthsImpl(format, index, 'monthsShort'); } function listWeekdays(localeSorted, format, index) { return listWeekdaysImpl(localeSorted, format, index, 'weekdays'); } function listWeekdaysShort(localeSorted, format, index) { return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort'); } function listWeekdaysMin(localeSorted, format, index) { return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin'); } getSetGlobalLocale('en', { eras: [ { since: '0001-01-01', until: +Infinity, offset: 1, name: 'Anno Domini', narrow: 'AD', abbr: 'AD', }, { since: '0000-12-31', until: -Infinity, offset: 1, name: 'Before Christ', narrow: 'BC', abbr: 'BC', }, ], dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal: function (number) { var b = number % 10, output = toInt((number % 100) / 10) === 1 ? 'th' : b === 1 ? 'st' : b === 2 ? 'nd' : b === 3 ? 'rd' : 'th'; return number + output; }, }); // Side effect imports hooks.lang = deprecate( 'moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale ); hooks.langData = deprecate( 'moment.langData is deprecated. Use moment.localeData instead.', getLocale ); var mathAbs = Math.abs; function abs() { var data = this._data; this._milliseconds = mathAbs(this._milliseconds); this._days = mathAbs(this._days); this._months = mathAbs(this._months); data.milliseconds = mathAbs(data.milliseconds); data.seconds = mathAbs(data.seconds); data.minutes = mathAbs(data.minutes); data.hours = mathAbs(data.hours); data.months = mathAbs(data.months); data.years = mathAbs(data.years); return this; } function addSubtract$1(duration, input, value, direction) { var other = createDuration(input, value); duration._milliseconds += direction * other._milliseconds; duration._days += direction * other._days; duration._months += direction * other._months; return duration._bubble(); } // supports only 2.0-style add(1, 's') or add(duration) function add$1(input, value) { return addSubtract$1(this, input, value, 1); } // supports only 2.0-style subtract(1, 's') or subtract(duration) function subtract$1(input, value) { return addSubtract$1(this, input, value, -1); } function absCeil(number) { if (number < 0) { return Math.floor(number); } else { return Math.ceil(number); } } function bubble() { var milliseconds = this._milliseconds, days = this._days, months = this._months, data = this._data, seconds, minutes, hours, years, monthsFromDays; // if we have a mix of positive and negative values, bubble down first // check: https://github.com/moment/moment/issues/2166 if ( !( (milliseconds >= 0 && days >= 0 && months >= 0) || (milliseconds <= 0 && days <= 0 && months <= 0) ) ) { milliseconds += absCeil(monthsToDays(months) + days) * 864e5; days = 0; months = 0; } // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absFloor(milliseconds / 1000); data.seconds = seconds % 60; minutes = absFloor(seconds / 60); data.minutes = minutes % 60; hours = absFloor(minutes / 60); data.hours = hours % 24; days += absFloor(hours / 24); // convert days to months monthsFromDays = absFloor(daysToMonths(days)); months += monthsFromDays; days -= absCeil(monthsToDays(monthsFromDays)); // 12 months -> 1 year years = absFloor(months / 12); months %= 12; data.days = days; data.months = months; data.years = years; return this; } function daysToMonths(days) { // 400 years have 146097 days (taking into account leap year rules) // 400 years have 12 months === 4800 return (days * 4800) / 146097; } function monthsToDays(months) { // the reverse of daysToMonths return (months * 146097) / 4800; } function as(units) { if (!this.isValid()) { return NaN; } var days, months, milliseconds = this._milliseconds; units = normalizeUnits(units); if (units === 'month' || units === 'quarter' || units === 'year') { days = this._days + milliseconds / 864e5; months = this._months + daysToMonths(days); switch (units) { case 'month': return months; case 'quarter': return months / 3; case 'year': return months / 12; } } else { // handle milliseconds separately because of floating point math errors (issue #1867) days = this._days + Math.round(monthsToDays(this._months)); switch (units) { case 'week': return days / 7 + milliseconds / 6048e5; case 'day': return days + milliseconds / 864e5; case 'hour': return days * 24 + milliseconds / 36e5; case 'minute': return days * 1440 + milliseconds / 6e4; case 'second': return days * 86400 + milliseconds / 1000; // Math.floor prevents floating point math errors here case 'millisecond': return Math.floor(days * 864e5) + milliseconds; default: throw new Error('Unknown unit ' + units); } } } // TODO: Use this.as('ms')? function valueOf$1() { if (!this.isValid()) { return NaN; } return ( this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + toInt(this._months / 12) * 31536e6 ); } function makeAs(alias) { return function () { return this.as(alias); }; } var asMilliseconds = makeAs('ms'), asSeconds = makeAs('s'), asMinutes = makeAs('m'), asHours = makeAs('h'), asDays = makeAs('d'), asWeeks = makeAs('w'), asMonths = makeAs('M'), asQuarters = makeAs('Q'), asYears = makeAs('y'); function clone$1() { return createDuration(this); } function get$2(units) { units = normalizeUnits(units); return this.isValid() ? this[units + 's']() : NaN; } function makeGetter(name) { return function () { return this.isValid() ? this._data[name] : NaN; }; } var milliseconds = makeGetter('milliseconds'), seconds = makeGetter('seconds'), minutes = makeGetter('minutes'), hours = makeGetter('hours'), days = makeGetter('days'), months = makeGetter('months'), years = makeGetter('years'); function weeks() { return absFloor(this.days() / 7); } var round = Math.round, thresholds = { ss: 44, // a few seconds to seconds s: 45, // seconds to minute m: 45, // minutes to hour h: 22, // hours to day d: 26, // days to month/week w: null, // weeks to month M: 11, // months to year }; // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) { var duration = createDuration(posNegDuration).abs(), seconds = round(duration.as('s')), minutes = round(duration.as('m')), hours = round(duration.as('h')), days = round(duration.as('d')), months = round(duration.as('M')), weeks = round(duration.as('w')), years = round(duration.as('y')), a = (seconds <= thresholds.ss && ['s', seconds]) || (seconds < thresholds.s && ['ss', seconds]) || (minutes <= 1 && ['m']) || (minutes < thresholds.m && ['mm', minutes]) || (hours <= 1 && ['h']) || (hours < thresholds.h && ['hh', hours]) || (days <= 1 && ['d']) || (days < thresholds.d && ['dd', days]); if (thresholds.w != null) { a = a || (weeks <= 1 && ['w']) || (weeks < thresholds.w && ['ww', weeks]); } a = a || (months <= 1 && ['M']) || (months < thresholds.M && ['MM', months]) || (years <= 1 && ['y']) || ['yy', years]; a[2] = withoutSuffix; a[3] = +posNegDuration > 0; a[4] = locale; return substituteTimeAgo.apply(null, a); } // This function allows you to set the rounding function for relative time strings function getSetRelativeTimeRounding(roundingFunction) { if (roundingFunction === undefined) { return round; } if (typeof roundingFunction === 'function') { round = roundingFunction; return true; } return false; } // This function allows you to set a threshold for relative time strings function getSetRelativeTimeThreshold(threshold, limit) { if (thresholds[threshold] === undefined) { return false; } if (limit === undefined) { return thresholds[threshold]; } thresholds[threshold] = limit; if (threshold === 's') { thresholds.ss = limit - 1; } return true; } function humanize(argWithSuffix, argThresholds) { if (!this.isValid()) { return this.localeData().invalidDate(); } var withSuffix = false, th = thresholds, locale, output; if (typeof argWithSuffix === 'object') { argThresholds = argWithSuffix; argWithSuffix = false; } if (typeof argWithSuffix === 'boolean') { withSuffix = argWithSuffix; } if (typeof argThresholds === 'object') { th = Object.assign({}, thresholds, argThresholds); if (argThresholds.s != null && argThresholds.ss == null) { th.ss = argThresholds.s - 1; } } locale = this.localeData(); output = relativeTime$1(this, !withSuffix, th, locale); if (withSuffix) { output = locale.pastFuture(+this, output); } return locale.postformat(output); } var abs$1 = Math.abs; function sign(x) { return (x > 0) - (x < 0) || +x; } function toISOString$1() { // for ISO strings we do not use the normal bubbling rules: // * milliseconds bubble up until they become hours // * days do not bubble at all // * months bubble up until they become years // This is because there is no context-free conversion between hours and days // (think of clock changes) // and also not between days and months (28-31 days per month) if (!this.isValid()) { return this.localeData().invalidDate(); } var seconds = abs$1(this._milliseconds) / 1000, days = abs$1(this._days), months = abs$1(this._months), minutes, hours, years, s, total = this.asSeconds(), totalSign, ymSign, daysSign, hmsSign; if (!total) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } // 3600 seconds -> 60 minutes -> 1 hour minutes = absFloor(seconds / 60); hours = absFloor(minutes / 60); seconds %= 60; minutes %= 60; // 12 months -> 1 year years = absFloor(months / 12); months %= 12; // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : ''; totalSign = total < 0 ? '-' : ''; ymSign = sign(this._months) !== sign(total) ? '-' : ''; daysSign = sign(this._days) !== sign(total) ? '-' : ''; hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : ''; return ( totalSign + 'P' + (years ? ymSign + years + 'Y' : '') + (months ? ymSign + months + 'M' : '') + (days ? daysSign + days + 'D' : '') + (hours || minutes || seconds ? 'T' : '') + (hours ? hmsSign + hours + 'H' : '') + (minutes ? hmsSign + minutes + 'M' : '') + (seconds ? hmsSign + s + 'S' : '') ); } var proto$2 = Duration.prototype; proto$2.isValid = isValid$1; proto$2.abs = abs; proto$2.add = add$1; proto$2.subtract = subtract$1; proto$2.as = as; proto$2.asMilliseconds = asMilliseconds; proto$2.asSeconds = asSeconds; proto$2.asMinutes = asMinutes; proto$2.asHours = asHours; proto$2.asDays = asDays; proto$2.asWeeks = asWeeks; proto$2.asMonths = asMonths; proto$2.asQuarters = asQuarters; proto$2.asYears = asYears; proto$2.valueOf = valueOf$1; proto$2._bubble = bubble; proto$2.clone = clone$1; proto$2.get = get$2; proto$2.milliseconds = milliseconds; proto$2.seconds = seconds; proto$2.minutes = minutes; proto$2.hours = hours; proto$2.days = days; proto$2.weeks = weeks; proto$2.months = months; proto$2.years = years; proto$2.humanize = humanize; proto$2.toISOString = toISOString$1; proto$2.toString = toISOString$1; proto$2.toJSON = toISOString$1; proto$2.locale = locale; proto$2.localeData = localeData; proto$2.toIsoString = deprecate( 'toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1 ); proto$2.lang = lang; // FORMATTING addFormatToken('X', 0, 0, 'unix'); addFormatToken('x', 0, 0, 'valueOf'); // PARSING addRegexToken('x', matchSigned); addRegexToken('X', matchTimestamp); addParseToken('X', function (input, array, config) { config._d = new Date(parseFloat(input) * 1000); }); addParseToken('x', function (input, array, config) { config._d = new Date(toInt(input)); }); //! moment.js hooks.version = '2.29.1'; setHookCallback(createLocal); hooks.fn = proto; hooks.min = min; hooks.max = max; hooks.now = now; hooks.utc = createUTC; hooks.unix = createUnix; hooks.months = listMonths; hooks.isDate = isDate; hooks.locale = getSetGlobalLocale; hooks.invalid = createInvalid; hooks.duration = createDuration; hooks.isMoment = isMoment; hooks.weekdays = listWeekdays; hooks.parseZone = createInZone; hooks.localeData = getLocale; hooks.isDuration = isDuration; hooks.monthsShort = listMonthsShort; hooks.weekdaysMin = listWeekdaysMin; hooks.defineLocale = defineLocale; hooks.updateLocale = updateLocale; hooks.locales = listLocales; hooks.weekdaysShort = listWeekdaysShort; hooks.normalizeUnits = normalizeUnits; hooks.relativeTimeRounding = getSetRelativeTimeRounding; hooks.relativeTimeThreshold = getSetRelativeTimeThreshold; hooks.calendarFormat = getCalendarFormat; hooks.prototype = proto; // currently HTML5 input type only supports 24-hour formats hooks.HTML5_FMT = { DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm', // DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss', // DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS', // DATE: 'YYYY-MM-DD', // TIME: 'HH:mm', // TIME_SECONDS: 'HH:mm:ss', // TIME_MS: 'HH:mm:ss.SSS', // WEEK: 'GGGG-[W]WW', // MONTH: 'YYYY-MM', // }; return hooks; }))); }); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } var PropertyDescription = /** @class */ (function () { function PropertyDescription() { var _this = this; var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this.propertyes = { props: [], events: [] }; _.each(args, function (arg) { _this.merge(arg); }); } PropertyDescription.prototype.merge = function (pd) { this.propertyes.props = (_.uniqBy(__spread(this.propertyes.props, pd.props), 'name')); if (pd.events) { if (this.propertyes.events) { this.propertyes.events = (_.uniqBy(__spread(this.propertyes.events, pd.events), 'name')); } else { this.propertyes.events = _.uniqBy(__spread(pd.events), 'name'); } } }; /** * 根据分组名 获取属性定义 */ PropertyDescription.prototype.getPropsByGroup = function (name) { return _.filter(this.propertyes.props, function (i) { return i.group === name; }); }; /** * 获取全部事件 */ PropertyDescription.prototype.getEvents = function () { return this.propertyes.events; }; return PropertyDescription; }()); var PropertyDescriptionTable = new Map(); var width = { name: 'width', default: '', group: 'common', desc: '宽', type: 'string' }; var height = { name: 'height', default: '', group: 'common', desc: '高', type: 'string' }; var fieldLabel = { name: 'fieldLabel', default: '', group: 'common', desc: '文本描述', type: 'string', expr: true, }; var text$1 = { name: 'text', default: '', group: 'common', desc: '文本描述', type: 'string', expr: true, }; var iconCls = { name: 'iconCls', default: '', group: 'common', desc: '图标', type: 'string', expr: true, }; var disabled = { name: 'disabled', default: false, group: 'common', desc: '禁用', type: 'boolean', expr: true, }; var value = { name: 'value', default: '', group: 'common', desc: '字段值', type: 'string', expr: true, }; var template = { name: 'template', default: '', group: 'common', desc: 'HTML内容', type: 'string', expr: true, }; var reference = { name: 'reference', default: '', group: 'common', desc: '组件句柄', type: 'string', expr: true, }; var tooltip = { name: 'tooltip', default: '', group: 'common', desc: '悬停提示', type: 'string' }; // =============事件 ============== var click = { name: 'click', default: '', group: 'listeners', desc: '点击事件', eventParamter: [ 'sender', 'e: any' ], type: 'listeners' }; var change = { name: 'change', default: '', group: 'listeners', desc: 'value change事件', eventParamter: [ 'sender', 'e: any' ], type: 'listeners' }; var keyup = { name: 'keyup', default: '', group: 'listeners', desc: '键盘按键抬起事件', eventParamter: [ 'sender', 'e' ], type: 'listeners' }; var afterrender = { name: 'afterrender', default: '', group: 'listeners', desc: '控件渲染后触发', eventParamter: [ 'sender', 'e' ], type: 'listeners' }; // =============特性 ============== var fix = { name: 'fix', default: '', group: 'fix', desc: '特性', type: 'fix', expr: true, }; PropertyDescriptionTable.set('cols', new PropertyDescription({ props: [ height ] })); PropertyDescriptionTable.set('layout', new PropertyDescription({ props: [ { name: 'borderless', default: true, group: 'css', desc: '有无边框', type: 'boolean' }, { name: 'type', default: '', group: 'css', desc: '布局类型', type: ['line', 'clean', 'wide', 'space', 'form'] }, { name: '_designMode', default: 'module', group: 'common', desc: '设计类型', type: ['none', 'module', 'scroll-module'] } ] })); var YvBase = { props: [ width, height, reference, afterrender, fix ], events: [ // {name: 'onRender', desc: '第一次控件被渲染时触发'} ] }; PropertyDescriptionTable.set('template', new PropertyDescription(YvBase, { props: [ template ] })); PropertyDescriptionTable.set('fieldset', new PropertyDescription(YvBase, { props: [ { name: 'label', default: '', group: 'common', desc: '字段组标题', type: 'string' } ] })); PropertyDescriptionTable.set('iframe', new PropertyDescription(YvBase, { props: [ { name: 'src', default: '', group: 'common', desc: '地址路径', type: 'string' } ] })); PropertyDescriptionTable.set('uploader', new PropertyDescription(YvBase, { props: [ width, height, { name: 'value', default: '上传', group: 'common', desc: '文本描述', type: 'string' }, { name: 'upload', default: '/upload', group: 'common', desc: '上传地址', type: 'string' }, ], events: [ { name: 'onFileUpload', desc: '文件上传成功结束时触发' }, { name: 'onFileUploadError', desc: '在上传过程中发生服务器端错误时触发' }, ] })); PropertyDescriptionTable.set('viewer', new PropertyDescription(YvBase, { props: [ value, { name: 'imgWidth', default: '', group: 'common', desc: '图片宽', type: 'string' }, { name: 'imgHeight', default: '', group: 'common', desc: '图片高', type: 'string' } ] })); PropertyDescriptionTable.set('image', new PropertyDescription(YvBase, { props: [ value, { name: 'imgWidth', default: '', group: 'common', desc: '图片宽', type: 'string' }, { name: 'imgHeight', default: '', group: 'common', desc: '图片高', type: 'string' } ] })); PropertyDescriptionTable.set('button', new PropertyDescription(YvBase, { props: [text$1, disabled, height, width, iconCls, click, afterrender], })); PropertyDescriptionTable.set('fieldSet', new PropertyDescription(YvBase, { props: [ fieldLabel, value, disabled, tooltip, width, height ], })); PropertyDescriptionTable.set('textfield', new PropertyDescription(YvBase, { props: [ fieldLabel, value, disabled, tooltip, width, height, keyup, afterrender, change ], })); PropertyDescriptionTable.set('searchfield', new PropertyDescription(YvBase, { props: [ fieldLabel, value, disabled, tooltip, width, height, keyup, afterrender, change ], })); PropertyDescriptionTable.set('radiogroup', new PropertyDescription(YvBase, { props: [ fieldLabel, value, disabled, tooltip, width, height, keyup, afterrender, change ], })); PropertyDescriptionTable.set('radio', new PropertyDescription(YvBase, { props: [ fieldLabel, value, disabled, tooltip, width, height, keyup, afterrender, change ], })); PropertyDescriptionTable.set('numberfield', new PropertyDescription(YvBase, { props: [ fieldLabel, value, disabled, tooltip, width, height, keyup, afterrender, change ], })); PropertyDescriptionTable.set('datetimepicker', new PropertyDescription(YvBase, { props: [ fieldLabel, value, disabled, tooltip, width, height, keyup, afterrender, change ], })); PropertyDescriptionTable.set('datetimefield', new PropertyDescription(YvBase, { props: [ fieldLabel, value, disabled, tooltip, width, height, keyup, afterrender, change ], })); PropertyDescriptionTable.set('datefield', new PropertyDescription(YvBase, { props: [ fieldLabel, value, disabled, tooltip, width, height, keyup, afterrender, change ], })); PropertyDescriptionTable.set('combogrid', new PropertyDescription(YvBase, { props: [ fieldLabel, value, disabled, tooltip, width, height ], })); PropertyDescriptionTable.set('combo', new PropertyDescription(YvBase, { props: [ fieldLabel, value, disabled, tooltip, width, height, keyup, afterrender, change ], })); PropertyDescriptionTable.set('checkboxgroup', new PropertyDescription(YvBase, { props: [ fieldLabel, value, disabled, tooltip, width, height, keyup, afterrender, change ], })); PropertyDescriptionTable.set('checkbox', new PropertyDescription(YvBase, { props: [ fieldLabel, value, disabled, tooltip, width, height, keyup, afterrender, change ], })); PropertyDescriptionTable.set('yvgrid', new PropertyDescription(YvBase, { props: [ fieldLabel, value, disabled, tooltip, width, height, afterrender, change ], })); /** * 弹出输入框,输入文字 * @param message 提示文字 * @param defaultValue 默认值 * @param multiLine 是否多行输入 */ function prompt(message, defaultValue, multiLine) { if (defaultValue === void 0) { defaultValue = ""; } if (multiLine === void 0) { multiLine = false; } return new Promise(function (resolve) { Ext.MessageBox.prompt('请输入', message, function (button, value) { if (button === 'ok') { resolve(value); } }, null, multiLine, defaultValue); }); } /** * 显示错误异常信息 * @param msg 错误内容 * @param sender 发送者按钮(可以为空) */ function showErrorDialog(msg, sender) { console.error(msg); Ext.MessageBox.show({ title: '错误', msg: msg, buttons: Ext.MessageBox.OK, animateTarget: sender, icon: 'error', cls: 'show-icon-messagebox', }); } /** * 显示错误异常信息 * @param msg 错误内容 * @param sender 发送者按钮(可以为空) */ function showInfoDialogSimple(msg, sender) { console.info(msg); Ext.MessageBox.show({ title: '提示', msg: msg, buttons: Ext.MessageBox.OK, animateTarget: sender, icon: 'info', cls: 'show-icon-messagebox', }); } function msgError(msg, sender) { showErrorDialog(msg, sender); } /** * 中间灰底白字提示 */ function msg(message) { console.log(message); var $body = $$1('body'); $body.find('[xtype=tooltip]').remove(); var $w = $$1('
' + '
' + _.escape(message) + '
'); $body.append($w); var iframeWidth = $w.parent().width(); var iframeHeight = $w.parent().height(); var windowWidth = $w.width(); var windowHeight = $w.height(); var setWidth = (iframeWidth - windowWidth) / 2; var setHeight = (iframeHeight - windowHeight) / 2; if (iframeHeight < windowHeight || setHeight < 0) { setHeight = 0; } if (iframeWidth < windowWidth || setWidth < 0) { setWidth = 0; } $w.css({ left: setWidth, top: setHeight }); setTimeout(function () { $w.remove(); }, 3000); } /** * 调用方法 */ function invokeMethod(fn, sender, args) { if (typeof fn === 'function') { fn.apply.apply(fn, __spread([sender], args)); } } /** * 判断事件是否为有效的输入字符 * @param e */ function isChartEvent(e) { if (e.key === 'Shift' || e.key === 'Control' || e.key === 'Alt' || e.key === 'Escape' || e.key === 'ArrowRight' || e.key === 'Tab' || e.key === 'ArrowLeft') { return false; } if (e.keyCode >= 48 && e.keyCode <= 57) { // 0-9 return true; } if (e.keyCode >= 65 && e.keyCode <= 90) { // a-z return true; } if (e.keyCode >= 96 && e.keyCode <= 111 && e.keyCode !== 108) { // 小键盘 0-9 return true; } return false; } if (!window["time_offset"]) { window["time_offset"] = 0; } function syncDate(date) { if (date && date.setTime && date.getTime) { date.setTime(date.getTime() + window["time_offset"]); } return date; } function toString(value) { if (typeof value === 'undefined' || value === null) { return ""; } if (typeof value === 'number' && isNaN(value)) { return ""; } if (value == 'N/A') { return ""; } return ("" + value); } function isEmpty(value) { if (typeof value === 'undefined' || value === null) { return true; } if (typeof value === 'number' && isNaN(value)) { return true; } if (value == 'N/A') { return true; } return ("" + value).trim().length <= 0; } function createUUID() { //@ts-ignore return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, function (c) { return (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16); }); } function getRegList() { var regList = _.get(window, 'yvanLib.regList'); if (!regList) { regList = []; _.set(window, 'yvanLib.regList', regList); } return regList; } function getRegParamList(methodName) { var regParamList = _.get(window, 'yvanLib.regParamList'); if (!regParamList) { regParamList = {}; _.set(window, 'yvanLib.regParamList', regParamList); } if (!_.has(regParamList, methodName)) { regParamList[methodName] = []; } return regParamList[methodName]; } /** * 模拟点击按钮 */ function raiseClick(buttonHandle) { if (!buttonHandle) { return false; } if (buttonHandle.disabled) { // 按钮是禁止状态 return false; } if (buttonHandle.hidden) { // 按钮是隐藏状态 return false; } // 按钮点击 buttonHandle.click(); return true; } /** * 标注系统全局函数的参数 * @param title 函数名称 * @param type 函数类型 * @param allowEmpty 可否为空 */ function LibParam(title, type, allowEmpty) { if (allowEmpty === void 0) { allowEmpty = false; } return function (target, methodName, paramsIndex) { var systemFnArgs = getRegParamList(methodName); systemFnArgs[paramsIndex] = { type: type, title: title, name: methodName, allowEmpty: allowEmpty, }; }; } /** * 标注函数变成"系统全局函数" */ function Lib(registe) { return function (target, propertyKey, descriptor) { var libList = getRegList(); libList.push(__assign(__assign({}, registe), { name: propertyKey, target: target[propertyKey] })); if (registe.type === 'system') { _.set(window, 'yvanLib.system.' + propertyKey, target[propertyKey]); } else if (registe.type === 'format') { _.set(window, 'yvanLib.format.' + propertyKey, target[propertyKey]); } return target; }; } /** * 解析事件 * 'scope.私有方法名' * 'system.系统函数名' * 'format.格式化名' */ function lookupFn(scope, event, errorWho) { if (window["IS_DESIGN_MODE"]) { return Ext.emptyFn; } if (!_.startsWith(event, 'scope.') && !_.startsWith(event, 'system.') && !_.startsWith(event, 'format.')) { console.error('无法识别的事件响应类型', event); throw new TypeError('无法识别的事件响应类型'); } // 为 eval 准备环境 var _a = window['yvanLib'], system = _a.system, format = _a.format; var data = scope.viewModel.data; var keys = []; var values = []; _.forOwn(data, function (value, key) { var idxKey = key.indexOf('//'); if (idxKey >= 0) { keys.push(key.substr(0, idxKey)); } else { keys.push(key); } values.push(value); }); var func = Function.apply(void 0, __spread(['scope', 'system', 'format'], keys, ['return ' + event])); var funcResult = func.apply(void 0, __spread([scope, system, format], values)); if (typeof funcResult !== 'function') { console.error('无法识别的事件响应类型', event, func, errorWho); throw new TypeError('无法识别的事件响应类型'); } return funcResult; } /** * 从 ext.element 获取 scope 对象 */ function lookupScope(extHandle) { if (!extHandle) { // @ts-ignore return; } if (extHandle.isScope) { return extHandle; } if (extHandle.column) { // 列上的组件 return extHandle.column.lookupReferenceHolder().yvanScope; } if (_.get(extHandle, 'alias[0]') === 'widget.button') ; var vm = extHandle.lookupViewModel(); return vm.yvanScope; } /** * 全局 ajax 方法 */ var ajax = {}; /** * 计算拼音的函数 */ var pinyinFunc = function (str) { return (str); }; exports.scopeOnLoad = null; exports.apiConvert = undefined; var baseConfigProcessList = []; /** * 在基类添加 Config 的处理方法 */ function baseConfigProcess(option) { return function (target, propertyKey) { baseConfigProcessList.push(target[propertyKey]); }; } var designMode = false; function isDesignMode() { return designMode; } function setDesignMode(v) { designMode = v; } /** * 将业务定义的 url 转换为调用服务端 groovy 的 url */ function serverInvokeUrlTransform(url, option) { return _.get(window, '_YvanUI_serverInvokePrefix')(url, option); } /** * 将业务定义的 url 转换为调用服务端 sql 的 Url */ function sqlUrlTransform(url) { return _.get(window, '_YvanUI_sqlPrefix')(url); } /** * YvanUI 全局扩展配置 */ function extend(option) { if (option.ajax) { ajax.func = option.ajax; } if (option.serverInvokeUrlTransform) { _.extend(window, { _YvanUI_serverInvokePrefix: option.serverInvokeUrlTransform }); } if (option.sqlUrlTransform) { _.extend(window, { _YvanUI_sqlPrefix: option.sqlUrlTransform }); } if (option.pinyinFunction) { pinyinFunc = option.pinyinFunction; } if (option.scopeOnLoad) { exports.scopeOnLoad = option.scopeOnLoad; } if (option.apiConvert) { exports.apiConvert = option.apiConvert; } if (typeof option.designMode !== 'undefined') { setDesignMode(option.designMode); } } function getApiConvert() { return exports.apiConvert; } function getPinyin(v) { return pinyinFunc(v); } /** * 适用于 Select / Tree 等,作筛选的通用方法. * 1.首字母模糊匹配(不区分大小写) * 2.标识的模糊匹配(不区分大小写) * 3.名称的模糊匹配,且支持以逗号(全角或半角)隔开的字词匹配,并自动去空格,如“南京, 物流 ”可以匹配出“南京九州通物流技术开发有限公司” */ function keywordFilter(keyword, label, value) { if (!keyword) { return true; } var ws = _.trim(keyword).split(/\s+|\.|,|\)|\(|,|。|-|—/g); // const labelPy = _.toLower(getPinyin(label)) //@ts-ignore var labelPy = _.toLower(getFirstPinyin2(label)); value = _.toLower(_.trim(value)); var found = 0; _.some(ws, function (word) { if (labelPy.indexOf(word.toLowerCase()) >= 0 || label.indexOf(word) >= 0) { found++; return; } if (value && value.indexOf(word.toLowerCase()) >= 0) { found++; return; } }); return found >= ws.length; } var Scope = /** @class */ (function () { function Scope(_a) { var model = _a.model, vjson = _a.vjson; /** * 业务模块的唯一编号 */ this.id = _.uniqueId('scope_'); /** * onload 运行完成之后才会设置本标记为 true */ this.isLoadFinish = false; this._isLoading = false; this.model = model; this.originalVjson = _.cloneDeep(vjson); this.vjson = this.originalVjson; // this.buildVjson() } Scope.prototype._addWatch = function (tplExpress, fn) { if (!this._watchList) { this._watchList = []; } this._watchList.push({ watch: tplExpress, fn: fn }); }; Scope.prototype._applyWatchList = function () { var _this = this; _.forEach(this._watchList, function (item) { _this.viewModel.bind(item.watch, item.fn.bind(_this)); }); }; Object.defineProperty(Scope.prototype, "isScope", { get: function () { return true; }, enumerable: true, configurable: true }); /** * 产生一个当前模块有效的唯一id * @param key 唯一编号 */ Scope.prototype.uid = function (key) { return this.id + key; }; /** * 对话框"保存"成功. * 关闭对话框,并响应 success 方法 * @param data 要傳回的數據(可以為空) */ Scope.prototype.dialogSuccess = function (data) { this._handle.fireEvent('success', this, data); var sender = this._handle.config.animateTarget; var scope = lookupScope(sender); if (typeof this['success'] === 'function') { this['success'].call(scope, sender, data); } this.close(); }; /** * 设置等待状态 * @param value * @param msg */ Scope.prototype.setLoading = function (value) { var _a; var scope = this; this._isLoading = value; (_a = scope._handle) === null || _a === void 0 ? void 0 : _a.setLoading(value); }; Scope.prototype.getLoading = function () { return this._isLoading; }; /** * 以对话框模式打开当前模块 * @param sender 发送者(按钮或Scope对象) * @param vjsonOption 界面覆盖选项(可以为空) * @param dataOption 数据覆盖选项(可以为空) */ Scope.prototype.showDialog = function (sender, vjsonOption, dataOption) { var _a; var that = this; var vmodel = _.defaultsDeep({ // }, dataOption, that.model); this.viewModel = new Ext.app.ViewModel(vmodel); this.viewModel.yvanScope = this; this._applyWatchList(); this["scopeKey"] = "dialog-" + getVjsonHash(JSON.stringify(this.vjson) + JSON.stringify(vjsonOption)); var config = _.defaultsDeep({ animateTarget: sender, viewModel: this.viewModel, yvanScope: this, referenceHolder: true, }, vjsonOption, that.vjson, windows); if (config.height === 'unset') { delete config.height; } if (config.width === 'unset') { delete config.width; } // const holder = sender?.lookupReferenceHolder() // delete config.constrain var topScope = (_a = lookupScope(sender)) === null || _a === void 0 ? void 0 : _a.topScope; if (topScope) { config.constrain = true; this.topScope = topScope; } var win = new Ext.Window(config); // if (holder) { // holder.add(win) // } if (topScope) { topScope._handle.add(win); } win.addListener('beforerender', function (sender) { // 记录句柄 if (sender && !that._handle) { that._handle = sender; } }); win.addListener('afterrender', function (sender) { // 调用onLoad回调 try { that._onLoad(); } catch (e) { console.error('errorAt onLoad', e); } window['cw'] = that; }); win.addListener('destroy', this._destroy.bind(this)); win.show(); }; /** * 以标签模式打开当前模块 * @param vjsonOption 界面覆盖选项(可以为空) * @param dataOption 数据覆盖选项(可以为空) */ Scope.prototype.showPage = function (vjsonOption, dataOption) { var _this = this; var that = this; this._vjsonOption = vjsonOption; this._dataOption = dataOption; var vmodel = _.defaultsDeep({ data: {} }, dataOption, that.model); this.viewModel = new Ext.app.ViewModel(vmodel); this.viewModel.yvanScope = this; this._applyWatchList(); this["scopeKey"] = "page-" + getVjsonHash(JSON.stringify(this.vjson) + JSON.stringify(vjsonOption)); // 根级不能设置id delete that.vjson.id; var config = _.defaultsDeep({ viewModel: this.viewModel, yvanScope: this, referenceHolder: true, }, vjsonOption, that.vjson); var tt = Ext.getCmp('TT'); var handle = tt.addScope(this, config, function (handle) { handle.addListener('added', function (sender) { // 记录句柄 if (sender && !that._handle) { that._handle = sender; } }); handle.addListener('afterrender', function (sender) { // 调用onLoad回调 try { that._onLoad(); } catch (e) { console.error('errorAt onLoad', e); } }); handle.addListener('destroy', _this._destroy.bind(_this)); }); return handle; }; /** * 直接渲染到元素 * @param element 渲染目标 * @param vjsonOption 界面覆盖选项(可以为空) * @param dataOption 数据覆盖选项(可以为空) */ Scope.prototype.renderTo = function (element, vjsonOption, dataOption) { var that = this; this._vjsonOption = vjsonOption; this._dataOption = dataOption; var vmodel = _.defaultsDeep({ data: {} }, that.model, dataOption); this["scopeKey"] = "render-" + getVjsonHash(JSON.stringify(this.vjson) + JSON.stringify(vjsonOption)); this.viewModel = new Ext.app.ViewModel(vmodel); this.viewModel.yvanScope = this; this._applyWatchList(); var config = _.defaultsDeep({ viewModel: this.viewModel, yvanScope: this, referenceHolder: true, renderTo: element, listeners: { afterrender: function (sender) { var _a; // 记录句柄 if (sender && !that._handle) { that._handle = sender; } // 调用onLoad回调 that._onLoad(); // 如果vjson中配置了 afterrender ,需要恢复状态 invokeMethod((_a = that.vjson.listeners) === null || _a === void 0 ? void 0 : _a.afterrender, that, arguments); }, }, }, vjsonOption, that.vjson); new Ext.container.Viewport(config); }; /** * 关闭对话框(或标签页) */ Scope.prototype.close = function () { this._handle.close(); }; Object.defineProperty(Scope.prototype, "data", { /** * 获取 viewModel 里包含的数据(只读) */ get: function () { return this.viewModel.getData(); }, enumerable: true, configurable: true }); /** * 设置 viewModel 中的数据 * 可以是 key, value 模式 * 也可以是 {key:value} 模式 */ Scope.prototype.set = function (path, value) { return this.viewModel.set(path, value); }; /** * 寻找模块内所有的 xtype 对应的对象 * @param xtypeKey */ Scope.prototype.down = function (xtypeKey) { return this._handle.down(xtypeKey); }; Object.defineProperty(Scope.prototype, "refs", { /** * 获取所有设置过 Reference 名称的组件 */ get: function () { var _a, _b; return (_b = (_a = this._handle) === null || _a === void 0 ? void 0 : _a.getReferences()) !== null && _b !== void 0 ? _b : {}; }, enumerable: true, configurable: true }); Scope.prototype._destroy = function () { var that = this; that.onDestroy(); delete that._watchList; delete that._handle; this.isLoadFinish = false; }; /** * 私有渲染完成后的回调 */ Scope.prototype._onLoad = function () { var _this = this; if (exports.scopeOnLoad && typeof exports.scopeOnLoad === 'function') { exports.scopeOnLoad(this); } this.onLoad(); _.defer(function () { _this.isLoadFinish = true; }); }; /** * 默认 渲染完成之后调用的函数 */ Scope.prototype.onLoad = function () { }; /** * 组件卸载之后的回调 */ Scope.prototype.onDestroy = function () { }; return Scope; }()); /** * 观察装饰器,viewModel 属性更改时触发成员方法 * @param tplExpress tpl表达式,例如 "{form.f1}" */ function watch(tplExpress, deep) { if (deep === void 0) { deep = false; } return function (target, propertyKey, pd) { target._addWatch({ bindTo: tplExpress, deep: deep }, target[propertyKey]); return target[propertyKey]; }; } // 获取vjson的hash值 function getVjsonHash(str) { var hash = 3465217896, i, ch; for (i = str.length - 1; i >= 0; i--) { ch = str.charCodeAt(i); hash ^= ((hash << 5) + ch + (hash >> 2)); } return (hash & 0x7FFFFFFF) + ""; } var ScopeEngine = /** @class */ (function () { function ScopeEngine() { } ScopeEngine.getVjsonAndModel = function (table, bill, layout) { // 生成controller var controller = {}; var title = table.name; var vjsonItem = { xtype: "form", items: [] }; for (var i = 0; i < table.fields.length; i++) { var item = table.fields[i]; if (item.hasOwnProperty("fieldset")) { vjsonItem.items.push({ xtype: 'fieldset', title: item.fieldset, items: [ item ] }); } if (item.hasOwnProperty("listeners")) { controller[item.listeners.change.split(".")[1]] = function () { console.log("fuck"); }; } } // 生成vjson var vjson = { title: title, layout: 'fit', items: [ vjsonItem ], referenceHolder: true, }; var scope = new Scope({ model: {}, vjson: vjson }); _.merge(scope, controller); return scope; }; return ScopeEngine; }()); function initComponent () { var ct = Ext.Component.prototype.constructor; Ext.Component.override({ constructor: function (config) { if (!window["IS_DESIGN_MODE"] && config) { var me_1 = this; // 任意组件 Ext.Component 构造时调用的方法, 可以用来在渲染之前加工处理 VJSON _.each(baseConfigProcessList, function (process) { process.call(me_1, me_1, config); }); } ct.call(this, config); } }); var _initComponent = Ext.picker.Date.prototype.initComponent; Ext.picker.Date.override({ initComponent: function () { var me = this; me.defaultValue = Ext.isDate(me.defaultValue) ? me.defaultValue : syncDate(new Date()); _initComponent.call(me); }, selectToday: function () { var me = this, btn = me.todayBtn, handler = me.handler; if (btn && !btn.disabled) { me.setValue(Ext.Date.clearTime(syncDate(new Date()))); me.fireEvent('select', me, me.value); if (handler) { Ext.callback(handler, me.scope, [me, me.value], null, me, me); } me.onSelect(); } return me; }, }); } function initMainTab () { Ext.define('Yvan.MainTab', { extend: 'Ext.tab.Panel', xtype: 'maintab', plugins: Ext.create('Ext.ux.TabCloseMenu', { closeTabText: '关闭', closeOthersTabsText: '关闭其他', closeAllTabsText: '关闭所有' }), constructor: function (config) { var me = this; var newConfig = _.defaultsDeep({ // 强制属性 }, config); this.superclass.constructor.call(me, newConfig); }, initComponent: function () { var me = this; this.on({ tabchange: function (tabPanel, newCard, oldCard, eOpts) { _.defer(function () { me.changeHash(newCard.id); window['cp'] = newCard.yvanScope; }); $$1(window).trigger('tabChange', { tabPanel: tabPanel, newCard: newCard, oldCard: oldCard, eOpts: eOpts }); }, afterrender: function () { _.defer(function () { me.tryRestoryPage(); }); } }); this.superclass.initComponent.call(me); }, tryRestoryPage: function () { var me = this; var hash = '' + window.location.hash; if (hash && hash.indexOf('page=') > 0) { if (hash.startsWith('#')) { hash = hash.substr(1); } if (hash) { var page = Qs.parse(hash).page; if (page) { // this.openScope(page) me.fireEvent('restorypage', page); } } } }, changeHash: function (id) { window.location.hash = Qs.stringify({ page: id }); }, /** * 添加一个业务模块实例到选项卡 * @param scopeInstance 业务对象实例 * @param config ExtJS配置对象 * @param panelInitCallback panel初始化之后会调用函数进行构造前的加工 */ addScope: function (scopeInstance, config, panelInitCallback) { scopeInstance.topScope = scopeInstance; var me = this; if (config.path) { for (var i = 0; i < this.items.items.length; i++) { // 找到当前 tabs 里有没有已经打开过 var tab = this.items.items[i]; if (_.isEqual(tab.path, config.path)) { // 激活 this.setActiveTab(tab); return tab; } } } var newPanel = new Ext.panel.Panel(__assign({ closable: true }, config)); if (typeof panelInitCallback === 'function') { panelInitCallback(newPanel); } // 添加业务模块 var newTab = this.add(newPanel); this.setActiveTab(newTab); newTab.on({ destroy: function (sender) { me.changeHash(''); delete window['cp']; } }); return newTab; } }); } /** * 构建所有组件的公共属性 * @param config 原始config * @param dragType 组件模式 * 不填,代表不能在设计时被拖拽 * row-container 是一个rows容器 * col-container 是一个cols容器 * col-item cols中的一个格子(非容器),比如 textfield / combofield 等等 * row-item rows中的一行,比如 tree / grid / panel 等等 */ function baseConfig(config, dragType) { if (config && window["IS_DESIGN_MODE"] && dragType) { var cc = ''; switch (dragType) { case "cols-container": cc = 'design_cols_container'; break; case "col-item": cc = 'design_col_item'; break; case "rows-container": cc = 'design_rows_container'; break; case "row-item": cc = 'design_row_item'; break; } if (typeof config.cls === 'string') { _.extend(config, { cls: [config.cls, 'yvan_design', cc] }); } else if (_.isArray(config.cls)) { _.extend(config, { cls: __spread(config.cls, ['yvan_design', cc]) }); } else { _.extend(config, { cls: ['yvan_design', cc] }); } } return config; } function initPanel () { /** * */ var ct = Ext.panel.Panel.prototype.constructor; Ext.panel.Panel.override({ constructor: function (config) { var newConfig = _.defaultsDeep({}, config, baseConfig(config, "rows-container"), panel); ct.call(this, newConfig); } }); var ss = Ext.form.FieldContainer.prototype; Ext.form.FieldContainer.override({ config: __assign({}, fieldContainer) }); } function initGridColumn () { var ct = Ext.grid.column.Column.prototype.constructor; Ext.grid.column.Column.override({ constructor: function (config) { var scope = lookupScope(config.$initParent.$initParent); var newConfig = _.defaults({}, config, column); if (typeof newConfig.summaryRenderer === 'string') { newConfig.summaryRenderer = lookupFn(scope, config.summaryRenderer); if (typeof newConfig.summaryRenderer === 'function') { newConfig.summaryRenderer = newConfig.summaryRenderer.bind(scope); } } // 在 grid.constructor 已经转换过了 // if (typeof newConfig.renderer === 'string') { // newConfig.renderer = lookupFn(scope, config.renderer) // if (typeof newConfig.renderer === 'function') { // newConfig.renderer = newConfig.renderer.bind(scope) // } // } ct.call(this, newConfig); } }); var ctAction = Ext.grid.column.Action.prototype.constructor; Ext.grid.column.Action.override({ constructor: function (config) { var scope = lookupScope(config.$initParent.$initParent); _.forEach(config.items, function (item) { if (typeof item.handler === 'string') { item.handler = lookupFn(scope, item.handler); if (typeof item.handler === 'function') { item.handler = item.handler.bind(scope); } } }); ctAction.call(this, config); } }); var ck = Ext.grid.column.Check.prototype.constructor; Ext.grid.column.Check.override({ constructor: function (config) { _.set(config, 'listeners.checkchange', function (sender, rowIndex, checked, record, e, eOpts) { var grid = sender.view.grid.ownerGrid; var column = grid.getColumns()[sender.fullColumnIndex]; var context = { event: e, column: column, field: sender.dataIndex, value: checked, record: record, rowIdx: rowIndex }; grid.fireEvent('editfinish', grid, sender, context, eOpts); }); ck.call(this, config); } }); // 227573 // const {onTitleElClick} = Ext.grid.column.Column.prototype // Ext.define('Yvan.ColumnOverride', { // override: 'Ext.grid.column.Column', // // config: { // enableSortOnClick: false, // }, // // // /**@Overrides*/ // onTitleElClick: function (e, t, sortOnClick) { // // return this.callParent([e, t, this.enableSortOnClick && sortOnClick]); // if (!$(e.target).is('.x-column-header-trigger')) { // // 不是点击菜单的情况下,让列自适应宽度 // this.autoSize() // } // return onTitleElClick.call(this, e, t, false) // } // }); } var SIMPLE_RE = /^(?:\{(?:(\d+)|([a-z_][\w\.]*))\})$/i; /** * 判断目标字符串与关键字是否重叠 * @param target 目标字符串 * @param keyword 搜索关键字 */ function pinyinMatch(target, keyword) { if (typeof target != 'string' || typeof keyword != 'string') { return false; } if (!keyword || !target) { return false; } var pyzh = _.toLower(window['getFirstPinyin2'](target)); keyword = _.toLower(keyword); var pos1 = _.toLower(target).indexOf(keyword); if (pos1 >= 0) { return true; } if (_.intersection(pyzh.split(''), keyword.split('')).length === keyword.length) { return true; } return false; } /** * 对某个表达式进行求值 * a:{query.a},b:{query.b} -> a:aValue,b:bValue * * @example * calcExpress(cc.viewModel.data, "WH_ID:{query.WH_ID},C:{theGrid.selection.data.WH_ID}") * 计算出来的值是: "WH_ID:queryWhId,C:JH000000001" * * @param data 数据环境对象 * @param express 表达式对象 */ function calcExpress(data, express) { var result = express; if (SIMPLE_RE.test(express)) { // '{foo}' 简单表达式 var path = express.substring(1, express.length - 1); var ret = _.get(data, path); return (ret === null || ret === void 0 ? void 0 : ret.isModel) ? ret.data : ret; } while (true) { var mlist = result.match(/{(.*?)}/); if (!mlist) { break; } var pathC = mlist[0]; // {query.a} var path = mlist[1]; // query.a var value = _.get(data, path); result = result.replaceAll(pathC, value || ''); } return result; } /** * 对个对象进行表达式求值,不用回调 * @example * calcObjectFlat({query:{a:'aValue',b1:'b1Value',b2:'b2Value',d1:1,d2:2}}, { a:'{query.a}', b:{b1:'{query.b1}', b2:'{query.b2}'},c:'aa',d:['{query.d1}','{query.d2}'] }) * * { * a: '{query.a}', * b: { * b1: '{query.b1}', * b2: '{query.b2}', * }, * c: 'aa', * d: [ * '{query.d1}', * '{query.d2}' * ] * } * * 计算结果为 * { * a: 'aValue', * b: { * b1: 'b1Value', * b2: 'b2Value' * }, * c: 'aa' * d: [ * '1', * '2' * ] * } * * @param data * @param paramObject */ function calcObjectFlat(data, paramObject) { var result = _.cloneDeep(paramObject); if (typeof paramObject === 'string') { return calcExpress(data, paramObject); } var trav = function (param) { _.forOwn(param, function (value, key) { if (_.isPlainObject(value)) { // 深度递归,对子对象进行求解 trav(value); } else if (_.isString(value)) { // 字符串直接用 calcExpress 表达式求解 param[key] = calcExpress(data, param[key]); } else if (_.isArray(value)) { // 数组求解 _.each(value, function (v, idx) { value[idx] = calcExpress(data, v); }); } }); }; trav(result); return result; } /** * 合併 data 到當前的 ViewModel 對象 */ function mergeViewModel(viewModel, propertyName, data, isFlat) { var newRow = {}; if (isFlat == false) { newRow = data; } else { flatObject(newRow, '', data); } _.forOwn(newRow, function (value, key) { viewModel.set(propertyName + "." + key, value); }); } /** * 转换内联结构的行,到平面结构 * company: { name:'公司1', id:'编号1' } => { company_id:'编号1', company_name:'公司1' } * * @param array * @param flatOption * @return {[]} */ function flatRow(array) { var ret = []; _.forEach(array, function (row) { var newRow = {}; flatObject(newRow, '', row); ret.push(newRow); }); return ret; } function flatObject(parentObj, parentProp, obj) { _.forOwn(obj, function (value, key) { var fullKey = parentProp ? parentProp + '_' + key : key; if (_.isArray(value)) { parentObj[fullKey] = _.map(value, function (row) { var newRow = {}; flatObject(newRow, '', row); return newRow; }); } else { if (typeof value === 'object') { flatObject(parentObj, fullKey, value); } else { parentObj[fullKey] = value; } } }); } /** * 替换内部结构中,所有 N/A */ function replaceNA(obj) { if (obj === 'N/A') { return ''; } if (_.isArray(obj)) { _.forEach(obj, function (value, idx) { if (value === 'N/A') { obj[idx] = ''; } else { replaceNA(value); } }); } else if (_.isPlainObject(obj)) { _.forOwn(obj, function (value, key) { if (value === 'N/A') { obj[key] = ''; } else { replaceNA(value); } }); } } /** * 根据表达式进入写值 * express="{query.a}" 写值就是 viewModel.set('query.a', value) * express="test-{query.a}" 写值就会失败 * * @example * tryWriteByExpress(cc.viewModel, "{query.WH_ID}", "111") * 写值成功 * * tryWriteByExpress(cc.viewModel, "test-{query.WH_ID}", "111") * 写值失败 * * @param viewModel VM对象 * @param express 表达式对象 * @param value 目标值 */ function tryWriteByExpress(viewModel, express, value) { if (SIMPLE_RE.test(express)) { // '{foo}' 简单表达式 express = express.substring(1, express.length - 1); viewModel.set(express, value); } } /** * 尝试根据含表达式的对象回写, calcObjectFlat 的逆向方法 * @example * tryWriteObject({ a:'{query.a}', b:{b1:'{query.b1}', b2:'{query.b2}'},c:'aa',d:['{query.d1}','{query.d2}']}, {a:'aValue', b:{b1:'b1Value', b2:'b2Value'}, c:'aa', d:[1,2]}) * * expressObject: * { * a: '{query.a}', * b: { * b1: '{query.b1}', * b2: '{query.b2}', * }, * c: 'aa', * d: [ * '{query.a}', * '{query.b2}' * ] * } * * valueObject: * { * a: 'aValue', * b: { * b1: 'b1Value', * b2: 'b2Value' * }, * c: 'aa' * c: [ * 'aValue', * 'b2Value' * ] * } * * 系统会尝试回写 * viewModel.set('query.a', 'aValue') * viewModel.set('query.b1', 'b1Value') * viewModel.set('query.b2', 'b2Value') * * @param expressObject 含表达式的对象 * @param valueObject 表达式计算完成之后的结果对象 * @param writeFn 写入的方法 (path, value)=>void */ function tryWriteObject(expressObject, valueObject, writeFn) { var trav = function (pathPrefix) { var parent = expressObject; if (_.size(pathPrefix) > 1) { parent = _.get(parent, pathPrefix.substring(1)); } _.forOwn(parent, function (value, key) { if (_.isPlainObject(value)) { // 深度递归,对子对象进行求解 trav(pathPrefix + "." + key); } else if (_.isString(value)) { // 字符串直接用 calcExpress 表达式求解 if (SIMPLE_RE.test(value)) { // If we have '{foo}' alone it is a literal 简单表达式 var targetPath = value.substring(1, value.length - 1); var targetValue = _.get(valueObject, (pathPrefix + "." + key).substr(1)); if (!writeFn) { console.log("viewModel.set('" + targetPath + "', '" + targetValue + "')"); } else { writeFn(targetPath, targetValue); } } } else if (_.isArray(value)) { _.each(value, function (v, idx) { if (SIMPLE_RE.test(v)) { var targetPath = (pathPrefix + "." + key).substr(1) + "[" + idx + "]"; var targetValue = _.get(valueObject, (pathPrefix + "." + key).substr(1) + "[" + idx + "]"); if (!writeFn) { console.log("viewModel.set('" + targetPath + "', '" + targetValue + "')"); } else { writeFn(targetPath, targetValue); } } }); } }); }; trav(""); } /** * 尝试去掉变量两边括号 * {a} => a * a => a */ function tryVarSimple(value) { if (SIMPLE_RE.test(value)) { // If we have '{foo}' alone it is a literal 简单表达式 return value.substring(1, value.length - 1); } return value; } /** * 对多个表达式进行求值. 异步回调的方式返回 * { * a: 1, * b: '{someBind}', * c: ['a', 'b', 'c'], * d: ['a', 'b', '{someBind}'], * e: { * y: 1, * z: 2 * }, * f: { * y: 1, * z: '{someBind}' * } * } * * // Will produce * { * b: value, * d: ['a', 'b', value], * f: { * y: 1, * z: value * } * } * @param viewModel scope.viewModel对象 * @param paramObject 求值对象 */ function calcObject(viewModel, paramObject) { // new Ext.app.bind.Multi({a:'1',b:'ddd{query.WH_ID}'},currentScope.viewModel,function(v){console.log(v)},currentScope, {single: true}) return new Promise(function (resolve) { var schedule = new Ext.app.bind.Multi(paramObject, viewModel, function (ret) { schedule.destroy(); // 从 Ext.data.Model 对象转换为 js-object 对象 ret = toPlainObject(ret); resolve(ret); }, viewModel, { single: true }); }); } /** * 用于任意组件 Ext.Component 构造时,获取当前组件对应的表格(如果不是 grid.columns 对象就会返回 undefined) * @param config 组件构造函数传入的 config 配置文件 */ function getParentGrid(config) { var _a; return (_a = config.$initParent) === null || _a === void 0 ? void 0 : _a.grid; } /** * 解析 * { * condition: "{skuId}", * errorMsg: "无法编辑", * notice: 'msg' * } */ function tryEnable(data, enableSetting) { if (!enableSetting) { // 没有这一段配置,可以编辑 return true; } var condition = enableSetting.condition, errorMsg = enableSetting.errorMsg, notice = enableSetting.notice; if (!evalFunction(data, condition)) { // 没有达成 condition 条件 // 计算 msg 消息内容 var msgContent = calcExpress(data, errorMsg); if (msgContent) { if (!notice || notice === 'msg') { // 进行提示 msg$1(msgContent); } } return false; } return true; } /** * 动态的为 combo 或 columns.combo 设置下拉框的值 * @param sender 目标对象 * @param config 目标对象的配置(在构造函数之前也可以) * @param getDictFn 获取字典的方法 * @param bizKey 传入字典的参数 * @param multiValueSeparator 多个字典值的分割符号 */ function setComboStore(sender, config, getDictFn, bizKey, multiValueSeparator) { if (multiValueSeparator === void 0) { multiValueSeparator = ""; } // sender 和 config为空的时候获取值、 if (_.isArray(getDictFn)) { // 如果 getDictFn 是直接给定的值,就造一个异步回调的方法 var realArray_1 = getDictFn; getDictFn = function () { return realArray_1; }; } if (!sender) { return new Promise(function (resolve, reject) { getDictFn(bizKey, function (r) { resolve({ config: config, r: r }); }); }); } if (sender.xtype === 'combotree') { getDictFn(bizKey, function (r) { if (sender.store) { // 异步回传 sender.setStore(new Ext.data.TreeStore({ root: r })); } else { // 同步回传 config.store = new Ext.data.TreeStore({ root: r }); } }); return; } else if (sender.$className === 'Ext.form.field.ComboBox') { getDictFn(bizKey, function (r) { var _a, _b; if (sender.store) { // 异步回传 sender.setStore(new Ext.data.Store(r)); // 这里有个bug, 异步回传完毕之后, 需要强制刷新一下 // 否则在 forceSelection 的模式下。displayField 不会强制做变更 var realValue = (_b = (_a = sender.bind) === null || _a === void 0 ? void 0 : _a.value) === null || _b === void 0 ? void 0 : _b.getValue(); if (typeof realValue !== 'undefined') { sender.setValue(realValue); } } else { // 同步回传 config.store = new Ext.data.Store(r); } }); return; } else if (sender.xtype === 'gridcolumn') { var grid = getParentGrid(config); var editor_1 = config.editor, renderer = config.renderer; getDictFn(bizKey, function (r) { if (sender.store) { // 已经渲染出来了, 用方法进行修改 var editor_2 = sender.getEditor(); if (editor_2 && editor_2.xtype === 'combo') { var valueField_1 = r.field[0]; var displayField_1 = r.field[1]; editor_2.valueField = valueField_1; editor_2.setDisplayField(displayField_1); editor_2.setStore(new Ext.data.Store(r)); } } else { // 没有渲染之前,修改 config 即可 if (editor_1 && editor_1.xtype === 'combo') { // 带编辑模式 editor_1.store = new Ext.data.Store(r); } } var renderer = function (value, metaData) { if (!value && value != 0) { return ''; } var valueField = r.field[0]; var displayField = r.field[1]; var separator = multiValueSeparator; if (separator) { var arr = value.split(separator); var displayValue_1 = ""; var _loop_1 = function (i) { var itv = arr[i]; if (i > 0) { displayValue_1 += separator; } _.each(r.data, function (row) { // 从 valueField 找到要显示的 displayField if (row[valueField] == itv) { displayValue_1 += row[displayField]; return false; } else { if (i >= r.data.length - 1) { displayValue_1 += itv; } } }); }; for (var i = 0; i < arr.length; i++) { _loop_1(i); } return displayValue_1; } _.each(r.data, function (row) { // 从 valueField 找到要显示的 displayField if (row[valueField] == value) { value = row[displayField]; return false; } }); return value; }; var dictForExcel = {}; var valueField = r.field[0]; var displayField = r.field[1]; _.each(r.data, function (row) { // 从 valueField 找到要显示的 displayField var key = row[valueField]; if (key != '' && typeof key != "undefined" && key != null) { dictForExcel[key] = row[displayField]; } }); if (sender.rendered) { // 已经渲染出来了, 对列进行渲染 sender.renderer = renderer; sender.dictForExcel = dictForExcel; sender.getView().refresh(); } else { sender.renderer = renderer; sender.dictForExcel = dictForExcel; config.renderer = renderer; config.dictForExcel = dictForExcel; } }); return; } throw new TypeError("无法识别的组件类型"); } /** * 调用服务器 Ajax */ function invokeServer(url) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } // @ts-ignore return ajax.func({ url: url, method: 'invoke', args: args }); } function clearViewModelValues(viewModel, propertyName) { if (!propertyName) { var dd_1 = viewModel.getData(); _.forOwn(dd_1, function (value, key) { viewModel.set(key, ''); }); return; } var dd = _.get(viewModel.getData(), propertyName); _.forOwn(dd, function (value, key) { viewModel.set(propertyName + '.' + key, ''); }); } function reloadGrid(scope, gridRefName) { var _a; (_a = scope.refs[gridRefName]) === null || _a === void 0 ? void 0 : _a.reload(); } /** * 将 Ext.data.Model 对象 (及子属性) 转换为 js.object 对象 */ function toPlainObject(obj) { if (obj.isModel) { obj = obj.data; } _.forOwn(obj, function (v, k) { // Ext.data.Model.constructor if (!v) { return; } if (v.isModel) { v = v.data; } if (typeof v === 'object') { obj[k] = toPlainObject(v); } else { obj[k] = v; } }); return obj; } function confirm(msg, sender) { return new Promise(function (resolve) { var _a, _b; var scope = (_a = lookupScope(sender)) === null || _a === void 0 ? void 0 : _a.topScope; var config = { title: '请确认', modal: true, animateTarget: sender, // resizable: false, // constrainHeader: true, // constrain: true, // constrainTo: scope._handle?.el?.dom || Ext.getBody(), layout: { type: 'hbox', pack: 'start', align: 'stretch' }, items: [ { html: '', border: false, }, { flex: 1, border: false, html: "
" + _.escape(msg) + "
" } ], buttons: [ { xtype: 'button', text: '确定', iconCls: 'x-fa fa-check-circle', handler: function () { resolve(); win.close(); } }, { xtype: 'button', text: '取消', iconCls: 'x-fa fa-power-off', handler: function () { win.close(); } } ], keyMapEnabled: true, keyMap: { ENTER: function () { resolve(); win.close(); } } }; if (scope === null || scope === void 0 ? void 0 : scope._handle) { config.constrain = true; } var win = new Ext.Window(config); if (scope === null || scope === void 0 ? void 0 : scope._handle) { (_b = scope === null || scope === void 0 ? void 0 : scope._handle) === null || _b === void 0 ? void 0 : _b.add(win); } win.show(); }); } /** * 任何符号字符串都替换成下换线 */ function normId(value) { return _.replace(value, /[^\w]/g, '_'); } /** * * @param sender * @param propertyName * @param gridRefName */ function clearViewModelReloadGrid(sender, propertyName, gridRefName) { var _a, _b; var scope = lookupScope(sender); clearViewModelValues(scope.viewModel, propertyName); if (!gridRefName) { (_a = scope.down('grid')) === null || _a === void 0 ? void 0 : _a.reload(); } else { (_b = scope.refs[gridRefName]) === null || _b === void 0 ? void 0 : _b.reload(); } } var keydown_fun_item = _.debounce(function (sender, event, eOpts) { if ([10, 13, 20, 40].includes(event.keyCode)) { // 获取读码器读取的内容,最好不要从 viewModel 中取值,而是从 sender.rawValue 中取值 var value = _.trim(sender.rawValue); raiseClick(eOpts.handle); } }, 150); var SystemEventFu = /** @class */ (function () { function SystemEventFu() { } SystemEventFu.prototype.enterToClick = function (btnReferenceName) { return function (sender, config) { if (!config.listeners) { config.listeners = {}; } config.listeners.afterrender = function (sender) { var scope = lookupScope(sender); // $(sender.el.dom).on('keydown', (e) => { // const xtype = Ext.fly(e.target).component.xtype // if (xtype === 'textfield' && e.keyCode === 13) { // Ext.defer(() => { // raiseClick(scope.refs[btnReferenceName]) // }) // e.preventDefault() // e.stopPropagation() // return false // } // }) $(sender.el.dom).on('keyup', function (e) { var tt = Ext.fly(e.target).component; var xtype = tt === null || tt === void 0 ? void 0 : tt.xtype; if ((xtype !== 'textfield' && xtype !== 'numberfield') || ![10, 13, 20, 40].includes(e.keyCode)) { return; } e.preventDefault(); e.stopPropagation(); keydown_fun_item(tt, e, { handle: scope.refs[btnReferenceName] }); return; }); }; }; }; SystemEventFu.prototype.confirm = function (text, fn) { return function (sender) { var scope = lookupScope(sender); var msg = calcExpress(scope.viewModel.data, text); confirm(msg, sender).then(function () { fn.call(scope, sender); }); }; }; SystemEventFu.prototype.gridRemoveCurrentRow = function (gridRefName) { return function (sender) { var scope = lookupScope(sender); var grid = scope.refs[gridRefName]; if (grid) { var records = grid.getSelectionModel().getLastSelected(); grid.store.remove(records); } }; }; SystemEventFu.prototype.loadForm = function (invokeUrl, invokeParam, //可以是 scope.XX / system.XX / string / lookup表达式 writeTarget) { return function (sender) { if (!invokeUrl) { return; } var scope = lookupScope(sender); scope.setLoading(true); var data = scope.viewModel.data; if (invokeParam) { data = calcObjectFlat(data, invokeParam); } invokeServer(invokeUrl, data).then(function (res) { if (res.success) { if (typeof writeTarget === "string") { _.forOwn(res.data, function (v, k) { scope.viewModel.set(writeTarget + "." + k, v); }); } else if (typeof writeTarget === 'function') { writeTarget.call(scope, res.data); } else if (typeof writeTarget === 'object') { var ret = calcObjectFlat(res.data, writeTarget); _.forOwn(ret, function (v, k) { scope.viewModel.set(k, v); }); } } else { showErrorDialog$1(res.msg || '未知错误', sender); } }).catch(function (e) { var _a, _b; var msg = (_b = (_a = e.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.msg; showErrorDialog$1(msg || e.toString(), sender); }).finally(function () { scope.setLoading(false); }); }; }; SystemEventFu.prototype.commit = function (groovyUrl, arg0, successCallback) { return function (sender) { var scope = lookupScope(sender); scope.setLoading(true); var data = scope.viewModel.data; if (arg0) { data = calcObjectFlat(data, arg0); } invokeServer(groovyUrl, data).then(function (res) { if (res.success) { if (res.msg) { msg(res.msg); } if (typeof successCallback === 'function') { successCallback.call(scope, sender, res.data); } } else { showErrorDialog$1(res.msg || '未知错误', sender); } }).catch(function (e) { var _a, _b; var msg = (_b = (_a = e.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.msg; showErrorDialog$1(msg || e.toString(), sender); }).finally(function () { scope.setLoading(false); }); }; }; SystemEventFu.prototype.formCommit = function (groovyUrl, arg0) { return function (sender) { var scope = lookupScope(sender); var form = scope.down('form'); if (form) { // 如果下级有表单,就做表单校验 var valid = form.isValid(); if (!valid) { return; } } scope.setLoading(true); var data = scope.viewModel.data; if (arg0) { data = calcObjectFlat(data, arg0); } invokeServer(groovyUrl, data).then(function (res) { if (res.success) { if (res.msg) { msg(res.msg); } scope.dialogSuccess(res); } else { showErrorDialog$1(res.msg || '未知错误', sender); } }).catch(function (e) { var _a, _b; var msg = (_b = (_a = e.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.msg; showErrorDialog$1(msg || e.toString(), sender); }).finally(function () { scope.setLoading(false); }); }; }; SystemEventFu.prototype.dialogSuccess = function (lookupObject) { return function (sender) { var scope = lookupScope(sender); if (lookupObject) { scope.dialogSuccess(calcObjectFlat(scope.viewModel.data, lookupObject)); } else { scope.dialogSuccess(); } }; }; SystemEventFu.prototype.clearViewModelValues = function (propertyName) { return function (sender) { var scope = lookupScope(sender); clearViewModelValues(scope.viewModel, propertyName); }; }; SystemEventFu.prototype.getGrid = function (url) { return function (sender, config) { if (config.xtype == "combogridmulti") { // @ts-ignore require([url], function (grid) { _.forOwn(grid.default, function (v, k) { sender[k] = v; sender.config[k] = v; if (sender.rendered) { // 已经渲染出来了,重新调用 reload 强制刷新 sender.reload(); } }); }); } else { // @ts-ignore require([url], function (grid) { sender.grid = grid.default; config.grid = grid.default; }); } }; }; SystemEventFu.prototype.clearViewModelReloadGrid = function (propertyName, gridRefName) { return function (sender) { clearViewModelReloadGrid(sender, propertyName, gridRefName); }; }; SystemEventFu.prototype.reloadGrid = function (gridRefName) { return function (sender) { var _a, _b; var scope = lookupScope(sender); if (!gridRefName) { (_a = scope.down('grid')) === null || _a === void 0 ? void 0 : _a.reload(); } else { (_b = scope.refs[gridRefName]) === null || _b === void 0 ? void 0 : _b.reload(); } }; }; SystemEventFu.prototype.showDialog = function (url, lookupForData, successCallback) { return function (sender) { var scope = lookupScope(sender); var data = scope.viewModel.data; var param = calcObjectFlat(data, lookupForData); // @ts-ignore require([url], function (module) { var ScopeClass = module.default; var scope = new ScopeClass(); scope.success = successCallback; scope.showDialog(sender, {}, { data: param }); }); }; }; SystemEventFu.prototype.showWidget = function (widgetUrl, lookup) { return function (sender, queryValue) { showWidget(widgetUrl, lookup, sender, queryValue); }; }; SystemEventFu.prototype.clearViewModelByLookup = function (lookup) { return function (sender) { clearViewModelByLookup(sender, lookup); }; }; SystemEventFu.prototype.closeMe = function (callBack) { return function (sender) { var scope = lookupScope(sender); scope.close(); if (callBack) { callBack.call(sender); } }; }; __decorate([ Lib({ title: '按下回车键之后默认是否按下某个按钮', author: '罗一帆', createAt: '2021-07-02', updateAt: '2021-07-02', type: 'system', category: '字典', }), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", void 0) ], SystemEventFu.prototype, "enterToClick", null); __decorate([ Lib({ title: '弹出确认对话框,回答 YES 之后调用某方法', author: '罗一帆', createAt: '2021-07-06', updateAt: '2021-07-06', type: 'system', category: '对话框', }), __param(0, LibParam('对话框的确认文字', 'string')), __param(1, LibParam('确认之后的调用的方法', 'event')), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", void 0) ], SystemEventFu.prototype, "confirm", null); __decorate([ Lib({ title: '删除表格当前的选中行(前端删除)', author: '罗一帆', createAt: '2021-07-08', updateAt: '2021-07-08', type: 'system', category: '表格', }), __param(0, LibParam('表格引用名', 'refs')), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", void 0) ], SystemEventFu.prototype, "gridRemoveCurrentRow", null); __decorate([ Lib({ title: '查询表单,如果 url 为空值,就取消查询', author: '罗一帆', createAt: '2021-07-06', updateAt: '2021-07-06', type: 'system', category: '表单', }), __param(0, LibParam('后端服务路径', 'string')), __param(1, LibParam('后端需要的数据,默认情况提交所有', 'lookup', true)), __param(2, LibParam('提交成功后的回调', 'viewModel', true)), __metadata("design:type", Function), __metadata("design:paramtypes", [String, Object, Object]), __metadata("design:returntype", void 0) ], SystemEventFu.prototype, "loadForm", null); __decorate([ Lib({ title: '提交(不做校验、不关闭窗体)', author: '罗一帆', createAt: '2021-07-02', updateAt: '2021-07-02', type: 'system', category: '表单', }), __param(0, LibParam('后端服务路径', 'string')), __param(1, LibParam('后端需要的数据,默认情况提交所有', 'lookup', true)), __param(2, LibParam('提交成功后的回调', 'event', true)), __metadata("design:type", Function), __metadata("design:paramtypes", [String, Object, Object]), __metadata("design:returntype", void 0) ], SystemEventFu.prototype, "commit", null); __decorate([ Lib({ title: '提交表单', author: '罗一帆', createAt: '2021-07-02', updateAt: '2021-07-02', type: 'system', category: '表单', }), __param(0, LibParam('后端服务路径', 'string')), __param(1, LibParam('后端需要的参数,默认情况提交所有', 'lookup', true)), __metadata("design:type", Function), __metadata("design:paramtypes", [String, Object]), __metadata("design:returntype", void 0) ], SystemEventFu.prototype, "formCommit", null); __decorate([ Lib({ title: '对话框成功回调', author: '罗一帆', createAt: '2021-07-02', updateAt: '2021-07-02', type: 'system', category: '对话框', }), __param(0, LibParam('传回给父窗口的成功参数对象', 'lookup', true)), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", void 0) ], SystemEventFu.prototype, "dialogSuccess", null); __decorate([ Lib({ title: '清空 viewModel 某个属性', author: '罗一帆', createAt: '2021-07-02', updateAt: '2021-07-02', type: 'system', category: '表单', }), __param(0, LibParam('属性路径', 'viewModel', true)), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", void 0) ], SystemEventFu.prototype, "clearViewModelValues", null); __decorate([ Lib({ title: '从其他资源获取表格设置', author: '罗一帆', createAt: '2021-07-02', updateAt: '2021-07-02', type: 'system', category: '表单', }), __param(0, LibParam('定义文件', 'module')), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", void 0) ], SystemEventFu.prototype, "getGrid", null); __decorate([ Lib({ title: '清空 viewModel 某个属性,并刷新表格', author: '罗一帆', createAt: '2021-07-02', updateAt: '2021-07-02', type: 'system', category: '表单', }), __param(0, LibParam('清空的属性', 'viewModel')), __param(1, LibParam('要刷新的表格', 'refs', true)), __metadata("design:type", Function), __metadata("design:paramtypes", [String, String]), __metadata("design:returntype", void 0) ], SystemEventFu.prototype, "clearViewModelReloadGrid", null); __decorate([ Lib({ title: '刷新表格', author: '罗一帆', createAt: '2021-07-02', updateAt: '2021-07-02', type: 'system', category: '表单', }), __param(0, LibParam('表格对象,不填的情况下就是第一个表格', 'refs', true)), __metadata("design:type", Function), __metadata("design:paramtypes", [String]), __metadata("design:returntype", void 0) ], SystemEventFu.prototype, "reloadGrid", null); __decorate([ Lib({ title: '显示对话框', author: '罗一帆', createAt: '2021-07-02', updateAt: '2021-07-02', type: 'system', category: '对话框', }), __param(0, LibParam('业务模块名', 'module')), __param(1, LibParam('参数数据 lookup 表达式', 'lookup', true)), __param(2, LibParam('成功回调(对话框成功结束后的回调方法)', 'event', true)), __metadata("design:type", Function), __metadata("design:paramtypes", [String, Object, Object]), __metadata("design:returntype", void 0) ], SystemEventFu.prototype, "showDialog", null); __decorate([ Lib({ title: '弹出查找框(不借助 search)', author: '罗一帆', createAt: '2021-07-02', updateAt: '2021-07-02', type: 'system', category: '对话框', }), __param(0, LibParam('模块名 (WidgetDialog)', 'module')), __param(1, LibParam('lookup 映射关系', 'lookup', true)), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", void 0) ], SystemEventFu.prototype, "showWidget", null); __decorate([ Lib({ title: '根据 lookup 清空 viewModel', author: '罗一帆', createAt: '2021-07-05', updateAt: '2021-07-05', type: 'system', category: '表单', }), __param(0, LibParam('设值表达式', 'lookup')), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", void 0) ], SystemEventFu.prototype, "clearViewModelByLookup", null); __decorate([ Lib({ title: '关闭对话框', author: '罗一帆', createAt: '2021-07-05', updateAt: '2021-07-05', type: 'system', category: '对话框', }), __param(0, LibParam('对话框的返回值回调', 'event', true)), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", void 0) ], SystemEventFu.prototype, "closeMe", null); return SystemEventFu; }()); /** * 清空 viewmodel 里下属的所有属性 * @param viewModel VM对象 * @param propertyKey 要清空的属性,可以是 "a.b.c" 这种表达模式 * @param ignoreProps 要忽略清空的属性名集合, 比如 ["a.b","b"] */ function clearViewModel(viewModel, propertyKey, ignoreProps) { var data = viewModel.data; if (propertyKey) { data = _.get(data, propertyKey); } _.forOwn(data, function (value, key) { var targetKey = propertyKey ? propertyKey + "." + key : key; if (ignoreProps && _.indexOf(ignoreProps, targetKey) >= 0) { return; } viewModel.set(targetKey, ''); }); } function clearViewModelByLookup(sender, lookup) { if (_.isPlainObject(lookup)) { var parentScope_1 = lookupScope(sender); _.forOwn(lookup, function (value, key) { if (SIMPLE_RE.test(value)) { // '{foo}' 简单表达式 var path = value.substring(1, value.length - 1); if (path !== 'queryValue') { parentScope_1.viewModel.set(path, ''); } } }); } } function showWidget(widgetUrl, lookup, sender, queryValue, vjson) { if (vjson === void 0) { vjson = {}; } var parentScope = lookupScope(sender); var me = sender; // @ts-ignore require([widgetUrl], function (widgetScope) { var WidgetScopeClass = widgetScope.default; widgetScope = new WidgetScopeClass(); // 传递进 widget.model 的数据 var widgetDialogData = calcObjectFlat(__assign({ queryValue: queryValue }, parentScope.viewModel.data), lookup); widgetScope.parentScope = parentScope; widgetScope.searchWidgetSuccess = function (data) { if (typeof lookup === 'string') { // lookup 是字符串的情况下,就是取某个列作为 value 值 me.setValue(data[lookup]); return; } /** * lookup: { * // 扩展到 viewModel 的值做更改 * WH_CODE: "{queryValue}", * WH_NAME: "{query.WH_NAME}", * } */ if (_.isPlainObject(lookup)) { var parentScope_2 = lookupScope(sender); tryWriteObject(lookup, data, function (path, value) { if (path === 'queryValue') { me.setValue(value); } else { parentScope_2.viewModel.set(path, value); } }); } return true; }; widgetScope.showDialog(sender, vjson, { data: widgetDialogData }); }); } /** * 停止事件的默认行为 * @param e */ function stopEvent(e) { e.preventDefault(); e.stopPropagation(); // @ts-ignore window.event.cancelBubble = true; e.returnValue = false; e.cancelBubble = true; } /** * 屏幕中央显示一个黑框提示 */ function msg$1(content) { msg(content); } /** * 错误对话框的强提醒 */ function showErrorDialog$1(msg, sender) { showErrorDialog(msg, sender); } /** * 错误对话框的强提醒 */ function showInfoDialog(msg, sender) { showInfoDialogSimple(msg, sender); } /** * 错误对话框的强提醒 */ function prompt$1(message, defaultValue, multiLine) { if (defaultValue === void 0) { defaultValue = ""; } if (multiLine === void 0) { multiLine = false; } return prompt(message, defaultValue, multiLine); } /** * 用于计算 express 表达式 */ function evalFunction(data, express) { var keys = []; var values = []; _.forOwn(data, function (value, key) { var match = key.match(/\-|\*|\\|\/|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)/i); if (match) { key = key.substring(0, match.index); } keys.push(key); values.push(value); }); var func = Function.apply(void 0, __spread(keys, ['return ' + express])); try { return func.apply(void 0, __spread(values)); } catch (e) { return; } } /** * 获取表格编辑的行数据 */ function getGridEditRows(grid) { return grid.getGridEditRows(); } var SystemLib = /*#__PURE__*/Object.freeze({ __proto__: null, SIMPLE_RE: SIMPLE_RE, pinyinMatch: pinyinMatch, calcExpress: calcExpress, calcObjectFlat: calcObjectFlat, mergeViewModel: mergeViewModel, flatRow: flatRow, replaceNA: replaceNA, tryWriteByExpress: tryWriteByExpress, tryWriteObject: tryWriteObject, tryVarSimple: tryVarSimple, calcObject: calcObject, getParentGrid: getParentGrid, tryEnable: tryEnable, setComboStore: setComboStore, invokeServer: invokeServer, clearViewModelValues: clearViewModelValues, reloadGrid: reloadGrid, toPlainObject: toPlainObject, confirm: confirm, normId: normId, clearViewModelReloadGrid: clearViewModelReloadGrid, SystemEventFu: SystemEventFu, clearViewModel: clearViewModel, clearViewModelByLookup: clearViewModelByLookup, showWidget: showWidget, stopEvent: stopEvent, msg: msg$1, showErrorDialog: showErrorDialog$1, showInfoDialog: showInfoDialog, prompt: prompt$1, evalFunction: evalFunction, getGridEditRows: getGridEditRows }); function initTree () { Ext.define('Yvan.Tree', { extend: 'Ext.tree.Panel', alias: 'widget.yvtree', xtype: 'yvtree', constructor: function (config) { var newConfig = _.defaultsDeep({ // 强制性属性 }, baseConfig(config, 'row-item'), config, tree); _.assign(newConfig, { root: [], rootVisible: false, tbar: [ { xtype: 'trigger', triggerCls: 'x-form-clear-trigger', flex: 1, emptyText: '搜索过滤', enableKeyEvents: true, listeners: { change: { fn: function (sender, e) { var _this = this; _.defer(function () { var scope = sender.up("yvtree"); scope.filterByText(_this.getRawValue()); }); }, buffer: 500 }, } }, ], }); if (!newConfig.hideRefresh) { newConfig.tbar.push({ xtype: 'button', iconCls: 'x-fa fa-refresh', tooltip: '刷新', listeners: { click: function (sender) { var scope = sender.up("yvtree"); scope.reload(); } } }); } if (!newConfig.hideExpand) { newConfig.tbar.push({ xtype: 'button', iconCls: 'x-fa fa-plus-square-o', tooltip: '全部展开', listeners: { click: function (sender) { var scope = sender.up("yvtree"); scope.expandAll(); } } }); } if (!newConfig.hideCollapse) { newConfig.tbar.push({ xtype: 'button', iconCls: 'x-fa fa-minus-square-o', tooltip: '全部收起', listeners: { click: function (sender) { var scope = sender.up("yvtree"); scope.collapseAll(); } } }); } this.superclass.constructor.call(this, newConfig); }, /** * 在根节点上增加一个节点,会触发 addNode 事件 * @param props */ addRoot: function (props) { var me = this; var tableNode = me.getRootNode(); var fieldNode = tableNode.createNode(new Ext.data.NodeInterface({})); if (_.isFunction(props)) { props = props.call(this, parent); } _.forOwn(props, function (value, key) { fieldNode.set(key, value); }); var node = tableNode.appendChild(fieldNode); me.ensureVisible(node); me.setSelection(node); me.fireEvent('addNode', me, { parent: tableNode, node: node, }); }, addLast: function (props) { var me = this; var sel = me.selModel.getSelection(); if (!sel || sel.length <= 0) { msg('请选择一个要添加的同级节点路径'); return; } var parent = sel[0].parentNode ? sel[0].parentNode : me.getRootNode(); var fieldNode = parent.createNode(new Ext.data.NodeInterface({})); if (_.isFunction(props)) { props = props.call(this, parent); } _.forOwn(props, function (value, key) { fieldNode.set(key, value); }); var node = parent.appendChild(fieldNode); me.ensureVisible(node); me.setSelection(node); me.fireEvent('addNode', me, { parent: parent, node: node, }); }, addChildren: function (props) { var me = this; var sel = me.selModel.getSelection(); if (!sel || sel.length <= 0) { msg('请选择一个要添加子节点的路径'); return; } var parent = sel[0]; if (_.isFunction(props)) { props = props.call(this, parent); } var fieldNode = parent.createNode(new Ext.data.NodeInterface({})); _.forOwn(props, function (value, key) { fieldNode.set(key, value); }); var node = parent.appendChild(fieldNode); parent.expand(); me.ensureVisible(node); me.setSelection(node); me.fireEvent('addNode', me, { parent: parent, node: node, }); }, initComponent: function () { var me = this; var config = me.config; var scope = lookupScope(this); if (!window["IS_DESIGN_MODE"]) { // 转换 dataSource 属性 convertDataSource(me, scope, config); } this.superclass.initComponent.call(this); this.on({ afterrender: function (sender) { var me = this; var config = this.config; var dataSource = config.dataSource; if (config.autoLoad) { if (config.dataSourceCallbackFn) { me.reload(); } else if (_.isPlainObject(dataSource) && dataSource.method === 'invoke') { me.reload(); } } } }); }, _setDataReal: function (value) { var me = this; // me.setStore(new Ext.data.TreeStore({ // root: { // expanded: true, // // children: value // children: [ // { // id: '1', text: 'A', // children: [ // {id: '1', text: 'A',}, // {id: '2', text: 'B'}, // ] // }, // {id: '2', text: 'B'}, // ] // } // })) me.store.setRoot({ expanded: true, children: value }); // me.store = new Ext.data.TreeStore({ // root: { // expanded: true, // // children: value // children: [ // { // id: '1', text: 'A', // children: [ // {id: '1', text: 'A',}, // {id: '2', text: 'B'}, // ] // }, // {id: '2', text: 'B'}, // ] // } // }) }, /** * 重新载入数据(重新计算参数) */ reload: function (reloadParams) { if (reloadParams === void 0) { reloadParams = {}; } var me = this; var config = me.config; if (config.dataSourceCallbackFn) { // 函数请求刷新 var scope = lookupScope(this); // me.setLoading(true) config.dataSourceCallbackFn.call(scope, me, { successCallback: function (value) { me._setDataReal(value); // me.setLoading(false) me.fireEvent('dataLoadComplete', me, true, value); }, failCallback: function (error) { // me.setLoading(false) me.fireEvent('dataLoadComplete', me, false, error); } }); return; } var dataSource = config.dataSource; if (_.isPlainObject(dataSource) && dataSource.method === 'invoke' && !window["IS_DESIGN_MODE"]) { var scope = lookupScope(me); var params = calcObjectFlat(scope.viewModel.data, _.defaultsDeep({}, reloadParams, dataSource.params)); me.setLoading(true); invokeServer(dataSource.url, params) .then(function (res) { me._setDataReal(res.data); me.fireEvent('dataLoadComplete', me, res); }) .finally(function () { me.setLoading(false); }); } }, filterByText: function (text) { this.filterBy(text, 'text'); }, filterBy: function (text, by) { this.clearFilter(); var view = this.getView(), me = this, nodesAndParents = []; this.getRootNode().cascadeBy(function (tree, view) { var currNode = this; if (currNode && currNode.data[by] && currNode.data[by].toString().toLowerCase().indexOf(text.toLowerCase()) > -1) { me.expandPath(currNode.getPath()); while (currNode.parentNode) { nodesAndParents.push(currNode.id); currNode = currNode.parentNode; } } }, null, [me, view]); this.getRootNode().cascadeBy(function (tree, view) { var uiNode = view.getNodeByRecord(this); if (uiNode && !Ext.Array.contains(nodesAndParents, this.id)) { Ext.get(uiNode).setDisplayed('none'); } }, null, [me, view]); }, clearFilter: function () { var view = this.getView(); this.getRootNode().cascadeBy(function (tree, view) { var uiNode = view.getNodeByRecord(this); if (uiNode) { Ext.get(uiNode).setDisplayed('table-row'); } }, null, [this, view]); }, }); } function convertDataSource(sender, scope, newConfig) { if (typeof newConfig.store !== 'undefined') { // 有 store 属性的情况下,不做任何事 return; } if (typeof newConfig.dataSource === 'undefined') { // 没有定义 dataSource 的情况下,不做任何事 return; } var dataSource = newConfig.dataSource; if (typeof dataSource === 'string') { // dataSource 是字符串的情况下,找到成员函数 dataSource = lookupFn(scope, dataSource); } if (typeof dataSource === 'function') { // dataSource 是函数的情况下,在 afterrender 之后进行回调 newConfig.store = new Ext.data.TreeStore({ root: { expanded: true, children: [] } }); newConfig.dataSourceCallbackFn = dataSource; return; } // throw new TypeError('无法识别的调用方法') } /** * 构建一个 grid 支持的 dataSource */ function gridInvokeBuild(scope, grid, config, dataSource, reloadParams, isExcelExport, excelExportCallBack) { if (reloadParams === void 0) { reloadParams = {}; } if (isExcelExport === void 0) { isExcelExport = false; } if (excelExportCallBack === void 0) { excelExportCallBack = null; } var me = grid; var params = calcObjectFlat(scope.viewModel.data, dataSource.params); var storeOption = {}; if (dataSource.method === 'invoke') { var fields_1 = []; _.forEach(grid.columns, function (col) { var c = {}; if (col.dataIndex) { c.name = col.dataIndex; fields_1.push(c); } if (col.dataType) { c.type = col.dataType; } }); // 默认支持 gridInvoke //@ts-ignore storeOption = { fields: fields_1, remoteSort: config.remoteSort, remoteFilter: config.remoteFilter, autoLoad: true, pageSize: me.store.pageSize || config.pageSize, proxy: { type: 'jsonAjax', $owner: me, url: serverInvokeUrlTransform(dataSource.url, { scope: scope, grid: grid, isExcelExport: isExcelExport, excelExportCallBack: excelExportCallBack }), extraParams: _.defaultsDeep({}, reloadParams, params), reader: { type: 'json', rootProperty: 'data', totalProperty: 'pagination.total', successProperty: 'success', messageProperty: 'msg', transform: function (data) { if (typeof window['ajaxProcess'] === 'function') { window['ajaxProcess'](data); } if (typeof grid._transform === 'function') { // 系统转换函数 grid._transform(data.data); } if (grid.dataTransform) { if (typeof grid.dataTransform === 'string') { grid.dataTransform = lookupFn(lookupScope(grid), grid.dataTransform); } return grid.dataTransform.call(scope, grid, data); } return data; } } }, listeners: { load: function (store, records, successful, operation) { var _a, _b, _c; var rep = (_a = operation.getResponse()) === null || _a === void 0 ? void 0 : _a.responseJson; if (rep.pagination) { grid.dbInfo = rep.pagination.dbInfo; grid.exportDataSql = rep.pagination.exportDataSql; grid.exportDataSqlParams = rep.pagination.exportDataSqlParams; } me.exportExcelTotal = ((_b = rep === null || rep === void 0 ? void 0 : rep.pagination) === null || _b === void 0 ? void 0 : _b.total) || ((_c = rep === null || rep === void 0 ? void 0 : rep.data) === null || _c === void 0 ? void 0 : _c.length) || 0; if (isExcelExport) { if (typeof excelExportCallBack === 'function') { excelExportCallBack(rep); } else if (excelExportCallBack) { console.error("导出回调方法错误!"); } me.fireEvent('excelDataLoadComplete', me, successful, records); } else { me.fireEvent('dataLoadComplete', me, successful, records); } } } }; } else if (exports.apiConvert) { // 外部扩展的 apiConvert //@ts-ignore storeOption = exports.apiConvert.gridInvokeBuild(scope, grid, config, dataSource, params, reloadParams); } else { throw new TypeError("不支持的 API 请求方式"); } if (isExcelExport) { var excelStore = new Ext.data.Store(storeOption); excelStore.load(); } else { if (me.groupField) { console.log('groupField', storeOption.groupField); storeOption.groupField = me.groupField; } me.setStore(new Ext.data.Store(storeOption)); } } function initStores () { Ext.define('Yvan.JsonAjaxProxy', { extend: 'Ext.data.proxy.Ajax', alias: 'proxy.jsonAjax', actionMethods: { create: "POST", read: "POST", update: "POST", destroy: "POST" }, timeout: storeAjax.timeout, buildRequest: function (operation) { // 参考源码 ext-all-debug.js:71468 method:buildRequest var me = this; var $owner = me.$owner; // 在 grid.initComponent 中赋值 $owner var scope = lookupScope($owner); var gridParam = me.getParams(operation); var customParam = {}; // 提取 srot 元素 if (gridParam.sort) { var sort = JSON.parse(gridParam.sort); // 字符串 [{"property":"BRANCHID","direction":"ASC"}] // 转换为对象 [{colId: "BRANCHID", sort: "asc"}] customParam.sortModel = []; _.forEach(sort, function (s) { customParam.sortModel.push({ colId: s.property, sort: _.toLower(s.direction) }); }); delete gridParam.sort; } // 提取筛选元素 if (gridParam.filter) { var filter = JSON.parse(gridParam.filter); // "[{"operator":"like","value":"1","property":"id"}]" // 转换为 filterModel: {BRANCHID: {filterType: "text", type: "contains", filter: "12"}} customParam.filterModel = {}; _.forEach(filter, function (s) { var newFilterItem = {}; if (s.operator === 'like') { newFilterItem.filterType = 'text'; newFilterItem.type = 'contains'; newFilterItem.filter = s.value; } else { // 无法识别的筛选类型 debugger; } customParam.filterModel[s.property] = newFilterItem; }); delete gridParam.filter; } // 被 grid.constructor 作为方法存在 var extraParams = _.cloneDeep(me.getExtraParams()); var params = _.defaultsDeep(gridParam, extraParams); // var request = this.superclass.buildRequest.apply(this, arguments); var request = new Ext.data.Request({ params: {}, action: operation.getAction(), records: operation.getRecords(), url: me.buildUrl(), jsonData: __assign({ args: [ params ] }, customParam), proxy: me }); operation.setRequest(request); return request; }, afterRequest: function (req, res) { // Extend.afterExtRequest(req, res) } }); Ext.define('Ext.ux.data.MyReader', { extend: 'Ext.data.reader.Json', xtype: 'yvgridreader', useSimpleAccessors: false, }); } window["EXPORT_DATA_HOST"] = "http://127.0.0.1:30000/exportData"; var hexToString = function (hex) { var arr = hex.split(""); var out = ""; for (var i = 0; i < arr.length / 2; i++) { var tmp = "0x" + arr[i * 2] + arr[i * 2 + 1]; // @ts-ignore var charValue = String.fromCharCode(tmp); out += charValue; } return out; }; var defaultGrid = grid; function initGrid () { Ext.define('Yvan.Grid', { extend: 'Ext.grid.Panel', xtype: 'yvgrid', constructor: function (config) { var _this = this; var _a, _b, _c, _d, _e, _f; var me = this; var dataSource = config.dataSource; if (!window["IS_DESIGN_MODE"]) { this.columnConfigCacheKey = this.makeColumnConfigCacheKey(config); if (Array.isArray(config.columns) && config.columns.length > 0) { var cacheData = this.getColumnConfigCache(); if (Array.isArray(cacheData) && cacheData.length > 0) { var newColumns = []; for (var j = 0; j < cacheData.length; j++) { var itData = cacheData[j]; for (var i = 0; i < config.columns.length; i++) { var column = config.columns[i]; if (itData.dataIndex === column.dataIndex) { if (itData.width) { column.width = itData.width; } column.hidden = itData.hidden; column.locked = itData.locked; newColumns.push(column); break; } } } config.columns = newColumns; } } } var newConfig = _.defaultsDeep({ // 强制性属性 bug. // lock 属性会造成 Cannot read properties of undefined (reading 'els') // enableLocking: false, // syncRowHeight: false, }, baseConfig(config, 'row-item'), config, grid); // 在面板上的组件 var scope = ((_a = newConfig.$initParent) === null || _a === void 0 ? void 0 : _a.yvanScope) || ((_c = (_b = newConfig.$initParent) === null || _b === void 0 ? void 0 : _b.lookupReferenceHolder()) === null || _c === void 0 ? void 0 : _c.yvanScope) || ((_d = config.$vmParent) === null || _d === void 0 ? void 0 : _d.yvanScope) || ((_f = (_e = newConfig.$vmParent) === null || _e === void 0 ? void 0 : _e._parent) === null || _f === void 0 ? void 0 : _f.yvanScope); var buttons = []; var getRowClass = newConfig.getRowClass; if (typeof getRowClass === 'string' && (_.startsWith(getRowClass, "scope.") || _.startsWith(getRowClass, "system."))) { var fn = lookupFn(scope, getRowClass); _.set(newConfig, 'viewConfig.getRowClass', fn); } if (!newConfig.hideExport) { buttons.push({ xtype: 'button', tooltip: '导出Excel', iconCls: 'x-fa fa-download', listeners: { click: this.exportExcel }, }); } if (!newConfig.hideAutoSize) { buttons.push({ xtype: 'button', iconCls: 'x-fa fa-text-width', tooltip: '自适应宽度', listeners: { click: this.autoSizeColumns } }); } if (!newConfig.hideClearFilter) { buttons.push({ xtype: 'button', tooltip: '清空筛选', iconCls: 'x-fa fa-filter', handler: this.clearFilter }); } if (!newConfig.hideSaveGridUIConfig) { buttons.push({ xtype: 'button', tooltip: '保存布局', iconCls: 'x-fa fa-cogs', handler: this.saveGridUIConfig }); } if (!newConfig.hideClearGridUIConfig) { buttons.push({ xtype: 'button', tooltip: '还原布局', iconCls: 'x-fa fa-reply-all', handler: this.clearGridUIConfig }); } if (!newConfig.hideFootbar) { if (newConfig.pagination) { newConfig.bbar = new Ext.PagingToolbar({ // pageSize: newConfig.pageSize, 这个值是无效的 displayInfo: true, store: this.store, emptyMsg: '没有记录', items: __spread([ { xtype: 'combobox', tooltip: '分页', queryMode: 'local', editable: false, allowBlank: true, labelAlign: 'right', width: 90, // labelWidth: 30, listConfig: { minWidth: null }, value: 50, valueField: undefined, displayField: undefined, hideClear: true, store: newConfig.pageSizeOption, listeners: { change: function (sender, nv, ov) { _this.store.pageSize = nv; _this.store.loadPage(1); } } } ], buttons) }); } else { newConfig.bbar = { xtype: 'toolbar', overflowHandler: 'menu', items: __spread([ { xtype: 'button', tooltip: '刷新', iconCls: 'x-fa fa-refresh', handler: function () { _this.reload(); } }, '-' ], buttons) }; if (newConfig.hideRefresh) { newConfig.bbar.items.splice(0, 1); } } } _.each(newConfig.columns, function (c) { var renderer = c.renderer, formatter = c.formatter; if (typeof renderer === 'string' && (_.startsWith(renderer, "scope.") || _.startsWith(renderer, "system."))) { if (newConfig.$initParent) { if (scope) { var rendererFn = lookupFn(scope, renderer); c.renderer = rendererFn.bind(scope); } } } if (formatter === 'button') { c.tdCls = 'td-btn'; if (!c.listeners) { c.listeners = {}; } c.listeners.click = function (sender, td, rowIdx, colIdx, event, record) { if ($(event.target).is('input')) { me.fireEvent('buttonclick', me, this, record); } }; } else if (formatter === 'percentRenderer') { c.tdCls = 'td-percent'; } }); this.superclass.constructor.call(this, newConfig); this.store.pageSize = newConfig.pageSize; }, setData: function (value) { var me = this; me._setDataReal(value); }, /** * 添加行,并进入编辑状态 * @param record 新行的属性集 * @param editRowCol 要编辑的列序号,或 dataIndex 的名称 */ appendEditRow: function (record, editRowCol) { var records = this.getStore().add(record); var recNew = records[0]; this.setSelection(records); if (typeof editRowCol === 'string' && editRowCol) { editRowCol = this.columns.findIndex(function (c) { return c.dataIndex === editRowCol; }); } if (typeof editRowCol === 'number') { var ce = this.findPlugin('cellediting'); this.editingPlugin = ce; ce.startEdit(recNew, editRowCol); } }, beginEdit: function (record, editRowCol) { if (typeof record === 'number') { record = this.store.data.getAt(record); } if (record.isEntity === true) { this.setSelection([record]); if (typeof editRowCol === 'string' && editRowCol) { editRowCol = this.columns.findIndex(function (c) { return c.dataIndex === editRowCol; }); } if (typeof editRowCol === 'number') { var ce = this.findPlugin('cellediting'); this.editingPlugin = ce; ce.startEdit(record, editRowCol); } } }, /** * 移除行 * @param record 如果记录传空,就是当前选中的行 */ removeEditRow: function (record) { if (!record) { record = this.selection; } if (!record) { msg('请选中要删除的行'); return; } this.getStore().remove(record); }, /** * 获取全部原始数据 */ getDataRows: function () { return this.getStore().data.items.map(function (r) { return r.data; }); }, /** * 获取全部原始数据, 不带 id/ 不带 origin */ getDataRowsOnlyData: function () { return _.map(_.cloneDeep(this.getDataRows()), function (r) { delete r.id; delete r._origin; return r; }); }, rowMoveUp: function () { var grid = this; if (!grid.selection) { msg('无法对多行进行移动'); return; } var record = grid.selection; // const records = grid.selModel.getSelection() // if (records.length !== 1) { // msg('无法对多行进行移动') // return // } // // const [record] = records var index = grid.store.indexOf(record); if (index > 0) { grid.store.removeAt(index); grid.store.insert(index - 1, record); grid.getView().refresh(); grid.selModel.select([record]); } }, rowMoveDown: function () { var grid = this; // const records = grid.selModel.getSelection() // if (records.length !== 1) { // msg('无法对多行进行移动') // return // } if (!grid.selection) { msg('无法对多行进行移动'); return; } var record = grid.selection; var index = grid.store.indexOf(record); if (index < grid.store.getCount() - 1) { grid.store.removeAt(index); grid.store.insert(index + 1, record); grid.getView().refresh(); grid.selModel.select([record]); } }, getEditRecord: function () { var _a, _b; var me = this; var editingPlugin = me.editingPlugin || me.ownerGrid.editingPlugin; var rowIdx = (_b = (_a = editingPlugin === null || editingPlugin === void 0 ? void 0 : editingPlugin.activeEditor) === null || _a === void 0 ? void 0 : _a.context) === null || _b === void 0 ? void 0 : _b.rowIdx; var record; if (typeof rowIdx === 'undefined') { record = me.getSelectionModel().getLastSelected(); } else { record = me.store.getAt(rowIdx); } return record; }, getEditRow: function () { var _a; var me = this; return (_a = me.getEditRecord()) === null || _a === void 0 ? void 0 : _a.data; }, setEditRow: function (rowValues) { var me = this; var record = me.getEditRecord(); if (record) { _.forOwn(rowValues, function (v, k) { record.set(k, v); }); } }, _transform: function (data) { // 无论是 grid._setDataReal 还是 stores.gridInvokeBuild 都会走这个函数,设值前都可以改变表格值 _.forEach(data, function (row) { row._origin = _.clone(row); }); }, _setDataReal: function (value) { var me = this; this._transform(value); var storeOpt = { fields: getFileds(this), data: value, }; if (this.groupField) { storeOpt.groupField = this.groupField; } var store = new Ext.data.Store(storeOpt); me.setStore(store); }, setStore: function (store) { var me = this; if (_.isArray(store)) { var value = store; this._transform(value); var storeOpt = { fields: getFileds(this), data: value, }; if (this.groupField) { storeOpt.groupField = this.groupField; } store = new Ext.data.Store(storeOpt); } me.superclass.setStore.call(this, store); var reference = this.reference; if (reference) { lookupScope(this).viewModel.set(reference + '.ischanged', false); } if (store) { store.on({ add: function (store, records, index, eOpts) { me._raiseChange(store, 'add'); }, remove: function (store, records, index, isMove, eOpts) { me._raiseChange(store, 'remove'); }, datachanged: function (sender, opt) { me._raiseChange(store, 'datachanged'); } }); } }, _raiseChange: function (store, type) { var _a, _b; var reference = this.reference; if (reference && store) { var ischanged = false; if (store.getModifiedRecords().length > 0 || store.getNewRecords().length > 0 || store.getRemovedRecords().length > 0) { ischanged = true; } else { ischanged = false; } (_b = (_a = lookupScope(this)) === null || _a === void 0 ? void 0 : _a.viewModel) === null || _b === void 0 ? void 0 : _b.set(reference + '.ischanged', ischanged); } }, /** * 轻量级刷新 */ refreshData: function () { var store = this.getStore(); if (store) { store.reload(); } }, /** * 为表格强制设置焦点 * @param seq 顺序号 */ focusRow: function (seq) { this.setSelection(this.store.getAt(seq)); this.getView().focusRow(seq); }, /** * 重新载入数据(重新计算参数) */ reload: function (reloadParams) { if (reloadParams === void 0) { reloadParams = {}; } var me = this; var config = me.config; if (config.dataSourceCallbackFn) { // 函数请求刷新 var scope = lookupScope(this); _.defer(function () { me.setLoading(true); }); config.dataSourceCallbackFn.call(scope, me, { successCallback: function (value) { me._setDataReal(value); _.defer(function () { me.setLoading(false); }); me.fireEvent('dataLoadComplete', me, true, value); }, failCallback: function (error) { _.defer(function () { me.setLoading(false); }); me.fireEvent('dataLoadComplete', me, false, error); } }); return; } // if (this.store) { // this.store.reload({aaaa: 1, bbbb: 2}) // } var dataSource = config.dataSource; if (_.isPlainObject(dataSource) && !window["IS_DESIGN_MODE"]) { var scope = lookupScope(me); gridInvokeBuild(scope, me, config, dataSource, reloadParams); } }, exportCurrentExcelClick: function () { var _a; var me = this; var config = me.config; var scope = lookupScope(me); var excelFileName = config.excelFileName || scope.vjson.title || _.uniqueId("excel-"); if (excelFileName.endsWith(".xlsx")) { excelFileName = excelFileName.split(".xlsx")[0]; } excelFileName += ".xlsx"; var rowsAll = (_a = this.getStore().getData().items) === null || _a === void 0 ? void 0 : _a.map(function (r) { return r.data; }); var excelData = me.makeExcelData(rowsAll); LAY_EXCEL.exportExcel(excelData, excelFileName, 'xlsx'); }, exportExcelClick: function (excelExportParams) { var me = this; var config = me.config; excelExportParams.isExcelExport = true; var scope = lookupScope(me); var dataSource = config.dataSource; scope.setLoading(true); var excelFileName = config.excelFileName || scope.vjson.title || _.uniqueId("excel-"); gridInvokeBuild(scope, me, config, dataSource, excelExportParams, true, function (responseData) { var _a, _b, _c, _d; var page = parseInt((_a = responseData.pagination) === null || _a === void 0 ? void 0 : _a.current) || 1; var size = parseInt((_b = responseData.pagination) === null || _b === void 0 ? void 0 : _b.size) || me.exportExcelPageSize; var total = parseInt((_c = responseData.pagination) === null || _c === void 0 ? void 0 : _c.total) || ((_d = responseData.data) === null || _d === void 0 ? void 0 : _d.length) || 0; me.exportExcelCurrentPage = page; me.exportExcelPageSize = size; me.exportExcelTotal = total; if (excelFileName.endsWith(".xlsx")) { excelFileName = excelFileName.split(".xlsx")[0]; } excelFileName += "(第" + me.exportExcelCurrentPage + "页,共" + Math.ceil(total / size) + "页、" + total + "条)"; excelFileName += ".xlsx"; var excelData = me.makeExcelData(responseData.data); LAY_EXCEL.exportExcel(excelData, excelFileName, 'xlsx'); if (page < total / size) { page++; me.exportExcelCurrentPage = page; } scope.setLoading(false); }); }, exportBigExcelClick: function () { var _a; var me = this; if (!((_a = me.dbInfo) === null || _a === void 0 ? void 0 : _a.jdbcurl) || !me.exportDataSql) { showErrorDialog('当前表格不支持大批量导出'); return; } var config = me.config; var scope = lookupScope(me); var excelFileName = config.excelFileName || scope.vjson.title || _.uniqueId("excel-"); var head = []; var dict = {}; _.forEach(me.columns, function (column) { if (column.isHidden()) return; if (!column.dataIndex) return; if (!column.text) return; head.push({ field: column.dataIndex, name: column.text }); if (column.dictForExcel) { dict[column.dataIndex] = column.dictForExcel; } }); // 判断是否需要解密 if (me.dbInfo.jdbcurl.indexOf("jdbc") < 0) { me.dbInfo.jdbcurl = hexToString(me.dbInfo.jdbcurl); me.dbInfo.password = hexToString(me.dbInfo.password); me.dbInfo.username = hexToString(me.dbInfo.username); } scope.setLoading(true); Ext.Ajax.request({ timeout: 15000, url: window["EXPORT_DATA_HOST"], method: "POST", jsonData: { file: excelFileName, dbInfo: me.dbInfo, exportDataSql: me.exportDataSql, exportDataSqlParams: me.exportDataSqlParams, head: head, dict: dict, }, }).then(function () { scope.setLoading(false); msg('请求成功'); }).catch(function () { scope.setLoading(false); showErrorDialog('请求失败,请确认是否已安装客户端'); }); }, makeExcelData: function (jsonData) { var me = this; me.fireEvent('onExcelDataLoadCompleted', me, jsonData); if (!Array.isArray(jsonData) || jsonData.length === 0) { return; } var data = []; // 获取表格的列定义 var headerTextArr = []; var headers = []; for (var i = 0; i < me.headerCt.getGridColumns().length; i++) { var header = me.headerCt.getGridColumns()[i]; if (!header.isHidden()) { var textStr = _.trim(header.text); var dataIndexStr = _.trim(header.dataIndex); if (dataIndexStr) { if (textStr === '') { headerTextArr.push(dataIndexStr); } else { headerTextArr.push(textStr); } headers.push(header); } } } if (headers.length === 0) { return; } data.push(headerTextArr); for (var i = 0; i < jsonData.length; i++) { var dataRow = jsonData[i]; var row = []; for (var j = 0; j < headers.length; j++) { var key = headers[j].dataIndex; var value = dataRow[key]; if (!value && value !== 0) { value = ''; } var oValue = value; // todo 导出处理字典日期等数据,如果有特殊的单元格渲染也可能出现导出的数据有特殊标记需要特殊处理一下 if (typeof headers[j].renderer === 'function' && (!headers[j].config.formatter)) { try { value = headers[j].renderer(value); if (!value && value !== 0) { value = oValue; } } catch (e) { value = oValue; } } row.push(value); } data.push(row); } return data; }, initComponent: function () { var _this = this; var _a; var me = this; var config = me.config; if (window["IS_DESIGN_MODE"]) { this.superclass.initComponent.call(this); return; } var scope = lookupScope(this); if (!window["IS_DESIGN_MODE"]) { // 转换 dataSource 属性 convertDataSource$1(me, scope, config); } this.on({ afterrender: function (sender) { var me = this; var config = this.config; var dataSource = config.dataSource; if (config.autoLoad) { if (config.dataSourceCallbackFn) { me.reload(); } else if (_.isPlainObject(dataSource)) { me.reload(); } } if (config.contextMenu === true && _.isArray(config.tbar)) { var vm = this.lookupViewModel(); this.contextMenu = this.add(new Ext.menu.Menu({ viewModel: vm, items: _.map(config.tbar, function (item) { var menuItem = __assign({}, item); if (menuItem.xtype === 'button') { delete menuItem.xtype; } return menuItem; }) })); } else if (_.isPlainObject(config.contextMenu)) { this.contextMenu = this.add(config.contextMenu); } var $dom = $(sender.el.dom); $dom.on('keydown', function (e) { me.fireEvent('keydown', me, e); }).on('keyup', function (e) { me.fireEvent('keyup', me, e); }); // 默认显示提示 if (this.cellTip) { this.tip = Ext.create('Ext.tip.ToolTip', { target: this.el, delegate: '.x-grid-cell-inner', trackMouse: true, ancor: 'top', style: 'background-color: #FFFFCC;', listeners: { beforeshow: function (tip) { var tipText = (tip.triggerElement.innerText || tip.triggerElement.textContent); if (Ext.isEmpty(tipText) || Ext.isEmpty(tipText.trim())) { return false; } tip.update(tipText); } } }); } }, itemcontextmenu: function (view, rec, node, index, e) { if (this.contextMenu) { e.stopEvent(); this.contextMenu.show().setLocalXY(e.getXY()); return false; } }, // columnmove(sender, column, fromIndex, toIndex, eOpts) { // this.setColumnConfigCache() // }, // columnhide(sender, column, eOpts) { // this.setColumnConfigCache() // }, // columnshow(sender, column, eOpts) { // this.setColumnConfigCache() // }, // columnresize(sender, column, width, eOpts) { // this.setColumnConfigCache() // }, destory: function () { }, selectionchange: function (sender, _a) { var _b = __read(_a, 1), record = _b[0]; itemselectFun(this, sender, record); }, itemclick: function (sender, record) { itemselectFun(this, sender, record); } }); _.defer(function () { var ce = _this.findPlugin('cellediting'); ce.on({ beforeedit: function (editor, context, eOpts) { me.fireEvent('editbefore', me, editor, context, eOpts); }, canceledit: function (editor, context, eOpts) { me.fireEvent('editcancel', me, editor, context, eOpts); }, edit: function (editor, context, eOpts) { me.fireEvent('editfinish', me, editor, context, eOpts); }, validateedit: function (editor, context, eOpts) { me.fireEvent('editvalidate', me, editor, context, eOpts); }, }); }); var itemselectFun = _.debounce(function (me, sender, record) { me.fireEvent('itemselect', sender, record); }, 100); if ((_a = this.store) === null || _a === void 0 ? void 0 : _a.proxy) { // 为 stores.proxy.buildRequest 做准备 this.store.proxy.$owner = this; } this.superclass.initComponent.call(this); }, // 生成列自定义的缓存key makeColumnConfigCacheKey: function (config) { var _a, _b, _c, _d, _e, _f; var scope = ((_a = config.$initParent) === null || _a === void 0 ? void 0 : _a.yvanScope) || ((_c = (_b = config.$initParent) === null || _b === void 0 ? void 0 : _b.lookupReferenceHolder()) === null || _c === void 0 ? void 0 : _c.yvanScope) || ((_d = config.$vmParent) === null || _d === void 0 ? void 0 : _d.yvanScope) || ((_f = (_e = config.$vmParent) === null || _e === void 0 ? void 0 : _e._parent) === null || _f === void 0 ? void 0 : _f.yvanScope); var key = "gridColumnCache-" + scope.scopeKey + "-"; if (config.reference) { key += config.reference; } else { var subKey = ""; for (var i = 0; i < config.columns.length; i++) { var column = config.columns[i]; if (column.dataIndex) { subKey += column.dataIndex; } } key += subKey; } return key; }, getColumnConfigCache: function () { var key = this.columnConfigCacheKey; var dataStr = localStorage.getItem(key); if (dataStr) { return JSON.parse(dataStr); } return ""; }, setColumnConfigCache: function () { var key = this.columnConfigCacheKey; var cacheData = []; var columns = this.headerCt.getGridColumns(); var index = 0; for (var i = 0; i < columns.length; i++) { var column = columns[i]; if (column.dataIndex) { cacheData.push({ dataIndex: column.dataIndex, width: column.width, hidden: column.hidden, locked: column.locked, index: index }); index++; } } localStorage.setItem(key, JSON.stringify(cacheData)); }, autoSizeColumns: function (sender) { var grid = sender ? sender.up('grid') : this; // const columns = grid.columns; // for (let i = 0; i < columns.length; i++) { // const column = columns[i]; // grid.getView().autoSizeColumn(column); // column.setWidth(column.getWidth() + 5); // } for (var i = 1; i < grid.headerCt.getColumnCount(); i++) { grid.headerCt.getGridColumns()[i].autoSize(i); grid.headerCt.getGridColumns()[i].setWidth(grid.headerCt.getGridColumns()[i].getWidth() + 15); } }, clearFilter: function (sender) { var grid = sender.up('grid'); grid.filters.clearFilters(); grid.getStore().sorters.removeAll(); // grid.getStore().reload() }, saveGridUIConfig: function (sender) { var grid = sender.up('grid'); grid.setColumnConfigCache(); msg('保存设置成功!'); }, clearGridUIConfig: function (sender) { var grid = sender.up('grid'); var key = grid.columnConfigCacheKey; localStorage.setItem(key, ""); msg('清空设置成功,重新打开后生效!'); }, setLoading: function (value) { if (value) { this.mask('读取中'); } else { this.unmask(); } }, exportExcel: function (sender) { var rect = sender.btnEl.dom.getBoundingClientRect(); var scope = lookupScope(this); var grid = sender.up('grid'); var treeMenu = new Ext.menu.Menu({ xtype: 'menu', floated: false, width: 300, docked: 'left', items: [ { text: '大批量导出 (需要客户端支持!)', iconCls: 'x-fa fa-download', listeners: { click: function (sender, value) { // @ts-ignore YvanUI.confirm('大批量数据导出会占用大量服务器资源和带宽资源,您真的要导出吗?') .then(function (res) { grid.exportBigExcelClick(); }); } } }, '-', { text: '导出当前数据', iconCls: 'x-fa fa-download', listeners: { click: function (sender, value) { grid.exportCurrentExcelClick(); } } }, { xtype: "textfield", fieldLabel: '当前导出页', maskRe: /[0-9]/, value: grid.exportExcelCurrentPage, listeners: { render: function (sender) { grid.exportExcelCurrentPageCmp = sender; }, change: function (sender, value) { var v = parseInt(value); if (isNaN(v) || v === 0) { window['system'].msg("页码不能为0"); v = 1; sender.setValue(v); } var size = parseInt(grid.exportExcelPageSize); var total = parseInt(grid.exportExcelTotal); if (v > total / size) { v = parseInt(total / size + ""); } grid.exportExcelCurrentPage = v + ""; } } }, { xtype: "textfield", fieldLabel: '导出页大小', maskRe: /[0-9]/, value: grid.exportExcelPageSize, listeners: { render: function (sender) { grid.exportExcelPageSizeCmp = sender; }, change: function (sender, value) { var v = parseInt(value); if (isNaN(v) || v === 0) { window['system'].msg("导出页大小不能为0"); v = defaultGrid.exportExcelPageSize; sender.setValue(v); } if (v > 10000) { window['system'].msg("导出页大小不能大于10000"); v = 10000; sender.setValue(v); } var page = parseInt(grid.exportExcelCurrentPage); var total = parseInt(grid.exportExcelTotal); if (page > total / v) { page = parseInt(total / v + "") + 1; grid.exportExcelCurrentPageCmp.setValue(page); } grid.exportExcelPageSize = v + ""; } } }, { xtype: "textfield", fieldLabel: '总条数', value: grid.exportExcelTotal, readOnly: true }, { text: '导出', iconCls: 'x-fa fa-download', listeners: { click: function (sender, value) { grid.exportExcelClick({ exportExcelPageSize: grid.exportExcelPageSize, exportExcelCurrentPage: grid.exportExcelCurrentPage }); } } }, ] }); treeMenu.showAt(rect.left, rect.top - 120); // for (let i = 1; i < grid.headerCt.getColumnCount(); i++) { // grid.headerCt.getGridColumns()[i].autoSize(i); // grid.headerCt.getGridColumns()[i].setWidth(grid.headerCt.getGridColumns()[i].getWidth() + 15); // } }, /** * 获取表格编辑的行数据 */ getGridEditRows: function () { var grid = this; var store = grid.getStore(); var rows = []; var modifyRows = []; var newRows = []; var err = ""; var records = store.getModifiedRecords(); var newRecords = store.getNewRecords(); var removeRecords = []; _.forEach(store.getRemovedRecords(), function (row) { removeRecords.push(row.data); }); _.forEach(records, function (record) { var colums = grid.columns; var errFunc = undefined; _.forEach(colums, function (col) { var name = col.dataIndex; var value = record.data[name]; var colIndex = col.getIndex(); //获得列号 var rowIndex = store.indexOfId(record.id); //获得行号 var editor = col.getEditor(); //使用的编辑器 var tmpErrFunc = function () { var text = col.text || col.name; msg(text + ' 校验失败, 请确保输入的数据正确'); grid.findPlugin('cellediting').startEdit(rowIndex, col); //如果不通过激活当前编辑状态 }; if (editor && !editor.allowBlank && isEmpty(value)) { errFunc = tmpErrFunc; return false; } if (editor && !isEmpty(value) && !editor.validateValue(value)) { errFunc = tmpErrFunc; return false; } }); if (typeof errFunc === 'function') { err = "1"; _.remove(rows, function (n) { return true; }); //@ts-ignore errFunc(); // Ext.Msg.alert('提示', '请确保输入的数据正确', errFunc) return false; } else { if (_.findIndex(newRecords, function (item) { return item === record; }) >= 0) { newRows.push(record.data); } else { modifyRows.push(record.data); } rows.push(record.data); } }); return { rows: rows, newRows: newRows, modifyRows: modifyRows, removeRecords: removeRecords, err: err }; } // reload() { // dataSourceReload(this) // }, }); } /** * 获取 columns 中所有的 dataIndex */ function getFileds(newConfig) { var fields = []; _.forEach(newConfig.columns, function (c) { if (c.dataIndex) { fields.push(c.dataIndex); } }); return fields; } function convertDataSource$1(sender, scope, newConfig) { if (typeof newConfig.store !== 'undefined') { // 有 store 属性的情况下,不做任何事 return; } if (typeof newConfig.dataSource === 'undefined') { // 没有定义 dataSource 的情况下,不做任何事 return; } if (_.isArray(newConfig.data)) { // 有 data 属性赋值的情况下 newConfig.store = { fields: getFileds(newConfig), data: newConfig.data }; delete newConfig.data; return; } var dataSource = newConfig.dataSource; if (typeof dataSource === 'string') { // dataSource 是字符串的情况下,找到成员函数 dataSource = lookupFn(scope, dataSource); } if (typeof dataSource === 'function') { // dataSource 是函数的情况下,在 afterrender 之后进行回调 newConfig.store = new Ext.data.Store({ fields: getFileds(newConfig), // data: [], autoLoad: true, proxy: { type: 'memory', data: [], } }); newConfig.dataSourceCallbackFn = dataSource; return; } // throw new TypeError('无法识别的调用方法') } /** * 创建一个 Ajax 客户端 */ function createAjax(createOption) { if (createOption.baseUrl) { axios__default.defaults.baseURL = createOption.baseUrl; axios__default.defaults.timeout = createOption.timeout; storeAjax.timeout = createOption.timeout; axios__default.defaults.timeoutErrorMessage = '网络超时'; } return function (option) { //@ts-ignore option.method = (option.method || 'get').toLocaleLowerCase(); //@ts-ignore var ax = __assign({}, option); switch (option.method) { case 'get': ax.method = 'GET'; ax.params = option.param; ax.headers = __assign({}, option.headers); break; case 'post': ax.method = 'POST'; ax.headers = __assign({ 'Content-Type': 'application/x-www-form-urlencoded' }, option.headers); ax.params = option.param; ax.data = Qs.stringify(option.data); break; case 'put': case 'patch': case 'delete': ax.method = option.method; ax.headers = option.headers; ax.params = option.param; ax.data = Qs.stringify(option.data); break; case 'download': downLoad(createOption.baseUrl + option.url, option.fileName || 'file', option.data, option.headers); return new Promise(function (resolver, reject) { }); case "invoke": ax.url = serverInvokeUrlTransform(option.url, option); ax.method = 'POST'; ax.headers = __assign({ 'Content-Type': 'application/json' }, option.headers); if (typeof option.args === 'object') { ax.data = JSON.stringify({ args: option.args, }); } else { ax.data = JSON.stringify({ args: [ __assign(__assign({}, option.data), option.param) ], filterModel: option.filterModel, sortModel: option.sortModel }); } break; case 'post-json': ax.method = 'POST'; ax.headers = __assign({ 'Content-Type': 'application/json' }, option.headers); ax.data = JSON.stringify(__assign(__assign({}, option.data), { filterModel: option.filterModel, sortModel: option.sortModel })); break; case 'post-file': //TODO 刘壮. 上传文件 var forms = new FormData(); ax.headers = __assign({ 'Content-Type': 'multipart/form-data' }, option.headers); _.forOwn(option.data, function (value, key) { if (key === 'files') { var i_1 = 0; _.each(value, function (f) { // @ts-ignore forms.append('file' + (++i_1), f); }); } else { forms.append(key, value); } }); ax.data = forms; ax.method = 'POST'; break; case "sql": ax.url = sqlUrlTransform(option.url); ax.method = 'POST'; ax.headers = __assign({ 'Content-Type': 'application/json' }, option.headers); ax.data = JSON.stringify({ args: [option.data], db: option.db, filterModel: option.filterModel, sortModel: option.sortModel }); break; default: throw new Error('not implements'); } return new Promise(function (resolver, reject) { axios__default(ax).then(function (resolverRaw) { var apiResult = { rawData: resolverRaw.data, status: resolverRaw.status, success: (resolverRaw.data && resolverRaw.data.success), data: resolverRaw.data.data, pagination: resolverRaw.data.pagination, msg: (resolverRaw.data.msg), errors: resolverRaw.data.errors, headers: resolverRaw.headers }; resolver(apiResult); }).catch(function (reason) { reject(reason); }); }); }; } function downLoad(downLoadUrl, filename, data, header, isJson) { if (isJson === void 0) { isJson = false; } var YvanUI = _.get(window, 'YvanUI'); YvanUI.loading(); var createObjectURL = function (object) { return (window.URL) ? window.URL.createObjectURL(object) : _.get(window, 'webkitURL').createObjectURL(object); }; // const formData = new FormData(); // _.forOwn(data, (v, k) => { // formData.append(k, v); // }); var formData = ''; var xhr = new XMLHttpRequest(); xhr.open('POST', downLoadUrl); xhr.responseType = 'blob'; // xhr.setRequestHeader('Authorization', $.cookie('auth')) if (isJson) { formData = data ? JSON.stringify(data) : ''; xhr.setRequestHeader('Content-Type', 'application/json'); } else { formData = data ? Qs.stringify(data) : ''; xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); } // if (header) { _.forOwn(header, function (v, k) { xhr.setRequestHeader(k, v); }); } xhr.onload = function (e) { if (this.status === 200) { var blob = this.response; if (_.hasIn(window, 'navigator.msSaveOrOpenBlob')) { navigator.msSaveBlob(blob, filename); YvanUI.clearLoading(); } else { var a = document.createElement('a'); var url = createObjectURL(blob); a.href = url; a.download = filename; document.append(a); a.click(); a.remove(); window.URL.revokeObjectURL(url); YvanUI.clearLoading(); } } }; xhr.send(formData); } function readExcel(file) { return new Promise(function (resolve, reject) { if (!file) { reject("文件读取失败!!!"); return; } var reader = new FileReader(); reader.onload = function (e) { if (e.target) { var data = e.target.result; var workbook = XLSX.read(data, { type: 'binary' }); resolve(workbook); } else { reject("文件读取失败!!!"); } }; try { reader.readAsBinaryString(file); } catch (e) { reject(e); } }); } function readExcelWithColumnsSet(topScope, file, columnsSet, dataStartRow, titleRowNumber, rowValidate, otherValidate, fieldValidate) { if (dataStartRow === void 0) { dataStartRow = 2; } if (titleRowNumber === void 0) { titleRowNumber = 1; } if (rowValidate === void 0) { rowValidate = undefined; } if (otherValidate === void 0) { otherValidate = undefined; } if (fieldValidate === void 0) { fieldValidate = undefined; } return new Promise(function (resolve, reject) { var promiseArr = []; for (var i = 0; i < columnsSet.length; i++) { var fix = columnsSet[i].fix; if (_.isArray(fix) && fix.length > 0) { var ss = fix[0].toLowerCase(); if (ss.indexOf("date") > -1 || ss.indexOf("time") > -1) { columnsSet[i].importFormatter = function (vdata) { // @ts-ignore return window.moment(vdata.ov) - 0; }; } else { var fn = lookupFn(topScope, fix[0]); promiseArr.push(fn(null, columnsSet[i])); delete columnsSet[i].fix; } } else if (_.isString(fix)) { var ss = fix.toLowerCase(); if (ss.indexOf("date") > -1 || ss.indexOf("time") > -1) { columnsSet[i].importFormatter = function (vdata) { // @ts-ignore return window.moment(vdata.ov) - 0; }; } else { var fn = lookupFn(topScope, fix); promiseArr.push(fn(null, columnsSet[i])); delete columnsSet[i].fix; } } } var read = function () { readExcel(file).then(function (workbook) { var sheetNames = workbook.SheetNames; // 工作表名称集合 var worksheet = workbook.Sheets[sheetNames[0]]; // 这里我们只读取第一张sheet var titleRowValue = []; var titleRowKey = []; var needLoop = false; // 是否需要迭代 var columns = []; if (worksheet && worksheet["!ref"]) { var t = worksheet["!ref"]; var tempArr = t.split(':'); if (tempArr.length >= 2) { var firstRowNumber = tempArr[0].replace(/[^0-9]/ig, ""); // 选取title的行,删除之前的行 if (titleRowNumber > firstRowNumber) { for (var i = firstRowNumber; i < titleRowNumber; i++) { for (var key in worksheet) { if (key.endsWith(i) && key.replace(/[^0-9]/ig, "") === i) { delete worksheet[key]; } } } var fc = tempArr[0].replace(/[^a-z]/ig, ""); firstRowNumber = titleRowNumber + ''; worksheet["!ref"] = fc + firstRowNumber + ":" + tempArr[1]; } var lastRowNumber = tempArr[1].replace(/[^0-9]/ig, ""); // const firstColNumber = tempArr[0].split(''+firstRowNumber)[0]; // const lastColNumber = tempArr[1].split(''+lastRowNumber)[0]; for (var key in worksheet) { if (key.endsWith(firstRowNumber) && key.replace(/[^0-9]/ig, "") === firstRowNumber) { titleRowKey.push(key); titleRowValue.push(worksheet[key].v); } } if (columnsSet && columnsSet.length > 0) { var length = columnsSet.length; length = length <= titleRowKey.length ? length : titleRowKey.length; for (var i = 0; i < length; i++) { var vk = titleRowKey[i]; var item = columnsSet[i]; var column = {}; if (typeof item === 'string') { column.dataIndex = item; column.header = worksheet[vk].v; worksheet[vk] = { t: "s", v: item, h: item, w: item }; } else if (typeof item.dataIndex === "string") { column.dataIndex = item.dataIndex; column.header = worksheet[vk].v; worksheet[vk] = { t: "s", v: item.dataIndex, h: item.dataIndex, w: item.dataIndex }; if (typeof item.validate === "function") { column.validate = item.validate; needLoop = true; } if (typeof item.importFormatter === "function") { column.importFormatter = item.importFormatter; needLoop = true; } if ((item.data instanceof Array && item.data.length > 0) || _.isPlainObject(item.data) && Object.keys(item.data).length > 0) { column.data = item.data; needLoop = true; } } columns.push(column); } } } } if (fieldValidate && typeof fieldValidate === "function") { if (fieldValidate(columns, titleRowValue) !== true) { reject("fields validate error"); return; } } var allData = XLSX.utils.sheet_to_json(worksheet); var okData = [], errorData = [], errorMsgData = []; var needItemLoop = needLoop; if (rowValidate && typeof rowValidate === "function") { needLoop = true; } if (needLoop === true) { for (var index = 0; index < allData.length; index++) { var row = allData[index]; var rowNumber = dataStartRow + index; row.__importID__ = rowNumber; var isRowOk = true; if (needItemLoop) { var _loop_1 = function (num) { var column = columns[num]; var ov = row[column.dataIndex]; var nv = ov; var hasError = false; var rowNumber_1 = dataStartRow + index; var ei = { errorId: rowNumber_1 + '_' + column.dataIndex, importID: rowNumber_1, dataIndex: column.dataIndex, header: column.header, value: ov, errormessage: "" }; // 格式化 if (column.data instanceof Array) { nv = undefined; ei.errormessage = "字典匹配失败"; _.forEach(column.data, function (v, index) { if (v.text === ov) { nv = v.id; return; } }); } else if (_.isPlainObject(column.data)) { nv = undefined; ei.errormessage = "字典匹配失败"; _.forEach(column.data, function (value, key) { if (value === ov) { nv = key; return; } }); } if (typeof column.importFormatter === 'function') { var vdata = { column: column, ov: ov, nv: nv, rowIndex: index, data: row, rowDatas: allData }; nv = undefined; ei.errormessage = "格式化失败"; nv = column.importFormatter(vdata); } if (!nv && nv != 0) { hasError = true; } else { row[column.dataIndex] = nv; ei.errormessage = ""; } // 校验 if (typeof column.validate === 'function') { var vdata = { column: column, ov: ov, nv: nv, rowIndex: index, data: row, rowDatas: allData }; var errormessage = column.validate(vdata); if (errormessage === true) ; else { hasError = true; ei.errormessage = ei.errormessage + "/" + errormessage; } } if (hasError === true) { isRowOk = false; errorMsgData.push(ei); } }; for (var num = 0; num < columns.length; num++) { _loop_1(num); } } if (rowValidate && typeof rowValidate === "function") { var errormessage = rowValidate({ columns: columns, data: row, rowIndex: index, rowDatas: allData }); if (errormessage === true) ; else { isRowOk = false; var ei = { errorId: rowNumber + '', dataIndex: "row", header: "数据行", value: "当前行的数据", importID: rowNumber, errormessage: errormessage }; errorMsgData.push(ei); } } row.__hasError__ = !isRowOk; if (isRowOk === true) { okData.push(row); } else { errorData.push(row); } } } else { // 添加数据的唯一标识 for (var index = 0; index < allData.length; index++) { var row = allData[index]; var rowNumber = dataStartRow + index; row.__importID__ = rowNumber; row.__hasError__ = false; } okData = allData; } if (otherValidate && typeof otherValidate === "function") { otherValidate({ allData: allData, okData: okData, errorData: errorData, errorMsgData: errorMsgData }, resolve); } else { resolve({ allData: allData, okData: okData, errorData: errorData, errorMsgData: errorMsgData }); } // clearLoading() }).catch(function (e) { reject(e); }); }; if (promiseArr.length > 0) { Promise.all(promiseArr).then(function (resArr) { for (var i = 0; i < resArr.length; i++) { var tmp = resArr[i]; tmp.config.data = []; if (tmp && tmp.r && Array.isArray(tmp.r.field) && Array.isArray(tmp.r.data)) { if (tmp.r.field.length > 1) { var keyKey = tmp.r.field[0]; var valueKey = tmp.r.field[1]; for (var j = 0; j < tmp.r.data.length; j++) { var it = tmp.r.data[j]; var newIt = {}; newIt.id = it[keyKey]; newIt.text = it[valueKey]; tmp.config.data.push(newIt); } } } } read(); }); } else { setTimeout(read, 50); } }); } var ExcelImportDialog = /** @class */ (function (_super) { __extends(ExcelImportDialog, _super); function ExcelImportDialog(option) { var _this = this; var vjson = vjsonFunc(option); _this = _super.call(this, { model: model, vjson: vjson }) || this; _this.importExcelOption = option; return _this; } ExcelImportDialog.prototype.onLoad = function () { _super.prototype.onLoad.call(this); }; ExcelImportDialog.prototype.fileChange = function (sender) { var _this = this; var file = sender.fileInputEl.dom.files[0]; // const senderScope = lookupScope(sender) var topScope = this.topScope; var rowValidate = this.importExcelOption.rowValidate; if (this.importExcelOption.rowValidate && typeof this.importExcelOption.rowValidate === 'string') { rowValidate = lookupFn(topScope, this.importExcelOption.rowValidate).bind(topScope); } var afterClientValidate = this.importExcelOption.afterClientValidate; if (this.importExcelOption.afterClientValidate && typeof this.importExcelOption.afterClientValidate === 'string') { afterClientValidate = lookupFn(topScope, this.importExcelOption.afterClientValidate).bind(topScope); } var fieldValidate = this.importExcelOption.fieldValidate; if (this.importExcelOption.fieldValidate && typeof this.importExcelOption.fieldValidate === 'string') { fieldValidate = lookupFn(topScope, this.importExcelOption.fieldValidate).bind(topScope); } this.setLoading(true); readExcelWithColumnsSet(topScope, file, this.importExcelOption.columns, this.importExcelOption.dataStartRow, this.importExcelOption.titleRowNumber, rowValidate, afterClientValidate, fieldValidate).then(function (res) { _this.importData = res; _this.refs.dataGrid.setData(res.allData); _this.viewModel.set("dataCount", res.allData.length); _this.refs.errGrid.setData(res.errorMsgData); _this.viewModel.set("errMsgCount", res.errorMsgData.length); }).catch(function (e) { _this.importData = null; _this.refs.dataGrid.setData(); _this.refs.errGrid.setData(); msg(e.toString()); }).finally(function () { _this.setLoading(false); }); }; ExcelImportDialog.prototype.getDataGridRowRecord = function (record, rowIndex, rowParams, store) { if (record.get('__hasError__')) { return "x-grid-record-bg-red"; } }; ExcelImportDialog.prototype.getErrGridRowRecord = function (record, rowIndex, rowParams, store) { return "x-grid-record-bg-red"; }; ExcelImportDialog.prototype.dataGridClick = function (sender, td, cellIndex, record, item, index, e, eOpts) { var _a; var id = record.data.__importID__; var subId = this.refs.dataGrid.headerCt.getGridColumns()[cellIndex].dataIndex; var selectRecord = null; var dataIndex = -1; var rows = (_a = this.refs.errGrid.getStore().getData().items) === null || _a === void 0 ? void 0 : _a.map(function (r) { return r.data; }); for (var i = 0; i < rows.length; i++) { if (rows[i].importID === id) { selectRecord = this.refs.errGrid.getStore().getAt(i); dataIndex = i; } if (rows[i].errorId === id + "_" + subId) { selectRecord = this.refs.errGrid.getStore().getAt(i); dataIndex = i; break; } } if (selectRecord) { this.refs.errGrid.ensureVisible(selectRecord); this.refs.errGrid.selModel.select(dataIndex); // this.refs.errGrid.reload() } }; ExcelImportDialog.prototype.errGridClick = function (sender, record, item, index, e, eOpts) { var _a; var id = record.data.importID; var rows = (_a = this.refs.dataGrid.getStore().getData().items) === null || _a === void 0 ? void 0 : _a.map(function (r) { return r.data; }); var selectRecord = null; var dataIndex = -1; for (var i = 0; i < rows.length; i++) { if (rows[i].__importID__ === id) { selectRecord = this.refs.dataGrid.getStore().getAt(i); dataIndex = i; break; } } if (selectRecord) { this.refs.dataGrid.ensureVisible(selectRecord); this.refs.dataGrid.selModel.select(dataIndex); // this.refs.dataGrid.reload() } }; ExcelImportDialog.prototype.filterData = function (sender, newValue, oldValue, eOpts) { this.viewModel.set("dataType", newValue); if (this.importData) { this.refs.dataGrid.setData(this.importData[newValue]); this.viewModel.set("dataCount", this.importData[newValue].length); } }; ExcelImportDialog.prototype.downloadTemplate = function (sender) { if (this.importExcelOption.dowLoadUrl && this.importExcelOption.dowLoadUrl.length > 0) { window.location.href = this.importExcelOption.dowLoadUrl; return; } var xt = []; _.forEach(this.importExcelOption.columns, function (v) { xt.push(v.header); }); var filename = this.importExcelOption.templateName ? this.importExcelOption.templateName : "模版"; //文件名称 if (filename.endsWith(".xlsx")) { filename = filename.split(".xlsx")[0]; } filename = filename + ".xlsx"; var ws_name = "Sheet1"; //Excel第一个sheet的名称 var wb = XLSX.utils.book_new(), ws = XLSX.utils.aoa_to_sheet([xt]); XLSX.utils.book_append_sheet(wb, ws, ws_name); //将数据添加到工作薄 XLSX.writeFile(wb, filename); //导出Excel }; ExcelImportDialog.prototype.getData = function (sender) { _.each(this.importData.okData, function (item) { delete item.id; delete item.__hasError__; delete item.__importID__; delete item._origin; }); _.each(this.importData.allData, function (item) { delete item.id; delete item.__hasError__; delete item.__importID__; delete item._origin; }); _.each(this.importData.errorData, function (item) { delete item.id; delete item.__hasError__; delete item.__importID__; delete item._origin; }); this.dialogSuccess(this.importData); }; return ExcelImportDialog; }(Scope)); var model = { data: { dataType: "all", errMsgCount: 0, dataCount: 0 } }; var vjsonFunc = function (option) { return { title: option.title || 'excel导入', layout: 'fit', items: [ { layout: 'border', tbar: { xtype: "form", items: [ { xtype: "cols", items: [ { xtype: "filefield", fieldLabel: 'excel文件', buttonText: '请选择excel文件', accept: ".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel", flex: 3, listeners: { change: "scope.fileChange" } }, { xtype: "button", iconCls: "x-fa fa-download", text: "下载模版", listeners: { click: "scope.downloadTemplate" } }, { xtype: 'container', border: false, layout: 'hbox', }, { xtype: "button", iconCls: "x-fa fa-upload", text: option.tQButtonText || "提取数据", listeners: { click: "scope.getData" } } ] }, ] }, items: [ { tbar: { xtype: "toolbar", title: "导入的数据", items: [{ xtype: 'label', html: '导入的数据', }, { xtype: 'radiogroup', items: [ { boxLabel: '所有数据', checked: true, inputValue: 'allData', }, { boxLabel: '正确数据', inputValue: 'okData', }, { boxLabel: '错误数据', inputValue: 'errorData', } ], listeners: { change: 'scope.filterData', }, }, { xtype: "textfield", readOnly: true, fieldLabel: "条目数", bind: "{dataCount}" }] }, xtype: 'yvgrid', reference: 'dataGrid', layout: 'fit', pagination: false, // pageSize: 50, getRowClass: 'scope.getDataGridRowRecord', columns: option.columns, region: 'center', split: true, listeners: { cellclick: "scope.dataGridClick", }, selModel: { // type: 'rowmodel', mode: 'SINGLE', }, }, { tbar: { xtype: "toolbar", items: [ { xtype: 'label', html: '错误信息', }, { xtype: "textfield", readOnly: true, fieldLabel: "条目数", bind: "{errMsgCount}" } ] }, xtype: 'yvgrid', reference: 'errGrid', layout: 'fit', pagination: false, getRowClass: 'scope.getErrGridRowRecord', height: "40%", columns: [ { dataIndex: "errorId", header: "ID", hidden: true }, { dataIndex: "importID", header: "行号", width: 80 }, { dataIndex: "errormessage", header: "错误信息", width: 200 }, { dataIndex: "value", header: "值", width: 120 }, { dataIndex: "header", header: "字段名", width: 120 }, { dataIndex: "dataIndex", header: "字段", width: 120 } ], region: 'south', split: true, listeners: { itemclick: "scope.errGridClick" }, selModel: { // type: 'rowmodel', mode: 'SINGLE', }, }, ], }, ], referenceHolder: true, }; }; function buildReportScope(config, reportId, invokeServerFn, getDictFnName) { var _a = buildVjson(config, invokeServerFn, getDictFnName), model = _a.model, vjson = _a.vjson, report = _a.report; var ret = new ReportScope({ model: model, vjson: vjson }, invokeServerFn); ret.report_id = reportId; ret.report = report; return ret; } function buildVjson(config, invokeServerFn, getDictFnName) { var e_1, _a, e_2, _b; var model = { data: { report_name: config.report_name, query: {}, sum: {}, } }; var json5 = window['YvanUI'].json5; var report = config.report ? json5.parse(config.report) : {}; var conditionRows = []; var sumRows = []; model.data.has_sum = _.size(report.summary) > 0; // query 查询条件 var newRow = false; var currentRow = { xtype: 'cols', items: [], }; conditionRows.push(currentRow); _.forEach(report.query, function (item) { if (newRow) { currentRow = { xtype: 'cols', items: [], }; conditionRows.push(currentRow); } var vj = json5.parse(item.conditionFieldExtend); if (item.conditionFieldXtype) { vj.xtype = item.conditionFieldXtype; if (item.conditionFieldXtype === 'combo') { vj.fix = ['system.' + getDictFnName + '("' + item.conditionFieldDict + '")']; } if (item.conditionFieldXtype === 'datetimefield') { //@ts-ignore _.set(model.data.query, item.conditionFieldBind, moment(window.getServerTime()).format('YYYY-MM-DD HH:mm:ss')); } else if (item.conditionFieldXtype === 'datefield') { //@ts-ignore _.set(model.data.query, item.conditionFieldBind, moment(window.getServerTime()).format('YYYY-MM-DD')); } else { model.data.query[item.conditionFieldBind] = ''; } } else { // 没有组件类型,是个空占位符 vj.border = false; } if (item.conditionFieldBind) { vj.bind = { value: '{query.' + item.conditionFieldBind + '}' }; } if (item.conditionFieldFlex) { vj.flex = item.conditionFieldFlex; } if (item.conditionFieldXtype) { vj.fieldLabel = item.conditionFieldLabel; } if (item.fieldLabel) { vj.fieldLabel = item.fieldLabel; } newRow = item.conditionFieldWrap || false; currentRow.items.push(vj); }); if (currentRow) { currentRow.margin = '10 0 10 0'; } // sum 汇总条件 newRow = true; try { for (var _c = __values(report.summary), _d = _c.next(); !_d.done; _d = _c.next()) { var item = _d.value; if (newRow) { currentRow = { xtype: 'cols', defaultType: 'displayfield', defaults: { labelWidth: 70, }, items: [] }; sumRows.push(currentRow); } var vj = __assign({}, json5.parse(item.sumFieldExtend)); if (item.sumFieldBind) { vj.bind = '{sum.' + item.sumFieldBind + '}'; model.data.sum[item.sumFieldBind] = ''; } else { // 没有组件类型,是个空占位符 vj.border = false; } if (item.sumFieldFlex) { vj.flex = item.sumFieldFlex; } if (item.sumFieldLabel) { vj.fieldLabel = item.sumFieldLabel; } // sumFieldBind: "zs" // sumFieldExtend: "{}" // sumFieldFlex: 1 // sumFieldLabel: "总数" // sumFieldWrap: false newRow = item.sumFieldWrap || false; currentRow.items.push(vj); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_d && !_d.done && (_a = _c.return)) _a.call(_c); } finally { if (e_1) throw e_1.error; } } if (currentRow) { currentRow.margin = '10 0 10 0'; } // column 结果字段 var columns = []; try { for (var _e = __values(report.columns), _f = _e.next(); !_f.done; _f = _e.next()) { var item = _f.value; var vj = __assign({ dataIndex: item.dataIndex, header: item.header, hidden: item.hidden, sortable: item.sortable, filterable: item.filterable }, json5.parse(item.fieldExtend)); if (item.xtype) { if (item.xtype == 'checkbox') { vj.xtype = 'checkcolumn'; vj.disabled = true; } else { vj.xtype = item.xtype; } } if (item.dataType) { vj.dataType = item.dataType; } if (item.align) { vj.align = item.align; } if (item.width) { vj.width = item.width; } if (item.dict) { vj.fix = ['system.' + getDictFnName + '("' + item.dict + '")']; } columns.push(vj); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_f && !_f.done && (_b = _e.return)) _b.call(_e); } finally { if (e_2) throw e_2.error; } } var vjson = { bind: { title: '{report_name}', }, layout: 'fit', referenceHolder: true, items: [ { layout: 'border', border: false, items: [ { region: 'north', border: false, tbar: { xtype: 'toolbar', border: false, items: [ { xtype: 'button', text: '查询', reference: 'btnSearch', iconCls: 'x-fa fa-search', listeners: { click: 'scope.reload', }, }, { xtype: 'button', text: '关闭', iconCls: 'x-fa fa-times', listeners: { click: 'system.closeMe()', }, }, ], }, defaults: { margin: '8 0 0 0' }, items: __spread(conditionRows, sumRows), fix: ['system.enterToClick("btnSearch")'], }, __assign({ region: 'center', xtype: 'yvgrid', reference: 'grid1', border: false, selModel: { selType: 'rowmodel', mode: 'SINGLE', }, autoLoad: false, dataSource: { method: 'invoke', url: '/report/Report@execute', params: { dataSource: report.dataSource, pagination: report.grid.pagination || true, report_id: config.report_id, query: '{query}', }, }, columns: columns }, report.grid), ], }, ], }; return { model: model, vjson: vjson, report: report }; } var ReportScope = /** @class */ (function (_super) { __extends(ReportScope, _super); function ReportScope(_a, invokeServerFn) { var model = _a.model, vjson = _a.vjson; var _this = _super.call(this, { model: model, vjson: vjson }) || this; _this.invokeServerFn = invokeServerFn; return _this; } ReportScope.prototype.onLoad = function () { // this.reload() }; ReportScope.prototype.reload = function () { var _this = this; // http://127.0.0.1:8095/api/com/galaxis/wms/report/Report@executeSum if (this.viewModel.get('has_sum')) { this.invokeServerFn('/report/Report@executeSum', { dataSource: this.report.dataSource, report_id: this.report_id, query: this.viewModel.get('query'), }).then(function (res) { if (!res.success) { showErrorDialog$1(res.msg); } else { window['system'].mergeViewModel(_this.viewModel, 'sum', res.data, false); } }); } this.refs.grid1.reload(); }; return ReportScope; }(Scope)); function initTextfield () { var cc = Ext.form.field.Text.prototype.constructor; var initComponent = Ext.form.field.Text.prototype.initComponent; Ext.form.field.Text.override({ constructor: function (config) { var newConfig = _.defaultsDeep({ // 强制属性 triggers: { clear: { weight: -1, cls: Ext.baseCSSPrefix + 'form-clear-trigger', hidden: true, handler: 'onClearClick', }, } }, baseConfig(config, 'col-item'), config, text); if (config === null || config === void 0 ? void 0 : config.nextFocus) { newConfig.enableKeyEvents = true; } cc.call(this, newConfig); }, /** * 清空所有值 */ onClearClick: function (sender, e) { var me = this; me.setValue(''); }, /** * 尝试获取下一个要获取焦点的控件 */ _raiseNextFocus: function (sender) { var config = sender.config; var scope = lookupScope(sender); if (typeof config.nextFocus === 'function') { config.nextFocus(sender); } else if (typeof config.nextFocus === 'string' && _.size(config.nextFocus) > 0) { if (_.startsWith(config.nextFocus, 'scope.')) { var fn = lookupFn(scope, config.nextFocus); if (typeof fn === 'function') { var nextCtlReference = fn(sender); if (typeof nextCtlReference === 'string' && _.size(nextCtlReference) > 0) { var ctl = scope === null || scope === void 0 ? void 0 : scope.refs[nextCtlReference]; if (ctl) { if (typeof ctl.focus2 === 'function') { ctl.focus2(); } else { ctl.focus(); } } } } } else { var ctl = scope === null || scope === void 0 ? void 0 : scope.refs[config.nextFocus]; if (ctl) { if (typeof ctl.focus2 === 'function') { ctl.focus2(); } else { ctl.focus(); } } } } }, initComponent: function () { /** * 改变必填项之前加星号 */ if (this.config.readOnly !== true && (this.allowBlank === false || this.validateBlank === true)) { // this.beforeLabelTextTpl = [ // '*' // ]; this.afterLabelTextTpl = [ '*' ]; } var me = this; this.on({ change: function (sender, newVal) { var hideTrigger = sender.hideTrigger, disabled = sender.disabled, readOnly = sender.readOnly, hideClear = sender.hideClear; if (hideTrigger || disabled || readOnly || hideClear) { // 禁用、隐藏、只读、隐藏清空状态下,不需要显示清空按钮 return; } var value = newVal; if (value) { me.getTrigger('clear').show(); me.updateLayout(); } else { me.getTrigger('clear').hide(); me.updateLayout(); } }, afterrender: function (sender) { var _this = this; var _a; if ((_a = sender.inputEl) === null || _a === void 0 ? void 0 : _a.dom) { sender.inputEl.dom.setAttribute('spellcheck', "false"); $$1(sender.inputEl.dom).on('click', function (e) { sender.fireEvent('click', _this, e); }); $$1(sender.inputEl.dom).on('keydown', function (e) { var _a, _b, _c, _d; // 表格内编辑器,按上下键时,可以切换到下一行/上一行 进入编辑 if (e.code === "ArrowDown" || e.code === 'ArrowUp') { if (sender.isExpanded === true) { // 弹开下拉框的基础上,不干预上下选择 return; } if (((_a = sender.ownerCt) === null || _a === void 0 ? void 0 : _a.xtype) === 'celleditor') { var grid = sender.ownerCt.up('grid'); var editingPlugin = grid.editingPlugin || grid.ownerGrid.editingPlugin; if (editingPlugin) { var rowIdx = (_c = (_b = editingPlugin === null || editingPlugin === void 0 ? void 0 : editingPlugin.activeEditor) === null || _b === void 0 ? void 0 : _b.context) === null || _c === void 0 ? void 0 : _c.rowIdx; var column = (_d = editingPlugin === null || editingPlugin === void 0 ? void 0 : editingPlugin.activeEditor) === null || _d === void 0 ? void 0 : _d.column; if (typeof rowIdx !== 'undefined' && typeof column !== 'undefined') { // editingPlugin var targetRecord = void 0; if (e.code === 'ArrowDown') { targetRecord = grid.store.data.getAt(rowIdx + 1); } else { targetRecord = grid.store.data.getAt(rowIdx - 1); } if (targetRecord) { grid.setSelection([targetRecord]); editingPlugin.startEdit(targetRecord, column); } e.stopPropagation(); e.preventDefault(); } } } } }); } var config = sender.config; if (config.ff && config.ff > 0) { setTimeout(function () { if (typeof sender.focus2 === 'function') { sender.focus2(); } else { sender.focus(); } }, config.ff); } } }); var config = this.config; if (config === null || config === void 0 ? void 0 : config.nextFocus) { this.on({ keyup: function (sender, e) { if ([10, 13, 20, 40].includes(e.keyCode)) { sender._raiseNextFocus(sender); } } }); } var that = this; this.on({ keyup: function (sender, e, eOpts) { if (![10, 13, 20, 40].includes(e.keyCode)) { return; } that.keydown_fun_item(sender, e, eOpts); } }); initComponent.call(this); }, keydown_fun_item: _.debounce(function (sender, event, eOpts) { var that = sender; if ([10, 13, 20, 40].includes(event.keyCode)) { // 获取读码器读取的内容,最好不要从 viewModel 中取值,而是从 sender.rawValue 中取值 var value = _.trim(sender.rawValue); var r = that.fireEvent('scancode', that, value, event); if (r === 'OK') { // 停止事件的默认处理程序,停止事件的冒泡 // event.stopEvent(); event.preventDefault(); event.stopPropagation(); } } }, 100) }); } function initTbFill () { /** * */ var ct = Ext.toolbar.Fill.prototype.constructor; Ext.toolbar.Fill.override({ constructor: function (config) { var newConfig = _.defaultsDeep({}, config, baseConfig(config, "col-item"), tbfill); ct.call(this, newConfig); } }); } function initTbSeparator () { /** * */ var ct = Ext.toolbar.Separator.prototype.constructor; Ext.toolbar.Separator.override({ constructor: function (config) { var newConfig = _.defaultsDeep({}, config, baseConfig(config, "col-item"), tbseparator); ct.call(this, newConfig); } }); } function initToolbar () { /** * */ var ct = Ext.toolbar.Toolbar.prototype.constructor; Ext.toolbar.Toolbar.override({ constructor: function (config) { var newConfig = _.defaultsDeep({ // 强制性属性 }, baseConfig(config, 'cols-container'), config, toolbar); ct.call(this, newConfig); } }); initTbFill(); initTbSeparator(); } function initSplitter () { var ct = Ext.resizer.Splitter.prototype.constructor; Ext.resizer.Splitter.override({ constructor: function (config) { var newConfig = _.defaultsDeep({}, config, baseConfig(config, "row-item"), splitter); ct.call(this, newConfig); } }); } /** * 通用 dataSource 解析, * Tree/Combo/Grid/PageList ... 都会从这里解析 */ function dataSourceReload(ctl, extraParam, _successCb, successCallback, failCallback) { var config = ctl.config; return new Promise(function (resolve, reject) { if (!config.dataSource) { // 没有设置数据源,直接置空 return Promise.resolve(); } var option = { extraParam: extraParam, _successCb: _successCb, successCallback: function (value) { if (typeof successCallback === "function") { successCallback(value); } else { ctl.setData(value); } ctl.fireEvent('dataLoadComplete', ctl, true, value); ctl.setLoading(false); resolve(value); }, failCallback: function (error) { if (typeof failCallback === "function") { failCallback(error); } ctl.fireEvent('dataLoadComplete', ctl, false); ctl.setLoading(false); reject(error); } }; // 请求前要求确认一下 var isCanceled = false; ctl.fireEvent('dataBeforeLoad', ctl, __assign({ cancel: function () { isCanceled = true; } }, option)); if (!isCanceled) { // 请求没有被取消 // 调用异步接口返回 Promise return _innerReload(ctl, option); } return reject(); }); } function _innerReload(ctl, option) { var config = ctl.config; ctl.setLoading(true); var scope = lookupScope(ctl); var dataSource = config.dataSource; if (typeof dataSource == 'string') { dataSource = lookupFn(scope, config.dataSource); } if (typeof dataSource === 'function') { // @ts-ignore dataSource.call(scope, ctl, option); return; } else if (typeof (dataSource === null || dataSource === void 0 ? void 0 : dataSource.url) === 'string' || typeof (dataSource === null || dataSource === void 0 ? void 0 : dataSource.sqlId) === 'string') { if (!ajax.func) { console.error("没有配置 ajax"); return; } var params_1 = {}; var sortModel = null; var filterModel = null; if (option.extraParam && option.extraParam.filterModel) { filterModel = option.extraParam.filterModel; } if (option.extraParam && option.extraParam.sortModel) { sortModel = option.extraParam.sortModel; } _.forOwn(option.extraParam, function (v, key) { if (key != "filterModel" && key != "sortModel") { if (typeof v === 'function') { params_1[key] = v(); } else { params_1[key] = v; } } }); var ds = dataSource; _.forOwn(ds.params, function (v, key) { if (typeof v === 'function') { params_1[key] = v(); } else { params_1[key] = v; } }); if (typeof (dataSource === null || dataSource === void 0 ? void 0 : dataSource.url) === 'string') { // @ts-ignore ajax.func({ method: dataSource.method, url: ds.url, data: params_1, filterModel: filterModel, sortModel: sortModel, }).then(function (res) { if (res.success) { option.successCallback(res.data); } else { option.failCallback(res.msg); } }).catch(function (e) { option.failCallback(e); }); } else if (typeof (dataSource === null || dataSource === void 0 ? void 0 : dataSource.sqlId) === 'string') { var ds_1 = ctl.dataSource; // @ts-ignore Extend.ajax.func({ url: ds_1.sqlId, data: params_1, db: ds_1.db, method: 'sql', filterModel: filterModel, sortModel: sortModel, }).then(function (res) { if (res.success) { option.successCallback(res.data); } else { option.failCallback(res.msg); } }).catch(function (e) { option.failCallback(e); }).finally(function () { ctl.loading = false; }); return; } else { console.error("非法的 dataSource", ctl.dataSource); debugger; throw new Error("非法的 dataSource"); } } } function initCombo () { var cc = Ext.form.field.ComboBox.prototype.constructor; var _a = Ext.form.field.ComboBox.prototype, initComponent = _a.initComponent, setData = _a.setData; Ext.form.field.ComboBox.override({ constructor: function (config) { var newConfig = _.defaultsDeep({ // 强制性属性 }, baseConfig(config, 'col-item'), config, combo); if (typeof newConfig.store == 'undefined') { if (_.isArray(newConfig.data)) { // ExtJS 无法直接接受数组模式 newConfig.store = { fields: [newConfig.valueField, newConfig.displayField], data: newConfig.data }; delete newConfig.data; } else if (typeof newConfig.data !== 'object') { newConfig.store = { fields: [newConfig.valueField, newConfig.displayField], data: [] }; delete newConfig.data; } } cc.call(this, newConfig); }, setData: function (value) { if (!value) { return; } var config = value.config; if (!this.store) { this.store = new Ext.data.Store({ fields: [config.valueField, config.displayField], data: value }); } else { this.store.getProxy().setData(value); this.store.load(); } }, setLoading: function (value) { if (value) { if (!this.loadMask) { this.loadMask = new Ext.LoadMask(this, { msg: "loading..." }); } } else { if (this.loadMask) { this.loadMask.destroy(); delete this.loadMask; } } }, reload: function () { dataSourceReload(this); }, initComponent: function () { var that = this; var toggle = function (e) { var readOnly = that.readOnly, disabled = that.disabled; if (readOnly || disabled) { return; } if ($(e.target).is('.x-form-trigger')) { return; } // 点击后下拉 if (that.isExpanded) { that.collapse(); } else { that.expand(); that.doQuery(that.allQuery, true); } }; this.on({ afterrender: function (sender) { var config = this.config; if (config.dataSource && config.autoLoad) { dataSourceReload(this); } // 点击后下拉 $(this.el.dom).on('click', toggle.bind(this)); }, focusenter: function (sender, event, opt) { var _a; if (((_a = sender.ownerCt) === null || _a === void 0 ? void 0 : _a.xtype) === 'celleditor') { // 表格内编辑框,获取焦点后自动弹开 toggle.call(this, event); } }, destory: function () { $(this.el.dom).off('click', toggle.bind(this)); }, beforequery: function (context) { var cancel = context.cancel, forceAll = context.forceAll, lastQuery = context.lastQuery, query = context.query, rawQuery = context.rawQuery, combo = context.combo; // console.log('beforequery', query) if (!forceAll && query) { combo.store.clearFilter(); combo.store.filterBy(function (record, id) { var text = record.get(combo.displayField); // 用拼音筛选的方式 return keywordFilter(query, text, id); }); combo.expand(); return false; } combo.store.clearFilter(); combo.expand(); return false; }, }); initComponent.call(this); }, focus2: function () { this.focus(); var that = this; _.defer(function () { if (that.isExpanded) { that.collapse(); } else { that.expand(); that.doQuery(that.allQuery, true); } }); } }); } function initComboGridMulti () { Ext.define('Yvan.LocalComboGrid', { extend: 'Ext.form.field.Picker', // extend: 'Yvan.PickerAlignCenter', xtype: 'combogridmulti', triggerCls: Ext.baseCSSPrefix + 'form-arrow-trigger', config: __assign(__assign({}, comboGridMulti), { store: null, displayField: null, columns: null, selectOnTab: true, maxPickerHeight: 300, minPickerHeight: 100, minPickerWidth: 350, rootVisible: true }), editable: false, initComponent: function () { this.on({ afterrender: function () { var config = this.config; if (config.dataSource && config.autoLoad) { dataSourceReload(this); } }, }); this.superclass.initComponent.apply(this, arguments); }, setStore: function (store) { this.store = store; var me = this; if (me.store) { if (me.picker) { me.picker.setStore(store); if (me.isExpanded) { me.collapse(); delete me.picker; me.expand(); } } this.onLoad(); me.mon(me.store, { scope: me, load: me.onLoad, update: me.onUpdate }); } }, reload: function () { dataSourceReload(this); }, setData: function (value) { var me = this; var config = me.config; if (!value) { return; } if (!this.store) { this.store = new Ext.data.Store({ fields: [config.valueField, config.displayField], data: value }); } else { this.store.getProxy().setData(value); this.store.load(); } this.onLoad(); }, createPicker: function () { var me = this; var picker = new Ext.grid.Panel(__assign(__assign({}, comboGridMultiPicker), { border: false, baseCls: Ext.baseCSSPrefix + 'boundlist', shrinkWrapDock: 2, store: me.store, floating: true, displayField: me.displayField, columns: me.columns, minHeight: me.minPickerHeight, maxHeight: me.maxPickerHeight, minWidth: me.minPickerWidth, manageHeight: false, shadow: false, scrollable: true, listeners: { scope: me, selectionchange: me.onSelectionChange, itemkeydown: me.onPickerKeyDown } })), view = picker.getView(); if (Ext.isIE9 && Ext.isStrict) { view.on({ scope: me, highlightitem: me.repaintPickerView, unhighlightitem: me.repaintPickerView, afteritemexpand: me.repaintPickerView, afteritemcollapse: me.repaintPickerView }); } return picker; }, repaintPickerView: function () { var style = this.picker.getView().getEl().dom.style; style.display = style.display; }, onSelectionChange: function (view, record, node, rowIndex, e) { this.selectItem(view, record); }, onPickerKeyDown: function (treeView, record, item, index, e) { var key = e.getKey(); if (key === e.ENTER || (key === e.TAB && this.selectOnTab)) { this.selectItem(treeView, record); } }, selectItem: function (sender, record) { var me = this; var ids = []; _.forEach(me.picker.getSelection(), function (record) { ids.push(record.get(me.valueField)); }); me.fireEvent('select', me, record); me.setValue(ids.join(me.splitChar)); // me.collapse(); }, onExpand: function () { var me = this; var picker = this.picker; var value = this.value; if (!me.store) { msg('正在初始化数据,请稍后'); me.collapse(); return; } var vs = _.split(value, me.splitChar); var records = me.store.queryRecordsBy(function (r) { return _.findIndex(vs, function (i) { return r.get(me.valueField) === i; }) >= 0; }); picker.setSelection(records); }, setValue: function (value) { var me = this; console.log('setValue', value); me.value = value; if (!me.store || me.store.loading) { // Called while the Store is loading. Ensure it is processed by the onLoad method. return me.mixins.field.setValue.call(me, value); // return me; } var vs = _.split(value, me.splitChar); var displayValues = []; _.forEach(vs, function (v) { var _a; var record = me.store.queryRecordsBy(function (r) { return r.get(me.valueField) === v; }); var dv = (_a = record[0]) === null || _a === void 0 ? void 0 : _a.get(me.displayField); if (dv) { displayValues.push(dv); } else { displayValues.push(v); } }); // set the raw value to the record's display field if a record was found me.setRawValue(displayValues.join(me.splitChar)); return me.mixins.field.setValue.call(me, value); }, getSubmitValue: function () { return this.value; }, getValue: function () { return this.value; }, onLoad: function () { var value = this.value; if (value) { this.setValue(value); } }, onUpdate: function (store, rec, type, modifiedFieldNames) { var display = this.displayField; var me = this; if (type === 'edit' && modifiedFieldNames && Ext.Array.contains(modifiedFieldNames, display) && this.value === rec.getId()) { me.mixins.field.setValue.call(me, this.value); this.setRawValue(rec.get(display)); } } }); } function initSearch () { Ext.define('Yvan.Search', { extend: 'Ext.form.field.Text', alias: 'widget.searchfield', xtype: 'searchfield', constructor: function (config) { var self = this; var newConfig = _.defaultsDeep({ // 强制性属性 triggers: { clear: { weight: 0, cls: Ext.baseCSSPrefix + 'form-clear-trigger', hidden: true, handler: 'onClearClick', }, search: { weight: 1, cls: Ext.baseCSSPrefix + 'form-search-trigger', handler: 'onSearchClick' }, }, listeners: { blur: function (sender, e) { this.revertOnblur(); }, specialkey: function (sender, e) { var _a; var me = this; if (e.getKey() === e.ENTER) { me.onSearchClick(sender, {}, e); return; } invokeMethod((_a = config.listeners) === null || _a === void 0 ? void 0 : _a.afterrender, sender, e); }, afterrender: function (sender, e) { var _a; this.replaceRawInputEvent(); invokeMethod((_a = config.listeners) === null || _a === void 0 ? void 0 : _a.afterrender, sender, e); } }, }, baseConfig(config, 'col-item'), config, search); this.superclass.constructor.call(self, newConfig); }, revertOnblur: function () { this.setRawValue(this.lastValue); }, onSearchClick: function (sender, vv, e) { var me = this; var config = me.config; var widget = config.widget, vjson = config.vjson, lookup = config.lookup; if (e) { e.preventDefault(); e.stopPropagation(); } this.fireEvent('search', sender, e); if (!widget) { return; } showWidget(widget, lookup, sender, me.getRawValue(), vjson); }, replaceRawInputEvent: function () { var me = this; var $dom = $(me.inputEl.dom); $dom.on('input', function (e) { stopEvent(e); // console.log('has input', e) }); $dom.on('keyup', function (e) { if (e.key === "Enter") { me.onSearchClick(me, {}, e); return; } stopEvent(e); }); $dom.on('change', function (e) { stopEvent(e); }); }, onChange: function (newVal, oldVal) { var me = this; var value = newVal; if (value) { me.getTrigger('clear').show(); me.updateLayout(); } else { me.getTrigger('clear').hide(); me.updateLayout(); } }, /** * 清空所有值 */ onClearClick: function (sender, e) { var me = this; var config = me.config; var lookup = config.lookup; me.setValue(''); clearViewModelByLookup(sender, lookup); } }); } function initMultipleSearch () { Ext.define('Yvan.MultipleSearch', { extend: 'Ext.form.field.Text', xtype: 'multiplesearch', bindTargert: '', constructor: function (config) { var _a, _b, _c, _d; var self = this; var newConfig = _.defaultsDeep({ // 强制性属性 triggers: { clear: { weight: 0, cls: Ext.baseCSSPrefix + 'form-clear-trigger', hidden: true, handler: 'onClearClick', } }, transformRawValue: function (o) { return o; }, listeners: { specialkey: function (sender, e) { var me = this; if (e.getKey() === e.ENTER) { me.fireEvent('search', me, e); } }, afterrender: function (sender, e) { var _a; this.replaceRawInputEvent(); invokeMethod((_a = config.listeners) === null || _a === void 0 ? void 0 : _a.afterrender, sender, e); } }, }, baseConfig(config, 'col-item'), config, search); this.superclass.constructor.call(self, newConfig); var vv = (_d = (((_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.bind) === null || _b === void 0 ? void 0 : _b.value) || ((_c = this.config) === null || _c === void 0 ? void 0 : _c.bind))) !== null && _d !== void 0 ? _d : ''; vv = _.replace(vv, "{", ""); vv = _.replace(vv, "}", ""); this.bindTargert = vv; this.bindTargert = _.trim(this.bindTargert); }, setBindValue: function (arrValue) { if (this.bindTargert) { this.lookupViewModel().yvanScope.viewModel.set(this.bindTargert, arrValue); } }, replaceRawInputEvent: function () { var me = this; var $dom = $(me.inputEl.dom); $dom.on('input', function (e) { var _a, _b, _c, _d, _e, _f; if ((_b = (_a = e.currentTarget) === null || _a === void 0 ? void 0 : _a.value) === null || _b === void 0 ? void 0 : _b.endsWith(" ")) { var a = _.trimEnd((_c = e.currentTarget) === null || _c === void 0 ? void 0 : _c.value); if (!a.endsWith(",") && a.length > 0) { e.currentTarget.value = a + ","; } else { e.currentTarget.value = a; } } e.currentTarget.value = (_d = e.currentTarget.value) === null || _d === void 0 ? void 0 : _d.replaceAll(",,", ","); var arr = (_f = (_e = e.currentTarget) === null || _e === void 0 ? void 0 : _e.value) === null || _f === void 0 ? void 0 : _f.split(","); _.remove(arr, function (it) { return !it; }); me.setBindValue(arr); stopEvent(e); }); $dom.on('keyup', function (e) { me.fireEvent('keyup', me, e); // invokeMethod(me.config.listeners?.keyup, me, e) stopEvent(e); }); $dom.on('keydown', function (e) { me.fireEvent('keydown', me, e); // invokeMethod(me.config.listeners?.keydown, me, e) //stopEvent(e) }); $dom.on('change', function (e) { stopEvent(e); }); $dom.on('paste', function (e) { var _a; // @ts-ignore var clipdata = e.originalEvent.clipboardData || window.clipboardData; var text = clipdata.getData("text/plain"); var spliter = ','; text = text.replaceAll("\r", ""); text = text.replaceAll("\n", spliter); text = ((_a = e.currentTarget) === null || _a === void 0 ? void 0 : _a.value) + "," + text; var arr = text.split(spliter); if (arr && Array.isArray(arr)) { for (var i = 0; i < arr.length; i++) { arr[i] = _.trim(arr[i]); } } _.remove(arr, function (it) { return !it; }); me.setBindValue(arr); stopEvent(e); }); }, onChange: function (newVal, oldVal) { var me = this; var value = newVal; if (value) { me.getTrigger('clear').show(); me.updateLayout(); } else { me.getTrigger('clear').hide(); me.updateLayout(); } }, /** * 清空所有值 */ onClearClick: function (sender, e) { var me = this; var config = me.config; var lookup = config.lookup; me.setValue(''); clearViewModelByLookup(sender, lookup); } }); } function initDate () { var cc = Ext.form.field.Date.prototype.constructor; var _a = Ext.form.field.Date.prototype, initComponent = _a.initComponent, getValue = _a.getValue, valueToRaw = _a.valueToRaw; Ext.form.field.Date.override({ format: 'Y-m-d', altFormats: 'Y-m-d', constructor: function (config) { var newConfig = _.defaultsDeep({ // 强制属性 }, baseConfig(config, 'col-item'), config, date); cc.call(this, newConfig); }, getValue: function () { var ov = getValue.call(this); var nv = Ext.util.Format.date(ov, 'Y-m-d'); // console.log('cc:', nv, ov) return nv; }, // focus2() { // const that = this // if (that.isExpanded) { // that.collapse() // // } else { // that.expand(); // } // _.defer(() => { // that.focus() // }) // }, initComponent: function () { this.on({ afterrender: function () { var config = this.config; // 日期框,不要默认弹出 // $(this.el.dom).on('click', toggle.bind(this)) }, destory: function () { // 日期框,不要默认弹出 // $(this.el.dom).off('click', toggle.bind(this)) }, change: { fn: function (sender) { if (sender.format === 'Y-m-d') { // 年月日格式 var value = sender.getRawValue(); if (/^\d{8}$/.test(value)) { // 8位数字,自动转换为 YYYY-MM-DD var newValue = [ value.substr(0, 4), value.substr(4, 2), value.substr(6, 2) ].join('-'); sender.setValue(newValue); } } }, } // focus: { // // 获得焦点后自动下拉 // fn(sender) { // sender.expand(); // this.doQuery(this.allQuery, true); // }, // }, }); initComponent.call(this); }, createInitialDate: function (value) { var minValue = this.minValue, maxValue = this.maxValue; value = value || syncDate(new Date()); if (minValue && minValue > value) { value = minValue; } else if (maxValue && maxValue < value) { value = maxValue; } return value; }, }); } function initDateTimePicker () { Ext.define('Yvan.DateTimePicker', { extend: 'Ext.picker.Date', alias: 'datetimepicker', alternateClassName: 'Ext.DateTimePicker', renderTpl: [ '', { firstInitial: function (value) { return Ext.picker.Date.prototype.getDayInitial(value); }, isEndOfWeek: function (value) { // convert from 1 based index to 0 based // by decrementing value once. value--; // eslint-disable-next-line vars-on-top var end = value % 7 === 0 && value !== 0; return end ? '' : ''; }, renderTodayBtn: function (values, out) { Ext.DomHelper.generateMarkup(values.$comp.todayBtn.getRenderTree(), out); }, renderMonthBtn: function (values, out) { Ext.DomHelper.generateMarkup(values.$comp.monthBtn.getRenderTree(), out); } } ], beforeRender: function () { var me = this, today = Ext.Date.format(syncDate(new Date()), me.format); this.superclass.beforeRender.call(this); function handleInput(extHandle, $input) { var $dom = $(extHandle.el.dom); // const $up = $dom.find('.x-form-spinner-up') // const $down = $dom.find('.x-form-spinner-down') // debugger // $up.on('mousedown', () => { // debugger // }); // $up.on('click', () => { // debugger // }); extHandle.on('click', function (sender) { var hideBak = me.hide; me.hide = Ext.emptyFn; extHandle.focus(); me.hide = hideBak; }); var changeValue = function (delta) { if (_.trim(extHandle.getValue()) === '') { extHandle.setValue(extHandle.minValue); } else { var v = parseInt('' + extHandle.getValue()); if (v + delta > extHandle.maxValue) { extHandle.setValue(extHandle.minValue); } else if (v + delta < extHandle.minValue) { extHandle.setValue(extHandle.maxValue); } else { extHandle.setValue(v + delta); } } }; $input.on('mousewheel', function (e) { e.stopPropagation(); var event = e.originalEvent; var eventDelta = event.wheelDelta || -event.deltaY + 40; // if (event.wheelDelta) { // delta = event.wheelDelta / 120; // } else if (event.detail) { // delta = -event.detail / 3; // } var zoomSize = Math.ceil(eventDelta / 120); changeValue(zoomSize); // console.log('delta', delta) // $input.focus() }); } me.input1 = Ext.create('Ext.form.field.Number', { minValue: 0, maxValue: 23, flex: 1, enableKeyEvents: true, fieldLabel: '时', labelWidth: 20, hideLabel: true, spinDownEnabled: false, spinUpEnabled: false, style: { marginLeft: '5px', }, listeners: { afterrender: function (sender) { var $input = $(sender.inputEl.dom); handleInput(me.input1, $input); }, change: function (sender, e) { if (me.getValue()) { me.value.setHours(sender.getValue()); } }, } }); me.input2 = Ext.create('Ext.form.field.Number', { minValue: 0, maxValue: 59, flex: 1, enableKeyEvents: true, fieldLabel: ' ', hideLabel: false, labelWidth: 8, spinDownEnabled: false, spinUpEnabled: false, listeners: { afterrender: function (sender) { var $input = $(sender.inputEl.dom); handleInput(me.input2, $input); }, change: function (sender, e) { if (me.getValue()) { me.value.setMinutes(sender.getValue()); } }, } }); me.input3 = Ext.create('Ext.form.field.Number', { minValue: 0, maxValue: 59, flex: 1, enableKeyEvents: true, fieldLabel: ' ', hideLabel: false, labelWidth: 8, spinDownEnabled: false, spinUpEnabled: false, style: { marginRight: '5px', }, listeners: { afterrender: function (sender) { var $input = $(sender.inputEl.dom); handleInput(me.input3, $input); }, change: function (sender, e) { if (me.getValue()) { me.value.setSeconds(sender.getValue()); } }, } }); me.confirmBtn = new Ext.button.Button({ text: '确认', handler: me.confirmClick, scope: me }); me.tdBtn = new Ext.button.Button({ text: '现在', handler: me.selectToday, scope: me }); me.todayBtn = Ext.create('Ext.container.Container', { layout: 'anchor', border: false, defaults: { border: false, anchor: '100%', margin: '0 0 5 0', }, items: [ { layout: 'hbox', items: [ me.input1, me.input2, me.input3, ] }, { layout: 'hbox', items: [ me.confirmBtn, me.tdBtn, ] } ] }); }, // finishRenderChildren() { // var me = this; // // this.superclass.finishRenderChildren.call(this); // //* // me.input1.finishRender(); // me.input2.finishRender(); // me.input3.finishRender(); // // // me.tdBtn.finishRender(); // me.confirmBtn.finishRender(); // }, setValue: function (value) { //this.value = Ext.Date.clearTime(value, true); this.value = value; this.input1.setValue(this.value.getHours()); this.input2.setValue(this.value.getMinutes()); this.input3.setValue(this.value.getSeconds()); return this.update(this.value); }, selectDate: function (value) { if (this.showTime) { value.setHours(this.input1.getValue()); value.setMinutes(this.input2.getValue()); value.setSeconds(this.input3.getValue()); } this.value = value; return this.update(this.value); }, setDisabledStatus: function (disabled) { var me = this; debugger; // me.callParent(); if (me.showTime) { me.confirmBtn.setDisabled(disabled); } if (me.isShowFooter()) { me.footerContainer.setDisabled(disabled); } }, handleDateClick: function (e, t) { var me = this, handler = me.handler; // e.stopEvent(); if (!me.disabled && t.dateValue && !Ext.fly(t.parentNode).hasCls(me.disabledCellCls)) { me.doCancelFocus = me.focusOnSelect === false; me.selectDate(new Date(t.dateValue)); delete me.doCancelFocus; /* 有时间输入时单击事件不退出选择,只移动光标 */ if (me.showTime) { return; } me.fireEvent('select', me, me.value); if (handler) { handler.call(me.scope || me, me, me.value); } me.onSelect(); } }, selectToday: function () { var me = this, btn = me.todayBtn, handler = me.handler; if (btn && !btn.disabled) { me.value = syncDate(new Date()); me.update(me.value); me.fireEvent('select', me, me.value); if (handler) { handler.call(me.scope || me, me, me.value); } me.onSelect(); me.hide(); } return me; }, confirmClick: function () { var me = this, btn = me.confirmBtn, handler = me.handler; if (btn && !btn.disabled) { me.fireEvent('select', me, me.value); if (handler) { handler.call(me.scope || me, me, me.value); } me.onSelect(); me.hide(); } return me; }, selectedUpdate: function (date) { var me = this, //t = date.getTime(), t = Ext.Date.clearTime(date, true).getTime(), cells = me.cells, cls = me.selectedCls, cellItems = cells.elements, c, cLen = cellItems.length, cell; cells.removeCls(cls); for (c = 0; c < cLen; c++) { cell = Ext.fly(cellItems[c]); if (cell.dom.firstChild.dateValue == t) { me.fireEvent('highlightitem', me, cell); cell.addCls(cls); if (me.isVisible() && !me.doCancelFocus) { Ext.fly(cell.dom.firstChild).focus(50); } break; } } }, // private, inherit docs beforeDestroy: function () { var me = this; if (me.rendered) { Ext.destroy(me.input1, me.input2, me.input3, me.confirmBtn, me.tdBtn, me.todayBtn); } me.superclass.beforeDestroy.call(this); } }); } function initDateTime () { Ext.define('Yvan.DateTimeField', { extend: 'Ext.form.field.Date', xtype: 'datetimefield', alternateClassName: ['Ext.form.DateTimeField', 'Ext.form.DateTime'], triggerCls: Ext.baseCSSPrefix + 'form-arrow-trigger', showTime: true, format: "Y-m-d H:i:s", constructor: function (config) { var newConfig = _.defaultsDeep({ // 强制属性 }, baseConfig(config, 'col-item'), config, date); this.superclass.constructor.call(this, newConfig); }, initComponent: function () { this.superclass.initComponent.call(this); var setInitValue = function () { var value = this.getRawValue(); if (!value) { // 没填内容的时候,自动设置当前时间 this.setValue(Ext.util.Format.date(syncDate(new Date()), this.format)); } }; this.on({ afterrender: function () { var config = this.config; // 日期框,不要默认弹出 $(this.el.dom).on('click', setInitValue.bind(this)); }, destory: function () { // 日期框,不要默认弹出 $(this.el.dom).off('click', setInitValue.bind(this)); }, change: { fn: function (sender) { if (sender.format === "Y-m-d H:i:s") { // 年月日格式 var value = sender.getRawValue(); if (/^\d{14}$/.test(value)) { // 8位数字,自动转换为 YYYY-MM-DD var newValue = [ value.substr(0, 4), '-', value.substr(4, 2), '-', value.substr(6, 2), ' ', value.substr(8, 2), ':', value.substr(10, 2), ':', value.substr(12, 2) ].join(''); sender.setValue(newValue); } } }, } }); }, getValue: function () { var ov = this.getRawValue(); //this.superclass.getValue.call(this) var nv = Ext.util.Format.date(ov, 'Y-m-d H:i:s'); // console.log('cc:', nv, ov) return nv; }, onExpand: function () { var strValue = this.getValue(); var value; if (/^\d\d\d\d-\d\d-\d\d\s\d\d:\d\d:\d\d$/.test(strValue)) { value = new Date(parseInt(strValue.substr(0, 4)), parseInt(strValue.substr(5, 2)) - 1, parseInt(strValue.substr(8, 2)), parseInt(strValue.substr(11, 2)), parseInt(strValue.substr(14, 2)), parseInt(strValue.substr(17, 2))); } else if (/^\d\d\d\d-\d\d-\d\d$/.test(strValue)) { value = new Date(parseInt(strValue.substr(0, 4)), parseInt(strValue.substr(5, 2)) - 1, parseInt(strValue.substr(8, 2))); } else { value = syncDate(new Date()); } this.picker.setValue(value); }, createPicker: function () { var me = this, format = Ext.String.format; //@ts-ignore return new Yvan.DateTimePicker({ pickerField: me, ownerCt: me.ownerCt, renderTo: document.body, floating: true, hidden: true, focusOnShow: true, minDate: me.minValue, maxDate: me.maxValue, disabledDatesRE: me.disabledDatesRE, disabledDatesText: me.disabledDatesText, disabledDays: me.disabledDays, disabledDaysText: me.disabledDaysText, format: me.format, showToday: me.showToday, showTime: me.showTime, startDay: me.startDay, minText: format(me.minText, me.formatDate(me.minValue)), maxText: format(me.maxText, me.formatDate(me.maxValue)), listeners: { scope: me, select: me.onSelect }, keyNavConfig: { esc: function () { me.collapse(); } } }); }, }); } function initNumber () { var cc = Ext.form.field.Number.prototype.constructor; var initComponent = Ext.form.field.Number.prototype.initComponent; Ext.form.field.Number.override({ constructor: function (config) { var newConfig = _.defaultsDeep({ // 强制属性 }, baseConfig(config, 'col-item'), config, numberfield); cc.call(this, newConfig); }, initComponent: function () { this.on({ afterrender: function (sender) { var _this = this; var _a; if ((_a = sender.inputEl) === null || _a === void 0 ? void 0 : _a.dom) { sender.inputEl.dom.setAttribute('spellcheck', "false"); $$1(sender.inputEl.dom).on('click', function (e) { sender.fireEvent('click', _this, e); }); } } }); initComponent.call(this); }, }); } function initCheckbox () { var cc = Ext.form.field.Checkbox.prototype.constructor; var _a = Ext.form.field.Checkbox.prototype, initComponent = _a.initComponent, getValue = _a.getValue, setValue = _a.setValue; Ext.form.field.Checkbox.override({ constructor: function (config) { var newConfig = _.defaultsDeep({ // 强制属性 }, baseConfig(config, 'col-item'), config, checkbox); cc.call(this, newConfig); }, getValue: function () { var _a = this, checkedValue = _a.checkedValue, uncheckedValue = _a.uncheckedValue; var ov = getValue.call(this); // const ov = this.getRawValue() return (ov ? checkedValue : uncheckedValue); }, setValue: function (nv) { var _a = this, checkedValue = _a.checkedValue, uncheckedValue = _a.uncheckedValue; var value; if (nv === checkedValue) { value = true; } else if (nv === uncheckedValue) { value = false; } else { value = !!nv; } // me.setRawValue(value) // me.checked = value // return me.mixins.field.setValue.call(me, value); setValue.call(this, value); }, updateCheckedCls: function (checked) { var me = this; var _a = this, uncheckedValue = _a.uncheckedValue, checkedValue = _a.checkedValue; checked = checked != null ? checked : me.getValue(); if (checked === uncheckedValue) { checked = false; } else if (checked === checkedValue) { checked = true; } me[checked ? 'addCls' : 'removeCls'](me.checkedCls); }, initComponent: function () { initComponent.call(this); }, }); } function initCheckboxGroup () { var cc = Ext.form.CheckboxGroup.prototype.constructor; var initComponent = Ext.form.CheckboxGroup.prototype.initComponent; Ext.form.CheckboxGroup.override({ constructor: function (config) { var newConfig = _.defaultsDeep({ // 强制属性 }, baseConfig(config, 'col-item'), config, checkboxgroup); cc.call(this, newConfig); }, initComponent: function () { initComponent.call(this); }, }); } function initRadio () { var cc = Ext.form.field.Radio.prototype.constructor; var initComponent = Ext.form.field.Radio.prototype.initComponent; Ext.form.field.Radio.override({ constructor: function (config) { var newConfig = _.defaultsDeep({ // 强制属性 }, baseConfig(config, 'col-item'), config, radio); cc.call(this, newConfig); }, initComponent: function () { initComponent.call(this); }, }); } function initRadioGroup () { var cc = Ext.form.RadioGroup.prototype.constructor; var initComponent = Ext.form.RadioGroup.prototype.initComponent; Ext.form.RadioGroup.override({ constructor: function (config) { var newConfig = _.defaultsDeep({ // 强制属性 }, baseConfig(config, 'col-item'), config, radiogroup); cc.call(this, newConfig); }, initComponent: function () { initComponent.call(this); }, }); } function initFieldset () { /** * */ var ct = Ext.form.FieldSet.prototype.constructor; Ext.form.FieldSet.override({ constructor: function (config) { var newConfig = _.defaultsDeep({}, config, baseConfig(config, "rows-container"), fieldSet); ct.call(this, newConfig); } }); } function initCombotree () { Ext.define('Yvan.ComboTree', { extend: 'Ext.form.field.Picker', xtype: 'combotree', triggerCls: Ext.baseCSSPrefix + 'form-arrow-trigger', config: { store: null, displayField: null, columns: null, selectOnTab: true, maxPickerHeight: 300, minPickerHeight: 100, minPickerWidth: 350, rootVisible: true, }, editable: false, setStore: function (store) { this.store = store; var me = this; if (me.store) { if (me.picker) { me.picker.setStore(store); if (me.isExpanded) { me.collapse(); delete me.picker; me.expand(); } } this.onLoad(); me.mon(me.store, { scope: me, load: me.onLoad, update: me.onUpdate }); } }, createPicker: function () { var me = this; var picker = new Ext.tree.Panel({ border: false, baseCls: Ext.baseCSSPrefix + 'boundlist', shrinkWrapDock: 2, store: me.store, floating: true, rootVisible: me.rootVisible, displayField: me.displayField, columns: me.columns, minHeight: me.minPickerHeight, maxHeight: me.maxPickerHeight, minWidth: me.minPickerWidth, manageHeight: false, shadow: false, scrollable: true, // modal: true, // constrain: true, // constrainTo: topScope._handle.el.dom, // renderTo: topScope._handle.el.dom, // alignTarget: topScope._handle, listeners: { scope: me, itemclick: me.onItemClick, itemkeydown: me.onPickerKeyDown } }), view = picker.getView(); if (Ext.isIE9 && Ext.isStrict) { view.on({ scope: me, highlightitem: me.repaintPickerView, unhighlightitem: me.repaintPickerView, afteritemexpand: me.repaintPickerView, afteritemcollapse: me.repaintPickerView }); } return picker; }, repaintPickerView: function () { var style = this.picker.getView().getEl().dom.style; style.display = style.display; }, onItemClick: function (view, record, node, rowIndex, e) { this.selectItem(view, record); }, onPickerKeyDown: function (treeView, record, item, index, e) { var key = e.getKey(); if (key === e.ENTER || (key === e.TAB && this.selectOnTab)) { this.selectItem(treeView, record); } }, selectItem: function (sender, record) { var me = this; me.setValue(record.getId()); me.fireEvent('select', me, record); me.collapse(); }, onExpand: function () { var picker = this.picker; var store = picker.store; var value = this.value; var node; if (value) { node = store.getNodeById(value); } if (!node) { node = store.getRoot(); } picker.ensureVisible(node, { select: true, focus: true }); }, setValue: function (value) { var me = this; console.log('setValue', value); me.value = value; if (!me.store || me.store.loading) { // Called while the Store is loading. Ensure it is processed by the onLoad method. return me.mixins.field.setValue.call(me, value); // return me; } var record = value ? me.store.getNodeById(value) : me.store.getRoot(); if (value === undefined) { record = me.store.getRoot(); console.log('setValue', record.getId()); me.value = record.getId(); return me.mixins.field.setValue.call(me, value); } else { record = me.store.getNodeById(value); } // set the raw value to the record's display field if a record was found me.setRawValue(record ? record.get(me.displayField) : ''); return me.mixins.field.setValue.call(me, value); }, getSubmitValue: function () { return this.value; }, getValue: function () { return this.value; }, onLoad: function () { var value = this.value; if (value) { this.setValue(value); } }, onUpdate: function (store, rec, type, modifiedFieldNames) { var display = this.displayField; var me = this; if (type === 'edit' && modifiedFieldNames && Ext.Array.contains(modifiedFieldNames, display) && this.value === rec.getId()) { me.mixins.field.setValue.call(me, this.value); this.setRawValue(rec.get(display)); } } }); } function initPickerPlus () { Ext.define('Yvan.PickerAlignCenter', { extend: 'Ext.form.field.Picker', /** * Performs the alignment on the picker using the class defaults * @private */ doAlign: function () { // 不要挪动就好 }, }); } function initCombogrid () { Ext.define('Yvan.ComboGrid', { extend: 'Ext.form.field.Picker', // extend: 'Yvan.PickerAlignCenter', xtype: 'combogrid', triggerCls: Ext.baseCSSPrefix + 'form-search-trigger', triggers: { clear: { weight: 0, cls: Ext.baseCSSPrefix + 'form-clear-trigger', hidden: true, handler: 'onClearClick', }, }, config: __assign({}, comboGrid), editable: true, _superBlur: false, allowCustomInput: false, pressEnterPopup: true, initComponent: function () { var that = this; if (window["IS_DESIGN_MODE"]) { this.superclass.initComponent.call(this, arguments); return; } this.on({ blur: function (sender, e) { if (this._superBlur) { // 挂起时不恢复内容 return; } // 离开焦点时,恢复原来的值 sender.setRawValue(sender.value); }, afterrender: function (sender) { var $dom = $(sender.inputEl.dom); that.scope = lookupScope(sender); if (sender.column) { // 列模式,拦截 keydown $dom.on('keydown', function (e) { if (isChartEvent(e) && !that.tryEnable()) { // 没有达成 editEnable 条件,不用响应 stopEvent(e); return; } if (that.pressEnterPopup !== false && e.key === 'Enter') { stopEvent(e); that.onTriggerClick(that, that.getPickerTrigger(), e); return; } }); } else { // 常规模式,拦截 keyup $dom.on('keyup', function (e) { if (e.key === 'Escape' || e.key === 'ArrowRight' || e.key === 'ArrowLeft') { return; } if (isChartEvent(e) && !that.tryEnable()) { // 没有达成 editEnable 条件,不用响应 stopEvent(e); return; } if (that.pressEnterPopup !== false && e.key === 'Enter') { stopEvent(e); that.onTriggerClick(that, that.getPickerTrigger(), e); return; } if (!that.allowCustomInput) { // 取消 keyup 事件,让 ext 不要吧当前输入的值记录到 value 中 stopEvent(e); } }); $dom.on('change', function (e) { // 这里注释掉,是因为 当鼠标点击触发弹出后,会导致取"e.target.value"值无效 // if (that.isExpanded) { // that.filterChange(that, e.target.value) // } stopEvent(e); }); } $dom.on('input', function (e) { stopEvent(e); }); }, }); this.superclass.initComponent.apply(this, arguments); }, createPicker: function () { var me = this; var cfg = { layout: 'fit', border: 5, style: { borderColor: 'black', borderWidth: '5px', borderStyle: 'solid' }, shadow: 'side', shadowOffset: 100, baseCls: Ext.baseCSSPrefix + 'boundlist', shrinkWrapDock: 2, floating: true, width: me.pickerWidth, height: me.pickerHeight, minWidth: me.pickerWidth, minHeight: me.pickerHeight, maxWidth: me.pickerWidth, maxHeight: me.pickerHeight, items: [ __assign(__assign(__assign({}, comboGridPicker), me.grid), { tbar: { xtype: 'toolbar', items: [ { xtype: 'textfield', fieldLabel: '筛选' }, { xtype: 'button', text: '查询', iconCls: 'x-fa fa-search', cssType: 'primary', listeners: { click: function () { me.reloadGrid(); } } }, ] }, autoLoad: false, listeners: { afterrender: function (grid) { me.grid = grid; grid.focus(); grid.on({ rowdblclick: function (sender, row) { me.selectItem(row); }, dataLoadComplete: function (sender) { _.defer(function () { me.setFocus(); }); }, keydown: function (sender, e) { if (me.column) { // 列模式,拦截 keydown me.processKey(e); } }, keyup: function (sender, e) { if (!me.column) { // 常规模式,拦截 keyup me.processKey(e); } } }); }, } }) ] }; // @ts-ignore var picker = new Ext.container.Container(cfg); return picker; }, setFocus: function () { if (this.grid.store.getCount() > 0) { this.grid.focusRow(0); } }, processKey: function (e) { if (this.pressEnterPopup !== false && e.key === 'Enter') { this.selectItem(this.grid.selection); stopEvent(e); } else if (e.key === 'Escape') { this.collapse(); } }, repaintPickerView: function () { var style = this.picker.getView().getEl().dom.style; style.display = style.display; }, onItemClick: function (view, record, node, rowIndex, e) { this.selectItem(record); }, onPickerKeyDown: function (treeView, record, item, index, e) { var key = e.getKey(); if ((this.pressEnterPopup !== false && key === e.ENTER) || (key === e.TAB && this.selectOnTab)) { this.selectItem(record); } }, filterChange: _.debounce(function (sender, value) { sender.onExpand(); }, 1000), selectItem: function (record) { var me = this; var lookup = this.lookup; var scope = lookupScope(this); me.fireEvent('select', me, record); if (record.isModel) { record = record.data; } tryWriteObject(lookup, record, function (path, value) { me._lookupSet(path, value); }); // lookup // fromColumn: 'toTarget' // fromColumn: 'toTarget' // fromColumn: 'toTarget' _.forOwn(lookup, function (toTarget, fromColumn) { var value = _.get(record, fromColumn); me._lookupSet(toTarget, value); }); // 选定之后不能做清空 // const {lookupClearOnChange} = me // if (_.isArray(lookupClearOnChange)) { // _.each(lookupClearOnChange, item => { // me._lookupSet(item, '') // }) // } me.collapse(); // 触发 _raiseNextFocus me._raiseNextFocus(me); }, onExpand: function () { // 展开时,根据 lookup 带入查询参数 var expressData = this.getExpressData(); var txtField = this.grid.down('toolbar').down('textfield'); txtField.setValue(expressData.queryValue); this.reloadGrid(); }, reloadGrid: function () { // 展开时,根据 lookup 带入查询参数 var expressData = this.getExpressData(); var reloadParam = calcObjectFlat(expressData, this.param) || {}; var txtField = this.grid.down('toolbar').down('textfield'); // 每个 combogrid 默认带上 __queryValue 属性 reloadParam["__queryValue"] = txtField.getValue(); this.grid.reload(reloadParam); }, onTriggerClick: function (sender) { var _a = this, isExpanded = _a.isExpanded, readOnly = _a.readOnly, disabled = _a.disabled, grid = _a.grid; if (!grid) { msg('正在初始化,请稍后'); return; } if (!this.tryEnable()) { // 没有达成 editEnable 条件,不用弹出 return; } if (isExpanded || readOnly || disabled) { // 已弹出、只读、禁用状态下,不允许弹出 return; } this._superBlur = true; this.superclass.onTriggerClick.apply(this, arguments); this._superBlur = false; }, onCollapse: function () { // 每次收回时,删除下拉组件 // delete this.picker }, /** * 本方法只会从 API 或外部调用,键盘输入的内容不会记录在内 */ setValue: function (value) { var me = this; // 设值用户看到的表面内容 this.setRawValue(value); // 设值 setValue 调用链,正常触发 change 事件等 return me.mixins.field.setValue.call(me, value); }, _lookupSet: function (path, value) { var me = this; path = tryVarSimple(path); if (me.column) { // 判断写入目标,是否与自己绑定的属性相等 if (path === 'queryValue' || me.column.dataIndex === path) { me.setValue(value); } // 列模式下,写当前编辑行 var parentRecord = me._lookupEditorRecord(); if (parentRecord) { // Ext.data.Record / Ext.data.Model parentRecord.set(path, value); } else { debugger; } } else { // 常规模式下,写 viewModel me.scope.viewModel.set(path, value); } }, _lookupGrid: function () { return this.column.up('grid'); }, _lookupEditorRecord: function () { var _a, _b, _c, _d; // parentGrid.getSelectionModel().getLastSelected() var grid = this._lookupGrid(); var editingPlugin = (_a = grid.editingPlugin) !== null && _a !== void 0 ? _a : (_b = grid.ownerGrid) === null || _b === void 0 ? void 0 : _b.editingPlugin; if (!editingPlugin) { return grid.getSelectionModel().getLastSelected(); } var rowIdx = (_d = (_c = editingPlugin.activeEditor) === null || _c === void 0 ? void 0 : _c.context) === null || _d === void 0 ? void 0 : _d.rowIdx; if (_.isNumber(rowIdx)) { return grid.store.getAt(rowIdx); } else { return grid.getSelectionModel().getLastSelected(); } }, onChange: function (newVal, oldVal) { var me = this; var value = newVal; var hideTrigger = me.hideTrigger, disabled = me.disabled, readOnly = me.readOnly, hideClear = me.hideClear; if (hideTrigger || disabled || readOnly || hideClear) { // 禁用、隐藏、只读、隐藏清空状态下,不需要显示清空按钮 return; } if (value) { me.getTrigger('clear').show(); me.updateLayout(); } else { me.getTrigger('clear').hide(); me.updateLayout(); } }, /** * 得到能用于 express 表达式计算的上下文数据 */ getExpressData: function () { var queryValue = this.getRawValue(); if (this.column) { // 列模式, 准备好判断 editEnable 表达式用的数据 var parentRecord = this._lookupEditorRecord(); if (!parentRecord) { debugger; } return __assign(__assign(__assign({}, this.scope.viewModel.data), parentRecord.data), { queryValue: queryValue }); } else { // 编辑模式,准备好判断用的数据 return __assign(__assign({}, this.scope.viewModel.data), { queryValue: queryValue }); } }, tryEnable: function () { return tryEnable(this.getExpressData(), this.editEnable); }, /** * 清空所有值 */ onClearClick: function (sender, e) { var me = this; var lookup = me.lookup, lookupClearOnChange = me.lookupClearOnChange; me.fireEvent('clear', sender, e); me.setValue(''); _.forOwn(lookup, function (toTarget, fromColumn) { me._lookupSet(toTarget, ''); }); _.each(lookupClearOnChange, function (item) { me._lookupSet(item, ''); }); } }); } function initRows () { Ext.define('Yvan.Rows', { extend: 'Ext.container.Container', xtype: 'rows', constructor: function (config) { var self = this; var newConfig = _.defaultsDeep({ // 强制性属性 layout: 'anchor', border: false, defaults: { border: false, anchor: '100%', margin: '0 0 5 0', }, }, baseConfig(config, 'rows-container'), config, rows); this.superclass.constructor.call(self, newConfig); }, }); } function initForm () { var ct = Ext.form.Panel.prototype.constructor; Ext.form.Panel.override({ constructor: function (config) { var newConfig = _.defaultsDeep({}, config, baseConfig(config, "cols-container"), form); ct.call(this, newConfig); } }); } function initCols () { Ext.define('Yvan.Cols', { extend: 'Ext.container.Container', xtype: 'cols', constructor: function (config) { var self = this; var newConfig = _.defaultsDeep({ // 强制性属性 layout: 'hbox', minHeight: config.designMode ? 32 : 0 }, baseConfig(config, 'cols-container'), config, cols); this.superclass.constructor.call(self, newConfig); }, }); } function initButton () { /** * */ var ct = Ext.button.Button.prototype.constructor; Ext.button.Button.override({ constructor: function (config) { var newConfig = _.defaultsDeep({}, config, baseConfig(config, "col-item"), button); ct.call(this, newConfig); }, setLoading: function (value) { if (value) { if (this.iconCls !== 'x-fa fa-spinner fa-spin fa-fw') { this._originIconCls = this.iconCls; } this.setIconCls('x-fa fa-spinner fa-spin fa-fw'); this.setDisabled(true); } else { this.setIconCls(this._originIconCls); this.setDisabled(false); } } }); } function initIframe () { Ext.define('Ext.ux.IFrame', { extend: 'Ext.Component', alias: 'widget.uxiframe', loadMask: 'Loading...', src: 'about:blank', renderTpl: [ '' ], childEls: ['iframeEl'], initComponent: function () { this.superclass.initComponent.call(this); this.superclass.initEvents.call(this); this.frameName = this.frameName || this.id + '-frame'; }, initEvents: function () { var me = this; this.superclass.initEvents.call(this); me.iframeEl.on('load', me.onLoad, me); }, initRenderData: function () { return Ext.apply(this.superclass.initRenderData.call(this), { src: this.src, frameName: this.frameName }); }, getBody: function () { var doc = this.getDoc(); return doc.body || doc.documentElement; }, getDoc: function () { try { return this.getWin().document; } catch (ex) { return null; } }, getWin: function () { var me = this, name = me.frameName, win = Ext.isIE ? me.iframeEl.dom.contentWindow : window.frames[name]; return win; }, getFrame: function () { var me = this; return me.iframeEl.dom; }, onLoad: function () { var me = this, doc = me.getDoc(); if (doc) { this.el.unmask(); this.fireEvent('load', this); } else if (me.src) { this.el.unmask(); this.fireEvent('error', this); } }, load: function (src) { var me = this, text = me.loadMask, frame = me.getFrame(); if (me.fireEvent('beforeload', me, src) !== false) { if (text && me.el) { me.el.mask(text); } frame.src = me.src = (src || me.src); } } }); } /** * 属性: * - autoLoad: true * - dataSource: '' * 方法: * - handleZoomBig * - handleZoomSmall * - handleZoomReset * - openDiagram * - getBpmn * - getBpmnCanvas * - getBpmnOverlays * - getBpmnZoomScroll * 事件: * - initFinish * - failed * - success * - itemHover * - itemOut * - itemClick * - itemDblclick * - itemMousedown * - itemMouseup */ function initBpmn () { Ext.define('Yvan.Bpmn', { // extend: 'Ext.container.Container', extend: 'Ext.panel.Panel', alias: 'widget.bpmn', xtype: 'bpmn', constructor: function (config) { var self = this; var newConfig = _.defaultsDeep({ // 强制性属性 }, baseConfig(config, 'row-item'), config, bpmn); if (!newConfig.hideToolbar) { newConfig.tbar = []; newConfig.tbar.push({ xtype: 'button', iconCls: 'x-fa fa-refresh', tooltip: '刷新', listeners: { click: function (sender) { self.reload(); } } }); newConfig.tbar.push({ xtype: 'button', tooltip: "放大", iconCls: "x-fa fa-search-plus", listeners: { click: function (sender) { self.handleZoomBig(); } }, }); newConfig.tbar.push({ xtype: 'button', tooltip: "缩小", iconCls: "x-fa fa-search-minus", listeners: { click: function (sender) { self.handleZoomSmall(); } }, }); newConfig.tbar.push({ xtype: 'button', tooltip: "还原", iconCls: "x-fa fa-reply", listeners: { click: function (sender) { self.handleZoomReset(); } }, }); } this.superclass.constructor.call(self, newConfig); }, initComponent: function () { var _this = this; var me = this; var config = me.config; var scope = lookupScope(this); if (!window["IS_DESIGN_MODE"]) { //@ts-ignore require(['bpmn-modeler', 'bpmn-navigated', 'bpmn-viewer'], function (BpModeler, BpNavigated, BpmnViewer) { console.log('BpNavigated', me, BpNavigated); var dom = me.el.dom; var $dom = $(dom); var $container = $dom.find('.x-autocontainer-innerCt'); var bpmn = new BpNavigated(__assign({ container: $container[0] }, config.bpmnConfig)); _this._bpmn = bpmn; if (_this.autoLoad) { _this.reload(); } _this.fireEvent('initFinish', _this); var eventBus = bpmn.get('eventBus'); eventBus.on('element.hover', function (e) { // this.fireEvent('itemHover', this, e); }); eventBus.on('element.out', function (e) { _this.fireEvent('itemOut', _this, e); }); eventBus.on('element.click', function (e) { _this.fireEvent('itemClick', _this, e); }); eventBus.on('element.dblclick', function (e) { _this.fireEvent('itemDblclick', _this, e); }); eventBus.on('element.mousedown', function (e) { _this.fireEvent('itemMousedown', _this, e); }); eventBus.on('element.mouseup', function (e) { _this.fireEvent('itemMouseup', _this, e); }); }); } this.superclass.initComponent.call(this); this.on({ afterrender: function (sender) { if (window["IS_DESIGN_MODE"]) { return; } } }); }, /** * 重新载入 */ reload: function () { var _this = this; var _a; if (typeof this.dataSource === 'string' && this.dataSource) { var scope = lookupScope(this); var fn = lookupFn(scope, this.dataSource); (_a = fn.call(scope, this)) === null || _a === void 0 ? void 0 : _a.then(function (res) { _this.openDiagram(res.data); }); } }, /** * 获取bpmn */ getBpmn: function () { return this._bpmn; }, getBpmnCanvas: function () { var _a; return (_a = this.getBpmn()) === null || _a === void 0 ? void 0 : _a.get('canvas'); }, getBpmnOverlays: function () { var _a; return (_a = this.getBpmn()) === null || _a === void 0 ? void 0 : _a.get('overlays'); }, getBpmnZoomScroll: function () { var _a; return (_a = this.getBpmn()) === null || _a === void 0 ? void 0 : _a.get('zoomScroll'); }, handleZoomBig: function () { var _a; (_a = this.getBpmnZoomScroll()) === null || _a === void 0 ? void 0 : _a.stepZoom(1); }, handleZoomSmall: function () { var _a; (_a = this.getBpmnZoomScroll()) === null || _a === void 0 ? void 0 : _a.stepZoom(-1); }, handleZoomReset: function () { var _a; (_a = this.getBpmnZoomScroll()) === null || _a === void 0 ? void 0 : _a.reset(); }, openDiagram: function (diagram) { var _this = this; if (!this.getBpmn()) { return; } this.getBpmn().importXML(diagram, function (err) { if (err) { // YvEventDispatch(this.onFailed, this, undefined); _this.fireEvent('failed', _this, err); return console.error('could not import BPMN 2.0 diagram', err); } // zoom to fit full viewport _this.getBpmnCanvas().zoom('fit-viewport'); _this.fireEvent('success', _this); }); }, }); } var FixClass = /** @class */ (function () { function FixClass() { } FixClass.prototype.fix = function (me, config) { var _this = this; var fix = config.fix; if (!fix) { return; } delete config.fix; // 这里有个 bug // 但凡是调用了 this.lookupViewModel() 就会出现绑定不了的情况 // const scope = config.$initParent.lookupReferenceHolder().yvanScope //lookupScope(me) var scope; if (config.$initParent) { // 在面板上的组件 scope = config.$initParent.lookupReferenceHolder().yvanScope; //lookupScope(me) } else if (config.column) { // 在列上的组件 scope = config.column.lookupReferenceHolder().yvanScope; //lookupScope(me) } if (_.isArray(fix)) { _.each(fix, function (f) { var fn = lookupFn(scope, f); fn.call(_this, me, config); }); } else if (_.isString(fix)) { var fn = lookupFn(scope, fix); fn.call(this, me, config); } }; __decorate([ baseConfigProcess(), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object]), __metadata("design:returntype", void 0) ], FixClass.prototype, "fix", null); return FixClass; }()); function init() { // 引入 filters 过滤插件 Ext.require([ 'Ext.grid.filters.Filters' ]); // 启用 tooltip 快捷提示 Ext.QuickTips.init(); // 定义日期格式化方法 if (Ext.util && Ext.util.Format) { Ext.apply(Ext.util.Format, { dateFormat: 'Y-m-d' }); } Ext.form.field.Display.override({ cls: 'yvan-display-field', labelAlign: 'right' }); Ext.define("Ext.locale.zh_CN.picker.Date", { override: "Ext.picker.Date", format: "Y-m-d", }); Ext.define("Ext.locale.zh_CN.form.field.Date", { override: "Ext.form.field.Date", format: "Y-m-d", }); Ext.define("Ext.locale.zh_CN.grid.PropertyColumnModel", { override: "Ext.grid.PropertyColumnModel", format: "Y-m-d", }); Ext.define("Ext.locale.zh_CN.view.AbstractView", { override: "Ext.view.AbstractView", loadingText: "读取中..." }); Ext.LoadMask.prototype.msg = '请稍后...'; Ext.define("Ext.locale.zh_CN.grid.header.Container", { override: "Ext.grid.header.Container", sortClearText: '不排序', sortAscText: "正序", sortDescText: "倒序", lockText: "锁定列", unlockText: "解除锁定", columnsText: "字段隐藏" }); Ext.define("Ext.locale.zh_CN.grid.filters.filter.Date", { override: "Ext.grid.filters.filter.Date", fields: { lt: { text: '之前' }, gt: { text: '之后' }, eq: { text: '相等' }, }, // Defaults to Ext.Date.defaultFormat dateFormat: null }); // Ext.grid.locking.Lockable.prototype.unlockText = '解锁' // Ext.grid.locking.Lockable.prototype.lockText = '锁定' // Ext.grid.filters.Filters.prototype.menuFilterText = "过滤" Ext.define("Ext.locale.zh_CN.grid.locking.Lockable", { override: "Ext.grid.locking.Lockable", lockText: "锁定", unlockText: '解锁', }); Ext.define("Ext.locale.zh_CN.grid.filters.Filters", { override: "Ext.grid.filters.Filters", menuFilterText: "过滤" }); Ext.define("Ext.locale.zh_CN.grid.filters.filter.Boolean", { override: "Ext.grid.filters.filter.Boolean", yesText: "已钩选", noText: "未勾选" }); Ext.define("Ext.locale.zh_CN.grid.filters.filter.String", { override: "Ext.grid.filters.filter.String", emptyText: "输入过滤文本..." }); Ext.define("Ext.locale.zh_CN.grid.filters.filter.Number", { override: "Ext.grid.filters.filter.Number", emptyText: "输入数字..." }); Ext.define("Ext.locale.zh_CN.toolbar.Paging", { override: "Ext.PagingToolbar", beforePageText: "第", // update afterPageText: "/ {0} 页", // update firstText: "第一页", prevText: "上一页", // update nextText: "下一页", lastText: "最后页", refreshText: "刷新", displayMsg: "总共 {2} 条", // update emptyMsg: '没有数据' }); /** * 改变事件的获取方式. * 具体见: ext-all-debug.js:23216 addListener * https://docs.sencha.com/extjs/6.6.0/classic/Ext.util.Observable.html#method-addListener * https://docs.sencha.com/extjs/6.6.0/classic/src/Observable.js.html#Ext.mixin.Observable-method-addListener */ var _doAddListener = Ext.mixin.Observable.prototype.doAddListener; Ext.mixin.Observable.prototype.doAddListener = function (ename, fn, scope, options, order, caller, manager) { if (typeof fn === 'string' && (_.startsWith(fn, 'scope.') || _.startsWith(fn, 'system.') || _.startsWith(fn, 'format.'))) { if (window["IS_DESIGN_MODE"]) { fn = Ext.emptyFn; } else { // console.log('doAddListener', ename, fn, scope, options, order, caller, manager) // const vm = this.lookupViewModel() // if (vm && vm.yvanScope) { // scope = vm.yvanScope // fn = scope[fn.substr('scope.'.length)] // } scope = lookupScope(this); fn = lookupFn(scope, fn, this); } } _doAddListener.call(this, ename, fn, scope, options, order, caller, manager); }; // 将 SystemLib 扩展到 window.system 下 if (!window['system']) { window['system'] = {}; } _.extend(window['system'], SystemLib); Ext.apply(Ext.util.Format, { // 百分比 percentRenderer: function (v, rd, model) { if (!v) { v = 0; } if (typeof v === 'string') { v = parseInt(v); } var valueString = v.toFixed(2); var valueFixed = v > 100 ? 100 : v; valueFixed = valueFixed < 0 ? 0 : valueFixed; var cls = ''; if (v < 90) { cls = 'danger'; } else if (v < 100) { cls = 'warning'; } else { cls = 'success'; } return Ext.String .format( // '
' // + '
' // + '
{0}%
' // + '
' // + '
', valueString, valueFixed, cls); '
{0}%
{4}%
', valueString, cls, valueFixed, ((100 / valueFixed) * 100), valueString); // .format( // '
' // + '
' // + '
{0}%
' // + '
' // + '
', v, valueFixed, valueString); }, //button button: function (v, rd, model) { return ""; } }); initComponent(); initPanel(); initGridColumn(); initTree(); initGrid(); initMainTab(); initTextfield(); initCombo(); initRows(); initCols(); initForm(); initToolbar(); initSplitter(); initButton(); initStores(); initSearch(); initMultipleSearch(); initDate(); initDateTimePicker(); initDateTime(); initNumber(); initCheckbox(); initCheckboxGroup(); initRadio(); initRadioGroup(); initFieldset(); initCombotree(); initPickerPlus(); initCombogrid(); initComboGridMulti(); initIframe(); initBpmn(); } exports.axios = axios; exports.qs = Qs; exports.lodash = _; exports.jquery = $$1; exports.recast = recast; exports.Defaults = Defaults; exports.ExcelImportDialog = ExcelImportDialog; exports.Lib = Lib; exports.LibParam = LibParam; exports.PropertyDescriptionTable = PropertyDescriptionTable; exports.ReportScope = ReportScope; exports.SIMPLE_RE = SIMPLE_RE; exports.Scope = Scope; exports.ScopeEngine = ScopeEngine; exports.SystemEventFu = SystemEventFu; exports.ajax = ajax; exports.baseConfigProcess = baseConfigProcess; exports.baseConfigProcessList = baseConfigProcessList; exports.buildReportScope = buildReportScope; exports.calcExpress = calcExpress; exports.calcObject = calcObject; exports.calcObjectFlat = calcObjectFlat; exports.clearViewModel = clearViewModel; exports.clearViewModelByLookup = clearViewModelByLookup; exports.clearViewModelReloadGrid = clearViewModelReloadGrid; exports.clearViewModelValues = clearViewModelValues; exports.confirm = confirm; exports.createAjax = createAjax; exports.createUUID = createUUID; exports.downLoad = downLoad; exports.evalFunction = evalFunction; exports.extend = extend; exports.flatRow = flatRow; exports.getApiConvert = getApiConvert; exports.getGridEditRows = getGridEditRows; exports.getParentGrid = getParentGrid; exports.getPinyin = getPinyin; exports.getRegList = getRegList; exports.getRegParamList = getRegParamList; exports.init = init; exports.invokeServer = invokeServer; exports.isDesignMode = isDesignMode; exports.isEmpty = isEmpty; exports.json5 = dist; exports.keywordFilter = keywordFilter; exports.lookupFn = lookupFn; exports.lookupScope = lookupScope; exports.mergeViewModel = mergeViewModel; exports.moment = moment$1; exports.msg = msg$1; exports.msgError = msgError; exports.normId = normId; exports.pinyinMatch = pinyinMatch; exports.prompt = prompt$1; exports.raiseClick = raiseClick; exports.reloadGrid = reloadGrid; exports.replaceNA = replaceNA; exports.serverInvokeUrlTransform = serverInvokeUrlTransform; exports.setComboStore = setComboStore; exports.setDesignMode = setDesignMode; exports.showErrorDialog = showErrorDialog$1; exports.showInfoDialog = showInfoDialog; exports.showWidget = showWidget; exports.sqlUrlTransform = sqlUrlTransform; exports.stopEvent = stopEvent; exports.toPlainObject = toPlainObject; exports.toString = toString; exports.tryEnable = tryEnable; exports.tryVarSimple = tryVarSimple; exports.tryWriteByExpress = tryWriteByExpress; exports.tryWriteObject = tryWriteObject; exports.watch = watch; Object.defineProperty(exports, '__esModule', { value: true }); }); //# sourceMappingURL=yvan-ext.js.map