UNPKG

choerodon-ui

Version:

An enterprise-class UI design language and React-based implementation

1,826 lines (1,575 loc) 96.5 kB
import _defineProperty from "@babel/runtime/helpers/defineProperty"; import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; import _regeneratorRuntime from "@babel/runtime/regenerator"; import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray"; import _objectSpread from "@babel/runtime/helpers/objectSpread2"; import _classCallCheck from "@babel/runtime/helpers/classCallCheck"; import _createClass from "@babel/runtime/helpers/createClass"; import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized"; import _inherits from "@babel/runtime/helpers/inherits"; import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn"; import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf"; function _createSuper(Derived) { function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } return function () { var Super = _getPrototypeOf(Derived), result; if (isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } import { __decorate } from "tslib"; import { action, computed, get as _get, isArrayLike, observable, runInAction, set as _set, toJS } from 'mobx'; import axiosStatic from 'axios'; import unionBy from 'lodash/unionBy'; import omit from 'lodash/omit'; import flatMap from 'lodash/flatMap'; import isNumber from 'lodash/isNumber'; import isArray from 'lodash/isArray'; import isObject from 'lodash/isObject'; import isNil from 'lodash/isNil'; import defer from 'lodash/defer'; import isString from 'lodash/isString'; import isPlainObject from 'lodash/isPlainObject'; import debounce from 'lodash/debounce'; import warning from '../../../es/_util/warning'; import { getConfig } from '../../../es/configure'; import localeContext, { $l } from '../locale-context'; import axios from '../axios'; import Record from './Record'; import Field from './Field'; import { adapterDataToJSON, arrayMove, axiosConfigAdapter, checkParentByInsert, doExport, exportExcel, findBindFieldBy, findRootParent, fixAxiosConfig, generateData, generateJSONData, generateResponseData, getFieldSorter, getOrderFields, getSpliceRecord, getSplitValue, isDirtyRecord, normalizeGroups, prepareForSubmit, prepareSubmitData, processExportValue, processIntlField, sliceTree, sortTree, useCascade, useSelected } from './utils'; import EventManager from '../_util/EventManager'; import DataSetSnapshot from './DataSetSnapshot'; import confirm from '../modal/confirm'; import { DataSetEvents, DataSetExportStatus, DataSetSelection, DataSetStatus, DataToJSON, ExportMode, FieldType, RecordStatus, SortOrder } from './enum'; import isEmpty from '../_util/isEmpty'; import * as ObjectChainValue from '../_util/ObjectChainValue'; import Transport from './Transport'; import PromiseQueue from '../_util/PromiseQueue'; import DataSetRequestError from './DataSetRequestError'; import defaultFeedback from './FeedBack'; var DataSet = /*#__PURE__*/ function (_EventManager) { _inherits(DataSet, _EventManager); var _super = _createSuper(DataSet); function DataSet(props) { var _this; _classCallCheck(this, DataSet); _this = _super.call(this); _this.children = {}; _this.pending = new PromiseQueue(); _this.originalData = []; _this.resetInBatch = false; _this.inBatchSelection = false; _this.syncChildrenRemote = debounce(function (remoteKeys, current) { var _assertThisInitialize = _assertThisInitialized(_this), children = _assertThisInitialize.children; remoteKeys.forEach(function (childName) { return _this.syncChild(children[childName], current, childName); }); }, 300); runInAction(function () { props = _objectSpread({}, DataSet.defaultProps, {}, props); _this.props = props; var _props = props, data = _props.data, fields = _props.fields, queryFields = _props.queryFields, queryDataSet = _props.queryDataSet, autoQuery = _props.autoQuery, autoCreate = _props.autoCreate, pageSize = _props.pageSize, selection = _props.selection, events = _props.events, id = _props.id, name = _props.name, children = _props.children, _props$queryParameter = _props.queryParameter, queryParameter = _props$queryParameter === void 0 ? {} : _props$queryParameter, dataToJSON = _props.dataToJSON; _this.name = name; _this.dataToJSON = dataToJSON; _this.records = []; _this.state = observable.map(); _this.fields = observable.map(); _this.totalCount = 0; _this.status = DataSetStatus.ready; _this.currentPage = 1; _this.cachedSelected = []; _this.queryParameter = queryParameter; _this.pageSize = pageSize; _this.selection = selection; _this.processListener(); if (id) { _this.id = id; } if (children) { _this.initChildren(children); } if (events) { _this.initEvents(events); } if (fields) { _this.initFields(fields); } _this.initQueryDataSet(queryDataSet, queryFields); if (data) { var length = data.length; if (length) { _this.loadData(data, length); } } // ssr do not auto query if (autoQuery && typeof window !== 'undefined') { _this.query(); } else if (autoCreate && _this.records.length === 0) { _this.create(); } }); return _this; } _createClass(DataSet, [{ key: "processListener", value: function processListener() { this.addEventListener(DataSetEvents.indexChange, this.handleCascade); } }, { key: "destroy", value: function destroy() { this.clear(); } }, { key: "setState", value: function setState(item, value) { if (isString(item)) { this.state.set(item, value); } else if (isPlainObject(item)) { this.state.merge(item); } return this; } }, { key: "getState", value: function getState(key) { return this.state.get(key); } }, { key: "snapshot", value: function snapshot() { return new DataSetSnapshot(this); } }, { key: "restore", value: function restore(snapshot) { if (snapshot.dataSet !== this) { this.events = {}; } else if (snapshot.events) { this.events = snapshot.events; } this.records = snapshot.records; this.originalData = snapshot.originalData; this.totalCount = snapshot.totalCount; this.currentPage = snapshot.currentPage; this.pageSize = snapshot.pageSize; this.cachedSelected = snapshot.cachedSelected; this.dataToJSON = snapshot.dataToJSON; this.children = snapshot.children; this.current = snapshot.current; return this; } }, { key: "toData", value: function toData() { return generateData(this.records).data; } /** * 对应参数后续会废弃 * @param isSelected * @param noCascade */ }, { key: "toJSONData", value: function toJSONData(isSelected, noCascade) { var dataToJSON = adapterDataToJSON(isSelected, noCascade) || this.dataToJSON; var records = useSelected(dataToJSON) ? this.selected : this.records; return generateJSONData(this, records).data; } /** * 等待选中或者所有记录准备就绪 * @returns Promise */ }, { key: "ready", value: function ready(isSelect) { return Promise.all([this.pending.ready()].concat(_toConsumableArray((isSelect || useSelected(this.dataToJSON) ? this.selected : this.data).map(function (record) { return record.ready(); })), _toConsumableArray(_toConsumableArray(this.fields.values()).map(function (field) { return field.ready(); })))); } /** * 查询记录 * @param page 页码 * @param params 查询参数 * @return Promise */ }, { key: "query", value: function query(page, params) { return this.pending.add(this.doQuery(page, params)); } /** * 查询更多记录,查询到的结果会拼接到原有数据之后 * @param page 页码 * @param params 查询参数 * @return Promise */ }, { key: "queryMore", value: function queryMore(page, params) { return this.pending.add(this.doQueryMore(page, params)); } }, { key: "doQuery", value: function () { var _doQuery = _asyncToGenerator( /*#__PURE__*/ _regeneratorRuntime.mark(function _callee(page, params) { var data; return _regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return this.read(page, params); case 2: data = _context.sent; this.loadDataFromResponse(data); return _context.abrupt("return", data); case 5: case "end": return _context.stop(); } } }, _callee, this); })); function doQuery(_x, _x2) { return _doQuery.apply(this, arguments); } return doQuery; }() }, { key: "doQueryMore", value: function () { var _doQueryMore = _asyncToGenerator( /*#__PURE__*/ _regeneratorRuntime.mark(function _callee2(page, params) { var data; return _regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return this.read(page, params); case 2: data = _context2.sent; this.appendDataFromResponse(data); return _context2.abrupt("return", data); case 5: case "end": return _context2.stop(); } } }, _callee2, this); })); function doQueryMore(_x3, _x4) { return _doQueryMore.apply(this, arguments); } return doQueryMore; }() /** * TODO 参数废弃 * 将数据集中的增删改的记录进行远程提交 * @param isSelect 如果为true,则只提交选中记录 * @param noCascade 如果为true,则不提交级联数据 * @return Promise */ }, { key: "submit", value: function () { var _submit = _asyncToGenerator( /*#__PURE__*/ _regeneratorRuntime.mark(function _callee3(isSelect, noCascade) { var dataToJSON; return _regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: dataToJSON = adapterDataToJSON(isSelect, noCascade) || this.dataToJSON; _context3.next = 3; return this.ready(); case 3: _context3.next = 5; return this.validate(); case 5: if (!_context3.sent) { _context3.next = 7; break; } return _context3.abrupt("return", this.pending.add(this.write(useSelected(dataToJSON) ? this.selected : this.records))); case 7: return _context3.abrupt("return", false); case 8: case "end": return _context3.stop(); } } }, _callee3, this); })); function submit(_x5, _x6) { return _submit.apply(this, arguments); } return submit; }() /** * 导出数据 * @param object columns 导出的列 * @param number exportQuantity 导出数量 */ }, { key: "export", value: function () { var _export2 = _asyncToGenerator( /*#__PURE__*/ _regeneratorRuntime.mark(function _callee4() { var columns, exportQuantity, data, totalCount, totalKey, params, newConfig, ExportQuantity, _args4 = arguments; return _regeneratorRuntime.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: columns = _args4.length > 0 && _args4[0] !== undefined ? _args4[0] : {}; exportQuantity = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : 0; _context4.t0 = this.checkReadable(this.parent); if (!_context4.t0) { _context4.next = 7; break; } _context4.next = 6; return this.ready(); case 6: _context4.t0 = _context4.sent; case 7: if (!_context4.t0) { _context4.next = 30; break; } _context4.next = 10; return this.generateQueryParameter(); case 10: data = _context4.sent; data._HAP_EXCEL_EXPORT_COLUMNS = columns; totalCount = this.totalCount, totalKey = this.totalKey; params = _objectSpread({ _r: Date.now() }, this.generateOrderQueryString()); ObjectChainValue.set(params, totalKey, totalCount); newConfig = axiosConfigAdapter('exports', this, data, params); if (!newConfig.url) { _context4.next = 29; break; } _context4.next = 19; return this.fireEvent(DataSetEvents["export"], { dataSet: this, params: newConfig.params, data: newConfig.data }); case 19: _context4.t1 = _context4.sent; if (!(_context4.t1 !== false)) { _context4.next = 27; break; } ExportQuantity = exportQuantity > 1000 ? 1000 : exportQuantity; if (!(this.exportMode !== ExportMode.client)) { _context4.next = 26; break; } doExport(this.axios.getUri(newConfig), newConfig.data, newConfig.method); _context4.next = 27; break; case 26: return _context4.abrupt("return", this.doClientExport(data, ExportQuantity, false)); case 27: _context4.next = 30; break; case 29: warning(false, 'Unable to execute the export method of dataset, please check the '); case 30: case "end": return _context4.stop(); } } }, _callee4, this); })); function _export() { return _export2.apply(this, arguments); } return _export; }() /** * 可以把json数组通过ds配置转化成可以直接浏览的数据信息 * @param result 需要转化内容 * @param columnsExport 表头信息 */ }, { key: "displayDataTransform", value: function displayDataTransform(result, columnsExport) { var _this2 = this; var newResult = []; if (result && result.length > 0) { // check: 这里做性能优化去掉实例化为record 从demo来看没啥问题 // toJS(this.processData(result)).map((item) => item.data); var processData = result; processData.forEach(function (itemValue) { var dataItem = {}; var columnsExportkeys = Object.keys(columnsExport); for (var i = 0; i < columnsExportkeys.length; i += 1) { var firstRecord = _this2.records[0] || _this2; var exportField = firstRecord.getField(columnsExportkeys[i]); var processItemValue = getSplitValue(toJS(itemValue), columnsExportkeys[i]); // 处理bind 情况 if (exportField && isNil(processItemValue) && exportField.get('bind')) { processItemValue = getSplitValue(getSplitValue(toJS(itemValue), exportField.get('bind')), columnsExportkeys[i], true); } dataItem[columnsExportkeys[i]] = processExportValue(processItemValue, exportField); } newResult.push(dataItem); }); } return newResult; } /** * 客户端导出方法 * @param data 表头数据 * @param quantity 输入一次导出数量 * @param isFile 是否导出为文件 */ }, { key: "doClientExport", value: function () { var _doClientExport = _asyncToGenerator( /*#__PURE__*/ _regeneratorRuntime.mark(function _callee5(data, quantity) { var _this3 = this; var isFile, columnsExport, totalCount, newResult, queryTime, queryExportList, i, params, newConfig, _args5 = arguments; return _regeneratorRuntime.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: isFile = _args5.length > 2 && _args5[2] !== undefined ? _args5[2] : true; columnsExport = data._HAP_EXCEL_EXPORT_COLUMNS; delete data._HAP_EXCEL_EXPORT_COLUMNS; totalCount = this.totalCount; runInAction(function () { _this3.exportStatus = DataSetExportStatus.start; }); newResult = []; if (!(totalCount > 0)) { _context5.next = 11; break; } queryTime = Math.ceil(totalCount / quantity); queryExportList = []; for (i = 0; i < queryTime; i++) { params = _objectSpread({}, this.generateQueryString(1 + i, quantity)); newConfig = axiosConfigAdapter('read', this, data, params); queryExportList.push(this.axios(newConfig)); runInAction(function () { _this3.exportStatus = DataSetExportStatus.exporting; }); } return _context5.abrupt("return", Promise.all(queryExportList).then(function (resultValue) { var reducer = function reducer(accumulator, currentValue) { return [].concat(_toConsumableArray(accumulator), _toConsumableArray(currentValue)); }; var todataList = function todataList(item) { return item ? item[_this3.dataKey] : []; }; runInAction(function () { _this3.exportStatus = DataSetExportStatus.progressing; }); var exportAlldate = resultValue.map(todataList).reduce(reducer); newResult = _this3.displayDataTransform(exportAlldate, columnsExport); newResult.unshift(columnsExport); runInAction(function () { _this3.exportStatus = DataSetExportStatus.success; }); if (isFile) { exportExcel(newResult, _this3.name); } else { return newResult; } })["catch"](function () { runInAction(function () { _this3.exportStatus = DataSetExportStatus.failed; }); })); case 11: case "end": return _context5.stop(); } } }, _callee5, this); })); function doClientExport(_x7, _x8) { return _doClientExport.apply(this, arguments); } return doClientExport; }() /** * 重置更改 */ }, { key: "reset", value: function reset() { this.resetInBatch = true; this.records = this.originalData.map(function (record) { return record.reset(); }); this.resetInBatch = false; if (this.props.autoCreate && this.records.length === 0) { this.create(); } this.fireEvent(DataSetEvents.reset, { dataSet: this, records: this.records }); return this; } /** * 定位到指定页码,如果paging为true或`server`,则做远程查询,约定当为Tree 状态的server时候 跳转到下一页也就是index为当前的index加上1 * @param page 页码 * @return Promise */ }, { key: "page", value: function page(_page) { if (_page > 0 && this.paging) { return this.locate((_page - 1) * this.pageSize + this.created.length - this.destroyed.length); } warning(_page > 0, 'Page number is incorrect.'); warning(!!this.paging, 'Can not paging query util the property<paging> of DataSet is true or `server`.'); return Promise.resolve(); } /** * 变更检查,当有变更时会弹确认框 * @param message 提示信息或者是confirm的参数 * @return Promise */ }, { key: "modifiedCheck", value: function modifiedCheck(message) { var _this$props = this.props, modifiedCheck = _this$props.modifiedCheck, modifiedCheckMessage = _this$props.modifiedCheckMessage; if (!modifiedCheck || !this.dirty) { return Promise.resolve(true); } return confirm(message || modifiedCheckMessage || $l('DataSet', 'unsaved_data_confirm')).then(function (result) { return result !== 'cancel'; }); } /** * 定位记录 * @param index 索引 * @return Promise */ }, { key: "locate", value: function () { var _locate = _asyncToGenerator( /*#__PURE__*/ _regeneratorRuntime.mark(function _callee6(index) { var paging, pageSize, totalCount, autoLocateFirst, currentRecord; return _regeneratorRuntime.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: paging = this.paging, pageSize = this.pageSize, totalCount = this.totalCount; autoLocateFirst = this.props.autoLocateFirst; currentRecord = this.findInAllPage(index); if (!currentRecord) { _context6.next = 6; break; } this.current = currentRecord; return _context6.abrupt("return", currentRecord); case 6: if (!(paging === true || paging === 'server')) { _context6.next = 17; break; } if (!(index >= 0 && index < totalCount + this.created.length - this.destroyed.length)) { _context6.next = 17; break; } _context6.next = 10; return this.modifiedCheck(); case 10: if (!_context6.sent) { _context6.next = 17; break; } _context6.next = 13; return this.query(Math.floor(index / pageSize) + 1); case 13: currentRecord = this.findInAllPage(index); if (!currentRecord) { _context6.next = 17; break; } this.current = autoLocateFirst ? currentRecord : undefined; return _context6.abrupt("return", currentRecord); case 17: warning(false, 'Located index of Record is out of boundary.'); return _context6.abrupt("return", Promise.resolve(undefined)); case 19: case "end": return _context6.stop(); } } }, _callee6, this); })); function locate(_x9) { return _locate.apply(this, arguments); } return locate; }() /** * 定位到第一条记录 * @return Promise */ }, { key: "first", value: function first() { return this.locate(0); } /** * 定位到最后一条记录 * @return Promise */ }, { key: "last", value: function last() { return this.locate((this.paging ? this.totalCount : this.length) - 1); } /** * 定位到当前记录的上一条记录 * 若当前页中当前记录为第一条记录且有上一页,则会查询上一页并定位到上一页的最后一条记录 * @return Promise */ }, { key: "pre", value: function pre() { return this.locate(this.currentIndex - 1); } /** * 定位到当前记录的下一条记录 * 若当前页中当前记录为最后一条记录且有下一页,则会查询下一页并定位到下一页的第一条记录 * @return Promise */ }, { key: "next", value: function next() { return this.locate(this.currentIndex + 1); } /** * 定位到首页 * @return Promise */ }, { key: "firstPage", value: function firstPage() { return this.page(1); } /** * 定位到上一页 * @return Promise */ }, { key: "prePage", value: function prePage() { return this.page(this.currentPage - 1); } /** * 定位到下一页 * @return Promise */ }, { key: "nextPage", value: function nextPage() { return this.page(this.currentPage + 1); } /** * 定位到尾页 * @return Promise */ }, { key: "lastPage", value: function lastPage() { return this.page(this.totalPage); } /** * 创建一条记录 * @param data 数据对象 * @param dataIndex 记录所在的索引 * @return 新建的记录 */ }, { key: "create", value: function create() { var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var dataIndex = arguments.length > 1 ? arguments[1] : undefined; if (data === null) { data = {}; } var record = new Record(data, this); var objectFieldsList = []; var normalFields = []; _toConsumableArray(record.fields.entries()).forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), name = _ref2[0], field = _ref2[1]; var fieldDefaultValue = field.get('defaultValue'); var multiple = field.get('multiple'); var defaultValue = multiple && isNil(fieldDefaultValue) ? [] : fieldDefaultValue; if (!isNil(defaultValue) && isNil(record.get(name))) { var type = field.get('type'); if (type === FieldType.object) { var level = name.split('.').length - 1; objectFieldsList[level] = (objectFieldsList[level] || []).concat([[name, defaultValue]]); } else { normalFields.push([name, defaultValue]); } } }); [].concat(objectFieldsList, [normalFields]).forEach(function (items) { if (items) { items.forEach(function (_ref3) { var _ref4 = _slicedToArray(_ref3, 2), name = _ref4[0], defaultValue = _ref4[1]; return record.init(name, toJS(defaultValue)); }); } }); if (isNumber(dataIndex)) { this.splice(dataIndex, 0, record); } else { this.push(record); } if (this.props.autoLocateAfterCreate) { this.current = record; } this.fireEvent(DataSetEvents.create, { dataSet: this, record: record }); return record; } /** * 立即删除记录 * @param records 记录或者记录数组,默认当前记录 * @param confirmMessage 提示信息或弹窗的属性 * @return Promise */ }, { key: "delete", value: function () { var _delete2 = _asyncToGenerator( /*#__PURE__*/ _regeneratorRuntime.mark(function _callee7(records, confirmMessage) { var res, current, record; return _regeneratorRuntime.wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: if (!records) { _context7.next = 25; break; } records = [].concat(records); _context7.t1 = records.length > 0; if (!_context7.t1) { _context7.next = 8; break; } _context7.next = 6; return this.fireEvent(DataSetEvents.beforeDelete, { dataSet: this, records: records }); case 6: _context7.t2 = _context7.sent; _context7.t1 = _context7.t2 !== false; case 8: _context7.t0 = _context7.t1; if (!_context7.t0) { _context7.next = 17; break; } _context7.t3 = confirmMessage === false; if (_context7.t3) { _context7.next = 16; break; } _context7.next = 14; return confirm(confirmMessage && confirmMessage !== true ? confirmMessage : $l('DataSet', 'delete_selected_row_confirm')); case 14: _context7.t4 = _context7.sent; _context7.t3 = _context7.t4 !== 'cancel'; case 16: _context7.t0 = _context7.t3; case 17: if (!_context7.t0) { _context7.next = 25; break; } this.remove(records, false); _context7.next = 21; return this.pending.add(this.write(this.destroyed, true)); case 21: res = _context7.sent; // 处理自动定位 current = this.current; if (current) { if (this.props.autoLocateAfterRemove) { record = this.get(0); if (record) { runInAction(function () { record.isCurrent = true; }); } } if (current !== record) { this.fireEvent(DataSetEvents.indexChange, { dataSet: this, record: record, previous: current }); } } return _context7.abrupt("return", res); case 25: case "end": return _context7.stop(); } } }, _callee7, this); })); function _delete(_x10, _x11) { return _delete2.apply(this, arguments); } return _delete; }() /** * 临时删除记录 * @param records 记录或者记录数组 * @param locate 是否需要进行定位操作 */ }, { key: "remove", value: function remove(records, locate) { if (records) { var data = isArrayLike(records) ? records.slice() : [records]; if (data.length && this.fireEventSync(DataSetEvents.beforeRemove, { dataSet: this, records: data }) !== false) { var current = this.current; data.forEach(this.deleteRecord, this); this.fireEvent(DataSetEvents.remove, { dataSet: this, records: data }); if (!this.current) { var record; if (locate !== false && this.props.autoLocateAfterRemove) { record = this.get(0); if (record) { record.isCurrent = true; } } if (locate !== false && current !== record) { this.fireEvent(DataSetEvents.indexChange, { dataSet: this, record: record, previous: current }); } } } } } /** * 临时删除所有记录 */ }, { key: "removeAll", value: function removeAll() { var current = this.current, data = this.data; if (data.length) { data.forEach(this.deleteRecord, this); this.fireEvent(DataSetEvents.remove, { dataSet: this, records: data }); if (current) { this.fireEvent(DataSetEvents.indexChange, { dataSet: this, previous: current }); } } } /** * 删除所有记录 * @param confirmMessage 提示信息或弹窗的属性 */ }, { key: "deleteAll", value: function () { var _deleteAll = _asyncToGenerator( /*#__PURE__*/ _regeneratorRuntime.mark(function _callee8(confirmMessage) { return _regeneratorRuntime.wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: _context8.t0 = this.records.length > 0; if (!_context8.t0) { _context8.next = 9; break; } _context8.t1 = confirmMessage === false; if (_context8.t1) { _context8.next = 8; break; } _context8.next = 6; return confirm(confirmMessage && confirmMessage !== true ? confirmMessage : $l('DataSet', 'delete_all_row_confirm')); case 6: _context8.t2 = _context8.sent; _context8.t1 = _context8.t2 !== 'cancel'; case 8: _context8.t0 = _context8.t1; case 9: if (!_context8.t0) { _context8.next = 12; break; } this.removeAll(); return _context8.abrupt("return", this.pending.add(this.write(this.destroyed, true))); case 12: case "end": return _context8.stop(); } } }, _callee8, this); })); function deleteAll(_x12) { return _deleteAll.apply(this, arguments); } return deleteAll; }() /** * 将若干数据记录插入记录堆栈顶部 * @param records 数据集 * @return 堆栈数量 */ }, { key: "push", value: function push() { var _this$records; checkParentByInsert(this); for (var _len = arguments.length, records = new Array(_len), _key = 0; _key < _len; _key++) { records[_key] = arguments[_key]; } return (_this$records = this.records).push.apply(_this$records, _toConsumableArray(this.transferRecords(records))); } /** * 将若干数据记录插入记录堆栈底部 * @param records 数据集 * @return 堆栈数量 */ }, { key: "unshift", value: function unshift() { var _this$records2; checkParentByInsert(this); for (var _len2 = arguments.length, records = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { records[_key2] = arguments[_key2]; } return (_this$records2 = this.records).unshift.apply(_this$records2, _toConsumableArray(this.transferRecords(records))); } /** * 从记录堆栈顶部获取记录 * @return 记录 */ }, { key: "pop", value: function pop() { return this.deleteRecord(this.data.pop()); } /** * 从记录堆栈底部获取记录 * @return 记录 */ }, { key: "shift", value: function shift() { return this.deleteRecord(this.data.shift()); } /** * 删除指定索引的若干记录,并可插入若干新记录 * @param from 索引开始的位置 * @default 0 * @param deleteCount 删除的数量 * @default 0 * @param records 插入的若干新记录 * @return 被删除的记录集 */ }, { key: "splice", value: function splice(from, deleteCount) { var fromRecord = this.get(from); var deleted = this.slice(from, from + deleteCount).map(this.deleteRecord, this); for (var _len3 = arguments.length, items = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) { items[_key3 - 2] = arguments[_key3]; } if (items.length) { checkParentByInsert(this); var records = this.records; var spliceRecord = getSpliceRecord(records, items, fromRecord); var transformedRecords = this.transferRecords(items); if (spliceRecord) { records.splice.apply(records, [records.indexOf(spliceRecord), 0].concat(_toConsumableArray(transformedRecords))); } else { records.push.apply(records, _toConsumableArray(transformedRecords)); } } return deleted; } /** * 切换记录的顺序 */ }, { key: "move", value: function move(from, to) { arrayMove(this.records, from, to); } /** * 截取指定索引范围的记录集,不改变原记录堆栈 * @param start 开始索引 * @default 0 * @param end 结束索引 * @default 记录堆栈长度 * @return 被删除的记录集 */ }, { key: "slice", value: function slice() { var start = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var end = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.length; return this.data.slice(start, end); } /** * 获取记录所在的索引 * @param record 记录 * @param fromIndex 开始检索的索引 * @return 索引 */ }, { key: "indexOf", value: function indexOf(record, fromIndex) { return this.data.indexOf(record, fromIndex); } /** * 根据函数查找记录 * @param fn 查询函数 * @returns 记录 */ }, { key: "find", value: function find(fn) { return this.data.find(fn); } /** * 根据函数查找记录所在的索引 * @param fn 查询函数 * @returns 索引 */ }, { key: "findIndex", value: function findIndex(fn) { return this.data.findIndex(fn); } /** * 根据函数遍历 * @param fn 遍历函数 * @param thisArg this对象 */ }, { key: "forEach", value: function forEach(fn, thisArg) { this.data.forEach(fn, thisArg); } /** * 根据函数遍历并输出新数组 * @param fn 遍历函数 * @param thisArg this对象 * @returns 输出新数组 */ }, { key: "map", value: function map(fn, thisArg) { return this.data.map(fn, thisArg); } /** * 根据函数遍历,当有返回值为true时,输出true * @param fn 遍历函数 * @param thisArg this对象 * @returns boolean */ }, { key: "some", value: function some(fn, thisArg) { return this.data.some(fn, thisArg); } /** * 根据函数遍历,当有返回值为false时,输出false * @param fn 遍历函数 * @param thisArg this对象 * @returns boolean */ }, { key: "every", value: function every(fn, thisArg) { return this.data.every(fn, thisArg); } /** * 根据函数过滤并返回记录集 * @param fn 过滤函数 * @param thisArg this对象 * @returns {Record[]} */ }, { key: "filter", value: function filter(fn, thisArg) { return this.data.filter(fn, thisArg); } /** * 为数组中的所有元素调用指定的回调函数。 回调函数的返回值是累计结果,并在下次调用回调函数时作为参数提供。 * @param fn 累计函数 * @param initialValue 初始值 * @returns {U} */ }, { key: "reduce", value: function reduce(fn, initialValue) { return this.data.reduce(fn, initialValue); } /** * 按降序调用数组中所有元素的指定回调函数。 回调函数的返回值是累计结果,并在下次调用回调函数时作为参数提供。 * @param fn 累计函数 * @param initialValue 初始值 * @returns {U} */ }, { key: "reduceRight", value: function reduceRight(fn, initialValue) { return this.data.reduceRight(fn, initialValue); } /** * 反转记录的顺序。 */ }, { key: "reverse", value: function reverse() { return this.records = this.records.reverse(); } /** * 服务端排序 * 排序新增加中间态 * @param fieldName */ }, { key: "sort", value: function sort(fieldName) { var field = this.getField(fieldName); if (field) { var currents = getOrderFields(this.fields); currents.forEach(function (current) { if (current !== field) { current.order = undefined; } }); switch (field.order) { case SortOrder.asc: field.order = SortOrder.desc; break; case SortOrder.desc: field.order = undefined; break; default: field.order = SortOrder.asc; } if (this.paging || !field.order) { this.query(); } else { this.records = this.records.sort(getFieldSorter(field)); } } } /** * 选中记录 * @param recordOrIndex 记录或记录索引 */ }, { key: "select", value: function select(recordOrIndex) { var selection = this.selection; if (selection) { var record = recordOrIndex; if (isNumber(recordOrIndex)) { record = this.get(recordOrIndex); } if (record && record.selectable && !record.isSelected) { var previous; if (selection === DataSetSelection.single) { this.selected.forEach(function (selected) { selected.isSelected = false; previous = selected; }); } if (record) { record.isSelected = true; } if (!this.inBatchSelection) { this.fireEvent(DataSetEvents.select, { dataSet: this, record: record, previous: previous }); } } } } /** * 取消选中记录 * @param recordOrIndex 记录或记录索引 */ }, { key: "unSelect", value: function unSelect(recordOrIndex) { if (this.selection) { var record = recordOrIndex; if (isNumber(recordOrIndex)) { record = this.get(recordOrIndex); } if (record && record.selectable && record.isSelected) { record.isSelected = false; if (!this.inBatchSelection) { var cachedIndex = this.cachedSelected.indexOf(record); if (cachedIndex !== -1) { this.cachedSelected.splice(cachedIndex, 1); } this.fireEvent(DataSetEvents.unSelect, { dataSet: this, record: record }); } } } } /** * 全选 */ }, { key: "selectAll", value: function selectAll(filter) { var _this4 = this; var selection = this.selection; if (selection) { this.inBatchSelection = true; if (selection === DataSetSelection.single) { if (!this.currentSelected.length) { this.select(filter ? this.filter(filter)[0] : 0); } } else { this.records.forEach(function (record) { if (!filter || filter(record) !== false) { _this4.select(record); } }); } this.fireEvent(DataSetEvents.selectAll, { dataSet: this }); this.inBatchSelection = false; } } /** * 取消全选 */ }, { key: "unSelectAll", value: function unSelectAll() { var _this5 = this; if (this.selection) { this.inBatchSelection = true; this.currentSelected.forEach(function (record) { _this5.unSelect(record); }); this.fireEvent(DataSetEvents.unSelectAll, { dataSet: this }); this.inBatchSelection = false; } } }, { key: "clearCachedSelected", value: function clearCachedSelected() { this.setCachedSelected([]); } }, { key: "setCachedSelected", value: function setCachedSelected(cachedSelected) { this.cachedSelected = cachedSelected; } /** * 获取指定索引的记录 * @param index 索引 * @returns {Record} */ }, { key: "get", value: function get(index) { var data = this.data; return data.length ? data[index] : undefined; } /** * 从树形数据中获取指定索引的根节点记录 * @param index 索引 * @returns {Record} */ }, { key: "getFromTree", value: function getFromTree(index) { var treeData = this.treeData; return treeData.length ? treeData[index] : undefined; } /** * 判断是否有新增、变更或者删除的记录 * @deprecated * @return true | false */ }, { key: "isModified", value: function isModified() { return this.dirty; } /** * 获取指定分页的记录集 * @param page 如果page为空或者paging为server,则获取当前分页的记录集 * @return 记录集 */ /** * 根据记录ID查找记录 * @param id 记录ID * @return 记录 */ }, { key: "findRecordById", value: function findRecordById(id) { if (id !== undefined) { return this.records.find(function (record) { return String(record.id) === String(id); }); } } /** * 校验数据记录是否有效 对应参数后续会废弃 * @param isSelected 是否只校验选中记录 * @param noCascade 是否级联校验 * @return true | false */ }, { key: "validate", value: function validate(isSelected, noCascade) { var dataToJSON = adapterDataToJSON(isSelected, noCascade) || this.dataToJSON; var cascade = noCascade === undefined && dataToJSON ? useCascade(dataToJSON) : !noCascade; var validateResult = Promise.all((useSelected(dataToJSON) ? this.selected : this.data).map(function (record) { return record.validate(false, !cascade); })).then(function (results) { return results.every(function (result) { return result; }); }); this.fireEvent(DataSetEvents.validate, { dataSet: this, result: validateResult }); return validateResult; } /** * 根据字段名获取字段 * @param fieldName 字段名 * @returns 字段 */ }, { key: "getField", value: function getField(fieldName) { if (fieldName) { return this.fields.get(fieldName); } } /** * 获取分组字段名 * @returns 字段名列表 */ }, { key: "getGroups", value: function getGroups() { return this.groups; } }, { key: "initFields", value: function initFields(fields) { var _this6 = this; fields.forEach(function (field) { var name = field.name; if (name) { _this6.addField(name, field); } else { warning(false, 'DataSet create field failed. Please check if property name is exists on field.'); } }); } /* * 增加新字段 * @param name 字段名 * @param field 字段属性 * @return 新增字段 */ }, { key: "addField", value: function addField(name) { var _this7 = this; var fieldProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return processIntlField(name, fieldProps, function (langName, langProps) { var field = new Field(langProps, _this7); _this7.fields.set(langName, field); return field; }, this); } }, { key: "commitData", value: function commitData(allData, total, onlyDelete) { var _this8 = this; var _this$props2 = this.props, autoQueryAfterSubmit = _this$props2.autoQueryAfterSubmit, primaryKey = _this$props2.primaryKey; if (this.dataToJSON === DataToJSON.normal) { flatMap(this.dirtyRecords).forEach(function (record) { return record.commit(omit(record.toData(), ['__dirty']), _this8); }); // 若有响应数据,进行数据回写 } else if (allData.length) { var statusKey = getConfig('statusKey'); var status = getConfig('status'); var restCreatedData = []; var restUpdatedData = []; allData.forEach(function (data) { var dataStatus = data[statusKey]; // 若有数据中含有__id,根据__id回写记录,否则根据主键回写非新增的记录 var record = data.__id ? _this8.findRecordById(data.__id) : primaryKey && dataStatus !== status[RecordStatus.add] && _this8.records.find(function (r) { return r.get(primaryKey) === data[primaryKey]; }); if (record) { record.commit(data, _this8); } else if (dataStatus === status[RecordStatus.add]) { restCreatedData.push(data); } else if (dataStatus === status[RecordStatus.update]) { restUpdatedData.push(data); } }); var created = this.created, updated = this.updated, destroyed = this.destroyed; // 没有回写成功的新增数据按顺序回写 if (restCreatedData.length === created.length) { created.forEach(function (r, index) { return r.commit(restCreatedData[index], _this8); }); } else if (autoQueryAfterSubmit) { // 若有新增数据没有回写成功, 必须重新查询来获取主键 this.query(); return this; } // 剩下未回写的非新增数据使用原数据进行回写 if (restUpdatedData.length === updated.length) { updated.forEach(function (r, index) { return r.commit(restUpdatedData[index], _this8); }); } else if (onlyDelete) { updated.forEach(function (r) { return r.commit(r.toData(), _this8); }); } else { updated.forEach(function (r) { return r.commit(omit(r.toData(), ['__dirty']), _this8); }); } destroyed.forEach(function (r) { return r.commit(undefined, _this8); }); if (isNumber(total)) { this.totalCount = total; } } else if (autoQueryAfterSubmit) { // 无回写数据时自动进行查询 warning(false, "The primary key which generated by database is not exists in each created records,\nbecause of no data `".concat(this.dataKey, "` from the response by `submit` or `delete` method.\nThen the query method will be auto invoke.")); this.query(); }