UNPKG

@winged/core

Version:

Morden webapp framekwork made only for ts developers. (UNDER DEVELOPMENT, PLEASE DO NOT USE)

1,334 lines (1,302 loc) 219 kB
// modules are defined as an array // [ module function, map of requires ] // // map of requires is short require name -> numeric require // // anything defined in a previous bundle is accessed via the // orig method which is the require for previous bundles // eslint-disable-next-line no-global-assign parcelRequire = (function (modules, cache, entry, globalName) { // Save the require from previous bundle to this closure if any var previousRequire = typeof parcelRequire === 'function' && parcelRequire; var nodeRequire = typeof require === 'function' && require; function newRequire(name, jumped) { if (!cache[name]) { if (!modules[name]) { // if we cannot find the module within our internal map or // cache jump to the current global require ie. the last bundle // that was added to the page. var currentRequire = typeof parcelRequire === 'function' && parcelRequire; if (!jumped && currentRequire) { return currentRequire(name, true); } // If there are other bundles on this page the require from the // previous one is saved to 'previousRequire'. Repeat this as // many times as there are bundles until the module is found or // we exhaust the require chain. if (previousRequire) { return previousRequire(name, true); } // Try the node require function if it exists. if (nodeRequire && typeof name === 'string') { return nodeRequire(name); } var err = new Error('Cannot find module \'' + name + '\''); err.code = 'MODULE_NOT_FOUND'; throw err; } localRequire.resolve = resolve; var module = cache[name] = new newRequire.Module(name); modules[name][0].call(module.exports, localRequire, module, module.exports, this); } return cache[name].exports; function localRequire(x){ return newRequire(localRequire.resolve(x)); } function resolve(x){ return modules[name][1][x] || x; } } function Module(moduleName) { this.id = moduleName; this.bundle = newRequire; this.exports = {}; } newRequire.isParcelRequire = true; newRequire.Module = Module; newRequire.modules = modules; newRequire.cache = cache; newRequire.parent = previousRequire; newRequire.register = function (id, exports) { modules[id] = [function (require, module) { module.exports = exports; }, {}]; }; for (var i = 0; i < entry.length; i++) { newRequire(entry[i]); } if (entry.length) { // Expose entry point to Node, AMD or browser globals // Based on https://github.com/ForbesLindesay/umd/blob/master/template.js var mainExports = newRequire(entry[entry.length - 1]); // CommonJS if (typeof exports === "object" && typeof module !== "undefined") { module.exports = mainExports; // RequireJS } else if (typeof define === "function" && define.amd) { define(function () { return mainExports; }); // <script> } else if (globalName) { this[globalName] = mainExports; } } // Override the current require with this new one return newRequire; })({"UnXq":[function(require,module,exports) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; Object.defineProperty(exports, "__esModule", { value: true }); var utils; (function (utils) { function listContains(list, item) { return list.indexOf(item) !== -1; } utils.listContains = listContains; function upperCamelToLowerCamel(str) { return str[0].toUpperCase() + str.slice(1); } utils.upperCamelToLowerCamel = upperCamelToLowerCamel; /** * clone object * @param source source object * @param deepClone true for deep clone, false for 1 level clone */ function clone(source, deepClone) { if (deepClone === void 0) { deepClone = false; } if (source instanceof Array) { var res = []; for (var _i = 0, source_1 = source; _i < source_1.length; _i++) { var item = source_1[_i]; if (deepClone) { res.push(utils.clone(item), deepClone); } else { res.push(item); } } return res; } else if ((typeof source === "undefined" ? "undefined" : _typeof(source)) === 'object') { var res = {}; for (var key in source) { if (deepClone) { res[key] = utils.clone(source[key], deepClone); } else { res[key] = source[key]; } } return res; } else { return source; } } utils.clone = clone; /** * convert a string into camelcase * any charactor followed a separator will be convert to uppercased letter, * otherwise convert to lowercased letter * @param key string to convert * @param separators list of separator, defauls to "-"/"_" */ function camelizeKey(key, separators) { if (separators === void 0) { separators = ['-', '_']; } var out = []; var i = 0; while (i < key.length) { if (separators.indexOf(key[i]) > -1) { out.push(key[i + 1].toUpperCase()); i++; } else { out.push(key[i]); } i++; } return out.join(''); } utils.camelizeKey = camelizeKey; /** * convert all keys in an object recursivly using utils.camelizeKey * @param obj */ function camelize(obj) { if (obj === null || obj === undefined) { return obj; } else if (obj instanceof Array) { return obj.map(function (item) { return utils.camelize(item); }); } else if ((typeof obj === "undefined" ? "undefined" : _typeof(obj)) === 'object') { var out = {}; for (var key in obj) { var v = obj[key]; out[utils.camelizeKey(key)] = utils.camelize(v); } return out; } else { return obj; } } utils.camelize = camelize; function generateId() { // TODO: consider conflicts return Date.now().toString(36) + parseInt(Math.random() * 1000000 + '').toString(36); } utils.generateId = generateId; function isEmptyObject(object) { for (var _ in object) { return false; } return true; } utils.isEmptyObject = isEmptyObject; function listToMap(list, hashKey) { var map = {}; if (hashKey) { for (var _i = 0, list_1 = list; _i < list_1.length; _i++) { var item = list_1[_i]; map[item[hashKey].toString()] = true; } } else { for (var _a = 0, list_2 = list; _a < list_2.length; _a++) { var item = list_2[_a]; map[item.toString()] = true; } } return map; } utils.listToMap = listToMap; })(utils = exports.utils || (exports.utils = {})); },{}],"R43f":[function(require,module,exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Observable = /** @class */function () { function Observable() { this._observableId = ++Observable.idCounter; this._watchedTargets = {}; this._watchers = []; } Observable.prototype._watchBy = function (context, callback) { this._watchers.push({ context: context, callback: callback }); }; Observable.prototype._stopWatchBy = function (context) { this._watchers = this._watchers.filter(function (w) { return w.context !== context; }); }; Observable.prototype._emitValueChange = function (modificationTree) { for (var _i = 0, _a = this._watchers; _i < _a.length; _i++) { var callback = _a[_i].callback; callback(modificationTree); } }; Observable.prototype._registerChild = function (field, child) { var _this = this; var id = child._observableId; if (!child._watchedTargets[id]) { child._watchedTargets[id] = { target: child, watcherCount: 0 }; } child._watchedTargets[id].watcherCount++; child._watchBy(this, function (modificationTree) { var _a; var s; if (typeof field === 'function') { s = field(); } else { s = field; } _this._emitValueChange((_a = {}, _a[s] = modificationTree, _a)); }); }; Observable.prototype._unregisterChild = function (childOrChildId) { var id; if (childOrChildId instanceof Observable) { id = childOrChildId._observableId + ''; } else { id = childOrChildId; } var watchInfo = this._watchedTargets[id]; if (watchInfo.watcherCount > 1) { watchInfo.watcherCount--; } else { this._watchedTargets[id].target._stopWatchBy(this); delete this._watchedTargets[id]; } }; Observable.idCounter = 0; return Observable; }(); exports.Observable = Observable; },{}],"WIKy":[function(require,module,exports) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var __extends = this && this.__extends || function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; }(); Object.defineProperty(exports, "__esModule", { value: true }); var Observable_1 = require("./Observable"); var ViewModel_1 = require("./ViewModel"); /** ViewModelList is only for internal use of the framework */ var ViewModelList = /** @class */function (_super) { __extends(ViewModelList, _super); function ViewModelList(items, stateDescriber) { var _this = _super.call(this) || this; _this.items = []; _this._itemStateDescriber = stateDescriber; items = _this._transformItems(items); _this.items = items; _this._handleChange(); return _this; } Object.defineProperty(ViewModelList.prototype, "lastIndex", { get: function get() { return this.length - 1; }, enumerable: true, configurable: true }); Object.defineProperty(ViewModelList.prototype, "length", { get: function get() { return this.items.length; }, enumerable: true, configurable: true }); ViewModelList.prototype.push = function (item) { var _item = this._transformItems([item])[0]; this.items.push(_item); this._handleChange(); this._emitValueChange(this._createModificationTree(this.items.length - 1)); return this.items.length; }; ViewModelList.prototype.pop = function () { var m = this.items.pop(); this._handleChange(); this._emitValueChange(this._createModificationTree(this.lastIndex + 1)); return m; }; ViewModelList.prototype.unshift = function (item) { var _item = this._transformItems([item])[0]; this.items.unshift(_item); this._handleChange(); this._emitValueChange(this._createModificationTree(0, this.lastIndex)); return this.items.length; }; ViewModelList.prototype.shift = function () { var v = this.items.shift(); this._handleChange(); this._emitValueChange(this._createModificationTree(0, this.lastIndex + 1)); return v; }; ViewModelList.prototype.splice = function (index, length) { if (length === void 0) { length = 0; } var newItems = []; for (var _i = 2; _i < arguments.length; _i++) { newItems[_i - 2] = arguments[_i]; } var _a; var _newItems = this._transformItems(newItems); if (index < 0) { index = 0; } if (index > this.lastIndex) { index = this.lastIndex; } if (length < 0) { index = index + length; length = Math.abs(length); } if (index + length > this.lastIndex) { length = this.lastIndex - index; } var oldLen = this.length; var removed = (_a = this.items).splice.apply(_a, [index, length].concat(_newItems)); this._handleChange(); this._emitValueChange(this._createModificationTree(index, Math.max(this.lastIndex, oldLen))); return removed; }; ViewModelList.prototype.slice = function (start, end) { return this.items.slice(start, end); }; ViewModelList.prototype.forEach = function (fn) { for (var i = 0; i < this.items.length; i++) { if (fn(this.items[i], i) === false) { break; } } }; ViewModelList.prototype.map = function (fn) { var res = []; for (var i = 0; i < this.items.length; i++) { res.push(fn(this.items[i], i)); } return res; }; ViewModelList.prototype.filter = function (fn) { return this.items.filter(fn); }; ViewModelList.prototype.some = function (fn) { return this.items.some(fn); }; ViewModelList.prototype.every = function (fn) { return this.items.every(fn); }; ViewModelList.prototype.sort = function (fn) { this.items = this.items.sort(fn); this._handleChange(); this._emitValueChange(this._createModificationTree(0, this.lastIndex)); return this; }; ViewModelList.prototype.reverse = function () { return this.items.reverse(); }; ViewModelList.prototype.join = function (separator) { return this.items.map(function (item) { return item.toString(); }).join(separator); }; ViewModelList.prototype.concat = function () { var newLists = []; for (var _i = 0; _i < arguments.length; _i++) { newLists[_i] = arguments[_i]; } var _a; return (_a = this.items).concat.apply(_a, newLists); }; ViewModelList.prototype.reduce = function (callbackfn, initialValue) { return this.items.reduce(callbackfn, initialValue); }; ViewModelList.prototype.reduceRight = function (callbackfn, initialValue) { return this.items.reduceRight(callbackfn, initialValue); }; ViewModelList.prototype.indexOf = function (item) { if ((typeof item === "undefined" ? "undefined" : _typeof(item)) === 'object' && !(item instanceof Observable_1.Observable)) { throw new Error('Passing raw object into viewModelList.indexOf() is not supported' + 'because raw object may be transformed into ViewModel transparently,' + 'please use value check instead of reference check.'); } for (var i = 0; i < this.items.length; i++) { if (this.items[i] === item) { return i; } } return -1; }; ViewModelList.prototype._createModificationTree = function (startIndex, endIndex) { if (endIndex === undefined) { endIndex = startIndex; } var tree = {}; for (var i = startIndex; i <= endIndex; i++) { tree[i] = {}; } return tree; }; ViewModelList.prototype._transformItems = function (items) { var describer = this._itemStateDescriber; return items.map(function (item) { if (!item) { console.error(items); throw new TypeError('TypeErraor: view state list can\'t have empty member'); } if (!describer) { // basictype // NOTE: // item can be raw object or raw list, // but if there's no describer specified, we can just their types // if (item instanceof Array) { // return new ViewModelList(item, {}); // } // if (typeof item === 'object') { // return new ViewModel(item, {}); // } return item; } else if (describer instanceof Array) { // array if (item instanceof Array) { item = new ViewModelList(item, describer[0]); } if (!(item instanceof ViewModelList)) { console.error(item); throw new TypeError("Can't set list member " + item + ": Expecting an array"); } return item; } else { // object if ((typeof item === "undefined" ? "undefined" : _typeof(item)) === 'object') { item = new ViewModel_1.ViewModel(item, describer); } if (!(item instanceof ViewModel_1.ViewModel)) { console.error(item); throw new TypeError("Can't set list member " + item + ": Expecting an object"); } return item; } }); }; ViewModelList.prototype._handleChange = function () { var _this = this; var aliveTargetIdMap = {}; this.items.forEach(function (item, i) { _this.defineIndexProperty(i); if (item instanceof Observable_1.Observable) { var id = item._observableId; aliveTargetIdMap[id] = true; if (!_this._watchedTargets[id]) { _this._registerChild(function () { return _this.indexOf(item) + ''; }, item); } } }); for (var id in this._watchedTargets) { if (!aliveTargetIdMap[id]) { this._unregisterChild(id); } } }; ViewModelList.prototype.defineIndexProperty = function (i) { var _this = this; if (Object.getOwnPropertyDescriptor(this, i)) { return; } Object.defineProperty(this, '' + i, { enumerable: true, set: function set(model) { _this._setItemByIndex(model, i); }, get: function get() { return _this._getItemByIndex(i); } }); }; ViewModelList.prototype._setItemByIndex = function (model, i) { if (i < 0 || i >= this.items.length) { console.error('Invalid index:', i, 'for modelList', this); throw new Error('Setting a model to ModelList[index] works only for model replacement.' + 'you must specify an index that reference a exisiting model'); } this.items[i] = this._transformItems([model])[0]; this._handleChange(); this._emitValueChange(this._createModificationTree(i)); }; ViewModelList.prototype._getItemByIndex = function (i) { if (i < 0 || i >= this.items.length) { return null; } return this.items[i]; }; return ViewModelList; }(Observable_1.Observable); exports.ViewModelList = ViewModelList; },{"./Observable":"R43f","./ViewModel":"JLq7"}],"JLq7":[function(require,module,exports) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var __extends = this && this.__extends || function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; }(); Object.defineProperty(exports, "__esModule", { value: true }); var Observable_1 = require("./Observable"); var ViewModelList_1 = require("./ViewModelList"); /** ViewModel is only for internal use of the framework */ var ViewModel = /** @class */function (_super) { __extends(ViewModel, _super); function ViewModel(data, stateDescriber) { var _this = _super.call(this) || this; // [key: string]: any; _this._stateStore = {}; _this._stateDescriber = stateDescriber; var _loop_1 = function _loop_1(field) { // for (const key in data) { // this[key as keyof this] = data[key as keyof typeof data]; // } Object.defineProperty(this_1, field, { get: function get() { return this._getRenderableState(field); }, set: function set(value) { this._setRenderableState(field, value); } }); }; var this_1 = this; for (var field in _this._stateDescriber) { _loop_1(field); } // if a field is described in describer, it will be set via this.setValue // otherwise, it will be set directly on context like plain objects for (var field in data) { _this[field] = data[field]; } return _this; } ViewModel.prototype._destory = function () { for (var id in this._watchedTargets) { this._watchedTargets[id].target._stopWatchBy(this); } delete this._watchedTargets; }; ViewModel.prototype._get = function (field) { if (this._stateDescriber[field]) { return this._getRenderableState(field); } else { return this[field]; } }; ViewModel.prototype._getFields = function () { var fields = []; for (var field in this) { if (Object.hasOwnProperty(field) && !ViewModel.bultinPropDict[field]) { fields.push(field); } } return fields.concat(Object.keys(this._stateStore)); }; ViewModel.prototype._set = function (field, value) { if (this._stateDescriber[field]) { this._setRenderableState(field, value); } else { this[field] = value; } }; ViewModel.prototype._getRenderableState = function (field) { return this._stateStore[field]; }; ViewModel.prototype._setRenderableState = function (field, value) { var _this = this; var _a; var describer = this._stateDescriber[field]; var oldValue = this._stateStore[field]; if (value === oldValue) { return; } if (oldValue && oldValue instanceof Observable_1.Observable) { this._unregisterChild(oldValue); } if (value === null || value === undefined) { // TODO: is setting _state[stateName] to 'null' or 'undefined' to be ok? this._stateStore[field] = value; } else if (describer === true) { // basicType state this._stateStore[field] = value; } else if (describer instanceof Array) { // ViewModelList if (value instanceof Array) { // replace this with monky-patched array // to watch every change of the list value = new ViewModelList_1.ViewModelList(value, describer[0]); } if (!(value instanceof ViewModelList_1.ViewModelList)) { console.error(value); throw new TypeError("Can't set state " + field + ": Expecting an array"); } var watchInfo = this._watchedTargets[value._observableId]; if (watchInfo) { watchInfo.watcherCount++; } else { this._watchedTargets[value._observableId] = { target: value, watcherCount: 1 }; value._watchBy(this, function (modificationTree) { var _a; _this._emitValueChange((_a = {}, _a[field] = modificationTree, _a)); }); } this._stateStore[field] = value; } else { // ViewModel if ((typeof value === "undefined" ? "undefined" : _typeof(value)) === 'object') { value = new ViewModel(value, describer); } if (!(value instanceof ViewModel)) { console.error(value); throw new TypeError("Can't set state " + field + ": Expecting an object"); } var watchInfo = this._watchedTargets[value._observableId]; if (watchInfo) { watchInfo.watcherCount++; } else { this._watchedTargets[value._observableId] = { target: value, watcherCount: 1 }; value._watchBy(this, function (modificationTree) { var _a; _this._emitValueChange((_a = {}, _a[field] = modificationTree, _a)); }); } this._stateStore[field] = value; } // console.log(`setting ${field} value of ${this.getModelId()} to ${value}`); this._emitValueChange((_a = {}, _a[field] = {}, _a)); }; ViewModel.bultinPropDict = { _stateStore: true, _stateDescriber: true }; return ViewModel; }(Observable_1.Observable); exports.ViewModel = ViewModel; },{"./Observable":"R43f","./ViewModelList":"WIKy"}],"3qoe":[function(require,module,exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** 数据取值路径,如['user','name'] 对应 user.name */ var DataPath = /** @class */function () { function DataPath(dataPathArr) { this.pathArr = dataPathArr; } DataPath.prototype.getDataFromState = function (state) { var s = state; for (var i = 0; i < this.pathArr.length; i++) { var name = this.pathArr[i]; if (s[name]) { if (i === this.pathArr.length - 1) { return s[name]; } else { s = s[name]; continue; } } else { return null; } } return null; }; DataPath.prototype.toString = function () { return this.pathArr.join('.'); }; DataPath.prototype.toStateDependencies = function () { var depsTree = {}; var node = null; for (var _i = 0, _a = this.pathArr; _i < _a.length; _i++) { var name = _a[_i]; if (node) { node[name] = {}; node = node[name]; } else { depsTree[name] = {}; node = depsTree[name]; } } return depsTree; }; return DataPath; }(); exports.DataPath = DataPath; },{}],"LKP/":[function(require,module,exports) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; Object.defineProperty(exports, "__esModule", { value: true }); var utils_1 = require("../utils"); var ViewModel_1 = require("../viewModel/ViewModel"); var DataPath_1 = require("./DataPath"); var DATA_NAME_REG = /^[a-z][a-zA-Z0-9]*$/; exports.vdomUtils = { parseDataPath: function parseDataPath(dataName) { var dataPath = dataName.split('.'); if (dataPath.length === 0) { return null; } for (var _i = 0, dataPath_1 = dataPath; _i < dataPath_1.length; _i++) { var name = dataPath_1[_i]; if (!name.match(DATA_NAME_REG)) { return null; } } return new DataPath_1.DataPath(dataPath); }, /** N for "New", means merge into new object */ mergeStateDependenciesN: function mergeStateDependenciesN(deps, newDeps) { for (var key in newDeps) { if (!deps[key]) { deps[key] = newDeps[key]; } else { this.mergeStateDependenciesN(deps[key], newDeps[key]); } } return deps; }, /** N for "New", means merge into new object */ mergeModificationTreeN: function mergeModificationTreeN(tree, newTree) { for (var key in newTree) { if (!tree[key]) { tree[key] = newTree[key]; } else { this.mergeModificationTreeN(tree[key], newTree[key]); } } return tree; }, /** N for "New", means merge into new object */ mergeStateN: function mergeStateN(state, newState) { var outputState = {}; if (state instanceof ViewModel_1.ViewModel) { for (var _i = 0, _a = state._getFields(); _i < _a.length; _i++) { var field = _a[_i]; outputState[field] = state[field]; } } else { for (var key in state) { outputState[key] = state[key]; } } for (var key in newState) { outputState[key] = newState[key]; } return outputState; }, mergeStateDependenciesWithChildren: function mergeStateDependenciesWithChildren(deps, children) { for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { var child = children_1[_i]; if (child.stateDependencies) { this.mergeStateDependenciesN(deps, child.stateDependencies); } } }, /** return true if needs update */ checkStateDependencies: function checkStateDependencies(modifiedState, stateDependencies) { var deepCompareStates = {}; // shallow compare for (var key in modifiedState) { if (!stateDependencies[key]) { if (stateDependencies['...']) { return true; } continue; } if (utils_1.utils.isEmptyObject(stateDependencies[key])) { return true; } deepCompareStates[key] = modifiedState[key]; } // deep compare for (var key in deepCompareStates) { var s = modifiedState[key]; if (s instanceof ViewModel_1.ViewModel || (typeof s === "undefined" ? "undefined" : _typeof(s)) === 'object') { var diff = this.checkStateDependencies(s, stateDependencies[key]); if (diff === true) { return true; } } } return false; }, mergeStateDescribers: function mergeStateDescribers(describer, newDescriber) { if (newDescriber === true) { return; } var dIsArray = describer instanceof Array; var ndIsArray = newDescriber instanceof Array; if (dIsArray !== ndIsArray) { throw new TypeError('Unable to merge state describer of type list and object'); } if (dIsArray) { var d = describer; var nd = newDescriber; if (d[0] === true) { d[0] = nd[0] || true; } else { this.mergeStateDescribers(d[0], nd[0]); } } else { var d = describer; var nd = newDescriber; for (var field in nd) { if (d[field] === true || d[field] === undefined) { d[field] = nd[field]; } else { this.mergeStateDescribers(d[field], nd[field]); } } } }, /** * NOTE: only for typing purpose, not actionaly needed. * ViewModel and ViewModelList can be correctly handled as ViewState */ observableToViewState: function observableToViewState(target) { return target; } }; },{"../utils":"UnXq","../viewModel/ViewModel":"JLq7","./DataPath":"3qoe"}],"gBLW":[function(require,module,exports) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var __extends = this && this.__extends || function () { var 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 function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; }(); Object.defineProperty(exports, "__esModule", { value: true }); var utils_1 = require("../../utils"); var vdomUtils_1 = require("../vdomUtils"); var ExpressionCompileError = /** @class */function (_super) { __extends(ExpressionCompileError, _super); function ExpressionCompileError(expression, index, message) { var _this = _super.call(this, message) || this; _this.expression = expression; _this.index = index; return _this; } return ExpressionCompileError; }(Error); exports.ExpressionCompileError = ExpressionCompileError; var Regs = { validNameStarterChar: /[a-zA-Z_]/, validNameChar: /[a-zA-Z0-9_]/, nameMatcher: /([a-zA-Z_]\w*)/g, stringMatcher: /(["'])((?:[^\1\\]|\\.)*?)\1/g }; var LexType; (function (LexType) { LexType[LexType["String"] = 0] = "String"; LexType[LexType["Name"] = 1] = "Name"; LexType[LexType["Operator"] = 2] = "Operator"; })(LexType || (LexType = {})); var GrammarNode = /** @class */function () { function GrammarNode() {} return GrammarNode; }(); var NameNode = /** @class */function (_super) { __extends(NameNode, _super); function NameNode() { return _super !== null && _super.apply(this, arguments) || this; } NameNode.prototype.getValue = function (dataSet) { var v = dataSet[this.dataName]; if (v === null || v === undefined) { return null; } if (this.child) { if (v[this.child.dataName]) { return this.child.getValue(v); } else { return null; } } else { if (utils_1.utils.listContains(['string', 'number', 'boolean'], typeof v === "undefined" ? "undefined" : _typeof(v))) { return v; } else { return true; } } }; NameNode.prototype.toStateDependencies = function () { var _a; var depsTree = (_a = {}, _a[this.dataName] = {}, _a); var node = this; var pathNode = depsTree[this.dataName]; while (node.child) { node = node.child; pathNode[node.dataName] = {}; pathNode = pathNode[node.dataName]; } return depsTree; }; return NameNode; }(GrammarNode); var ValueNode = /** @class */function (_super) { __extends(ValueNode, _super); function ValueNode() { return _super !== null && _super.apply(this, arguments) || this; } ValueNode.prototype.getValue = function (dataSet) { if (this.type === 'string') { return this.stringValue; } else { return this.nameNode.getValue(dataSet); } }; return ValueNode; }(GrammarNode); var ConditionNode = /** @class */function (_super) { __extends(ConditionNode, _super); function ConditionNode() { return _super !== null && _super.apply(this, arguments) || this; } ConditionNode.prototype.getValue = function (dataSet) { if (this.cond.getValue(dataSet)) { return this.trueValue.getValue(dataSet); } else { if (this.falseValue) { return this.falseValue.getValue(dataSet); } else { return null; } } }; return ConditionNode; }(GrammarNode); var CalculationNode = /** @class */function (_super) { __extends(CalculationNode, _super); function CalculationNode() { return _super !== null && _super.apply(this, arguments) || this; } CalculationNode.prototype.getValue = function (dataSet) { if (!this.operation) { return this.leftHand.getValue(dataSet); } if (this.operation === '||') { var leftValue = this.leftHand.getValue(dataSet); if (leftValue !== null && leftValue !== undefined) { return leftValue; } else { return this.rightHand.getValue(dataSet); } } if (this.operation === '!=') { if (this.leftHand.getValue(dataSet) !== this.rightHand.getValue(dataSet)) { return true; } else { return false; } } if (this.operation === '==') { if (this.leftHand.getValue(dataSet) === this.rightHand.getValue(dataSet)) { return true; } else { return false; } } if (this.operation === '!') { return !this.leftHand.getValue(dataSet); } return false; }; return CalculationNode; }(GrammarNode); exports.CalculationNode = CalculationNode; var DataExpression = /** @class */function () { function DataExpression(expression) { // ** 数据依赖 */ this.stateDependencies = {}; /** 求值表达式, 包括包裹符, 如 "{{a?1:2}}" */ this.lexicialParts = []; this.expression = expression; this.compile(); } Object.defineProperty(DataExpression.prototype, "fullExpression", { get: function get() { return "{{" + this.expression + "}}"; }, enumerable: true, configurable: true }); DataExpression.prototype.evaluate = function (dataSet) { return this.rootGrammarNode.getValue(dataSet); }; DataExpression.prototype.getExpression = function () { return this.expression; }; DataExpression.prototype.reCompile = function (expression) { this.expression = expression; this.lexicialParts = []; delete this.rootGrammarNode; this.compile(); }; /** * 在调用每个 getNode 方法时,传入的 index 是下一个需要取用的 lexicialPart 的下标 * 每个 getNode 方法都会返回一个 [LexicialNode, offset] 结果数组 * 其中的 offset 代表此方法最后取用的 lexicialPart 的下标,需要由调用方手动处理向后偏移(通常 +1 即可) */ DataExpression.prototype.getRootNode = function () { var _a, _b, _c; var rootNode; var offset; // {{Value}} _a = this.getValueNode(0), rootNode = _a[0], offset = _a[1]; if (rootNode && offset === this.lexicialParts.length - 1) { return rootNode; } // {{Calc}} _b = this.getCalculationNode(0), rootNode = _b[0], offset = _b[1]; if (rootNode && offset === this.lexicialParts.length - 1) { return rootNode; } // {{Cond}} _c = this.getConditionNode(0), rootNode = _c[0], offset = _c[1]; if (rootNode && offset === this.lexicialParts.length - 1) { return rootNode; } return null; }; DataExpression.prototype.getConditionNode = function (index) { var _a, _b, _c; // Calc?Value:Value // Calc?Value var rootNode = new ConditionNode(); var offset; _a = this.getCalculationNode(index), rootNode.cond = _a[0], offset = _a[1]; if (!rootNode.cond) { return [null, null]; } index = offset + 1; if (this.getLexicialPart(index).operator !== '?') { return [null, null]; } index += 1; _b = this.getValueNode(index), rootNode.trueValue = _b[0], offset = _b[1]; if (!rootNode.trueValue) { throw new ExpressionCompileError(this.expression, index, "Invalid condition expression in data point " + this.fullExpression + ", expected a value or name after \"?\""); } index = offset + 1; if (this.getLexicialPart(index).operator !== ':') { return [rootNode, index - 1]; } index += 1; _c = this.getValueNode(index), rootNode.falseValue = _c[0], offset = _c[1]; if (!rootNode.falseValue) { throw new ExpressionCompileError(this.expression, index, "Invalid condition expression in data point " + this.fullExpression + ", expected a value or name after \":\""); } return [rootNode, offset]; }; DataExpression.prototype.getCalculationNode = function (index) { var _a, _b, _c; // Value==Value // Value!=Value // Value||Value // !Value // Value var rootNode = new CalculationNode(); var offset; if (this.getLexicialPart(index).operator === '!') { // !Value index += 1; _a = this.getValueNode(index), rootNode.leftHand = _a[0], offset = _a[1]; if (!rootNode.leftHand) { throw new ExpressionCompileError(this.expression, index, "Invalid calculation expression in data point " + this.fullExpression + ", expected a value or name after \"!\""); } rootNode.operation = '!'; return [rootNode, offset]; } else { // Value _b = this.getValueNode(index), rootNode.leftHand = _b[0], offset = _b[1]; if (!rootNode.leftHand) { return [null, null]; } // Value==Value or Value||Value or Value!=Value index = offset + 1; var operator = this.getLexicialPart(index).operator; if (operator !== '==' && operator !== '||' && operator !== '!=') { return [rootNode, index - 1]; } else { rootNode.operation = operator; } index += 1; _c = this.getValueNode(index), rootNode.rightHand = _c[0], offset = _c[1]; if (!rootNode.rightHand) { throw new ExpressionCompileError(this.expression, index, "Invalid calculation expression in data point " + this.fullExpression + ", expected a value or name after \"==\""); } return [rootNode, offset]; } }; DataExpression.prototype.getValueNode = function (index) { var _a; var rootNode = new ValueNode(); if (this.getLexicialPart(index).type === LexType.String) { rootNode.type = 'string'; rootNode.stringValue = this.getLexicialPart(index).value; return [rootNode, index]; } var offset; _a = this.getNameNode(index), rootNode.nameNode = _a[0], offset = _a[1]; vdomUtils_1.vdomUtils.mergeStateDependenciesN(this.stateDependencies, rootNode.nameNode.toStateDependencies()); if (rootNode.nameNode) { rootNode.type = 'name'; return [rootNode, offset]; } return [null, null]; }; DataExpression.prototype.getNameNode = function (index) { var _a; var rootNode = new NameNode(); var offset; var part = this.getLexicialPart(index); if (part.type !== LexType.Name) { return [null, null]; } rootNode.dataName = part.value; index += 1; if (this.getLexicialPart(index).operator !== '.') { return [rootNode, index - 1]; } index += 1; _a = this.getNameNode(index), rootNode.child = _a[0], offset = _a[1]; if (!rootNode.child) { throw new ExpressionCompileError(this.expression, index, "Invalid data getter in data point " + this.fullExpression + ", expected a name after \".\""); } return [rootNode, offset]; }; DataExpression.prototype.compile = function () { // lexicial analysis var state = 'none'; var stringQuote = null; var nameBuffer = []; for (var arr = this.expression, i = 0; i < arr.length; i++) { var c = arr[i]; if (state === 'name') { if (!Regs.validNameChar.test(c)) { state = 'none'; var name = nameBuffer.join(''); this.checkName(name, i - 1); this.lexicialParts.push({ type: LexType.Name, value: name }); // roll back 1 turn to check this char i -= 1; } else { nameBuffer.push(c); } } else if (state === 'string') { if (c === stringQuote) { state = 'none'; stringQuote = null; this.lexicialParts.push({ type: LexType.String, value: nameBuffer.join('') }); } else { nameBuffer.push(c); } } else { // null if (c === '"' || c === '\'') { // handle string starter state = 'string'; stringQuote = c; nameBuffer = []; } else if (c === '=' || c === '|') { // handle operator "==" and "||" if (arr[i + 1] === c) { if (c === '=') { this.lexicialParts.push({ type: LexType.Operator, operator: '==' }); } else { this.lexicialParts.push({ type: LexType.Operator, operator: '||' }); } } else { throw new ExpressionCompileError(this.expression, i, "Invalid char \"" + c + "\", do you mean \"" + c + c + "\"?"); } // step over next '=' or '|' i += 1; } else if (c === '!') { if (arr[i + 1] === '=') { this.lexicialParts.push({ type: LexType.Operator, operator: '!=' }); // step over next '=' i += 1; } else { this.lexicialParts.push({ type: LexType.Operator, operator: '!' }); } } else if (c === ' ') { // skip space continue; } else if (c === '.' || c === '?' || c === ':') { // handle other operators this.lexicialParts.push({ type: LexType.Operator, operator: c }); } else if (Regs.validNameStarterChar.test(c)) { // handle name starter state = 'name'; nameBuffer = [c]; } else { // handle standalone digital if (c.match('[0-9]')) { throw new ExpressionCompileError(this.expression, i, "Invalid char \"" + c + "\" in " + this.fullExpression + ", the use of number value was not permitted."); } else if (c === '>') { throw new ExpressionCompileError(this.expression, i, "Invalid char \"" + c + "\" in " + this.fullExpression + "," + 'If you wan\'t to use ViewPoint/ViewListPoint, make sure it\'s placed on the right place;'); } else { throw new ExpressionCompileError(this.expression, i, "Invalid char \"" + c + "\" in " + this.fullExpression); } } } } if (state === 'name') { var name = nameBuffer.join(''); this.checkName(name, 0); this.lexicialParts.push({ type: LexType.Name, value: name }); } // grammar analysis var rootNode = this.getRootNode(); if (!rootNode) { throw new ExpressionCompileError(this.expression, 0, "Can't parse data expression \"" + this.fullExpression + "\""); } this.rootGrammarNode = rootNode; }; DataExpression.prototype.checkName = function (name, index) { if (name === 'true' || name === 'false') { throw new ExpressionCompileError(this.expression, index, "Invalid name " + name + ". in " + this.fullExpression + "." + ' If you want to use conditional render, use grammar like {{flag?\'res\'}} or {{!flag?\'res\'}} instead');